Friday 30 May 2014

SharePoint Post back to work after clicking on export documents

For use below code in .ascx page automatically post back document download link

<script type="text/javascript" language="javascript">
    //sharepoint postback to work after clicking on export to pdf
    if (typeof (_spBodyOnLoadFunctionNames) != 'undefined' && _spBodyOnLoadFunctionNames != null) {
        _spBodyOnLoadFunctionNames.push("supressSubmitWraper");
    }
    function supressSubmitWraper() {
        _spSuppressFormOnSubmitWrapper = true;
    }
</script>

Wednesday 28 May 2014

Generate .ascx.g.cs file manually for visual webpart

Here are the steps:

Ensure the Project’s, not the Solution’s, “Site URL” is set to a valid SharePoint URL. (Impressive dependency, to regenerate your designer code locally, you need to have a valid working reachable SharePoint url)


Right click on .ascx file, select Properties, and update the property “Custom Tool” to “SharePointWebPartCodeGenerator”.


Right click on the .ascx file and click Run Custom Tool. At this point, if the “SampleWebPart1.ascx.g.cs” is regenerated, your frustration is acceptable.


Open the project.csproj file in Notepad++ or other editor, find the line SampleWebPart1.ascx.g.cs
You should see something like this:


<Content Include=”SampleWebPart\SampleWebPart.ascx”>
<Generator>SharePointWebPartCodeGenerator</Generator><LastGenOutput>SampleWebPart1.ascx.g.cs</LastGenOutput>
</Content>


Change the LastGenOutput value to SampleWebPart.ascx.g.cs


Go back to Visual Studio 2012 and it asks to Reload the project (or Discard). 


Reload the project.


Right click on .ascx file and Run Custom Tool again.


Voila, the 1 is gone and the file should be now called SampleWebPart.ascx.g.cs.

Monday 26 May 2014

Organization Structure in SharePoint using VisualStudio

Create SharePoint Solution In Visual Studio


Add Layout Folder in That solution

Download below files and paste that file into /Layout/Organization/ folder


Create Visual Web part

Add below Code in web part Design page


<script src="../_layouts/15/Organization/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../_layouts/15/Organization/prettify.js" type="text/javascript"></script>
<script src="../_layouts/15/Organization/jquery.jOrgChart.js" type="text/javascript"></script>
<link href="../_layouts/15/Organization/custom.css" rel="stylesheet" type="text/css" />
<link href="../_layouts/15/Organization/jquery.jOrgChart.css" rel="stylesheet"
    type="text/css" />
<link href="../_layouts/15/HRMS.EmployeeManagement/OrganizationalUnit/prettify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    jQuery(document).ready(function () {
        //alert('here');
        $("#org").jOrgChart({
            chartElement: '#chart',
            dragAndDrop: true
        });
    });

    var mynode;
    function fnExpand(node) {
        var image = node.find("img");
        //alert(image);
        //alert(image.attr("src"));
        if (image.attr("src") == '../_layouts/15/images/HRMS.EmployeeManagement/Collapse.png') {
            image.attr("src", '../_layouts/15/images/HRMS.EmployeeManagement/Expand.png')
        }
        else {
            image.attr("src", '../_layouts/15/images/HRMS.EmployeeManagement/Collapse.png')
        }
    }
</script>
<asp:Label ID="lblChartHtml" runat="server" Text=""></asp:Label>
<div id="chart" class="orgChart">
</div>


Add below Code in Webpart Code behind Page

