Tuesday, November 6, 2012

Programming in Sharepoint 2010

Move Item and Document

​using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Configuration;
using System.Xml;
using System.Xml.Linq;
using Microsoft.SharePoint;
namespace BPCLContentArchival
{
    class MoveItemMethods
    {
        #region Global Variables
        private static string LogFilePath = ConfigurationManager.AppSettings["LogFileFolderPath"];
        private static string RecordListXML = ConfigurationManager.AppSettings["RecordListXML"];
        #endregion
       
        /// <summary>
        /// Logging is a method to add record in log Files
        /// </summary>
        /// <param name="exMessage">Pass Exception</param>
        /// <param name="functionName">Pass Meassage</param>
        private static void Logging(Exception exMessage, string functionName)
        {
            string FileName = Convert.ToDateTime(DateTime.Today).ToString("dd-MMM-yyyy");
            using (StreamWriter writer = File.AppendText(LogFilePath + "\\" + FileName + ".txt"))
            {
                writer.Write("\r\nLog Entry : ");
                writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongDateString());
                writer.WriteLine("  :");
                if (exMessage != null)
                {
                    writer.WriteLine("Source Function:{0}", functionName);
                    writer.WriteLine("  :{0}", exMessage.Message);
                    writer.WriteLine("  :{0}", exMessage.StackTrace);
                }
                else
                {
                    writer.WriteLine("Source Function:{0}", functionName);
                }
                writer.WriteLine("-------------------------------");
                // Update the underlying file.
                writer.Flush();
                // Close the writer and underlying file.
                writer.Close();
            }
        }
        /// <summary>
        /// CreateListNameTableStructure is  a method to Create DataTable Structure.
        /// </summary>
        /// <returns>Returns DataTable Structure</returns>
        public DataTable CreateListsNameTableStructure()
        {
            DataTable ListsName = new DataTable();
            DataColumn SiteUrl = new DataColumn("SiteUrl");
            DataColumn Source = new DataColumn("Source");
            DataColumn Destination = new DataColumn("Destination");
            DataColumn Type = new DataColumn("Type");
            try
            {
                /// Add Columns to DataTable.

                SiteUrl.DataType = System.Type.GetType("System.String");
                Source.DataType = System.Type.GetType("System.String");
                Destination.DataType = System.Type.GetType("System.String");
                Type.DataType = System.Type.GetType("System.String");
                ListsName.Columns.Add(SiteUrl);
                ListsName.Columns.Add(Source);
                ListsName.Columns.Add(Destination);
                ListsName.Columns.Add(Type);
                Console.WriteLine("CreateListsNameTableStructure() : Create DataTable Structure.");
                Logging(null, "CreateListsNameTableStructure() : Create DataTable Structure.");
               
            }
            catch (Exception ex)
            {
                Logging(ex, "Error in CreateListsNameTableStructure()");
            }
            finally
            {
                SiteUrl = null;
                Source = null;
                Destination = null;
                Type = null;
            }
            return ListsName;
       }
        /// <summary>
        /// ReadRecordXMl is a method to read values from XML File
        /// And Add values in DataTable
        /// </summary>
        /// <returns>Returns DataTable with values</returns>
        public DataTable ReadRecordXML()
        {
            //RecordListXML = "RecordListNames.xml";
            string SiteUrl = string.Empty;
            string Source = string.Empty;
            string Destination = string.Empty;
            string Type = string.Empty;
            DataRow row;
            DataTable ListsName = CreateListsNameTableStructure();
            string xmlPath = Path.GetFullPath(Environment.CurrentDirectory) +"\\"+ RecordListXML;
            Console.WriteLine("ReadRecordXML() : Record List XML Path=" + xmlPath);
            Logging(null, "ReadRecordXML() : Record List XML Path=" + xmlPath);
            XDocument groupsXml = XDocument.Load(xmlPath);
            try
            {
                var fields = from fieldsGroup in groupsXml.Root.Elements("Field")
                             select new
                             {
                                 SiteUrl = fieldsGroup.Attribute("SiteUrl").Value,
                                 Source = fieldsGroup.Attribute("Source").Value,
                                 Destination = fieldsGroup.Attribute("Destination").Value,
                                 Type = fieldsGroup.Attribute("Type").Value
                             };
                ///Start of For Loop: Add row with values from xml to DataTable
                foreach (var fieldsGroup in fields)
                {
                    row = ListsName.NewRow();
                    row["SiteUrl"] = fieldsGroup.SiteUrl;
                    row["Source"] = fieldsGroup.Source;
                    row["Destination"] = fieldsGroup.Destination;
                    row["Type"] = fieldsGroup.Type;
                    ListsName.Rows.Add(row);
                }
                ///End of For Loop
                Console.WriteLine("ReadRecordXML() : Add values from XMl file to DataTable.");
                Logging(null, "ReadRecordXML() : Add values from XMl file to DataTable.");
            }
            catch (Exception ex)
            {
                Logging(ex, "Error in ReadRecordXML()");
            }
            finally
            {
                 SiteUrl = null;
                 Source = null;
                 Destination = null;
                 Type = null;
                 row = null;
                 xmlPath = null;
                 groupsXml = null;
            }
            return ListsName;
        }
        /// <summary>
        /// MoveToDocLib is a method to move Document from Source Library to Destination Library
        /// </summary>
        /// <param name="siteUrl">Pass Site url of SiteCollection</param>
        /// <param name="Source">Pass Source Library Name</param>
        /// <param name="Destination">Pass Destination Library Name</param>
        public void MoveToDocLib(string siteUrl, string Source, string Destination)
        {
            SPQuery qry = new SPQuery();
            string camlquery = string.Empty;
            string destlibUrl = string.Empty;
            SPListItemCollection Srccollitem;
            SPList destlib;
            SPFile moveFile;
            try
            {
                using (SPSite rootSite = new SPSite(siteUrl))
                {
                    using (SPWeb spWeb = rootSite.OpenWeb())
                    {
                        //TODO: only less than operator
                        camlquery = "<Where>"
                                          + "<Lt>"
                                          + "<FieldRef Name='Expiry_x0020_Date' />"
                                          + "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
                                          + "</Lt>"
                                          + "</Where>";
                        qry.Query = camlquery;
                        ///Get the Collection of SourceLibraryDocument by Caml Query
                        Srccollitem = spWeb.Lists[Source].GetItems(qry);
                        destlib = (SPDocumentLibrary)spWeb.Lists[Destination];
                        destlibUrl = destlib.RootFolder.Url;
                        ///Start of ForEach Loop to Move Document one by one from Source List ot Destination List.
                        foreach (SPListItem item in Srccollitem)
                        {
                            moveFile = item.File;
                            Console.WriteLine("MoveToDocLib() : FileName=" + item.File.Name + ", SiteUrl=" + siteUrl + ", Source=" + Source + ", Destination=" + Destination);
                            Logging(null, "MoveToDocLib() : FileName=" + item.File.Name + ", SiteUrl=" + siteUrl + ", Source=" + Source + ", Destination=" + Destination);
                            moveFile.MoveTo(destlibUrl + "/" + moveFile.Name, true);
                        }
                        ///End of ForEach Loop
                    }
                }
            }
            catch (Exception ex)
            {
                Logging(ex, "Error in MoveToDocLib()");
            }
            finally
            {
                 qry = null;
                 camlquery = null;
                 destlibUrl = null;
                 Srccollitem=null;
                 destlib=null;
                 moveFile=null;
           
            }
          
        }
        /// <summary>
        /// MoveToList is a method to move Item from Source List to Destination List
        /// </summary>
        /// <param name="siteUrl">Pass Site url of SiteCollection</param>
        /// <param name="Source">Pass Source List Name</param>
        /// <param name="Destination">Pass Destination List Name</param>
        public void MoveToList(string siteUrl, string Source, string Destination)
        {
            SPQuery qry = new SPQuery();
            string camlquery = string.Empty;
            SPListItemCollection Srccollitem;
            SPList destlib;
            SPListItem item;
            SPListItem targetItem;
            try
            {
                using (SPSite rootSite = new SPSite(siteUrl))
                {

                    using (SPWeb spWeb = rootSite.OpenWeb())
                    {
                        camlquery = "<Where>"
                                           + "<Lt>"
                                           + "<FieldRef Name='Expiry_x0020_Date' />"
                                           + "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
                                           + "</Lt>"
                                           + "</Where>";
                        qry.Query = camlquery;
                        ///Get the Collection of SourceListItem by Caml Query
                        Srccollitem = spWeb.Lists[Source].GetItems(qry);
                        destlib = spWeb.Lists[Destination];
                        ///Start of For Loop to move items one by one from Source List to Destination List
                        for (int i = Srccollitem.Count - 1; i >= 0; i--)
                        {
                            item = Srccollitem[i];
                            targetItem = destlib.Items.Add();
                            ///Start of ForEach Loop to add value of each Field from Source to Destionation
                            foreach (SPField f in item.Fields)
                            {
                                //Copy all except attachments.
                                if (!f.ReadOnlyField && f.InternalName != "Attachments"
                                    && null != item[f.InternalName])
                                {
                                    targetItem[f.InternalName] = item[f.InternalName];
                                }
                            }
                            ///End of ForEach Loop
                            Console.WriteLine("MoveToList() : ItemName=" + item.Name + ", SiteUrl=" + siteUrl + ", Source=" + Source + ", Destination=" + Destination);
                            Logging(null, "MoveToList() : ItemName=" + item.Name + ", SiteUrl=" + siteUrl + ", Source=" + Source + ", Destination=" + Destination);
                            spWeb.AllowUnsafeUpdates = true;
                            targetItem.Update();
                            item.Delete();
                            spWeb.AllowUnsafeUpdates = false;
                        }
                        ///End of For Loop.
                    }
                }
            }
            catch (Exception ex)
            {
                Logging(ex, "Error in MoveToList()");
            }
            finally
            {
                qry = null;
                camlquery = null;
                Srccollitem=null;
                destlib=null;
                item=null;
                targetItem=null;
           
            }
           
        }
        /// <summary>
        /// GetArchivalDetails is a method to get Data from DataTable.
        /// And according to Type it Call method to Move File/Item from 1
        /// Library/List to another Library/List.
        /// </summary>
        public void GetArchivalDetails()
        {
            DataTable dt;
            string siteurl=string.Empty;
            string Source=string.Empty;
            string Destination=string.Empty;
            string Type=string.Empty;
            try
            {
                Console.WriteLine("GetArchivalDetails() : Start Of Function.");
                Logging(null, "GetArchivalDetails() : Start Of Function.");
                dt = ReadRecordXML();
                ///Start of For Loop to get parameter use to move Item.
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    siteurl = dt.Rows[i]["SiteUrl"].ToString();
                    Source = dt.Rows[i]["Source"].ToString();
                    Destination = dt.Rows[i]["Destination"].ToString();
                    Type = dt.Rows[i]["Type"].ToString();
                    Console.WriteLine("GetArchivalDetails() : SiteUrl=" + siteurl + ", SourceListName=" + Source + ", DestinationListName=" + Destination + ", Type=" + Type);
                    Logging(null, "GetArchivalDetails() : SiteUrl=" + siteurl + ", SourceListName=" + Source + ", DestinationListName=" + Destination + ", Type=" + Type);
                    if (Type == "Library")
                    {
                        MoveToDocLib(siteurl, Source, Destination);
                    }
                    else if (Type == "List")
                    {
                        MoveToList(siteurl, Source, Destination);
                    }
                }
                ///End of for Loop.
                Console.WriteLine("GetArchivalDetails() : End Of Function.");
                Logging(null, "GetArchivalDetails() : End Of Function.");
            }
            catch (Exception ex)
            {
                Logging(ex, "Error in GetArchivalDetails()");
            }
            finally
            {
                 dt=null;
                 siteurl = null;
                 Source = null;
                 Destination = null;
                 Type = null;
           
            }
           
        }
    }
}

