Thursday, 9 March 2017

Read From Excel and update in a list

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data;

using System.IO;
using System.Xml;
using System.Net;
using Excel;
using System.Data.SqlClient;
//using Excel = Microsoft.Office.Interop.Excel;
namespace Solstad_ReadFromExcelUpdateCharteringContarct
{
    class Program
    {
        static void Main(string[] args)
        {
            AddIntoDB();
            return;
            FileStream stream = File.Open("C:\\CCS\\Console Applications\\Solstad\\HSE_PPIR.xlsx", FileMode.Open, FileAccess.Read);
                    DataSet result = null;
                        System.Data.DataTable dtResult = null;
                        //Reading Excel file from document library.

                        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                        excelReader.IsFirstRowAsColumnNames = true;

                        //Converting it into Dataset.
                        result = excelReader.AsDataSet();
                        dtResult = result.Tables[0];
                        //  saasWeb.AllowUnsafeUpdates = true;
                        for (int i = 0; i < dtResult.Rows.Count; i++)
                        {
                            //Parent List
                            //string parentList= "Chartering Contract";
                            string parentList = "";
                            //string childList = "Vessel Chartering Contract";
                            string childList = "";
                           
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                using (SPSite site = new SPSite(""))
                                {
                                    SPWeb web = site.OpenWeb();
                                    SPList spList = web.Lists[parentList];
                                    SPQuery spQItems = new SPQuery();
                                    spQItems.Query = "<Where><Eq><FieldRef Name='Kontrakts_x0020_ID' /><Value Type='Text'>"+Convert.ToString(dtResult.Rows[i]["Contract ID"])+"</Value></Eq></Where>";
                                    SPListItemCollection items = spList.GetItems(spQItems);
                                    if (items.Count > 0)
                                    {
                                        foreach (SPListItem item in items)
                                        {
                                            item["ApplyStaircaserates"] = false;
                                            using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                                            {
                                                item.SystemUpdate(false);
                                            }

                                            SPList lstChildList = web.Lists["Vessel Chartering Contract"];
                                            SPQuery spqChild = new SPQuery();
                                            spqChild.Query = "<Where><Eq><FieldRef Name='Contract_x0020_ID' /><Value Type='Text'>" + Convert.ToString(item["ID"]) + "</Value></Eq></Where>";
                                            SPListItemCollection childItemsColn = lstChildList.GetItems(spqChild);
                                            if (childItemsColn.Count > 0)
                                            {
                                                foreach (SPListItem childItem in childItemsColn)
                                                {
                                                    childItem["ApplyStaircaserates"] = false;
                                                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                                                    {
                                                        childItem.SystemUpdate(false);
                                                        Console.WriteLine("ID:" + Convert.ToString(item["ID"]));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            });
         
         
                        }

        }
        public static void AddIntoDB()
        {
            FileStream stream = File.Open("C:\\CCS\\Console Applications\\Solstad\\HSE_PPIR.xlsx", FileMode.Open, FileAccess.Read);
            DataSet result = null;
            System.Data.DataTable dtResult = null;
            //Reading Excel file from document library.

            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            excelReader.IsFirstRowAsColumnNames = true;

            //Converting it into Dataset.
            result = excelReader.AsDataSet();
            dtResult = result.Tables[0];
            if (dtResult.Rows.Count > 0)
            {
                for (int i = 0; i < dtResult.Rows.Count; i++)
                {
                    string strVessel = Convert.ToString(dtResult.Rows[i]["Column1"]);
                    string strPPIR = Convert.ToString(dtResult.Rows[i]["Column11"]);
                    if (strVessel.Trim() != "")
                    {

                    }
                }
            }
        }
     
   
    }
    class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
    {
        public DisabledItemEventsScope()
        {
            base.DisableEventFiring();
        }

        #region IDisposable Members

        public void Dispose()
        {
            base.EnableEventFiring();
        }

        #endregion
    }
}

Webpart property Updates via a console

using System;
using System.Collections.Generic;

using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace WebpartPropertyConsole
{
    class Program
    {
       
        static void Main(string[] args)
        {
            try
            {
             
                SPSite tempSite = new SPSite("");
                SPWeb tempSPWeb = tempSite.OpenWeb();

                //chartering contract list
               
                //SPList _PGList = tempSPWeb.Lists["Companies"];
                int iTotalItems = _PGList.ItemCount;
                int count = 1;


                int intStartIndex = 106;
                int intEndIndex = 696;

                for (int i = intStartIndex; i <= intEndIndex; i++)
                {
                    //if (i != 2416)
                    {
                        try
                        {
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                try
                                {
                                    SPListItem spli = _PGList.GetItemById(i);
                                    if (spli["Link"] != null)
                                    {
                                        SPFieldUrlValue spfuv = new SPFieldUrlValue(spli["Link"].ToString());
                                        //AddWebpartProperty(spfuv.Url, "Sub Projects", "MainListFilterField", "Link to main project", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Sub Projects", "PortfolioField", "Main project", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Ongoing Valve Delivery Process", "SourceFields", "IQS unique ID,Project name,Link,Project Type,Department,End user", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "All Valve Delivery Process", "SourceFields", "IQS unique ID,Project name,Link,Project Type,Department,End user", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Parts", "ParentListSerialNoField", "Serial No", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Parts", "EquOrPartNo", "Part no", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Parts", "SerialNo", "Part Serial no", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Tools", "PartInventory", "Equipment inventory", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Tools", "PartInventoryFieldPartNo", "Equipment no", spli["ID"].ToString(), _PGList.ID.ToString());
                                        AddWebpartProperty(spfuv.Url, "Chartering Contract | Details", "LinkStyle", "font-family:verdana;color:#002B54;padding-top:16px;padding-left:16px;font-size:15px;font-weight:bold;", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Parts", "StatusFieldValue", "", spli["ID"].ToString(), _PGList.ID.ToString());

                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Tools", "Hidenewserialno", "NO", spli["ID"].ToString(), _PGList.ID.ToString());
                                        //AddWebpartProperty(spfuv.Url, "Assign Serial Number for Tools", "Equipmentserialnoguidformat", "NO", spli["ID"].ToString(), _PGList.ID.ToString());
                                        Console.WriteLine(count + "/" + iTotalItems);
                                        count++;

                                    }
                                    else
                                    {

                                    }
                                }
                                catch
                                {



                                }
                            });
                        }

                        catch
                        {
                            ;
                        }
                    }

                }

            }
            catch
            {
                ;
            }

        }
     

        #region Add Property
        /// <summary>
        ///
        /// </summary>
        /// <param name="weburl"></param>
        /// <param name="webPartName"></param>
        /// <param name="webpartProprty"> property that is set in webpart code (note: not display name)</param>
        /// <param name="webpartPropertyValue"></param>
        /// <param name="id"></param>
        /// <param name="strlist"></param>
        /// <param name="spWeb1Parent"></param>

        public static void AddWebpartProperty(string weburl, string webPartName, string webpartProprty, string webpartPropertyValue, string id, string strlist)
        {

            //string strTargetSite = "http://ccsentshivm058/shibu/default.aspx";
            string strTargetSite = weburl;
            SPSite spsSite = new SPSite(strTargetSite);
            SPWeb spwWeb = spsSite.OpenWeb();

            string stringrelativeurl = spwWeb.ServerRelativeUrl;
            spwWeb.AllowUnsafeUpdates = true;

            //const string KEY_CHK = "DWIndivid_weburl";

            //if (!spwWeb.Properties.ContainsKey(KEY_CHK))
            //{
            //    spwWeb.Properties.Add("DWIndivid_weburl", spWeb1Parent.Url);  // create web url
            //}
            //else
            //{
            //    spwWeb.Properties.Remove("DWIndivid_weburl");  // create web url
            //    spwWeb.Properties.Add("DWIndivid_weburl", spWeb1Parent.Url);
            //}

            //if (!spwWeb.Properties.ContainsKey("DWIndivid_RelativeWebUrl"))
            //{
            //    spwWeb.Properties.Add("DWIndivid_RelativeWebUrl", spWeb1Parent.ServerRelativeUrl); //relatiev url

            //}
            //else
            //{
            //    spwWeb.Properties.Remove("DWIndivid_RelativeWebUrl");
            //    spwWeb.Properties.Add("DWIndivid_RelativeWebUrl", spWeb1Parent.ServerRelativeUrl);
            //}
            //if (!spwWeb.Properties.ContainsKey("DWIndivid_ListID"))
            //{
            //    spwWeb.Properties.Add("DWIndivid_ListID", strlist); //relatiev url
            //}
            //else
            //{
            //    spwWeb.Properties.Remove("DWIndivid_ListID");
            //    spwWeb.Properties.Add("DWIndivid_ListID", strlist);
            //}
            //if (!spwWeb.Properties.ContainsKey("DWIndivid_ItemID"))
            //{
            //    spwWeb.Properties.Add("DWIndivid_ItemID", id); //relatiev url
            //}
            //else
            //{
            //    spwWeb.Properties.Remove("DWIndivid_ItemID");
            //    spwWeb.Properties.Add("DWIndivid_ItemID", id);
            //}

            //spwWeb.Properties.Update();//save site property


            // checking webpart property is having ',' at the end
            //checking webpart propertyvalue is having ','at the end

            string str = webpartProprty.Substring(webpartProprty.Length - 1);
            if (str == ",")
            {


            }
            else
            {
                webpartProprty = webpartProprty + ",";
            }
            string strpro = webpartPropertyValue.Substring(webpartPropertyValue.Length );
            if (strpro == ",")
            {

            }
            else
            {
                webpartPropertyValue = webpartPropertyValue + ",";
            }

            //Delivery%20Ticket%20Report.aspx
            //SPWebPartCollection wpcWebParts = spwWeb.GetWebPartCollection("default.aspx", Storage.Shared);

            //SPWebPartCollection wpcWebParts = spwWeb.GetWebPartCollection("/webpartpages/bussprocess.aspx", Storage.Shared);
            //WorkOrderOutReport.aspx
            //    string strRelativeUrl = spwWeb.ServerRelativeUrl.ToString() + "/" + "webpartpages/bussprocess.aspx";
            //string strRelativeUrl = spwWeb.ServerRelativeUrl.ToString() + "/WebPage/OngoingProjects.aspx"; //+ "/" + "webpartpages/Quotation And Invoice Webpart.aspx";
            // string strRelativeUrl = spwWeb.ServerRelativeUrl.ToString() + "/default.aspx"; //+ "/" + "webpartpages/Quotation And Invoice Webpart.aspx";
            //string strRelativeUrl = spwWeb.ServerRelativeUrl.ToString() + "/webpartpages/Serial No Allocation WebPart For Part.aspx"; //+ "/" + "webpartpages/Quotation And Invoice Webpart.aspx";
            string strRelativeUrl = spwWeb.ServerRelativeUrl.ToString() + "/default.aspx"; //+ "/" + "webpartpages/Quotation And Invoice Webpart.aspx";

            //Serial%20No%20AllocationWebPart.aspx
            // string strRelativeUrl = spwWeb.ServerRelativeUrl.ToString() + "/" + "webpartpages/busprocess.aspx";
            SPWebPartCollection wpcWebParts = spwWeb.GetWebPartCollection(strRelativeUrl, Storage.Shared);

            //http://nos.signin.no/DivAB-12-004587/webpartpages/Delivery%20Ticket%20Report.aspx

            foreach (Microsoft.SharePoint.WebPartPages.WebPart wptWebPart in wpcWebParts) //going through each webpart
            {
                //Console.WriteLine(wptWebPart.Title.ToString());
                //if (wptWebPart.Title == webPartName.ToString()) //comparing webpart name with title
                string str3 = wptWebPart.Title;
                if (wptWebPart.Title == webPartName)
                {
                    PropertyInfo[] pinProperties = wptWebPart.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                    foreach (PropertyInfo pinProperty in pinProperties)
                    {
                        string[] prpname = webpartProprty.Split(','); //Taking webpart property name;
                        string[] val = webpartPropertyValue.Split(',');//Taking webpart property value
                        string strwebpartPropertyValue = webpartPropertyValue.ToString();
                        strwebpartPropertyValue = strwebpartPropertyValue.Remove(strwebpartPropertyValue.Length - 1);

                        int i = 0;

                        foreach (string word in prpname)
                        {
                            //Console.WriteLine(strwebpartPropertyValue.ToString());
                            if (pinProperty.Name == word)
                            {
                                // Console.WriteLine(pinProperty.Name.ToString());

                                //pinProperties.SetValue(wptWebPart,

                                // bool bValue = true;                              
                                //   pinProperty.SetValue(wptWebPart, bValue, null); // setting true or false


                                //pinProperty.SetValue(wptWebPart, val[i], null); //setting  webpart  value
                               
                                pinProperty.SetValue(wptWebPart, strwebpartPropertyValue, null);
                                wpcWebParts.SaveChanges(wptWebPart.StorageKey);//saving changes

                            }
                            i++;
                        }


                    }
                    //if (webPartName == "Ongoing Valve Delivery Process")
                    //{
                    //    wptWebPart.Title = "Ongoing Business Process";
                    //}
                    //if (webPartName == "All Valve Delivery Process")
                    //{
                    //    wptWebPart.Title = "All Business Process";
                    //}
                    //wpcWebParts.SaveChanges(wptWebPart.StorageKey);

                    break;
                }
            }


            spwWeb.AllowUnsafeUpdates = false;
            spwWeb.Dispose();
            spsSite.Dispose();
            //Console.ReadLine();

        }


        #endregion
    }
}

Hide Webpart and Remove it from Quick Launch

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web;
using System.Xml;
using System.Web.UI;
using Microsoft.SharePoint.Navigation;
namespace Solstad_HIdeWebpartandQuickLaunch
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            string ListName = "ListNAme";

            Int32 intStartItmID = 106;
            Int32 intEndItmID = 648;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite("SiteName"))
                {

                    SPWeb web = site.OpenWeb();
                    SPList spList = web.Lists[ListName];
                    SPQuery spQItems = new SPQuery();
                    spQItems.Query = "<Where>   <And>  <Geq>  <FieldRef Name='ID' /><Value Type='Counter'>" + intStartItmID + "</Value> " +
                                   "  </Geq>         <Leq><FieldRef Name='ID' />     <Value Type='Counter'>" + intEndItmID + "</Value>   " +
                                   "  </Leq>               </And>       </Where>";
                    SPListItemCollection items = spList.GetItems(spQItems);
                    if (items.Count > 0)
                    {
                        i = items.Count;
                        foreach (SPListItem item in items)
                        {
                            //string strPropjectType = Convert.ToString(item["Project_x0020_type_x002e_"]);
                            //if (strPropjectType == "General Project")
                            //{
                            string strLink = Convert.ToString(item["Link"]);
                         
                                if (strLink != "")
                                {
                                    try
                                    {
                                        SPFieldUrlValue spfuv = new SPFieldUrlValue(strLink.ToString());

                                        SPSite SubSite = new SPSite(spfuv.Url);
                                        SPWeb subWeb = SubSite.OpenWeb();

                                        /*
                                        Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
                                        mgr = subWeb.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                                        foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
                                        {
                                            if (myWebPart.Title == "IQS_BusinessProcess_ProcessesViewer")
                                            {
                                                myWebPart.Hidden = false;
                                                mgr.SaveChanges(myWebPart);
                                                break;
                                            }
                                            //Business Process

                                        }
                                         */
                                     
                                        int j;
                                        SPNavigationNodeCollection quickLaunchNodes = subWeb.Navigation.QuickLaunch;
                                        foreach (SPNavigationNode node in quickLaunchNodes)
                                        {
                                            //for (int k = 0; k < quickLaunchNodes[0].Children.Count; k++)
                                            //{
                                            SPNavigationNode nn;
                                            try
                                            {
                                                nn = quickLaunchNodes.Navigation.GetNodeById(quickLaunchNodes[0].Children[0].Id);
                                                if (nn.Title.Equals("Contract Life Cycle Process"))
                                                {
                                                    nn.Delete();
                                                }
                                               
                                            }
                                            catch { }
                                            try
                                            {
                                                nn = quickLaunchNodes.Navigation.GetNodeById(quickLaunchNodes[0].Children[1].Id);
                                                if (nn.Title.Equals("Contract Life Cycle Process"))
                                                {
                                                    nn.Delete();
                                                }
                                            }
                                            catch { }
                                            //nn = nodesDemo.Navigation.GetNodeById(nodesDemo[i].Children[j].Id);
                                            //if (node.Title.Equals("QCP Process"))
                                            //{;
                                            //    node.Delete();
                                            //}
                                            //}
                                        }
                                        i = i - 1;
                                       
                                        Console.WriteLine("ID" + Convert.ToString(item["ID"]));
                                        //Console.ReadLine();
                                        //for (j = subWeb.Navigation.QuickLaunch.Count - 1; j > 0; j--)
                                        //{

                                        //    //subWeb.Navigation.QuickLaunch.Delete(subWeb.Navigation.QuickLaunch[i]);
                                        //}
                                    }
                                    catch { }
                                }
                           
                            //}
                           
                        }
                    }
               

                }
            });
        }
     
    }
}

