Wednesday 23 October 2013

Difference between List Definition, List Template and List Instance in Sharepoint

List Definition:
A list definition defines a schema for a SharePoint list. It contains information on what views are being used, which columns and content types are being used, and other metadata information.
 
List Template:
A list template can either be created by end users through the SharePoint user interface using an existing list as a pattern or using an existing list instance. If based on a user-created list it is called a custom list template. A custom list template includes everything that defines the list, including list columns and site columns used by the list, content types used by the list, views defined for the list, and so on.
 
Tips
A list template may sound like a list definition but they are effectively the same thing, a pattern for a SharePoint list. They differ mainly in how they are created:
- A list templates are created in SharePoint or SharePoint designer.
- A list definitions in Visual Studio.

List Instance:
A list instance is an instance of a specific SharePoint list definition or list template. All of its data is stored in the relevant content database. Typically a list in SharePoint used by end users to enter and view data and it is based on either a list template or list definition.

Sunday 20 October 2013

Retrieving table data from SQL Server using C#

This is a simple task which can be accomplished with below code. Below code is useful to retrieve table data from SQL Server using C#.net .

    public List<Contact> LoadContacts()
    {
        List<Contact> ContactDetails= new List<Contact>();
       string selectQuery = "SELECT * FROM Contact";
        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog = DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(selectQuery , connection );
        try
        {
            connection.Open();
            SqlDataReader dataReader = command.ExecuteReader();
            while (dataReader.Read())
            {
                Contact contact = new Contact();
                contact.ID = Convert.ToInt32(dataReader["ID"]);
                contact.Name = dataReader["Name"].ToString();
                contact.EmailID = dataReader["EmailID"].ToString();
                contact.Mobile = dataReader["Mobile"].ToString();
                contact.LandLine = dataReader["LandLine"].ToString();
                contact.WebSite = dataReader["WebSite"].ToString();
                contact.Address = dataReader["Address"].ToString();
                ContactDetails.Add(contact);
            }
            dataReader.Close();
        }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
         return ContactDetails;
    }


Connection string's options :
  •   Integrated Security=SSPI; – This means we want to connect using Windows authentication.
  •  Initial Catalog=DataBaseName; – This means the database we want to first connect to is named “DataBaseName”.
  •  Data Source=(local); – This means that we want to connect to the SQL Server instance located on the local machine.

Delete data from SQL Server using C#.net

This is simple task which can be accomplished with below code. Below code is useful to Delete data (contact) from SQL Server database using C#.net .

    public void DeleteContact_OnClick(object sender, EventArgs e)
    {
       string myDeleteCommand = @"DELETE Contact where ID=@ID";

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog = DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myDeleteCommand , connection );
        cmd.Parameters.AddWithValue("@ID", Convert.ToInt32( tbID.Text));
        try
        {
            connection .Open();
            cmd.ExecuteNonQuery();
         }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
    }


Connection string's options :
  •   Integrated Security=SSPI; – This means we want to connect using Windows authentication.
  •  Initial Catalog=DataBaseName; – This means the database we want to first connect to is named “DataBaseName”.
  •  Data Source=(local); – This means that we want to connect to the SQL Server instance located on the local machine.

How to Update data into SQL Server using C#.net

This is simple task which can be accomplished with below code. Below code is useful to Update data into SQL Server database using C#.

    public void UpdateContact_OnClick(object sender, EventArgs e)
    {
       string myUpdateCommand = @"Update Contact set Name=@name, EmailID=@emailid, Mobile=@mobile, LandLine=@landline, WebSite=@website, Address=@address where ID=@ID" ;

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog = DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myUpdateCommand , connection );
        cmd.Parameters.AddWithValue("@name", tbName.Text);
        cmd.Parameters.AddWithValue("@emailid", tbEmailID.Text);
        cmd.Parameters.AddWithValue("@mobile", tbMobile.Text);
        cmd.Parameters.AddWithValue("@landline", tbLandLine.Text);
        cmd.Parameters.AddWithValue("@website", tbWebSite.Text);
        cmd.Parameters.AddWithValue("@address", tbAddress.Text);
        cmd.Parameters.AddWithValue("@ID", Convert.ToInt32( tbID.Text));
        try
        {
            connection .Open();
            cmd.ExecuteNonQuery();
         }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
    }