Tuesday, 28 February 2012

Use to add or remove user from site collection Administrator in c# in sharepoint

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Administration;
using System.Configuration;

namespace CCMListUserProject.EventRCCMListUser
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventRCCMListUser : SPItemEventReceiver
    {

        private string SiteUrl = ConfigurationManager.AppSettings["SiteURL"];
        private string AdminUrl = ConfigurationManager.AppSettings["AdminUrl"];
        private string ListName = ConfigurationManager.AppSettings["CCMListName"];
        private string DomainName = ConfigurationManager.AppSettings["DomainName"];
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
       }

       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           if (properties.ListTitle.ToString() == ListName)
           {
               SPListItem _currentItem = properties.ListItem;

               using (SPSite spSite = new SPSite(SiteUrl))
               {
                   SPWebApplication spwebapp = new SPWebApplication();
                   spwebapp = spSite.WebApplication;
                   SPSiteCollection allsitecoll;
                   allsitecoll = spwebapp.Sites;
                   foreach (SPSite site in allsitecoll)
                   {
                       SPWeb web = site.OpenWeb();
                       string CCMUserName = DomainName + "\\" + _currentItem["CCMUserName"].ToString();
                       SPUser objSpuser = web.AllUsers[CCMUserName];
                       objSpuser.IsSiteAdmin = false;
                       web.AllUsers.Remove(CCMUserName);
                       SPSecurity.RunWithElevatedPrivileges(delegate()
                       {
                           web.AllowUnsafeUpdates = true;
                           objSpuser.Update();
                           web.AllowUnsafeUpdates = false;
                       });
                   }

               }
               using (SPSite spSite = new SPSite(AdminUrl))
               {

                   SPWeb web = spSite.OpenWeb();
                   string CCMUserName = DomainName + "\\" + _currentItem["CCMUserName"].ToString();
                   SPUser objSpuser = web.AllUsers[CCMUserName];
                   objSpuser.IsSiteAdmin = false;
                   web.AllUsers.Remove(CCMUserName);
                   SPSecurity.RunWithElevatedPrivileges(delegate()
                   {
                       web.AllowUnsafeUpdates = true;
                       objSpuser.Update();
                       web.AllowUnsafeUpdates = false;
                   });

               }
           }    
           base.ItemDeleting(properties);
       }

       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           if (properties.ListTitle.ToString() == ListName)
           {
               SPListItem _currentItem = properties.ListItem;

               using (SPSite spSite = new SPSite(SiteUrl))
               {
                   SPWebApplication spwebapp = new SPWebApplication();
                   spwebapp = spSite.WebApplication;
                   SPSiteCollection allsitecoll;
                   allsitecoll = spwebapp.Sites;
                   foreach (SPSite site in allsitecoll)
                   {
                       SPWeb web = site.OpenWeb();
                       string CCMUserName = DomainName + "\\" + _currentItem["CCMUserName"].ToString();
                       web.AllUsers.Add(CCMUserName, "", "", "");
                       SPUser objSpuser = web.AllUsers[CCMUserName];
                       objSpuser.IsSiteAdmin = true;
                       SPSecurity.RunWithElevatedPrivileges(delegate()
                       {
                           web.AllowUnsafeUpdates = true;
                           objSpuser.Update();
                           web.AllowUnsafeUpdates = false;
                       });
                   }

               }
               using (SPSite spSite = new SPSite(AdminUrl))
               {

                   SPWeb web = spSite.OpenWeb();
                   string CCMUserName = DomainName + "\\" + _currentItem["CCMUserName"].ToString();
                   web.AllUsers.Add(CCMUserName, "", "", "");
                   SPUser objSpuser = web.AllUsers[CCMUserName];
                   objSpuser.IsSiteAdmin = true;
                   SPSecurity.RunWithElevatedPrivileges(delegate()
                   {
                       web.AllowUnsafeUpdates = true;
                       objSpuser.Update();
                       web.AllowUnsafeUpdates = false;
                   });

               }
           }    
           base.ItemAdded(properties);
       }

       /// <summary>
       /// An item was deleted.
       /// </summary>
       public override void ItemDeleted(SPItemEventProperties properties)
       {
           base.ItemDeleted(properties);
       }


    }
}

