Thursday, 9 June 2016

ItemAdded EventReceiver To Add Item In Another List

SPList lst = properties.Web.GetList(properties.WebUrl + "/Lists/ListName1/AllItems.aspx");
           if (lst != null && lst.ID == properties.ListId)
           {
               SPList lstRes = properties.Web.GetList(properties.WebUrl + "/Lists/ListName/AllItems.aspx");
               if (lstRes != null)
               {
                   string str =Convert.ToString(properties.ListItem["Title"]);
                   int res =Convert.ToInt16(properties.ListItem["Marks"]);

                   SPListItem itm = lstRes.Items.Add();
                   if (res >= 40)
                       itm["Title"] = "Pass";
                   else
                       itm["Title"] = "Fail";

                   itm.Update();
               }
           }

SPGridView SharePoint 2010

1. Add Below Code To Your .ascx File

<SharePoint:SPGridView ID="spgvOrder" runat="server" AutoGenerateColumns="false"
                valign="top" AllowPaging="true" AllowSorting="true" AllowFiltering="true" FilterDataFields="Title,FirstName,LastName,State,Marks"
                FilteredDataSourcePropertyName="FilterExpression" FilteredDataSourcePropertyFormat="{1} like '{0}'"
                OnSorting="spgvOrder_Sorting">
                <Columns>
                    <SharePoint:SPBoundField DataField="Title" HeaderText="Code" ItemStyle-HorizontalAlign="Left" />
                    <SharePoint:SPBoundField DataField="FirstName" HeaderText="First Name" ItemStyle-HorizontalAlign="Left" />
                    <SharePoint:SPBoundField DataField="LastName" HeaderText="Last Name" ItemStyle-HorizontalAlign="Left" />
                    <SharePoint:SPBoundField DataField="State" HeaderText="State" ItemStyle-HorizontalAlign="Left" />
                    <SharePoint:SPBoundField DataField="Marks" HeaderText="Marks" ItemStyle-HorizontalAlign="Left" />
                </Columns>
            </SharePoint:SPGridView>
            <asp:ObjectDataSource runat="server" ID="gridds" OnFiltering="gridds_Filtering" OnObjectCreating="gridds_ObjectCreating" />
            <SharePoint:SPGridViewPager ID="SPGridViewPager1" GridViewId="spgvOrder" runat="server"></SharePoint:SPGridViewPager>


2. Add Below Code To Bind List Items To  SPGridView With Sorting & Filtering

protected void Page_Load(object sender, EventArgs e)
        {
            gridds.TypeName = this.GetType().AssemblyQualifiedName;
            spgvOrder.DataSourceID = gridds.ID;
            gridds.SelectMethod = "LoadData";
            spgvOrder.PageSize = 50;
            spgvOrder.DataBind();
        }
protected void spgvOrder_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["FilterExpression"] != null)
            {
                gridds.FilterExpression = (string)ViewState["FilterExpression"];
            }
        }
        protected void gridds_Filtering(object sender, ObjectDataSourceFilteringEventArgs e)
        {
            ViewState["FilterExpression"] = ((ObjectDataSourceView)sender).FilterExpression;
        }
        protected sealed override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            if (Context.Request.Form["__EVENTARGUMENT"] != null &&
                 Context.Request.Form["__EVENTARGUMENT"].EndsWith("__ClearFilter__"))
            {
                // Clear FilterExpression
                ViewState.Remove("FilterExpression");
            }
        }
        protected void gridds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = this;
        }

