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("");
        }
    }
}