Friday 8 January 2016

Fetching values from Web.config in SharePoint if scope is site

Fetching values from Web.config in SharePoint in webapplication level if scope is site it won't allow directly to web.config we can able to fetch the data using below method


public string GetConnectionstring(string Url, string Key)
        {
            try
            {
                using (SPSite site = new SPSite(Url))
                {
                    Configuration config = WebConfigurationManager.OpenWebConfiguration("/", site.WebApplication.Name);
                    return config.AppSettings.Settings[Key].Value;
                }
            }
            catch (Exception ex)
            {
                logToList(ex.Message);
                return string.Empty;
            }
        }

Maintaining Cache in Application Level

1. Create Cache Manager Class
public class CacheManager
    {
    }

2. Add below method into CacheManager Class for Adding Data to Cache
     
        /// <summary>
        /// Add data to Cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="bShortTime"></param>
        public static void AddToCache<T>(string key, T value, bool bShortTime)
        {
            try
            {
                if (bShortTime)
                {
                    HttpContext.Current.Cache.Insert(key,
                     value,
                    null,
                    DateTime.Now.AddMinutes(20),
                    System.Web.Caching.Cache.NoSlidingExpiration);
                }
                else
                {
                    AddToCache(key, value);
                }
            }
            catch (Exception ex) {
                throw ex; ;
                 }

        }
     

3. Add below method into CacheManager Class for Adding Data to Cache
        /// <summary>
        /// Add data to Cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private static void AddToCache<T>(string key, T value)
        {
            try
            {
                HttpContext.Current.Cache.Insert(key,
                 value,
                null,
               System.Web.Caching.Cache.NoAbsoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration);
            }
            catch (Exception ex) { throw ex; }

        }


4. Add below method into CacheManager Class for Checking Cache Exists or not based on key
        /// <summary>
        /// Checking Cache Exists or not
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            try
            {
                bool bKey = false;
                if (HttpContext.Current.Cache.Get(key) != null)
                {
                    bKey = true;
                }
                return bKey;
            }
            catch (Exception ex) { throw ex; }
        }

        /// <summary>
        /// ReadFromCache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T ReadFromCache<T>(string key)
        {
            T value;
            value = (T)HttpContext.Current.Cache.Get(key);
            return value;
        }


5. Add below method into CacheManager Class for Remove data From Cache based on key
        /// <summary>
        /// Remove data From Cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool RemoveFromCache(string key)
        {
            try
            {
                bool bKey = false;
                if (HttpContext.Current.Cache.Get(key) != null)
                {
                    HttpContext.Current.Cache.Remove(key);
                    bKey = true;
                }
                return bKey;
            }
            catch (Exception ex) { throw ex; }
        }
     
Creating Property class for Cache
/// <summary>
        /// Cache Properties for RequestType
        /// </summary>
        public class RequestType
        {
            public int RequestTypeID { get; set; }
            public string RequestTypeName { get; set; }
        }


Using below method we can able to interact data to through Cache


public List<CacheProperties.RequestType> GetRequestType()
        {
            List<CacheProperties.RequestType> RequestType = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (!CacheManager.Exists("RequestType"))
                    {
                        RequestType = BusinessLogicLayer.GetBusinessLogicLayerInstance.MainForm.GetRequestType();
                        CacheManager.AddToCache<List<CacheProperties.RequestType>>("RequestType", RequestType, true);
                    }
                    else
                    {
                        RequestType = CacheManager.ReadFromCache<List<CacheProperties.RequestType>>("RequestType");
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return RequestType;
        }


Maintaining Data in Cache and Fetching with key value fields

Create ConfigurationManager Class
 public static class ConfigurationManager
    {
     }

Add below Code in ConfigurationManager Class for maintaining Context
        private static ServerContext serverContext = null;

Add below Code in ConfigurationManager Class for Creating instance of
        /// <summary>
        /// ConfigurationManager
        /// </summary>
        static  ConfigurationManager()
        {
            try
            {
                serverContext =  ServerContext.GetServerContextInstance;
            }
            catch (Exception ex) { throw ex;  }
        }

Add below Code in ConfigurationManager Class for getting values using key and default value
        /// <summary>
        /// GetValue
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string GetValue(string Key, string defaultValue)
        {
            try
            {
                Dictionary<string, string> configurationSetting = new Dictionary<string, string>();
                //if (null != Key)
                //{
                //    throw new ArgumentNullException();
                //}

                if (CacheManager.Exists(Constants.Cache.CONFIGURATION_KEY))
                {
                    configurationSetting = CacheManager.ReadFromCache<Dictionary<string, string>>(Constants.Cache.CONFIGURATION_KEY);
                }
                else
                {
                    configurationSetting = serverContext.GetConfiguration();
                    CacheManager.AddToCache<Dictionary<string, string>>(Constants.Cache.CONFIGURATION_KEY, configurationSetting, true);
                }

                if (configurationSetting.ContainsKey(Key))
                {
                    defaultValue = configurationSetting[Key];
                }
                return defaultValue;
            }
            catch (Exception ex) { return null; }
        }


/// <summary>
        /// GetConfiguration
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetConfiguration()
        {
            try
            {
                Dictionary<string, string> configurationSetting = new Dictionary<string, string>();
                SPList configurationList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.ServerContext.CONFIGURATION_SETTINGS_LIST);
                SPQuery query = new SPQuery();
                SPListItemCollection items = configurationList.Items;
                foreach (SPListItem item in items)
                {
                    configurationSetting.Add(item["Key"].ToString().Trim(), item["Value"].ToString().Trim());
                }
                return configurationSetting;
            }
            catch (Exception ex) {  return null; }
        }

Custom Webpart Properties

Adding Custom webpart properties in SharePoint Visual Webpart

1. Add Property in  Webpart1.ascx.cs Page

public Webpart1 WebPart { get; set; }//Change Webpart class name in place of "Webpart1"


2.Overrite CreateChildControls method in Webpart1.cs Page

protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            if (control != null)
            {
                ((Webpart1UserControl)control).WebPart = this; //Change Webpart User Control Name
            }
            Controls.Add(control);
        }

3.Add Custom Properties in Webpart1.cs page

        #region Custom Properties

        [Category("GMDM Properties"), //Change Custom Property Group Name
        Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        WebDisplayName("URL"), //Change Property name
        WebDescription("Please Enter URL")] //Change Property Description

        public string strUrl
        {
            get;
            set;
        }
        #endregion