public DataTable LoadData()
        {
            DataTable dt = null;
            try
            {
                dt = new DataTable();
                dt.Columns.Add("Title", typeof(string));
                dt.Columns.Add("FirstName", typeof(string));
                dt.Columns.Add("LastName", typeof(string));
                dt.Columns.Add("State", typeof(string));
                dt.Columns.Add("Marks", typeof(Int16));

                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList lst = web.Lists["ListName"];
                        SPListItemCollection itmcol = lst.Items;

                        if (itmcol != null && itmcol.Count > 0)
                        {
                            DataRow dr = null;
                            foreach (SPListItem itm in itmcol)
                            {
                                dr = dt.NewRow();
                                dr["Title"] = itm["Title"];
                                dr["FirstName"] = itm["FirstName"];
                                dr["LastName"] = itm["LastName"];
                                dr["State"] = itm["State"];
                                dr["Marks"] = itm["Marks"];

                                dt.Rows.Add(dr);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            return dt;
        }

Create Timer Job Step By Step

1. Add new SharePoint Empty Project.
2. Add new class as below.

public class CustomTimerJob : SPJobDefinition
    {
        public CustomTimerJob() : base() { }
        public CustomTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {

        }
        public CustomTimerJob(string jobName, SPWebApplication webapp) :
            base(jobName, webapp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = jobName;
        }
        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webApp = this.Parent as SPWebApplication;
            SPList taskList = webApp.Sites[0].RootWeb.Lists["ListName"];


            //SPListItem newTask = taskList.Items.Add();
            //newTask["Title"] = "NewTask";
            //newTask.Update();




                                                              OR



         
                string siteURL = this.Properties["siteurl"].ToString();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spSite = new SPSite(siteURL))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            SPList lst = spWeb.Lists["ListName"];
                            SPListItem itm = lst.Items.Add();
                            itm["Title"] = "NewTask";
                            itm.Update();
                        }
                    }
                });
           
        }
    }



Now Create New Feature Event Receiver and perform below steps in event receiver cs file

   private const string LIST_JOB = "Testing Timer Job";
   private const string LIST_JOB = "Testing Timer Job1";
   private const string LIST_JOB = "Testing Timer Job2";


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            Guid SiteID = ((SPSite)properties.Feature.Parent).ID;
            SPSecurity.RunWithElevatedPrivileges(delegate(){
                SPSite site = new SPSite(SiteID);
                if (site != null)
                {
                    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                    {
                        if (job.Name == LIST_JOB )
                            job.Delete();
                    }
                    CustomTimerJob TimeJob = new CustomTimerJob(LIST_JOB, site.WebApplication);
                    SPDailySchedule schedule = new SPDailySchedule();
                    schedule.BeginHour = 15;
                    schedule.BeginMinute = 30;
                    schedule.EndHour = 15;
                    schedule.EndMinute = 45;

                    TimeJob.Schedule = schedule;
                    TimeJob.Properties.Add("siteurl", site.Url);
                    TimeJob.Update();
                }
            });
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == LIST_JOB )
                    job.Delete();
            }
        }


Friday, 22 April 2016

Increase Max Length Of Multiple People Picker Control






Sometimes you got warning message like "Item cannot be more than 256 characters" at the people editor control while adding or updating large number of data. To avoid this just add below script to content editor web part & Change g_MAX_LEN value as required.


<script language="ecmascript" type="text/ecmascript">
function onPageLoad() {
  g_MAX_LEN = 2000;
}
$(document).ready(onPageLoad);
</script>

Thanks & Regards
Modi Vishal

Tuesday, 5 April 2016

SharePoint 2010 Shortcuts

http://<Site>/_vti_bin/Lists.asmx: - List Web Service
http://<Site>/_layouts/viewlsts.aspx:- View All Site Contents
http://<Site>/Page.aspx?contents=1:- View Web part For Current Page 

Wednesday, 16 September 2015

Event Receivers BeforeProperties and AfterProperties

SharePoint 2010 Create Monthly Timer Job Which Execut On Last Day Of Month

      
 MonthlyTJService is helper class in which your logic for timer job is implemented



       string MonthlyTJ = "Monthly TJ";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
                 SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = properties.Feature.Parent as SPSite;
                    DeleteJob(site);
                    CreateJob(site);
                });
          
         }

        private static void DeleteJob(SPSite site)
        {
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                 job.Delete();
            }
        }

        private static void CreateJob(SPSite site)
        {
            if (site == null)
                throw new ArgumentNullException("site", "site is null.");
          
            MonthlyTJService monthlyTJ = new MonthlyTJService(MonthlyTJ, site.WebApplication);
            SPMonthlySchedule monthlyTJSchedule = new SPMonthlySchedule()
            {
                BeginDay = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month),
                EndDay = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month),
                BeginHour = 23,
                BeginMinute = 15,
                EndHour = 23,
                EndMinute = 45
            };

            monthlyTJ.Schedule = monthlyTJSchedule;
            monthlyTJ.Properties.Add("siteurl", site.Url);
            monthlyTJ.Update();
       }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            DeleteJob(properties.Feature.Parent as SPSite); // Delete the Job
        }

