Tuesday 25 November 2014

Setting up Forms Based Authentication for Active Directory

PART 1 – SETTINGS

Three settings are required for the process:
1. The LDAP Path used for Active Directory
2. The name to use for the AD Connection
3. The name to use for the Membership Provider

The LDAP Path

Most important is the Lightweight Directory Access Protocol (LDAP) path – this can be assumed based on the domain – for example, demo.com but should be double checked via the Active Directory management console. LDAP is actually not that complicated – it’s simply a ‘path’ to identify a user, computer, etc. The path is used to identify the specific ‘object’:



For this process, the only thing to be concerned about is the OU and DC’s needed for the connection. Login to the Domain Control and open Active Directory Users and Computers – from there the DC’s (and OU’s) can be determined:


From the example above, the LDAP path is quite simple: dc=gglportmon,dc=com (note, never use spaces). If an Organization Unit (OU) was in use, for example “SPUsers”, it would appear as a folder (like Users shown) and is included in the path, for example ou=SPUsers,dc=gglportmon,dc=com.

The AD Connection

The AD connection is the connection to the LDAP path that will be added to the web.config files for the SharePoint Site – the name is not important but must be consistent across all entries made. In this example, “adconn” is used.

The Membership Provider

The membership provider is simply a name that will be used when setting up a SharePoint Claims Based site. This can be any name though like the AD Connection, it must be consistent. In this example, “admembers” is used.

PART 2 – SETTING UP THE SECURITY TOKEN SERVICE

The Security Token Service (STS) is a specialized Web service that is designed to respond to requests for security tokens and provide identity management. This service is specifically used for trusted claims based authentication and can use simple to complex types of authentication. See the overall background here: http://technet.microsoft.com/en-us/library/ee806864(v=office.14).aspx
For the purposes of setting up “AD based FBA” however, the only changes required are adding entries to the web.config file of the STS Application. While the SPWebConfigModification method should be used, in this example, it is done manually.
First, locate the ‘root’ folder of the STS application; while it is usually in the same place, it should be checked since it may not be. To check this, login to the SharePoint Web Front End (WFE) hosting the SharePoint Central Administration site – once there, open the Internet Information Services (IIS) management console.  Right click on the SharePoint Web Service and select Explore:

By default, this should open the folder< drive>:\Program Files\Common Files\Microsoft Shared\Web Server Extenisons\14\WebServices\SecurityToken:


In this folder is the ‘web.config’ file to be edited (note that by default, the file extension is not shown). Before ANY editing, make a backup of this file (above, a simple zip was created).  Two completely new sections need to be added to this file – the connectionStrings and system.web sections. These are added directly in between the </system.net> end tag and the< /configuration> end tag in the existing file as follows:
      <connectionStrings>
            <add name="adconn"
                   connectionString="
LDAP://gglportmon.com/DC=gglportmon,DC=com" />
      </connectionStrings>
      <system.web>
            <membership defaultProvider="admembers">
                  <providers>
                        <add name="admembers"
                               type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                               connectionStringName="adconn"
                               enableSearchMethods="true"
                               attributeMapUsername="sAMAccountName" />
                  </providers>
            </membership>
      </system.web>

Note that in these entries, the “AD Connection” name (adconn) and the “Membership Provider” name (admembers) are specified. Visually in the file, this should look like this:

Once these changes are made, save and close the file. To double check the service, run IISReset then browse to Central Administration. Use the IIS Management Console to ensure that the SharePoint Web Service site has not stopped – if it has it means an error in the web.config file; double check the entries and in worst case, restore the web.config from the backup and try again.

NOTE: If other sites have different kinds of authentication (FBA, etc.), there MAY ALREADY be <connectionStrings> section - if so, add ONLY the <add name="adconn" INSIDE the section following any others - for example:

<connectionStrings>
   <add name="SQLConnectionString" connectionString="Data Source=MySQL;Initial Catalog=MyFBA;Integrated Security=true;" />


   <add name="adconn" connectionString="LDAP://gglportmon.com/DC=gglportmon,DC=com" />

</connectionStrings>
In addition, there MAY ALREADY be a <system.web> section - in this case, place the place the             <membership defaultProvider="admembers"> entry just before the </system.web> tag after the last </membership> tag in the file.

PART 3 – SETTING UP CENTRAL ADMINISTRATION

Setting up the Central Administration web.config requires three entries; remember that all naming must match for the connection and membership provider; as always, make a backup of the web.config before modifying it.