Tuesday, 7 February 2017

SPForm How to get a hidden field value on edit form




We can't directly get the value on edit form. So first we need to add the column in Edit form and on its property window hide them via CSS by setting the Style property in ‘display: none’:




 

SPForm GetCurrentItemID on edit form

//Current web
var currentURL=GetUrlKeyValue('Source');
//Current ItemID
var CurrentItemID=GetUrlKeyValue('ID');

//Lookup field  value
var cmp=fd.field('Company').control()._el().find('select option:selected').text();

Set Value to a SingleLineText Field

fd.field('CompanyName').value(cmp);

How to set read only for field in JSeditor

fd.field('Company').readonly(true);

Friday, 3 February 2017

SPForm Custom fields change function not triggered

fd.field('Project1').control()._el().find('select').change(function() {
  // your code here
});
 
fd.field('Project1').control()._el().find('select option:selected').text();

Rest Form Settings by programmatically

using (SPSite site = new SPSite("SiteURL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList projectGeneral = web.Lists["ListName"];
                    for (int i = 0; i < projectGeneral.Fields.Count;i++ )
                        try
                        {
                            Console.WriteLine(projectGeneral.Fields[i].Title);
                            projectGeneral.Fields[i].ShowInNewForm = null;
                            projectGeneral.Fields[i].ShowInDisplayForm = null;
                            projectGeneral.Fields[i].ShowInEditForm = null;
                            projectGeneral.Fields[i].ShowInViewForms = null;                          
                            projectGeneral.Fields[i].Update();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error  : " + ex.Message);
                        }
                    Console.WriteLine("Press Enter Key");
                    Console.ReadLine();
                }
            }