List<SPListItem> listItems = null;

        string childRecords = string.Empty;
        string image = string.Empty;
        string orgDOMstart = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            BuildOrgChart();
        }

        /// <summary>
        /// Method will build the org chart html, which will be used by the JQuery plugin to rendered the org chart UI.
        /// </summary>
        private void BuildOrgChart()
        {

            string orgBody = string.Empty;
            string orgDOMEnd = "</ul></li></ul>";




            string spWebUrl = SPContext.Current.Web.Url;

            //Get the OrgChart list items
            SPSite objSite = SPContext.Current.Site;
            using (SPWeb objWeb = objSite.OpenWeb())
            {
                string Title = objWeb.Title;
                orgDOMstart = "<ul id=\"org\" style=\"display:none\"><li>" + Title + " Chart<ul>";

                var list = objWeb.Lists.TryGetList("Employees");
                listItems = GetListItemsAsList(list.Items);


            }

            //Get tol level nodes(employees), whom managers are not assigned.           
            //var topLevelNodes = listItems.Where(i => ((i["Manager"] == null) ? "" : i["Manager"].ToString()) == "").ToList<SPListItem>();

            var topLevelNodes = listItems.Where(i => ((i["Manager"] == null) ? "" : i["Manager"].ToString()) == "" || GetIdValueFromLookup(i["Manager"]) == Convert.ToString(i["ID"])).ToList<SPListItem>();

            listItems = listItems.Where(i => GetIdValueFromLookup(i["Manager"]) != Convert.ToString(i["ID"])).ToList<SPListItem>();

            foreach (var item in topLevelNodes)
            {
                //For each top node recursively build the html
                GenerateChilRecords(item);
                orgBody = orgBody + childRecords;
                childRecords = string.Empty;
            }

            //Assign the HTML to a Label text.
            lblChartHtml.Text = orgDOMstart + orgBody + orgDOMEnd;
        }

        /// <summary>
        /// Method used to recursively to build the chart html
        /// </summary>
        /// <param name="item"></param>
        private void GenerateChilRecords(SPListItem item)
        {
            //Get the reportees

            var empReportees = listItems.Where(i => GetIdValueFromLookup(i["Manager"]) == Convert.ToString(item["ID"])).ToList<SPListItem>();
            //var empReportees = listItems.Where(i => ((String.IsNullOrEmpty(GetStringValueFromLookup(i["Manager"]))) ? "" : (GetStringValueFromLookup(i["Manager"]))) == (item["Full Name"].ToString())).ToList<SPListItem>();

            //Add the collpase image, if there are any reportess for the employee
            if (empReportees.Count > 0)
            {
                image = "<img class='image' src='../../../_layouts/15/OrgChart/Img/Collapse.png'></img>";
            }

            //childRecords = childRecords + "<li>" + image + "&nbsp;<span style='font-size: .9em'><u>" + item["Employee"] + "</u></span><br><span style='font-size: .8em'>&nbsp;&nbsp;" + item["Designation"] + "</span>";

            childRecords = childRecords + "<li>&nbsp;<span style='font-size: .9em'><u>" + GetStringValueFromLookup(item["Full Name"]) + "</u></span><br><span style='color:black; font-size: .8em'>&nbsp;&nbsp;" + (String.IsNullOrEmpty(Convert.ToString(item["Job_x0020_Roles"])) ? "" : Convert.ToString(item["Job_x0020_Roles"]).Split('#')[1]) + "</span><span style='color:black; font-size: .8em'>&nbsp;&nbsp;" + (String.IsNullOrEmpty(Convert.ToString(item["Org_x0020_Unit"])) ? "" : (", " + Convert.ToString(item["Org_x0020_Unit"]).Split('#')[1])) + "</span>";

            //if there are any reportess for the employee, call the method recursively to check if reportees have any reportess under them.
            if (empReportees.Count > 0)
            {
                childRecords = childRecords + "<ul>";
                foreach (var employee in empReportees)
                {
                    GenerateChilRecords(employee);
                }
                childRecords = childRecords + "</ul></li>";
            }
            else
            {
                childRecords = childRecords + "</li>";
                return;
            }
        }

        /// <summary>
        /// Method returns list of SPListItem, upon which we can use LINQ queries
        /// </summary>
        /// <param name="liCol"></param>
        /// <returns></returns>
        private List<SPListItem> GetListItemsAsList(SPListItemCollection liCol)
        {
            List<SPListItem> toReturn = new List<SPListItem>();
            foreach (SPListItem li in liCol)
            {
                toReturn.Add(li);
            }
            return toReturn;
        }

        public string GetStringValueFromLookup(object lookupValue)
        {
            if (string.IsNullOrEmpty(Convert.ToString(lookupValue))) return string.Empty;
            if (isLookup(lookupValue))
            {
                var value = Convert.ToString(lookupValue).Split(new[] { ";#" }, StringSplitOptions.None)[1];
                return value;
            }
            else
            {
                return Convert.ToString(lookupValue);
            }
        }

        public string GetIdValueFromLookup(object lookupValue)
        {
            if (string.IsNullOrEmpty(Convert.ToString(lookupValue))) return string.Empty;
            if (isLookup(lookupValue))
            {
                var value = Convert.ToString(lookupValue).Split(new[] { ";#" }, StringSplitOptions.None)[0];
                return value;
            }
            else
            {
                return Convert.ToString(lookupValue);
            }
        }

        public bool isLookup(object lookupval)
        {
            bool retflag = false;
            int indexcolon = Convert.ToString(lookupval).IndexOf(';');
            int indexhash = Convert.ToString(lookupval).IndexOf('#');
            int diff = indexhash - indexcolon;
            if (indexcolon > 0 && indexhash > 0 && diff == 1)
                retflag = true;
            return retflag;
        }


In this Code I have Used one list "Employees"
In this List I have Created below fields

Full Name
Manager  ----Look-up of "Full Name"
Job Roles --- Look-up with another list
Org Unit --- Look-up with another list