SharePoint 2010 CAML Query For Search Within Folder

Search For Non Lookup Field Value

   <Query>
       <Where>
           <Eq>
               <FieldRef Name='Title'/>
               <Value Type='Text'>Val</Value>
           </Eq>
       </Where>
   <Query>
   <QueryOptions>
       <ViewAttributes Scope='Recursive' />
   </QueryOptions>



Search For Lookup Field Value 

   <Query>
       <Where>
           <Eq>
               <FieldRef Name='Title' LookupId='True'/>
               <Value Type='Lookup'>Val</Value>
           </Eq>
       </Where>
   <Query>
   <QueryOptions>
       <ViewAttributes Scope='Recursive' />
   </QueryOptions>

Thursday, 12 September 2013

Create treeview structure of document library and its item using client object model

private void FillTreeView()
        {
            documentLibraryStructureTreeView.Nodes.Clear();

            ClientContext clientContext = new ClientContext("http://sp2013:10021/demo");
            clientContext.Credentials = new System.Net.NetworkCredential("username", "password", "servername");
            clientContext.Load(clientContext.Web.Lists);
            clientContext.ExecuteQuery();
            foreach (List list in clientContext.Web.Lists)
            {
                try
                {

                    if (list.BaseType.ToString() == "DocumentLibrary" && !list.IsApplicationList && !list.Hidden && list.Title != "Form Templates" && list.Title != "Customized Reports" && list.Title != "Site Collection Documents" && list.Title != "Site Collection Images" && list.Title != "Images" && list.Title != "Style Library")
                    {
                        clientContext.Load(list);
                        clientContext.ExecuteQuery();
                        clientContext.Load(list.RootFolder);
                        clientContext.Load(list.RootFolder.Folders);
                        clientContext.ExecuteQuery();
                        documentLibraryStructureTreeView.ShowLines = true;
                        TreeNode LibraryNode = new TreeNode(list.Title);
                        documentLibraryStructureTreeView.Nodes.Add(LibraryNode);
                        Folder root = list.RootFolder;
                        FillTreeViewNodes(root, LibraryNode, clientContext);
                    }
                }
                catch
                {
                }
            }
        }

        public void FillTreeViewNodes(Folder SubFolder, TreeNode MainNode, ClientContext clientcontext)
        {
            clientcontext.Load(SubFolder.Files);
            clientcontext.ExecuteQuery();
            foreach (Microsoft.SharePoint.Client.File Fol in SubFolder.Files)
            {
                TreeNode SubNode = new TreeNode(Path.ChangeExtension(Fol.Name,string.Empty));
                MainNode.ChildNodes.Add(SubNode);
            }
        }

Wednesday, 4 September 2013

Convert Excel To PDF Using Microsoft.Office.Interop.Excel

private void ExportExcelToPDF()
        {
            string sourceFilePath = @"SourceFilePath";
            string destinationFilePath = @"DestinationFilePath";

            Microsoft.Office.Interop.Excel.Application myExcelApp;
            Microsoft.Office.Interop.Excel.Workbooks myExcelWorkbooks = null;
            Microsoft.Office.Interop.Excel.Workbook myExcelWorkbook = null;


            try
            {
                object misValue = System.Reflection.Missing.Value;
                myExcelApp = new Microsoft.Office.Interop.Excel.Application();

                myExcelApp.Visible = true;
                object varMissing = Type.Missing;
                myExcelWorkbooks = myExcelApp.Workbooks;

                //if file already exist then delete the file
                if (System.IO.File.Exists(destinationFilePath))
                {
                    System.IO.File.Delete(destinationFilePath);
                }


                myExcelWorkbook = myExcelWorkbooks.Open(sourceFilePath, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

                myExcelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF,
                                    destinationFilePath, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard,
                                    varMissing, false, varMissing, varMissing, false, varMissing);


                myExcelWorkbooks.Close();
                myExcelApp.Quit();
            }
            catch
            {
            }
            finally
            {
                myExcelApp = null;
            }

        }