Connection string's options :
  •   Integrated Security=SSPI; – This means we want to connect using Windows authentication.
  •  Initial Catalog=DataBaseName; – This means the database we want to first connect to is named “DataBaseName”.
  •  Data Source=(local); – This means that we want to connect to the SQL Server instance located on the local machine.

How to Insert data into sql server using C#.net

This is simple task which can be accomplished with below code. Below code is useful to insert data into SQL Server database using C#. I wrote code in 2 ways in which second way is preferred by many developers.

Method 1 :

    public void InsertContact_OnClick(object sender, EventArgs e)
    {
        string myInsertCommand = @"Insert into Contact (Name, EmailID, Mobile, LandLine, WebSite, Address) values( tbName.TexttbEmailID.TexttbMobile.Text, tbLandLine.Text,  tbWebSite.Text,  tbAddress.Text )";

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog=DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myInsertCommand, connection );
        try
        {
            connection .Open();
            cmd.ExecuteNonQuery();
         }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
    }


Method 2 :

    public void InsertContact_OnClick(object sender, EventArgs e)
    {
        string myInsertCommand = @"Insert into Contact (Name, EmailID, Mobile, LandLine, WebSite, Address) values(@name, @emailid, @mobile, @landline, @website, @address)";

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog=DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myInsertCommand, connection );
        cmd.Parameters.AddWithValue("@name", tbName.Text);
        cmd.Parameters.AddWithValue("@emailid", tbEmailID.Text);
        cmd.Parameters.AddWithValue("@mobile", tbMobile.Text);
        cmd.Parameters.AddWithValue("@landline", tbLandLine.Text);
        cmd.Parameters.AddWithValue("@website", tbWebSite.Text);
        cmd.Parameters.AddWithValue("@address", tbAddress.Text);
        try
        {
            connection .Open();
            cmd.ExecuteNonQuery();
         }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
    }


Connection string's options :
  •   Integrated Security=SSPI; – This means we want to connect using Windows authentication.
  •  Initial Catalog=DataBaseName; – This means the database we want to first connect to is named “DataBaseName”.
  •  Data Source=(local); – This means that we want to connect to the SQL Server instance located on the local machine.

Friday 18 October 2013

Get user Email ID from a sharepoint people picker field / column of a list

The below code works fine to get an Email ID from people picker field for an Item of a list.

        string userEmailID = GetUserEmail(spListItem, "PeoplePickerfieldName");

        public string GetUserEmail(SPListItem spListItem, string fieldName)
        {
            SPFieldUser spFieldUser = (SPFieldUser)spListItem.Fields[fieldName];
            SPFieldUserValue spFieldUserValue = (SPFieldUserValue)spFieldUser.GetFieldValue(spListItem[fieldName].ToString());
            return spFieldUserValue.User.Email;
        }



Send Email from Sharepoint Event Receiver

There are two types of Event Receivers i.e., Before event receiver and After event receiver. Before event receivers will trigger before the create / insert / delete / update operations of a list / item /site / web . After event receivers will trigger after the create / insert / delete / update operation completed.

So, generally we send an Email to a concern person after the List or List item is inserted or deleted or updated. It means the Email should send from After event receiver.

Please find the below code to Send Email from Sharepoint Event Receiver :


       public override void ItemAdded(SPItemEventProperties properties)
       {
           try
           {
               MailMessage mail = new MailMessage();
               mail.From = new MailAddress("YourEmailID@gmail.com");
               mail.Bcc.Add("bccEmail@gmail.com");
               mail.CC.Add("sampleEmail@ymail.com");
               mail.To.Add("FriendEmailID@yahoo.com");
               mail.Subject = "Test Mail";
               mail.Body = "Hi...!!! This is a test mail.";
               mail.IsBodyHtml = true;
               SmtpClient smtpClient = new SmtpClient();
               smtpClient.Host = "smtp.gmail.com";
               smtpClient.Port = 587;
               smtpClient.UseDefaultCredentials = false;
               smtpClient.Credentials = new System.Net.NetworkCredential("YourEmailID@gmail.com", "YourPassword");
               smtpClient.EnableSsl = true;
               ServicePointManager.ServerCertificateValidationCallback = delegate
               {
                   return true;
               };
               smtpClient.Send(mail);
           }
           catch (Exception ex)
           {
                 //Your Exception code
           }
       }