Thursday, 5 January 2012

Terms & Conditions in my link

Remove User who complete the Document

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Configuration;

namespace SharePointProject_RemoveUser.EventReceiver_RemoveUser
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver_RemoveUser : SPItemEventReceiver
    {
        private string libname = ConfigurationManager.AppSettings["MyDocumentLibraryName"];
        private string docstatus = ConfigurationManager.AppSettings["MyDocumentLibraryDocStatus"];
        private string docsharedmembers = ConfigurationManager.AppSettings["MyDocumentLibrarySharedMembers"];
        private string docAuthor = ConfigurationManager.AppSettings["MyDocumentAuthor"];
        /// <summary>
        /// An item was updated.
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {

           try
           {

               if (properties.ListTitle.ToString() == libname)
               {

                   SPListItem _currentItem = properties.ListItem; /// Gets Items from listitem.

                   if (!string.IsNullOrEmpty(_currentItem[docstatus].ToString())) /// Check DocStatus not Empty.
                   {
                       if (_currentItem[docstatus].ToString().ToLower() == "completed") //// Check DocStatus is Completed
                       {
                           SPUser user = properties.Web.CurrentUser; // Getting Current User
                           string fieldValue = _currentItem[docsharedmembers].ToString(); ///Getting Mutiple Users from Shared Member.
                           string Author = _currentItem[docAuthor].ToString();  ///Getting Created by User.
                           SPFieldUserValueCollection users = new SPFieldUserValueCollection(_currentItem.Web, fieldValue); ///Collect Multiple Users.
                           SPFieldUserValueCollection AuthorUser = new SPFieldUserValueCollection(_currentItem.Web, Author); ///Collect created by User.
                           SPFieldUserValueCollection values = new SPFieldUserValueCollection(); ///Use to Store the Filter Users

                           ///Use this condition for clearing shared members field if Author completed the status
                           if (AuthorUser[0].User.LoginName.ToString().ToLower() == user.LoginName.ToString().ToLower() && users.Count >= 0)
                           {
                               users.Clear();
                               _currentItem[docstatus] = _currentItem[docstatus].ToString();
                               _currentItem[docsharedmembers] = users;
                           }
                           else
                           {
                               /// Use condition to Remove users from shared members field .
                               foreach (SPFieldUserValue uv in users)
                               {
                                   if (uv.User.LoginName.ToLower() != user.LoginName.ToLower())
                                   {
                                       values.Add(new SPFieldUserValue(properties.Web, uv.User.ID, uv.User.Name));
                                   }
                               }
                               _currentItem[docstatus] = ""; ///empty the status field
                               _currentItem[docsharedmembers] = values;
                           }

                           _currentItem.Update();

                        
                       }

                   }


               }
           }
           catch (Exception)
           {

               //   throw;
           }
         

           base.ItemUpdated(properties);
       }


    }
}