Monday, 10 September 2012

Creating Color-Coded Calendar Events in SharePoint 2010


A great addition to SharePoint 2010 is the Calendar Overlay functionality, allowing the user to create color-coded events in a calendar based on user-defined event categories, out of the box.  Below is a simple walkthrough of the process.
 
1. Modify the default categories created by the list (Calendar Tab on Ribbon -> List Settings -> Category Column)
Modify Calendar Categories
 
2. Add a couple of events, at least one in each category for testing purposes
 Add Calendar Events by Category

 
3. Create a separate view to display each Category (Calendar Tab on Ribbon -> Create View -> Calendar View)  
 Create Category Views
**You will end up with one view for each category**
 
4. Make one more view that will be the view with all color coded views overlaid  (Calendar Tab on Ribbon -> Create View -> Calendar View) 
Create View for Overlays
 
5. Add a new calendar (category view)  to the Calendar Color Overlay View (Calendar Tab on Ribbon -> Calendars Overlay) with a Category that is blank **You must do this FROM the Calendar Color Overlay View
Calendar Overlay Settings
 
6. Name the Calendar, select SharePoint, select a color for the category, and click Resolve to populate the Lists and List Views available in the SharePoint site under Web URL. Select your Calendar and the View you created in Step 3.  Select Always Show.  **Repeat steps 4 and 5 for each category view**
Color Coding Details
 
7. Your Calendar Overlay Settings for the Calendar Color Overlay View will look similar to the screenshot with a Calendar for each category
All Overlaid Views
 
8. Your resulting calendar view will have the four views overlaid, with a color for each category.  A legend is displayed on the left corresponding to each view.  
Overlaid Calendar Events

Thursday, 6 September 2012

Add List Item Using Infopath Form SharePoint 2010


using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
using Microsoft.SharePoint;

namespace Form1
{
    public partial class FormCode
    {
        // Member variables are not supported in browser-enabled forms.
        // Instead, write and read these values from the FormState
        // dictionary using code such as the following:
        //
        // private object _memberVariable
        // {
        //     get
        //     {
        //         return FormState["_memberVariable"];
        //     }
        //     set
        //     {
        //         FormState["_memberVariable"] = value;
        //     }
        // }

        // NOTE: The following procedure is required by Microsoft InfoPath.
        // It can be modified using Microsoft InfoPath.
        public void InternalStartup()
        {
            ((ButtonEvent)EventManager.ControlEvents["CTRL5_5"]).Clicked += new ClickedEventHandler(CTRL5_5_Clicked);
        }

        public void CTRL5_5_Clicked(object sender, ClickedEventArgs e)
        {
            SPSite site = new SPSite("siteurl");
            SPWeb web = site.OpenWeb();
            web.AllowUnsafeUpdates = true;
            SPList InfopathList = web.Lists["InfopathList"];
         
            XPathNavigator xnav = MainDataSource.CreateNavigator();
            XPathNodeIterator rows = xnav.Select("/my:myFields", NamespaceManager);
            while (rows.MoveNext())
            {
                SPListItem item = InfopathList.Items.Add();

                string Title = rows.Current.SelectSingleNode("@my:Title", NamespaceManager).Value;
                string EmployeeId = rows.Current.SelectSingleNode("my:EmployeeId", NamespaceManager).Value;
                string EmployeeName = rows.Current.SelectSingleNode("my:EmployeeName", NamespaceManager).Value;


                item["Title"] = Title;
                item["EmployeeId"] = EmployeeId;
                item["EmployeeName"] = EmployeeName;
                item.Update();
            }
            XPathNavigator x1 = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/@my:Title", this.NamespaceManager);
            XPathNavigator x2 = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:EmployeeId", this.NamespaceManager);
            XPathNavigator x3 = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:EmployeeName", this.NamespaceManager);

            x1.SetValue("");
            x2.SetValue("");
            x3.SetValue("");
        }
    }
}