First Update

The first part to add is the connection string – this is added directly after the </SharePoint> tag:
<connectionStrings>
   <add name="adconn" connectionString="
LDAP://gglportmon.com/DC=gglportmon,DC=com" />
</connectionStrings>

Visually in the file, this should look like this:


NOTE: If other sites have different kinds of authentication (FBA, etc.), there MAY ALREADY be <connectionStrings> section - if so, ONLY add the <add name="adconn" INSIDE the section - for example:
<connectionStrings>
   <add name="SQLConnectionString" connectionString="Data Source=MySQL;Initial Catalog=MyFBA;Integrated Security=true;" />


   <add name="adconn" connectionString="LDAP://gglportmon.com/DC=gglportmon,DC=com" />

</connectionStrings>

Second Update

The next section is to update the “PeoplePicker” section of the web.config – this enables the SharePoint People Picker dialog box to find the AD users via the new connection. In the file search for the “PeoplePickerWildcards” section then under the <clear /> tag, add a new key value:
      <add key="admembers" value="%" />
Visually in the file, this should look like this:


NOTE: Again, there may be other keys included! Be sure to simply add the proper key line as highlighted.

Third Update

The last update is to create the membership section – this will create the actual “provider” and make it accessible for Central Administration. This section updates the existing one in the CA web.config file (located directly below the </roleManager> end tag. By default, this section looks like this:
       < membership>
             < providers>
             < /providers>
       < /membership>

Edit this and add the new provider as shown:
       < membership defaultProvider="admembers">
             < providers>
                    <add name="admembers"
                           type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                           connectionStringName="adconn"
                           enableSearchMethods="true"
                           attributeMapUsername="sAMAccountName" />
             < /providers>
        </membership>

Visually in the file, this should look like this:

Once these changes are made, save and close the file. To double check the service, run IISReset then browse to Central Administration. If there are any problems with the web.config, it will be reported. Double check the entries and try again. Worst case, restore from the backup file and try again.
NOTE: If other sites have different kinds of authentication, there may ALREADY BE providers listed in the <providers> section, if that is the case, you ONLY want to add the provider entry above the </providers> tag:
                    <add name="admembers"
                           type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                           connectionStringName="adconn"
                           enableSearchMethods="true"


                           attributeMapUsername="sAMAccountName" />
Be aware that the name indicated by the "defaultProvider" may be set - you should leave this 'as is' OR if 'admembers' will be the default, change it.
Trouble Shooting:
Depending on the setup, an error may redirect to the default SharePoint error page thus masking what the real issue may be. To properly ‘debug’ the issue it is necessary to enable debugging in SharePoint. In the SharePoint Hive (usually c:\program files\common files\microsoft shared\web server extensions\14, but the installation may be different), open that folder and locate and open the TEMPLATE folder then the LAYOUTS folder. In this folder, there is also a web.config file. Edit this file and locate the< customErrors tag and change the mode from “On” to “Off”:


Run an IISReset then attempt to browse to Central Administration again – this time the full ‘stack trace’ of the error will appear. Any specifics on errors in the web.config file will be displayed.

PART 4 – SETTING UP THE SITE

The next activity is to setup the actual site (through CA) and to modify the web.config of that site to accommodate the AD membership provider.

Creating the new Application – Part 1

Navigate to the Central Administration site then click Manage Web Applications; when there, click New Application. On the New Application page, select Claims Based Authentication then set the Port number the site will run under (set the number then click outside of the box). If desired, specify a different name than the default:

Creating the new Application – Part 2

Scroll down the New Application page to the “Claims Authentication Types” section. For the initial setup, it is recommended that ‘Enable Windows Authentication’ be left checked – when working, this will enable either Windows or FBA to be selected when logging in. When the site has been tested, this can be disabled (see Part 4 below).
Click to select ‘Enable Forms Based Authentication (FBA)’ then under the ASP.NET Membership provider name, enter the name used for updating the web.config files – in this example, ‘admembers’ as shown:

Scroll down to the Sign In Page URL, click the radio button for "Custom Sign In Page" then enter the URL of /_forms/default.aspx. If you do not do this, the default setting will be to "/_login/default.aspx" - this virtual directory points to a common login page (i.e. for ALL sites) located here: c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\identitymodel\login\default.aspx - it is NOT recommended that you modify that login page.
Scroll down and select to create or use an existing application pool then set the Database name as desired (the default will be “WSS_Content” or “WSS_Content_<SiteGuid>”); it is recommended this be done so that the database is easily identified in SQL Server (i.e. “WSS_Content_Site80).
Click OK to create the application. When done, navigate to the “Inetpub” directory – by default, SharePoint sites are created under the folder c:\inetpub\wwwroot\wss\VirutalDirectories\<port number> - in the example above, port 80 was used:

Notice that a folder called _forms is under this folder and the site web.config has been created. The _forms folder is where the site Login Page is stored (called ‘default.aspx’) – this file can be modified to add branding, etc. Note that if this file is modified in a multi-server farm that is already configured, the modified file must be copied to all front end servers. If modified during setup, it will be copied automatically when additional servers are added.

Creating the new Application – Part 3

The next activity is to update the newly created site web.config file. The changes here are similar to those made for the Central Administration web.config.

Updating the Web.confg –Part 1

Make a backup of the web.config in the site folder (under inetpub) then open in an editor. Find the </SharePoint> end tag and add the following between the </SharePoint> and <system.web> tags:
  <connectionStrings>
    <add name="adconn" connectionString="
LDAP://gglportmon.com/DC=gglportmon,DC=com" />
  </connectionStrings>

Visually in the file, this should look like this:

Updating the Web.config – Part 2

The next section is to update the “PeoplePicker” section of the web.config – this enables the SharePoint People Picker dialog box to find the AD users via the new connection. In the file search for the “PeoplePickerWildcards” section then under the <clear /> tag, add a new key value:
      <add key="admembers" value="%" />
Visually in the file, this should look like this:

Updating the Web.config – Part 3

The final change in the web config.is to update the Membership provider section; this section is added when Forms Based Authentication was set when creating the application. In the web.config file, search for the <providers> tag. Under the <add name=”I” line already included, added the following:
        <add name="admembers"
                   type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                   connectionStringName="adconn"
                   enableSearchMethods="true"
                   attributeMapUsername="sAMAccountName" />

Be SURE that the name used (admembers) is the same as was used when creating the application (and added to the other web.config files). Visually in the file, this should look like this:


Creating the new Application – Part 4

Use of Windows Authentication can be removed after the site is operating properly. Disabling this is done by navigating to the Central Administration Site, clicking Manage Web Applications. On the Web Applications page, click to select the site created then in the ribbon click “Authentication Providers”. Click the ‘Default’ link on the popup to open the Web Application page. Scroll down the New Application page to the “Claims Authentication Types” section, uncheck ‘Enable Windows Authentication’ then scroll down to click OK. Opening the site (to show the Login Page), the ‘drop down’ will no longer appear indicating that the site is only using FBA.

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;
}

