Monday, September 12, 2016

What is SPServices

What is SPServices?
SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use. It also includes functions which use the various Web Service operations to provide more useful (and cool) capabilities. It works entirely client side and requires no server install.

  • Website:SPServices 
  • Supports: SharePoint 2013/SharePoint 2010/Foundation 2010/MOSS 2007/WSS v3/Cloud/Office 365 
  • Ideal for: Developers/Designers 
  • Price: US $ 0.00 
  • Licensing:Free License 
 SharePoint's Web Services allow you to interact directly with SharePoint objects such as lists, webs, pages, and permissions without deploying any server-side code. The Web Service operations can be built together into more full-featured functionality that can provide real value to SharePoint users and improve the overall user experience.
SPServices includes not only jQuery "wrappers" for most commonly used Web Services and their operations, but also value-added functions that let you add functionality to forms and pages with very little work.
Some of the most popular value-added functions are:
  • $().SPServices.SPCascadeDropdowns - The SPCascadeDropdowns function lets you set up cascading dropdowns on SharePoint forms. What this means is that you can enforce hierarchical relationships between column values, like Site/State or Product Family/Product Code.
  • $().SPServices.SPSetMultiSelectSizes - Sets the size of the boxes in a multi-select picker based on the values they contain.
  • $().SPServices.SPComplexToSimpleDropdown - Converts a "complex" dropdown (which SharePoint displays if there are 20+ options) to a "simple" dropdown (select).
Reference: http://www.sharepointreviews.com/sharepoint-development/747-jquery-library-for-sharepoint-web-services

Tuesday, October 11, 2011

Get UserProfile Object of Logged-in User

In this article, I will explain how to get UserProfile object for Logged-in User (current user).
//Function Call
UserProfile objUserProfile= GetProfileOfCurrentUser(SPContext.Current.Web.CurrentUser.LoginName)
public UserProfile GetProfileOfCurrentUser(string accountName)
        {
            UserProfile profile = null;
            try
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    return null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = SPContext.Current.Site;
                    ServerContext context = ServerContext.GetContext(site);

                    UserProfileManager profileManager = new UserProfileManager(context);
                    if (!profileManager.UserExists(accountName))
                    {
                        profile = null;
                    }

                    profile = profileManager.GetUserProfile(accountName);
                });
            }
            catch (Exception ex)
            {
                profile = null;
            }
            return profile;
        }

Event receiver to update an item's in list

How to update Created By and Modified By fields in sharepoint list using C#
In this article I will explain, how to update list item in event receiver. In event receiver, I will update Created By /Modified By/Title metadata of list item.
Code:

public override void ItemUpdated(SPItemEventProperties properties)
    {
        int userID=0;
        string userNTID = "WIN\AMITKUMAR";
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
        SPListItem CurrentItem = properties.ListItem;
        CurrentItem.Web.AllowUnsafeUpdates = true;
        CurrentItem.Web.Site.AllowUnsafeUpdates = true;
        // In the next statment i am updating CreatedBy(Author) filed with SystemAccount
        CurrentItem["Author"] = CurrentItem.Web.Site.SystemAccount.ID; //CreatedBy
        //We can also update CreatedBy(Author)/ModifiedBy(Editor) field with Any user account
         FindUserIDByNTID(userNTID, CurrentItem.Web.Site, ref userID);
         if (userID > 0)
         {
            CurrentItem["Editor"] = userID; //ModifiedBy
         }
         else
         {
            CurrentItem["Editor"] = CurrentItem.Web.Site.SystemAccount.ID; //ModifiedBy
         }
        CurrentItem["Title"] = "Amit Kumar";
        CurrentItem.Update();
        CurrentItem.ParentList.Update();
        CurrentItem.Web.Update();
        CurrentItem.Web.AllowUnsafeUpdates = false;
        CurrentItem.Web.Site.AllowUnsafeUpdates = false;
        });
    }
public static void FindUserIDByNTID(string userNTID, SPSite site, ref int userID)
        {
          try
            {
              //--Check user NTID is null or not
              if (!string.IsNullOrEmpty(userNTID))
              {
               //--userNTID is not null
               //--then fetch ID of the user
               userID = site.RootWeb.AllUsers[userNTID].ID;
              }
              else
              {
               //--If userNTID is null
               userID = 0;
              }
          }
        catch (ArgumentException ex)
            {
              userID = 0;
            }
      catch (Exception ex)
      {
      userID = 0;
      }
     }

Get unique value from Array (String/Integer):