Timer Job In Sharepoint 2010


1. Open Visual Studio 2010 and select File –> New –> Project…image
2. In the New Project window, under Installed Templates, select SharePoint –> 2010 and select Empty SharePoint Project. Give the project a Name and click OK.image
3. Enter the URL for SharePoint local site, check the Deploy as a farm solution, and click Finish.image
4. Create a new class.  Right click on the project in the Solution Explorer window and select Add –> New Item…image
5. In the Add New Item window, under Installed Templates, select Visual C# –> Code and select Class.  Give the class a name and click OK.image
6. The new class needs to inherit from the Microsoft.SharePoint.Administration.SPJobDefinition class. Copy and paste the following code, which creates a the constructors, overrides the Execute() method, and inherits theSPJobDefinition class: (Note: In this code example, an item is added to a SharePoint list every time the Execute() method is called.  The list called “ListTimerJob” must reside within SharePoint.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
 
namespace UpshotSP
{
    class ListTimerJob : SPJobDefinition
    {
         public ListTimerJob()
 
            : base()
        {
 
        }
 
        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
 
            : base(jobName, service, server, targetType)
        {
 
        }
 
        public ListTimerJob(string jobName, SPWebApplication webApplication)
 
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
 
            this.Title = "List Timer Job";
 
        }
 
        public override void Execute(Guid contentDbId)
        {
 
            // get a reference to the current site collection's content database
 
            SPWebApplication webApplication = this.Parent as SPWebApplication;
 
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
 
            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
 
            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
 
            // create a new list Item, set the Title to the current day/time, and update the item
 
            SPListItem newList = Listjob.Items.Add();
 
            newList["Title"] = DateTime.Now.ToString();
 
            newList.Update();
 
        }
    }
}

7. Add a Feature to the solution by right clicking on Features in the Solution Explorer window and selecting Add Feature.image
8. Right click on Feature1 and select Add Event Receiver.image
9.  A new class is created that handles the feature’s events.  Copy and paste the following code, which handles theFeatureActivated event, installing the custom timer job, and handles the FeatureDeactivating event, uninstalling the custom timer job:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
namespace UpshotSP.Features.Feature1
{
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
public class Feature1EventReceiver : SPFeatureReceiver
    {
        const string List_JOB_NAME = "ListLogger";
        // Uncomment the method below to handle the event raised after a feature has been activated.
 
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
 
            // make sure the job isn't already registered
 
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
 
                if (job.Name == List_JOB_NAME)
 
                    job.Delete();
 
            }
 
            // install the job
 
            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);
 
            SPMinuteSchedule schedule = new SPMinuteSchedule();
 
            schedule.BeginSecond = 0;
 
            schedule.EndSecond = 59;
 
            schedule.Interval = 5;
 
            listLoggerJob.Schedule = schedule;
 
            listLoggerJob.Update();
 
        }
 
        // Uncomment the method below to handle the event raised before a feature is deactivated.
 
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
 
            // delete the job
 
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
 
                if (job.Name == List_JOB_NAME)
 
                    job.Delete();
 
            }
 
        }
 
    }
 
}

10. Select the appropriate scope where the new feature will be activated.  Double click Feature1.Feature in theSolution Explorer window and choose the desired Scope from the dropdown menu.image
11. Deploy the solution by right clicking on the project in the Solution Explorer window and selecting Deploy.image
12. Navigate to the SharePoint “ListTimerJob” list and verify that a new item has been added with the current day/time as the title. (Note: The custom timer job , and many other services, can be modified within Central Administration site.)
13. Finished!