Monday, November 5, 2012

Create a Workflow using Visual Studio 2010

Introduction

In this article we can experiment with creating a Workflow using Microsoft Visual Studio 2010. Visual Studio along with SharePoint 2010 Extensions provides sophisticated development tools to enable Workflow development.

Types of Workflows

There are basically two types of workflows inside Visual Studio:
  • Sequential Workflow
  • State Machine Workflow
Sequential Workflow once invoked continues execution until it is completed.
State Machine Workflow will have states persisted in between. The state could be continued execution between machine restarts.
In this example we are trying to create a Workflow which on activation updates the null Address column of the Manager list. (You need to have a Contact template named Manager.)
Step 1: Create Sequential Workflow Project
For the time being, we can start with a Sequential Workflow. Start Visual Studio and create a new project from the template SharePoint > Sequential Workflow.

In the next screen select the option Site Workflow as shown below:

In the next screen, leave the default option saying the user manually starts the Workflow. Click the Finish button to create the project.

You will get the following screen once the project is created.

Step 2: Create Activity
We need to create an Activity to perform our job.

What is an Activity?

A Workflow consists of a series of Activities. We can add Activities using the Toolbox. There are different types of Activities like Code Activity, SendEmail, etc. For our example we are using the more functional Code Activity.

Drag and drop a Code Activity from the toolbox. You can locate this from the v3.0 group inside Toolbox.

Step 3: Add code for the Activity
Now we need to add code for this Activity. Double click on the codeActivity1 item shown above. Place the following code in the appearing code view.
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
    using (SPWeb web = SPContext.Current.Web)
    {
        SPList list = web.Lists["Manager"];
        foreach (SPListItem item in list.Items)
        {
            if (item["Address"] == null)
            {
                item["Address"] = "PLEASE SET THE ADDRESS!";

                item.Update();
            }
        }
    }
}
Step 4: Build and Deploy the Solution
Now we are ready to build and deploy the solution. Right click on the solution and use the Build and Deploy command.

Step 5: Execute the Workflow inside SharePoint
Now we are ready to test the Workflow inside SharePoint. As the Workflow was created as a Site Workflow it will be accessible for all the Lists and Libraries. You can click the Lists link inside the site.

Now click on the Site Workflows link. You will get the following screen.

Before executing the Workflow, you need to create a Manager item with Address not assigned.
Click on the highlighted button and your workflow gets executed. Wait for a while and you can see the invalid manager record is updated with the message.

This concludes our article on Workflow using Visual Studio.