Problem: In one of my project, I am getting values from one datasource in the form of .net Array. In the .NET Framework 3.5 there is a function called Distinct(). This Distinct() function return unique values from Array. This function works fine in the case of integer array. In string array, it not able to handle case sensitivity. If all items in the string array in same case, then it will work fine. Due to this, I was facing problem in getting unique value from String Array. Resolution: To Solve this problem, I have created functions, which used Stringcomparison. InvariantCultureIgnoreCase. .NET Framework 3.5: It is one line of code.
//If integer array
int [] intArr={5,2,3,3,5};
intArr = intArr.Distinct().ToArray(); // Output : intArr ={5,2,3}
//If string array
string [] strArr={“Amit”,”Amit”,”Kumar”,”Kumar”};
strArr = strArr.Distinct().ToArray(); //Output: strArr ={“Amit”,,”Kumar” }
string [] strArrCase={“Amit”,”AMIT”,”Kumar”,”KUMAR”,”Amit”,”Kumar”};
strArrCase = strArrCase.Distinct().ToArray(); //Output: strArrCase ={“Amit”,”AMIT”,”Kumar”,”KUMAR” }
Custom Function:
//Function call
string [] strArr={“Amit”,”Amit”,”Kumar”,”Kumar”};
strArr= GetUniqueArray(strArr); //Output: strArr ={“Amit”,”Kumar” }
        #region Get unique From Array
        public static string[] GetUniqueArray(string[] itemValues)
        {
            string stringList=string.Empty;
            string currentValue=string.Empty;
            string[] newArray=null;
            ArrayList uniqueList = new ArrayList();
            try
            {
                for (int counter = 0; counter < itemValues.Length; counter++)
                {
                    currentValue = Convert.ToString(itemValues[counter]);
                    if (!CheckDuplicateArray(currentValue, uniqueList))
                    {
                       uniqueList.Add(itemValues[counter]);
                    }
                }
                if (uniqueList.Count != 0)
                {
                    newArray = uniqueList.ToArray(Type.GetType("System.String")) as string[]; 
                }
            }
            catch (Exception ex)
            {
            }
            return newArray;
        }
        #endregion

        #region Check Duplicates From Array
        public static bool CheckDuplicateArray(string value, ArrayList uniqueList)
        {
            bool itemFound = false;
            try
            {
                foreach (string currentValue in uniqueList)
                {
                    if (string.Equals(value, currentValue, StringComparison.InvariantCultureIgnoreCase))
                    {
                        itemFound = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return itemFound;
        }
        #endregion

Tuesday, September 06, 2011

Render(Parse) XML using XSLT

Requirement:
The requirement is to render xml data into a page.
Resolution:
We can perform this task by following ways:
1. Read xml file using C#.Net and iterate the xml node. At the time of iteration, render data from xml to page.
2. Use the XSL. In this approach, create .XSLT file, which store the formatting in the form of HTML/CSS. By using XSL, we can separate the data rending from the data itself.
Example to render (parse) xml using xslt:
Save given xml in to file called "myNavigation.xslt":



  
    
  



Now add following tag in your .ASPX page:


In the code behind file of .ASPX page (.ASPX.CS file), add following directive:
using System.Xml;
using System.Xml.Xsl;

After that,in the code behind file of .ASPX page (.ASPX.CS file), write following code in the Page_Load method:

string languageDetails =
 @"
    
        
            
                
                
                
            
            
                
                
            
            
            
            
                
                
                
                
                
              
            
            
              
            
        
      ";
XmlDocument myNavigationDoc = new XmlDocument();
myNavigationDoc.LoadXml(languageDetails);

XslTransform myNavigationTransform = new XslTransform();
myNavigationTransform.Load(Server.MapPath("myNavigation.xslt"));

this.myNavigationControl.Document = myNavigationDoc;
this.myNavigationControl.Transform = myNavigationTransform;

How to read XML using LINQ

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.
One of the big programming model improvements being made in .NET 3.5 is LINQ. "LINQ", stands for .NET Language Integrated Query.
LINQ supports a rich extensibility model that facilitates the creation of efficient domain-specific providers for data sources. .NET 3.5 ships with built-in libraries that enable LINQ support against Objects, XML, and Databases.
“Microsoft original motivation behind LINQ was to address the impedance mismatch between programming languages and database.”
What is LINQ to XML?
LINQ to XML is a built-in LINQ data provider that is implemented within the "System.Xml.Linq" namespace in .NET 3.5. Formerly LINQ is XLinq. It means Queries performed against the XML source. LINQ to XML provides a clean programming model that enables you to read, construct and write XML data. You can use LINQ to XML to perform LINQ queries over XML that you retrieve from the file-system, from a remote HTTP URL or web-service, or from any in-memory XML content.
Using LINQ to XML to read XML file:
using System;
using System.Xml.Linq;
using System.Text;

namespace ReadXMLData
{
  class Program  
	{
		static void Main(string[] args)
		{
			DisplayXmlData();

		}

public static void DisplayXmlData()
{
string languageDetails =

  @"                           ";

////Create XDocument object using string.
XDocument xmlDoc = XDocument.Parse(languageDetails);
/*
////Load XDocument object using xml document/file:
string xmlPath=""; //// Complete path of xml
XDocument xmlDoc = XDocument.Load(xmlPath);
*/
string languageTitle=GetLanguageTitle(xmlDoc);

////Find language xml

List languagesXml = GetLanguageXml(xmlDoc);

if (languagesXml != null)
     {
      ////Loop of language xml :: Begins
      foreach (XElement languageXml in languagesXml)
      {

       Console.WriteLine(languageXml.Attribute("URL").Value);
       Console.WriteLine(languageXml.Attribute("Name").Value);
      }
      ////Loop of language xml :: Ends
     }
}


 public static string GetLanguageTitle(XDocument xmlDoc)
  {
   string languageTitle = string.Empty;

   try
   {

    List objXElements = new List();
    objXElements = (from localeXml in xmlDoc.Descendants("LanguageTitle")
        select localeXml).ToList();

    if (objXElements != null)
    {
     languageTitle = objXElements[0].Attribute("Name").Value;
    }
   }
   catch (Exception ex)
   {

   }

   return languageTitle;
  }


  public static List GetLanguageXml(XDocument xmlDoc)
  {
   List objXElements = new List();

   try
   {

    objXElements = (from localeXml in xmlDoc.Descendants("Language")
        select localeXml).ToList();
   }
   catch (Exception ex)
   {

   }

   return objXElements;
  }

        }
}

Friday, July 01, 2011

Highlight the link(href Tag/HTML link Tag) on click:

Highlight the link(href Tag/HTML link Tag) on click:

With the help of style sheet(CSS), we can highlight the link after click.

Write below mentioned styles in STYLE tag before HEAD Tag of page:



a:link {font-size: 11px;color:green;text-decoration: none} /* unvisited link */
a:visited {font-size: 11px;orange:orange;text-decoration: none} /* visited link */
a:hover {font-size: 11px;text-decoration: underline;color:#FF00FF;} /* mouse over link */
a:active {font-size: 11px;color:orange;text-decoration: none} /* selected link */



Write below mentioned HTML in BODY Tag of page:



Amit Kumar1


Amit Kumar2


Amit Kumar3




How to get Publishing Page Meta Data (Column Value) in Sharepoint

Requirement:

The requirement is to identify status (Draft/Approved/Checkout/Pending/Published) of page in Pages library and also fetch the metadata of page using SharePoint Ojbect Model in Publishing Web.

Resolution:

With the help of PublishingWeb class (Microsoft.SharePoint.Publishing), we can access different components of Published Web site like Pages document library, Published site navigation bar and etc.

The PublishingWeb class provides publishing behavior for an SPWeb instance that supports publishing. This class cannot be inherited.

Namespace: Microsoft.SharePoint.Publishing
Assembly: Microsoft.SharePoint.Publishing (in microsoft.sharepoint.publishing.dll)


In this example we will identify status (Draft/Approved/Checkout/Pending/Published) of page and access metadata of Pages from Pages Library in Publishing Web:



using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Publishing;


namespace GetPublishedData
{
class Program
{
static void Main(string[] args)
{
try
{

using (SPSite site = new SPSite("http://amitkumarmca04.blogspot.com"))
{
using (SPWeb web = site.OpenWeb())
{
// Check web is PublishingWeb or not
if (PublishingWeb.IsPublishingWeb(web))
{
// Get the PublishingWeb
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
// Get the Page list from PublishingWeb
SPList pagesList = publishingWeb.PagesList;
if (pagesList != null && pagesList.Items.Count > 0)
{
// Get a reference to a publishing page

foreach (SPListItem page in pagesList.Items)
{
//Find status (Draft/Approved/Checkout/Pending/Published) of page
if (page.ModerationInformation.Status == SPModerationStatusType.Draft)
{
Console.WriteLine("Page in Draft mode.");
}
else if (page.ModerationInformation.Status == SPModerationStatusType.Approved)
{
Console.WriteLine("Page in Approved mode.");
}
else if (page.ModerationInformation.Status == SPModerationStatusType.Pending)
{
Console.WriteLine("Page in Pendig mode.");
}

if (page.Level == SPFileLevel.Checkout)
{
Console.WriteLine("Page in Checkout mode.");
}
else if (page.Level == SPFileLevel.Published)
{
Console.WriteLine("Page in Published mode.");
}
else if (page.Level == SPFileLevel.Draft)
{
Console.WriteLine("Page in Draft mode.");
}

//Find metadata of page
if (string.Equals(page.Name, "AmitKumar.aspx", StringComparison.InvariantCultureIgnoreCase))
{
//Access the page metadata
Console.WriteLine(Convert.ToString(page["Title"]));
}
}
}
}
else
{
// If the SPWeb is not a PublishingWeb,
// then GetPagesListName returns the URL
// that would be used by the Pages list
// if the Publishing feature were to be
// activated.
string pagesListName = PublishingWeb.GetPagesListName(web);
//After getting the url we can access Pages list
}
}
}

}
catch (Exception ex)
{
throw;
}

}
}
}

Tuesday, June 07, 2011

Upload (Import) data from excel (spreadsheet) file to SharePoint list using c#

Upload (Import) data from excel (spreadsheet) file to SharePoint list using c#:

When we have data in excel format and want to import that data to a SharePoint list, then how to do. By default SharePoint will provide us an option to edit in spreadsheet or download list items in spread sheet. But, it doesn't have an option to import the excel data to SharePoint list. To resolve this problem, I have created web part.
In this web part, I am using SharePoint list called “Employee”. The name of columns are Tile and LastName.
With the help of this web part, user will enter the data in the excel and then give the path of the file in the input box present in the page. Now instead of uploading the whole excel file into a document library the code will read the file and update the list with the data present in the excel file.

The web part code is:



using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Data.OleDb;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebControls;




namespace Example1
{
public class wp_ImportXLSFile : WebPart
{
#region Member Variables
System.Web.UI.WebControls.Button btnUpload;
FileUpload fleDoc;
#endregion

#region Properties
private const string _defaultList = "Employee";
private string _listName = "Employee";
[DefaultValue(_defaultList)]
[WebPartStorage(Storage.Personal)]
[XmlElement(ElementName = "List Name", IsNullable = false)]
public string InternalList
{
get { return this._listName; }
set { this._listName = value; }
}


#endregion

#region Render Controls and Handle Controls Event

#region Create Child Controls
protected override void CreateChildControls()
{

try
{
Table tbl = new Table();
TableRow tr = new TableRow();
TableCell tc = new TableCell();

tc.Text = "Select file:";
tr.Cells.Add(tc);
tc = new TableCell();
//Create browse object
fleDoc = new FileUpload();
tc.Controls.Add(fleDoc);
tr.Cells.Add(tc);
tbl.Rows.Add(tr);


tr = new TableRow();
tc = new TableCell();
tc.RowSpan = 2;
tc.HorizontalAlign = HorizontalAlign.Center;
//Create button
btnUpload = new System.Web.UI.WebControls.Button();
btnUpload.Text = "Upload File";
btnUpload.Click += new EventHandler(btnUpload_Click);
tc.Controls.Add(btnUpload);
tr.Cells.Add(tc);
tbl.Rows.Add(tr);
this.Controls.Add(tbl);

}
catch (Exception ex)
{
this.Page.Response.Write(ex.Message);
}
}

#endregion

#region Handle button click event
void btnUpload_Click(object sender, EventArgs e)
{
try
{
if (fleDoc != null && fleDoc.PostedFile != null)
{
#region If File exist

if (fleDoc.PostedFile.ContentLength > 0)
{
#region File size is greater than 0

string fileExt = System.IO.Path.GetExtension(fleDoc.FileName);
if (string.Equals(fileExt, ".xls", StringComparison.InvariantCultureIgnoreCase) )
{
#region If not xls file
string Path = fleDoc.PostedFile.FileName;
string listname = "Sheet1";

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties=Excel 8.0");
//OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=Excel 12.0 Xml;HDR=YES");
//Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Extended Properties="Excel 12.0;HDR=YES";
//Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Extended Properties="Excel 12.0 Xml;HDR=YES";
con.Open();


//Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference
DataSet myDataSet = new DataSet();
OleDbCommand myCommand = new OleDbCommand(" SELECT * FROM [" + listname + "$]", con);
System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(myCommand);

da.Fill(myDataSet);
con.Close();

if (myDataSet != null && myDataSet.Tables.Count > 0 && myDataSet.Tables[0].Rows.Count > 0 && !string.IsNullOrEmpty(this.InternalList))
{
#region If record found

SPWeb web = SPContext.Current.Web;

SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite fullSite = new SPSite(web.Site.ID))
{
using (SPWeb fullWeb = fullSite.OpenWeb())
{

#region Find list exist or not
if (chkListExist(fullWeb))
{
fullWeb.AllowUnsafeUpdates = true;
SPList oList = fullWeb.Lists[this.InternalList];

#region Travers through each row in the dataset
foreach (DataRow myDataRow in myDataSet.Tables[0].Rows)
{
#region Datarow Loop
Object[] cells = myDataRow.ItemArray;
string strFirstName = string.Empty;
string strLastName = string.Empty;
int cellCount = 1;
foreach (object cellContent in cells)
{
#region Cell Loop

string cellText = cellContent.ToString();
cellText = cellText.Replace("\n", "|");
//Read the string and put into Array of characters chars
if (cellCount == 1)
{
strFirstName = cellText;
cellCount++;
}
else if (cellCount == 2)
{
strLastName = cellText;
cellCount = 1;
}
this.Page.Response.Write("\n" + cellText);
#endregion
}
insertRecordInList(oList, strFirstName, strLastName);
#endregion
}
#endregion

fullWeb.AllowUnsafeUpdates = false;

}

#endregion

}
}
});

#endregion
}
else
{
#region If record not found
this.Page.Response.Write("No record found.");
#endregion
}
#endregion

}
else
{
#region If not xls file
this.Page.Response.Write("Only .xls files allowed!");
#endregion
}



#endregion
}
else
{
#region File size is 0
this.Page.Response.Write("Uploaded file size is 0.");
#endregion
}


#endregion
}
else
{
#region If File not exist
this.Page.Response.Write("Uploaded file does not exist.");
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
}

#endregion

#endregion

#region Helper


#region Check list exist or not
private Boolean chkListExist(SPWeb web)
{
Boolean blnExist = false;
try
{
#region Try
if (!String.IsNullOrEmpty(this.InternalList) && this.InternalList.ToString().Trim().Length != 0)
{
try
{
if (web.Lists[this.InternalList] != null)
{
blnExist = true;
}
}
catch
{
#region If internal news list name is not valid
blnExist = false;
#endregion

}

}
else
{
#region If internal news list name is empty
blnExist = false;
#endregion
}

#endregion

}
catch (Exception ex)
{
#region Catch
blnExist = false;
#endregion
}
return blnExist;
}
#endregion


#region Insert record in list
private void insertRecordInList(SPList oList,string strFirstName,string strLastName)
{
try
{
#region Try
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = strFirstName;
oListItem["LastName"] = strLastName;
oListItem.Update();
#endregion

}
catch (Exception ex)
{
#region Catch
throw ex;
#endregion
}
}
#endregion

#endregion

}
}

Monday, June 06, 2011

Get changed user profiles in SharePoint using C#

Get all the user profiles/properties which are modified since yesterday date or any datetime interval:

With the help of UserProfileManager class (Microsoft.Office.Server.UserProfiles), we can access properties of user profile and changed profile which are modified since yesterday date or any datetime interval.
In this example we will access different components of UserProfileManager :


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
using System.Collections;

namespace UserProfilesOMApp
{
class Program
{
static void Main(string[] args)
{

using (SPSite site = new SPSite("http://amitkumarmca04.blogspot.com"))
{
ServerContext context = ServerContext.GetContext(site);
UserProfileManager profileManager =
new UserProfileManager(context);

//Fetch all user profile properties
Microsoft.Office.Server.UserProfiles.PropertyCollection props = profileManager.Properties;
//Print all user profile properties


Console.WriteLine("_______________________Start:Print all user profile properties.");

foreach (Property prop in props)
{
Console.WriteLine(prop.Name);
}
Console.WriteLine("_______________________End:Print all user profile properties.");


//Find user profile changes.

// this gets some subset of changes to a user profile, changed 5 days before
DateTime startDate =
DateTime.UtcNow.Subtract(TimeSpan.FromDays(5));

/* If we want to access changes after "4/30/2011 11:33:47 PM" then we can use below mentioned code:

StartTime="5/30/2010 11:33:47 PM"
System.TimeSpan dateDiff = DateTime.UtcNow.Subtract(Convert.ToDateTime(StartTime));
DateTime startDate = DateTime.UtcNow.Subtract(dateDiff);
*/

UserProfileChangeQuery changeQuery = new UserProfileChangeQuery(true, true);
changeQuery.ChangeTokenStart = new UserProfileChangeToken(startDate);
UserProfileChangeCollection changes = profileManager.GetChanges(changeQuery);
//Used to store unique user names
ArrayList arrLstUsers = new ArrayList();
foreach (UserProfileChange change in changes)
{
if (arrLstUsers != null && !arrLstUsers.Contains(change.AccountName))
{
//Add user to array list
arrLstUsers.Add(change.AccountName);
//Print chagned profile user name
Console.Write(change.AccountName);
}
}
Console.Read();
}
}
}
}

Accessing SharePoint Publishing site Navigation (Global Navigation bar) using C#

Accessing SharePoint Publishing site Navigation (Global Navigation bar) using C#:

With the help of PublishingWeb class (Microsoft.SharePoint.Publishing), we can access different components of Published Web site like Pages document library, Published site navigation bar and etc.
In this example we will access different components of Published site:


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Publishing;


namespace GetPublishedData
{
class Program
{
static void Main(string[] args)
{

using (SPSite site = new SPSite("http://amitkumarmca04.blogspot.com/"))
{
using (SPWeb web = site.RootWeb)
{
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);

//Display Global Navigation menu items(Home > Site Settings > Modify Navigation)
foreach (Microsoft.SharePoint.Navigation.SPNavigationNode node in publishingWeb.GlobalNavigationNodes)
{

Console.WriteLine(node.Title + " " + node.Url);

}
// Get the Id for the Pages list.
Guid pagesListId = publishingWeb.PagesListId;
SPList pagesList = publishingWeb.PagesList;

// The PublishingWeb.PagesListName is equivalent
// to PublishingWeb.PagesList.RootFolder.Url.
string pagesListUrl = publishingWeb.PagesListName;

}
}
}
}
}


Reference: MSDN

Accessing SharePoint Quick Launch menu (SPNavigation.QuickLaunch) using C#:

Accessing SharePoint Quick Launch menu (SPNavigation.QuickLaunch) using C#:
With the help of SPNavigation, we will be able to access the Quick Launch menu of SharePoint site. Sometimes we need to show/hide Quick Launch menu item, so with the help of SPNavigation. QuickLaunch, we can loop through Quick Launch menu item.
In this example we will access Quick Launch menu:


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
using Microsoft.SharePoint.Navigation;


namespace GetQuickLaunch
{
class Program
{
static void Main(string[] args)
{

using (SPSite site = new SPSite("http://amitkumarmca04.blogspot.com/"))
{
using (SPWeb web = site.OpenWeb())
{
SPNavigationNodeCollection qlNodes = web.Navigation.QuickLaunch;
foreach (SPNavigationNode node in qlNodes)
{
Console.WriteLine(node.Title + "--" + node.Url);
}
}
}
}
}
}




Reference: MSDN

Saturday, June 04, 2011

SharePoint web parts properties validation

SharePoint web parts properties validation

Sometimes, in a custom web part we define the custom properties. It’s very difficult to validate properties every time by opening the web part in edit mode. So we needed to include validations on it so that whenever the user clicked OK or Apply the error message should be shown so that the correct input should be given.


Solution 1:

Earlier definition of the Property

private string _amitKumar=String.Empty;
public string AmitKumar
{
get {return _amitKumar;}
set {_amitKumar = value;}
}

Updated web part property definition,
private string _amitKumar =String.Empty;
public string AmitKumar
{
get {return _amitKumar;}
set
{
If(String.IsNullOrEmpty(value)
{
throw new Exception (“Value is required”);
}
else
_amitKumar =value;
}

}


The above approach works perfectly fine and will not let you close the properties pane until you provide the value in the _amitKumar field, you will keep getting exception for that web part. Now the disadvantage here is the user does not get a friendly message telling him what exactly is going wrong, though we specify the message in the new Exception constructor, it still shows a generic message.

Solution 2:

Now the above does fulfill the requirement but the client would clearly says they don’t like it because the error message does not talk about what happened and where, and hence there has to be a way to show the user our custom error message. So, we have used new exception of type WebPartPageUserException instead of Excepton. WebPartPageUserException class shows the exception custom message in the webpart property pane itself. So the correct or rather more appropriate way of implementing the above code would be,


private string _amitKumar =String.Empty;
public string AmitKumar
{
get {return _amitKumar;}
set
{
If(String.IsNullOrEmpty(value)
{
throw new WebPartPageUserException (“Value is required”);
}
else
_amitKumar =value;
}

}

And this will show the custom error message in the property pane so user knows what’s exactly is wrong.

Wednesday, May 11, 2011

Amit Kumar awarded “Microsoft Community Contributor Award 2011”

Amit Kumar awarded “Microsoft Community Contributor Award 2011”:



I’m very pleased and honored to share this with all of you that my community contributions have been recognized by Microsoft. I have received the Microsoft Community Contributor Award for year 2011. This is really great and I would like to thank Microsoft for honoring me with such an award!

Saturday, April 02, 2011

How to convert absolute url to relative url

How to convert absolute url to relative url:


URL: URL is just a fancy name for "address". You use a "url" to give the address to a link or image.

Absolute url: An url that is ABSOLUTE shows the complete address. In other words, there is no confusion about where this item is located, as the ABSOLUTE URL gives the entire path to that file. http://amitkumarmca04.blogspot.com/2011/02/get-list-data-using-sharepoint-object.html is an example of an ABSOLUTE url.

Relative url: A url that is RELATIVE only shows a partial address - like /2011/02/get-list-data-using-sharepoint-object.html - and the success or failure of finding the file is contingent on certain conditions being met - which means the outcome can and will vary, depending largely how the directories within your website are structured.

Problem:
After restoring the site from development environment to staging environment.
If some document library having metadata like “ListURL”. This metadata contains url in the form of absolute url, then it will show development environment url into staging site. Now, application team decided to change this metadata value from absolute url to relative url, in that case we need to change value, which exist at present in the form of absolute url into relative url.

Resolution:
In this scenario, we can use SharePoint Object Model classes to access data from custom SharePoint list and pass the value of “ListURL” to following function:

public string GetRelativeURL(string urlToConvert)
{
char[] chrsplitter1 = { '/' };
string[] strsplitter1 = { "://" };
string convertedURL = string.Empty;
if (!string.IsNullOrEmpty(urlToConvert) && !string.IsNullOrEmpty(urlToConvert))
{
//If url is not null
//Replace "https" with "http"
if (urlToConvert.ToLower().Contains("https"))
{
urlToConvert = urlToConvert.Replace("https", "http");
}

//Remove "/" from start and end of the string
urlToConvert = urlToConvert.TrimStart(chrsplitter1).TrimEnd(chrsplitter1);

if (urlToConvert.ToLower().Contains("http"))
{
// urlToConvert is a full URL, i.e. absolute URL
// For Example : -- "http://amitkumarmca04.blogspot.com/2011/02/get-list-data-using-sharepoint-object.html"
// So we are converting it into :-- /2011/02/get-list-data-using-sharepoint-object.html

//Replace "\\" with "//"
if (urlToConvert.ToLower().Contains("\\"))
{
urlToConvert = urlToConvert.Replace("\\", "//");
}

//Spilt url with "://"
// For Example : -- "http://amitkumarmca04.blogspot.com/2011/02/get-list-data-using-sharepoint-object.html"
string[] arrHTTP = urlToConvert.Split(strsplitter1, System.StringSplitOptions.RemoveEmptyEntries);
//arrHTTP[0]="http"
//arrHTTP[1]="amitkumarmca04.blogspot.com/2011/02/get-list-data-using-sharepoint-object.html"
if (arrHTTP != null && arrHTTP.Length >= 2)
{
if (!string.IsNullOrEmpty(arrHTTP[1]))
{
//If arrHTTP[1] is not null
string relativeURL = string.Empty;
if (arrHTTP[1].IndexOf("/") >= 0)
{
//If "/" found in the string
relativeURL = arrHTTP[1].Substring(arrHTTP[1].IndexOf("/"));
}
else
{
//If "/" not found in the string
relativeURL = arrHTTP[1];
}

if (!string.IsNullOrEmpty(relativeURL))
{
//We will receive relativeURL ="2011/02/get-list-data-using-sharepoint-object.html"
relativeURL = relativeURL.TrimStart(chrsplitter1).TrimEnd(chrsplitter1);
//We will receive convertedURL ="/2011/02/get-list-data-using-sharepoint-object.html"
convertedURL = "/" + relativeURL;
}
}
}

}
else
{
//We will receive convertedURL ="/2011/02/get-list-data-using-sharepoint-object.html"
convertedURL = "/" + urlToConvert;
}
}
else
{
//If url is null
}
return convertedURL;
}



Above function return the relative url.

Reference: gallery.menalto.com

Saturday, March 19, 2011

Add password reset page in Form Based Authentication MOSS 2007 site

Add password reset page in Form Based Authentication MOSS 2007 site:

Overview:

This article explains how to add a reset password page in Form Based Authentication enable SharePoint 2007 (MOSS) site, so the user can reset his/her password. We will add this page in standard menu.

Problem:

When you enable forms authentication on SharePoint 2007 (MOSS), it means that users credentials are stored in membership database like ASP.NET database. In Form Based Authentication site, if we want to reset password then reset password page should be accessible to anonymous user also.

Solution:

We are going to add new feature (ResetPasswordPage feature) in the standard user menu:

1. Write code .cs file(c# file), In this class, we will inherit the class Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase

For example:

public class ExtranetPasswordReset_Test : Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase


2. Creating ExtranetPasswordReset_Test.aspx
3. Creating ResetPasswordPage feature
4. Deployment

1. Creation of ExtranetPasswordReset_Test.aspx:

We will create new ExtranetPasswordReset.aspx with the help of VS 2005.

<%@ Assembly Name="Microsoft.SharePoint,Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" Inherits="Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase" MasterPageFile="~/_layouts/simple.master" %>
<%@ Assembly Name="Test.Security, Version=3.0.0.0, Culture=neutral, PublicKeyToken=8b7a42e9b9b5355f" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>



Site Title:




Code behind file of ExtranetPasswordReset_Test.aspx, called ExtranetPasswordReset_Test.aspx.cs:

1. We need add two functions:
I. protected override bool AllowAnonymousAccess
II. protected void Page_Load(object sender, EventArgs e)






2. Inherit the class with UnsecuredLayoutsPageBase class.







namespace Test.Security.Web.UI
{


public class ExtranetPasswordReset_Test : Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase
{
protected override bool AllowAnonymousAccess
{
get
{
return true;

}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Test");
}


}
}









2. Create ResetPasswordPage feature:

We will create Feature file and put into the ResetPasswordPage folder inside the Feature folder.










We also need to create elements.xml file.










Set CustomAction properties as shown, Location to be ‘StandardMenu’ and UrlAction URL property should be “_layouts/ExtranetPasswordReset_Test.aspx”
3. Deployment
1. Copy ‘ExtranetPasswordReset_Test.aspx’ file to the following path:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\
2. Copy ResetPasswordPage folder that contains elements.xml and feature.xml to the following path: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\

3. run the following command:










Now the feature is installed successfully, but needs to be activated.

4. Go to your site-> Site Actions -> Site Settings -> Modify All Site Settings->Site Collection Features ->Activate ResetPasswordPage feature.

Now you can find Reset Password action in the standard user menu

Monday, March 07, 2011

How to deploy DLL’s into GAC using batch (.bat) file

How to deploy DLL’s into GAC using batch (.bat) file:

Global Assembly Cache Tool (Gacutil.exe):
The Global Assembly Cache tool allows you to view and manipulate the contents of the global assembly cache and download cache.




gacutil [options] [assemblyName assemblyPath assemblyListFile]

The Gacutil is a tool used by developers to install versioned assemblies into the system Global Assembly Cache (GAC) to become part of the assemblies that are available for all applications at runtime.

Parameter:

assemblyName:The name of an assembly. You can supply either a partially specified assembly name such as myAssembly or a fully specified assembly name such as myAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0038abc9deabfle5.

assemblyPath:The name of a file that contains an assembly manifest.

assemblyListFile:The path to an ANSI text file that lists assemblies to install or uninstall. To use a text file to install assemblies, specify the path to each assembly on a separate line in the file. The tool interprets relative paths, relative to the location of the assemblyListFile. To use a text file to uninstall assemblies, specify the fully qualified assembly name for each assembly on a separate line in the file. See the assemblyListFile contents examples later in this topic.


Option:

/cdl :Deletes the contents of the download cache.

/f :Specify this option with the /i or /il options to force an assembly to reinstall. If an assembly with the same name already exists in the global assembly cache, the tool overwrites it.

/h[elp] :Displays command syntax and options for the tool.

/i assemblyPath :Installs an assembly into the global assembly cache.

/if assemblyPath :Installs an assembly into the global assembly cache. If an assembly with the same name already exists in the global assembly cache, the tool overwrites it.
Specifying this option is equivalent to specifying the /i and /f options together.

/il assemblyListFile :Installs one or more assemblies specified in assemblyListFile into the global assembly cache.

/ir assemblyPath :Installs an assembly into the global assembly cache and adds a reference to count the assembly. You must specify the assemblyPath, scheme, id, and description parameters with this option. For a description of the valid values you can specify for these parameters, see the /r option. Specifying this option is equivalent to specifying the /i and /r options together.

/l [assemblyName] :Lists the contents of the global assembly cache. If you specify the assemblyName parameter, the tool lists only the assemblies matching that name.

/ldl :Lists the contents of the downloaded files cache.

/lr [assemblyName] :Lists all assemblies and their corresponding reference counts. If you specify the assemblyName parameter, the tool lists only the assemblies matching that name and their corresponding reference counts.

/nologo :Suppresses the Microsoft startup banner display.

/r [assemblyName assemblyPath] :Specifies a traced reference to an assembly or assemblies to install or uninstall. Specify this option with the /i, /il, /u, or /ul options.
To install an assembly, specify the assemblyPath, scheme, id, and description parameters with this option. To uninstall an assembly, specify the assemblyName, scheme, id, and description parameters.
To remove a reference to an assembly, you must specify the same scheme, id, and description parameters that were specified with the /i and /r (or /ir) options when the assembly was installed. If you are uninstalling an assembly, the tool also removes the assembly from the global assembly cache if it is the last reference to remove and if Windows Installer has no outstanding references to the assembly.

/silent :Suppresses the display of all output.

/u assemblyName :Uninstalls an assembly from the global assembly cache.

/uf assemblyName :Forces a specified assembly to uninstall by removing all references to the assembly. Specifying this option is equivalent to specifying the /u and /f options together.
Note :You cannot use this option to remove an assembly that was installed using Microsoft Windows Installer. If you attempt this operation, the tool displays an error message.

/ul assemblyListFile :Uninstalls one or more assemblies specified in assemblyListFile from the global assembly cache.

/u[ngen] assemblyName :Uninstalls a specified assembly from the global assembly cache. If the specified assembly has existing reference counts, the tool displays the reference counts and does not remove the assembly from the global assembly cache.
Note: In the .NET Framework version 2.0, /ungen is not supported. Instead, use the uninstall command of the Native Image Generator (Ngen.exe).
In the .NET Framework versions 1.0 and 1.1, specifying /ungen causes Gacutil.exe to remove the assembly from the native image cache. This cache stores the native images for assemblies that have been created using the Native Image Generator (Ngen.exe).

/ur assemblyName :Uninstalls a reference to a specified assembly from the global assembly cache. To remove a reference to an assembly, you must specify the same scheme, id, and description parameters that were specified with the /i and /r (or /ir) options when the assembly was installed. For a description of the valid values you can specify for these parameters, see the /r option. Specifying this option is equivalent to specifying the /u and /r options together.

/? :Displays command syntax and options for the tool.


Problem: How to deploy DLL’s into GAC using batch (.bat) file
Resolution:
There are 2 ways to deploy DLL’s into GAC using batch (.bat) file:
1. Using ul & il option of Gacutil.exe in batch file:
For example, we need to un-install some Microsoft.Practices.EnterpriseLibrary.Common,Version=3.1.0.0 dll from GAC and need to install some Microsoft.Practices.EnterpriseLibrary.Common,Version= 5.0.414.0 into GAC. For this I created a text files which contain the details of DLL’s which we need to un-install and install:

i. UnInstallAssemblyList.txt:


Microsoft.Practices.EnterpriseLibrary.Common,Version=3.1.0.0,Culture=Neutral,PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.Data,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.Security.Cryptography,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a



ii. InstallAssemblyList.txt:


Microsoft.Practices.EnterpriseLibrary.Common,Version=5.0.414.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.Data,Version=5.0.414.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling,Version=5.0.414.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging,Version=5.0.414.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.Logging,Version=5.0.414.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.Practices.EnterpriseLibrary.Security.Cryptography,Version=5.0.414.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a



iii. InstallMicrosoftEnterpriseLibrary.bat:



@echo off
setlocal
Echo Un-Installing dll from GAC
%GACUTIL% /ul UnInstallAssemblyList.txt
Echo Installing dll in GAC
%GACUTIL% /il InstallAssemblyList.txt



For running InstallMicrosoftEnterpriseLibrary.bat:
Set the environment variables for
1. GACUTIL
Navigate to folder where InstallMicrosoftEnterpriseLibrary.bat stored and execute the following scripts:

1. InstallMicrosoftEnterpriseLibrary.bat

2. Using uf & i option of Gacutil.exe in batch file:

For example, we need to un-install some Microsoft.Practices.EnterpriseLibrary.Common,Version=3.1.0.0 dll from GAC and need to install some Microsoft.Practices.EnterpriseLibrary.Common,Version= 5.0.414.0 into GAC. For this I created a batch file called InstallMicrosoftEnterpriseLibrary.bat:



@echo off
setlocal
Echo Un-Installing dll from GAC
%GACUTIL% /uf "Microsoft.Practices.EnterpriseLibrary.Common,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
%GACUTIL% /uf "Microsoft.Practices.EnterpriseLibrary.Data,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
%GACUTIL% /uf "Microsoft.Practices.EnterpriseLibrary.ExceptionHandling,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
%GACUTIL% /uf "Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
%GACUTIL% /uf "Microsoft.Practices.EnterpriseLibrary.Logging,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
%GACUTIL% /uf "Microsoft.Practices.EnterpriseLibrary.Security.Cryptography,Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

Echo Installing dll in GAC
%GACUTIL% /i "Microsoft.Practices.EnterpriseLibrary.Common.dll"
%GACUTIL% /i "Microsoft.Practices.EnterpriseLibrary.Data.dll"
%GACUTIL% /i "Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll"
%GACUTIL% /i "Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll"
%GACUTIL% /i "Microsoft.Practices.EnterpriseLibrary.Logging.dll"
%GACUTIL% /i "Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll"

For running InstallMicrosoftEnterpriseLibrary.bat:
Set the environment variables for
1. GACUTIL
Navigate to folder where InstallMicrosoftEnterpriseLibrary.bat stored and execute the following scripts:
1. InstallMicrosoftEnterpriseLibrary.bat


Reference: MSDN

Tuesday, February 22, 2011

Default/Integrated role in SharePoint 2007

Default/Integrated role in SharePoint 2007:

A role consists of two parts:

1. Role definition
2. Role assignment.

The role definition, or permission level, is the list of rights associated with the role. A right is a uniquely controllable action within a SharePoint Web site. For example, a user with the Read role can browse pages in the Web site and view items in lists. Unlike in Windows SharePoint Services 2.0, in Windows SharePoint Services 3.0 user permissions are never managed directly using rights. All user and group permissions are managed through roles. A role definition is a collection of rights bound to a specific object. Role definitions are scoped to the Web site (for example, Full Control, Read, Contribute, Design, or Limited Access) and mean the same thing everywhere within the Web site, but their meanings can differ between sites within the same site collection. Role definitions can also be inherited from the parent Web site, just as permissions.

The role assignment is the relationship among the role definition, the users and groups, and the scope (for example, one user may be a reader on list one, while another user is a reader on list two). The relationship expressed through the role assignment is the key to making Windows SharePoint Services security management role-based. All permissions are managed through roles; you never assign rights directly to a user, but only meaningful collections of rights (role definitions) that are well defined and consistent. You manage unique permissions by adding or removing users and groups to or from role definitions through role assignments.

The default/integrated role in SharePoint 2007:
1. Full Control
2. Read
3. Contribute
4. Design
5. Limited Access


Reference: MSDN

Tuesday, February 15, 2011

Encrypting Web.Config

Encrypting Web.Config using RSAProtectedConfigurationProvider in SharePoint

Overview:

One of the most common uses of the protected configuration is to encrypt connection strings in web.confg (that's one of the reasons for creating a separate tag for connection strings instead of adding it in appSettings tag). Adding this connection string as plain text is not the best practice for sharepoint web application security and this might cause serious hacking problems. Sharepoint also support for encrypting and decrypting configuration sections in web.config file. In this article, we will explore how to encrypt and decrypt sections of the web.config. We can encrypt the configuration sections by using two built-in providers: DPAPI (Windows Data Protection API) Provider or the RSA provider. The RSA provider (default) uses an RSA key which holds public and private keys, where as the DPAPI provider uses built-in machine-specific key. Let us explore the steps required to encrypt the sections using RSA.

Below are steps in detail:

Step 1: Add a web.config file to the project. Right click the project > Add New Item > Web Configuration File
Step 2: To create the custom configuration section in Web.Config file please create the custom class inherited from ConfigurationSection class.


using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;

namespace AmitKumar.GeneralSite.Web.UI
{
class CustomUpdateProfileSection : ConfigurationSection
{
private static CustomUpdateProfileSection settings = ConfigurationManager.GetSection("CustomUpdateProfileSection") as CustomUpdateProfileSection;
public static CustomUpdateProfileSection Settings
{
get
{
return settings;
}
}
[ConfigurationProperty("UpdateProfileUserDomain", DefaultValue = "v4", IsRequired = true)]
public string UpdateProfileUserDomain
{
get { return (string)this["UpdateProfileUserDomain"]; }
set { this["UpdateProfileUserDomain"] = value; }
}

[ConfigurationProperty("UpdateProfileUserName", IsRequired = true)]
public string UpdateProfileUserName
{
get { return (string)this["UpdateProfileUserName"]; }
set { this["UpdateProfileUserName"] = value; }
}
[ConfigurationProperty("UpdateProfileUserPassword", IsRequired = true)]
public string UpdateProfileUserPassword
{
get { return (string)this["UpdateProfileUserPassword"]; }
set { this["UpdateProfileUserPassword"] = value; }
}

}
}


Step 3: Sign the assembly with the strong name and deploy in the GAC.
Step 4: Define the custom section in the Web.Config file










Note: "AmitKumar.Web.UI.CustomUpdateProfileSection" is the name of the class. "AmitKumar" is the name of the Assembly.
Step 5: Now add two buttons to the page, called btnEncrypt and btnDecrypt. We will use these buttons to encrypt and decrypt the sections of the web.config file. Add the following code in the button click event of the two buttons:


public void btnEncrypt_OnClick(object sender, EventArgs e)
{
try
{
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection objSection = config.GetSection("CustomUpdateProfileSection");
if ((config != null) && (!objSection.SectionInformation.IsProtected))
{
if (!objSection.ElementInformation.IsLocked)
{
objSection.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save();
this.lblCustomError.Visible = false;
this.lblSuccess.Text = "Successfully Encrypted, Kindly check the Web.Config file.";
this.lblSuccess.Visible = true;
}
}

}
catch (Exception ex)
{
string strErrorMsg = "Error, DateTime :" + DateTime.Now.ToLongTimeString() + ", Error : " + ex.Message.ToString() + ", Stack Trace : " + ex.StackTrace.ToString();
this.lblCustomError.Text = strErrorMsg;
this.lblCustomError.Visible = true;
}
}

public void btnDecrypt_OnClick(object sender, EventArgs e)
{
try
{
System.Configuration.Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection objSection = objConfig.GetSection("CustomUpdateProfileSection");
if (objConfig != null && objSection.SectionInformation.IsProtected)
{
if (!objSection.ElementInformation.IsLocked)
{
objSection.SectionInformation.UnprotectSection();
objConfig.Save();
this.lblCustomError.Visible = false;
this.lblSuccess.Text = "Successfully Decrypted, Kindly check the Web.Config file.";
this.lblSuccess.Visible = true;
}
}

}
catch (Exception ex)
{
string strErrorMsg = "Error, DateTime :" + DateTime.Now.ToLongTimeString() + ", Error : " + ex.Message.ToString() + ", Stack Trace : " + ex.StackTrace.ToString();
this.lblCustomError.Text = strErrorMsg;
this.lblCustomError.Visible = true;
}
}

Sunday, February 13, 2011

Get list data using SharePoint Object Model

Get list data using SharePoint Object Model:

This article explains how you can use the SharePoint Object Model(MOSS 2007) classes like SPSite and SPWeb in C# or Visual Basic code to fetch data from a custom SharePoint list.

This article explains how you can use the SharePoint Object Model(MOSS 2007) classes like SPSite and SPWeb in C# or Visual Basic code to fetch data from a custom SharePoint list.

Problem:
You want to get data on the basis of url (including siteurl+listname) from the custom SharePoint list.

Resolution:
In this scenario, we can use SharePoint Object Model classes to access data from custom SharePoint list.

public static bool CheckListExists(string listName, SPWeb web,ref SPList list)
{
try
{
//---Check list exist or not
if (web.Lists[listName]!=null)
{
list = web.Lists[listName];
return true;
}
return false;
}
catch (ArgumentException ex)
{
return false;
}
catch (Exception ex)
{
return false;

}
}



Above function used to check list exist in the SharePoint site or not.


public static void GetListData(string listUrl)
{
SPList objList = null;
char [] chrSplitter={'/'};
try
{
listUrl = listUrl.TrimEnd(chrSplitter);
string[] arrList = listUrl.Split(chrSplitter);
if (arrList != null && arrList.Length > 0)
{

using (SPSite site = new SPSite(listUrl))
{
using (SPWeb web = site.OpenWeb())
{
if(CheckListExists(SPEncode.UrlDecodeAsUrl(arrList[arrList.Length - 1]),web,ref objList))
{
//Add business logic here
}
}
}
}


}
catch (Exception ex)
{

}
}



Above function used to get data from SharePoint site by passing the url only. The url contain both site url and list name. For example:

From presentation layer, we make a call to GetListData function

string listUrl="http://amitkumarmca04.blogspot.com/sites/mcapassion/Lists/AmitKumar";
GetListData(listUrl);