The above code works fine to send an email from Event Receiver using SMTP server.

How to get list item url in Editmode or Displaymode in sharepoint 2010

Below given code works fine to get the list item url in Edit Form :

string listItemUrl = string.Format("{0}{1}?ID={2}", properties.WebUrl, splist.DefaultEditFormUrl, spListItem.ID);

In the above code:

  • properties.WebUrl gets the Current Web url. Ex: http://SharepointSite:8888.
  • splist.DefaultEditFormUrl gets the given list url. Ex/Lists/YourListName/EditForm.aspx. If your want to use display form then you can use splist.DefaultDisplayFormUrl instead of edit form.
  • spListItem.ID gets the list item ID to which you want to edit.

Below given code works fine to get the list item url in Display Form :

string listItemUrl = string.Format("{0}{1}?ID={2}", properties.WebUrl, splist.DefaultEditFormUrl, spListItem.ID);

Thursday 17 October 2013

Error message when you insert a smart card in a reader on a Windows 7-based or Windows Server 2008 R2-based computer: "Device driver software was not successfully installed"

When you insert a smart card into a smart card reader, Windows tries to download and install the smart card minidrivers for the card through Plug and Play services. If the driver for the smart card is not available at any of the preconfigured locations, such as Windows Update, WSUS, or intranet paths, and a custom Crypto service provider is not already installed on the system, you receive the following error message in the notification area:

Device driver software was not successfully installed 
Click here for details.

If your deployment uses Plug and Play smart card solutions, then follow the below steps to enable Smart Card Plug and Play. By default it is disabled in Windows Server 2008 R2.


To Enable Smart Card Plug and Play in local Group Policy, follow these steps:

  1. Click Start, type gpedit.msc in the Search programs and files box, and then press ENTER.
  2. In the console tree under Computer Configuration, click Administrative Templates.
  3. In the details pane, double-click Windows Components, and then double-click Smart Card.
  4. Right-click Turn on Smart Card Plug and Play service, and then click Edit.
  5. Click Enabled, and then click OK.
For more information go through the link http://support.microsoft.com/kb/976832

Error : The user does not exist or is not unique.

This error occurs due to one of the policy(feature) enabled in Windows Server 2008 by default. It is a local policy in 2008 R2 that is required to be disabled (and machine restart is required after reset). 
This policy name is "Domain member: Digitally encrypt or sign secure channel data (always)". It is Enabled by default when you configure Windows Server 2008 R2. 


Steps to reach the policy and disable it:


Step 1 : Start -> Run -> type gpedit.msc and press enter.
Step 2 : Browse to Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Security Options

Step 3Under Security Options on the right hand side, you will find this policy. Double click to open the policy, Click 'Disable' radio option. Save the changes.
Step 4 : Restart the machine. 

Even after configuring above one if you find the same error then follow the below steps:


Step 1 :  Start -> Run -> type inetmgr and press enter.
Step 2 :  Go to Application Pools 
Step 3 : Select your application on the right hand side. Right-click on it and select Advance Settings.
Step 4 : Under Process Model heading -> select identity field and click on the button of the field to change it.
Step 5 : Select Built-in Account -> select NetworkServices . Press OK.

Now, your issue will be solved.

Saturday 12 October 2013

How to Create Lookup field(dropdownlist) in sharepoint visual webpart and update its value into sharepoint list programmatically :

Here, in my code dropdownlist is a lookup field. The below code shows how to bind data to the dropdownlist and then shows how to save the data into sharepoint list Lookup field when an item is selected in dropdownlist.

Create dropdownlist in .ascx visual webpart as below:

<asp:DropDownList ID="dropdownlist" runat="server"></asp:DropDownList>

Now copy and paste below code in page load :


        string siteUrl = SPContext.Current.Web.Url;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (SPSite spsite = new SPSite(siteUrl))
                {
                    using (SPWeb spweb = spsite.OpenWeb())
                    {
                        SPList list= spweb.Lists["YourLookUpListName"];
                        SPListItemCollection items = list.GetItems();
                        dropdownlist.DataSource = items;
                        dropdownlist.DataTextField = "FieldName"; //List field holding name
                        dropdownlist.DataValueField = "FieldName"; //List field holding value
                        dropdownlist.DataBind();
                    }
                }
            }
        }

