Here I will brief you about the method which will give you a Configuration value depending upon the key passed. Of course, the key and value pair will be residing in your SharePoint list.
Being a good developer you should make your application as configurable as possible to avoid last minute rush to small changes and hence resulting in another deployment of a solution.
E.g. Consider a case where you have marked your Custom Top Navigation code to have 6 nodes(Hard coded value / taken from constants ); But due to some requirement changes you need to make it 8 nodes now.How you will do it ? Again a Code Change ? If you do; this will require another solution deployment.
Instead of that; identify these kind of parameters in your custom application and try and make those as configurable as possible which may lead to changes in future.
For this to have create a new list Named Configuration Settings at root site collection (of course you can have any name), with 3 site columns :
- Rename Title as Config Key : A key used in solution E.g. NumberOfTopNavigationNodes
- Config Value : Value for a key E.g. 6
- Description : Description of Key and Value or where it is pointing to. E.g. Number of top Navigation nodes used in Top Navigation web part under Controls WSP.
Note: I have used internal Name of Title column in query so rename the column aa.
Lets have a look at the code which will do it for us:
-
-
-
-
-
- public static string GetValueForCoreSettingsKey(SPWeb web, string configKey)
- {
- string resultValue = string.Empty;
- try
- {
- if (web == null)
- {
- throw new ArgumentNullException("Web");
- }
- else
- {
- SPQuery Query = new SPQuery();
- string query = "<Where><Eq><FieldRef Name = 'Title'/><Value Type='Text'>"
- + configKey
- + "</Value></Eq></Where>";
- Query.Query = query;
- SPList CoreConfigrationList = web.Lists.TryGetList("Configuration Settings");
- if (CoreConfigrationList != null)
- {
- SPListItemCollection ListItemCollection = CoreConfigrationList.GetItems(Query);
-
- if (ListItemCollection != null)
- {
- foreach (SPListItem ListItem in ListItemCollection)
- {
- resultValue = ListItem["ConfigurationValue"].ToString();
- }
- }
- }
- }
- }
- catch (Exception)
- {
- throw;
- }
- return resultValue;
- }
Here you need to pass the parameter of SPWeb Object and Configuration Key of which you need a value.
E.g.
GetValueForCoreSettingsKey(web,NumberOfTopNavigationNodes)
By this way you can keep your application configurable and easy to maintain in future. Simply changing the value for an entry will solve your purpose.
Happy SharePoint!!!