Thursday 10 April 2014

Changing Site Collection Primary Administrator in SharePoint Using SQL SERVER


If you  want to Change Site Collection Primary administrator Using SQL Server

update [ContentDataBaseName].[dbo].[UserInfo] set tp_Login='Domain\UserName', tp_Title='UserName' where tp_ID=UserID and tp_SiteID='SiteCollectionID'


If you  want to Change Site Collection Secondary administrator Using SQL Server

update [ContentDataBaseName].[dbo].[AllSites] set OwnerID=UserID , SecondaryContactID=UserID where id='SiteCollectionID'

Find User Information In SharePoint Content Data Base using SQL SERVER

****** Script for SelectTopNRows command from SSMS  ******/
SELECT TOP 1000 [tp_SiteID]
      ,[tp_ID]
      ,[tp_DomainGroup]
      ,[tp_SystemID]
      ,[tp_Deleted]
      ,[tp_SiteAdmin]
      ,[tp_IsActive]
      ,[tp_Login]
      ,[tp_Title]
      ,[tp_Email]
      ,[tp_Notes]
      ,[tp_Token]
      ,[tp_ExternalToken]
      ,[tp_ExternalTokenLastUpdated]
      ,[tp_Locale]
      ,[tp_CalendarType]
      ,[tp_AdjustHijriDays]
      ,[tp_TimeZone]
      ,[tp_Time24]
      ,[tp_AltCalendarType]
      ,[tp_CalendarViewOptions]
      ,[tp_WorkDays]
      ,[tp_WorkDayStartHour]
      ,[tp_WorkDayEndHour]
      ,[tp_Mobile]
      ,[tp_Flags]
  FROM [WSS_Content_2010_Solar_Test_181213].[dbo].[UserInfo]