Now copy and paste below code in the button submit :


        protected void Submit_Click(object sender, EventArgs e)
        {
            using (SPSite spsite = new SPSite(siteUrl))
            {
                using (SPWeb spWeb = spsite.OpenWeb())
                {
                    SPList spList = spWeb.Lists["ListName"];
                    SPListItem spListItem = spList.Items.Add();
                    spListItem["LookUpFieldName"] = Convert.ToInt32(dropdownlist.SelectedItem.Value);
                    spListItem.Update();
                 }
             }
        }

The above code works fine for all the dropdown lookup fields in sharepoint visual webpart.





How to create sharepoint people picker textbox using asp.net :

To create people picker in Sharepoint use people editor tag in .ascx page as shown below :

<SharePoint:PeopleEditor runat="server" ID="peopleEditorID"  PlaceButtonsUnderEntityEditor="false"  SelectionSet="User" />

The above code works well for single user/people selector at a time . To select multiple users/peoples at a time you have to add "MultipleUser=true" attribute to the above tag.
Now the people editor is able to select the people and display in textbox. But in order to reflect/store this into the Sharepoint List follow the below code.

Code to save people editor selected user into Sharepoint List people picker field :(code-behind code)


         string siteUrl = SPContext.Current.Web.Url;
         using (SPSite spsite = new SPSite(siteUrl))
         {
              using (SPWeb spWeb = spsite.OpenWeb())
                {
                    SPList spList = spWeb.Lists["YourListName"];
                    SPListItem spListItem = spList.Items.Add();
                        try
                        {
                            string name= GetUserName(peopleEditorID);
                            if (name != null)
                            spListItem["PeoplePickerFeildName"] = spWeb.EnsureUser(name);
                            spListItem.Update();
                        }
                        catch (Exception e)
                        {
                        }
                 }
        }

        public string GetUserName(PeopleEditor editorName)
        {
            if (editorName.ResolvedEntities.Count <= 0)
                return null;
            using (SPSite spsite = new SPSite(siteUrl))
            {
                using (SPWeb spWeb = spsite.OpenWeb())
                {
                    var picker = spWeb.EnsureUser(editorName.CommaSeparatedAccounts);
                    String userName = picker.Name;
                    return userName;
                }
            }
        }



How to retrieve sharepoint List data and bind its field to DropdownList Programmatically?


Using SPListItemCollection class :

                string siteUrl = SPContext.Current.Web.Url;
                using (SPSite spsite = new SPSite(siteUrl))
                {
                    using (SPWeb spweb = spsite.OpenWeb())
                    {
                        SPList myList= spweb.Lists["ListName"];
                        SPListItemCollection items = myList.GetItems();
                        dropdownlist.DataSource = items;
                        dropdownlist.DataTextField = "FieldName"; //List field holding name
                        dropdownlist.DataValueField = "FieldName"; //List field holding value
                        dropdownlist.DataBind();
                    }
                }

Error : “Trying to use an SPWeb object that has been closed or disposed and is no longer valid"


This error occurs when we try to use "SPContext.Current.Web" in the Using statement. If you use "SPContext.Current.Web" in the Using statement,then it forces to SPSite object Dispose() method to be invoked. You did not create that SPSite object, so you should not dispose it manually. Never dispose of anything in SPContext. Sharepoint will take care of SPSite object Dispose() and disposes it when its work gets done.

So, remove SPContext from the Using statement and modify your code as below:

                string siteUrl = SPContext.Current.Web.Url;
                 using (SPSite spsite = new SPSite(siteUrl))
                {
                    using (SPWeb spweb= spsite.OpenWeb())
                    {
                        //Your Code
                    }
                }


The above code works fine without disposing SPSite object.

Tuesday 1 October 2013

Difference between Major and Minor version in SharePoint 2010:

  • Version numbers are the sequential numbers applied to lists and libraries when a file is created or changed.
  • Major versions are appear as whole numbers( i.e., 1,2,3,4...etc), while Minor versions appear as decimal numbers( i.e., 0.1, 0.2, 0.3, ... etc)
  • Lists should be always in Major version whereas Libraries can either be in Major/Minor version.
  • Minor versions in libraries are assigned to documents that are in Draft status.  If a document is Published, it will increment to the next major version.  For example, if you publish version 2.51, it becomes version 3.0.

Total Pageviews