After Creating List You can Deploy and add  web-part in Site-Page.
It will come  as below

Creating a custom WCF REST service for SharePoint 2013 without a Visual Studio template


  • Create a new SharePoint 2013 Empty Project as a Farm Solution



  • Add a WCF Service Application project to your solution





  • Add the ISAPI mapped folder to your SharePoint project



  • Drag the Service1.svc and Service1.svc.cs files from the WCF project to the SharePoint project under the ISAPI mapped folder


  • Drag the IService1.cs file from the WCF project to the SharePoint project



  • Add the WCF references to your SharePoint project


  1. System.Runtime.Serialization
  2. System.ServiceModel
  3. System.ServiceModel.Web





  • Change the namespace from MyService to your assembly's namespace (e.g., MyRestService) in Service1.svc.cs and IService1.cs



  • Remove a WCF Service Application project to your solution



  • Build your project



  • Using the Visual Studio Command Prompt, go to the project output folder of the SharePoint project


sn -T MyRestService.dll

  • In Service1.svc, change the Service attribute on the ServiceHost directive to be in the following format:
<%@ ServiceHost Language="C#" Debug="true" Service="{NameSpace}.{ServiceName}, {AssemblyName}, Version=1.0.0.0, Culture=Neutral, PublicKeyToken={PublicKeyToken}" CodeBehind="Service1.svc.cs" %>


Replace the tokens here, represented by {Token} with the appropriate values for your project. e.g.,

<%@ ServiceHost Language="C#" Debug="true" Service="MyRestService.Service1, MyRestService, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=099213f2a077836f" CodeBehind="Service1.svc.cs" %>


  • Deploy your solution
  • Verify the service loads
  • Note: see below for troubleshooting a common error.
  • Add a HelloWorld operation to your contract, IService1.cs that is set up for REST.
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "HelloWorld")]
string HelloWorld();


  • Implement the operation in Service1.svc.cs
public string HelloWorld()
{
    return "Hello World";

}

  • Update web.config with the appropriate info for your service
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true">
          </serviceMetadata>
          <serviceDebug includeExceptionDetailInFaults="true">
          </serviceDebug>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="jsonBehaviour">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="MyRestService.Service1" behaviorConfiguration="MyServiceServiceBehavior">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="jsonBehaviour" contract="MyRestService.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
        </endpoint>
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
    </serviceHostingEnvironment>
  </system.serviceModel>

Test your HelloWorld operation and you should see the following:

http://win-0n4jtsv8137/_vti_bin/Service1.svc/HelloWorld



If you want to use multiple services for same solution you can add Service Details in web config file like below


<services> <service name="LeaveManagementSystem.LMSService" behaviorConfiguration="LMSServiceServiceBehavior"> <endpoint address="" binding="webHttpBinding" behaviorConfiguration="jsonBehaviour" contract="LeaveManagementSystem.LMSIService"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"> </endpoint> </service> <service name="MyRestService.Service1" behaviorConfiguration="LMSServiceServiceBehavior"> <endpoint address="" binding="webHttpBinding" behaviorConfiguration="jsonBehaviour" contract="MyRestService.IService1"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"> </endpoint> </service> </services>




  • If you want to pass values through WCF Service

you can write Below code in IService.cs



[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Types")]

List<Types> Types();


[DataContract]
    public class Types
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Title { get; set; }

    }



you can write Below code in Service.svc.cs



List<Types> IService.Types()
        {
            var resultTypes = new List<Types>();
            DataTable dtType = objLMS.GetType();

            resultLeaveTypes = (from DataRow row in dtType.Rows
                                select new Types
                                {
                                    ID = Convert.ToInt32(row["ID"]),
                                    Title = Convert.ToString(row["Title"])

                                }).ToList();

            return resultTypes;

        }

  • If you want to get values From WCF Service

you can write Below code in IService.cs



[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "ApplyforLeave?Leavetype={Leavetype}&FromDate={FromDate}&ToDate={ToDate}&Duration={Duration}&PhoneNumber={PhoneNumber}&Reason={Reason}")]
void ApplyforLeave(Int32 Leavetype, DateTime FromDate, DateTime ToDate, Int32 Duration, String PhoneNumber, String Reason);


you can write Below code in Service.svc.cs


public void ApplyforLeave(int Leavetype, DateTime FromDate, DateTime ToDate, int Duration, string PhoneNumber, string Reason) {
return "Your value is " + Convert.ToString(Leavetype) + " FromDate is " + Convert.ToString(FromDate) + " ToDate is " + Convert.ToString(ToDate) + " Duration is " + Convert.ToString(Duration) + " PhoneNumber is " + PhoneNumber + " Reason is " + Reason;
}