Friday, December 19, 2014

Setting Timespan for forms authenticated user in SharePoint

If you want to make user logout after one min of idle status try the below code, this is only for forms authenticated users.
Run the below script in powershell script

$Data = Get-SPSecurityTokenServiceConfig
$Data .UseSessionCookies = $true
$Data .FormsTokenLifetime = (New-Timespan –Minutes 2)
$Data .LogonTokenCacheExpirationWindow = (New-Timespan –Minutes 1)
$Data .Update() 

Enabling session in SharePoint


Error:System.Web.HttpException: Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

When you see the above error try the below resolution
Enable-SPSessionStateService -DefaultProvision

I have tried many solutions that are out there on other site but nothing seems to resolve my issue
finally used powershell command and site came up like magic.

Thursday, December 18, 2014

Important points on OAuth for SharePoint 2013


first and most important point is that OAuth is for apps and not for users in SharePoint
OAuth is Web Standard to manage permissions and security for modules like App on Web
OAuth is used to authenticate and authorize app and service
If you are developing an app on SharePoint online there is no need to create OAuth exclusively, it is integrated with the app by default
If development is done on SharePoint Onprem then we have two options:

1.Create a "high trust" app and deploy it, in this scenario tactically there wont be OAuth because there wont be any Authentication server(ACS) to send and get tokens. this type of method is used for creating internal Apps with in the network.

2.The other way is having an azure account and
   Set up SP2013 with Azure account
   create a certificate for SharePoint 2013
   register it in SharePoint server
the above all process is not so easy which it looks like.

CRUD operations in SharePoint 2013 using REST and C#.Net

Below is CRUD operations on a SharePoint list using Rest and C#
to get this working replace site with your site name
here i am using ContactList for CRUD operations


using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
namespace REST
{
    class Program
    {
        static string sharepointUrl = "http://Site/_api/web/Lists/getByTitle('ContactList')/items";
       public static Stream postStream;
       public static string results;
       public static string newFormDigest;

        static void Main(string[] args)
        {
            GetItems();
            PostItems();
            UpdateItems();
            DeleteItem();

         
        }

        private static void DeleteItem()
        {
             //184 in the below url is Item ID of a list
            Uri uri = new Uri("http://Site/_api/web/lists/GetByTitle('ContactList')/items(184)");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.ContentType = "application/json;odata=verbose";
            request.Headers["X-RequestDigest"] = RequestDigestValue(out postStream, out results, out newFormDigest);
            request.Headers["X-HTTP-Method"] = "DELETE";
            request.Headers["IF-MATCH"] = "*";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept = "application/json;odata=verbose";
            request.Method = "POST";
            request.ContentLength = 0;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
        }

        private static void UpdateItems()
        {
         
            Uri uri = new Uri("http://Site/_api/web/lists/GetByTitle('ContactList')/items(185)");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.ContentType = "application/json;odata=verbose";
            request.Headers["X-RequestDigest"] = RequestDigestValue(out postStream, out results, out newFormDigest);
            request.Headers["X-HTTP-Method"] = "MERGE";
            request.Headers["IF-MATCH"] = "*";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept = "application/json;odata=verbose";
            request.Method = "POST";
            string stringData = "{'__metadata':{'type':'SP.Data.ContactListListItem'}, 'Title':'Jaffa','Street':'Mystreet','City':'Chennai'}";
           // string stringData = "{ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }";
            request.ContentLength = stringData.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(stringData);
            writer.Flush();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
        }
        public Uri WebUri { get; private set; }
        private static void PostItems()
        {
            // 1st request to get the context information

         
            newFormDigest= RequestDigestValue(out postStream, out results, out newFormDigest);

            Uri webUri = new Uri("http://Site/");
       
            var digestRequest = new Uri(webUri, string.Format("/_api/web/lists/getbytitle('{0}')/items", "ContactList"));
            HttpWebRequest spNewRequest = (HttpWebRequest)HttpWebRequest.Create(digestRequest);
            CredentialCache credNewCache = new CredentialCache();

            //credNewCache.Add(new Uri(digestRequest), "NTLM", CredentialCache.DefaultNetworkCredentials);
            credNewCache.Add(digestRequest, "NTLM", CredentialCache.DefaultNetworkCredentials);
            spNewRequest.Credentials = credNewCache;
            spNewRequest.Method = "POST";
            spNewRequest.Accept = "application/json;odata=verbose";
            spNewRequest.ContentType = "application/json;odata=verbose";
            spNewRequest.Headers.Add("X-RequestDigest", newFormDigest);
            string listPostBody = "{'__metadata':{'type':'SP.Data.ContactListListItem'}, 'Title':'MyTitle','Street':'MystreetName','City':'Delhi'}";
   


            // For Content Length

            byte[] postByte = Encoding.UTF8.GetBytes(listPostBody);
            spNewRequest.ContentLength = postByte.Length;
            Stream postStreamBody = spNewRequest.GetRequestStream();
            postStreamBody.Write(postByte, 0, postByte.Length);
            postStreamBody.Close();
            HttpWebResponse webResponse = (HttpWebResponse)spNewRequest.GetResponse();
            results = GetHTTPResponse(webResponse, out postStream, out results);

        }

        private static string RequestDigestValue(out Stream postStream, out string results, out string newFormDigest)
        {
            string formdigestRequest = "http://Site/_api/contextinfo";
            CredentialCache credCache = new CredentialCache();
            credCache.Add(new Uri(formdigestRequest), "NTLM", CredentialCache.DefaultNetworkCredentials);
            HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(formdigestRequest);

            spRequest.Credentials = credCache;
            spRequest.Method = "POST";
            spRequest.Accept = "application/json;odata=verbose";
            spRequest.ContentLength = 0;


            HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();
            results = GetHTTPResponse(endpointResponse, out postStream, out results);



            // Get the FormDigest Value

            var startTag = "FormDigestValue";
            var endTag = "LibraryVersion";
            var startTagIndex = results.IndexOf(startTag) + 1;
            var endTagIndex = results.IndexOf(endTag, startTagIndex);
            newFormDigest = null;
            if ((startTagIndex >= 0) && (endTagIndex > startTagIndex))
            {

                newFormDigest = results.Substring(startTagIndex + startTag.Length + 2, endTagIndex - startTagIndex - startTag.Length - 5);

            }
            return newFormDigest;
        }
        private static String GetHTTPResponse(HttpWebResponse endpointResponse, out  Stream postStream, out  string results)
        {
            postStream = endpointResponse.GetResponseStream();
            StreamReader postReader = new StreamReader(postStream);
            results = postReader.ReadToEnd();
            postReader.Close();
            postStream.Close();
            return results;
        }
        private static void GetItems()
        {
           //Replace "Site" with your site name
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("http://Site/_api/web/Lists/getByTitle('ContactList')/items");

            endpointRequest.Method = "GET";
            endpointRequest.Accept = "application/json;odata=verbose";
            NetworkCredential cred = new System.Net.NetworkCredential("UserName", "Password", "Domain");
            endpointRequest.Credentials = cred;
            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            try
            {
                WebResponse webResponse = endpointRequest.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                JObject jobj = JObject.Parse(response);
                JArray jarr = (JArray)jobj["d"]["results"];

                foreach (JObject j in jarr)
                {
                    //City and County are column names in a list
                    Console.WriteLine(j["City"] + "  " + j["County"]);

                }

                responseReader.Close();
                Console.ReadLine();

            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message); Console.ReadLine();
            }
        }
    }

}

Tuesday, March 11, 2014

1.difference between visual webpart and a standard webpart'
the SharePoint 2010 Visual Web Part is an ASCX web user control that is hosted inside a standard Web Part.

2.Difference between web user control and webpart
user control:
a.User controls must be compiled before use, which adds to the time it takes to load the control.
b.The Visual Web Developer designer provides support for designing the UI by using drag-and-drop operations that gives the control a consistent look-and-feel, which results in faster development.
Webpart:
a.Web Parts are precompiled and ready for use as soon as you need them.
b.The controls in Web Parts must be added by using code.

3.SharePoint site pages vs application pages
Site Pages:- Site Pages are Site or Web Scoped, User can customize Site Pages, Site Pages are stored in Content Database,
You cannot have custom code in Site Pages, Site Pages are Un-ghosted Pages.

Application Page:-
Application Pages are farm scoped, No customization can be done by the user, Application Pages are stored in WFE(Web Front End) in _layouts folder, You can have custom code in your Application Pages, Application Pages are Ghosted Pages.

4.Difference between WFE and application server
Microsoft SharePoint Foundation Web Application makes WFE in SharePoint farm

5.Difference between page library and site library
The Pages library is for storing Publishing Pages whereas the Site Pages library is for storing wiki and web part pages.
You only get the Pages library once the SharePoint Server Publishing feature is activated on the site. This library is usually used when you have requirements for content-centric pages that may use the scheduling, workflow and caching capabilities of SharePoint; such as in the case of public-facing websites. In a more collaborative scenario, you'd want to use the Site Pages library to create wiki and web part pages.

Saturday, March 16, 2013

Sandbox solutions support:

  1. Web parts
  2. Event Receivers
  3. Workflows
  4. List definitions

What is Sandbox solutions and its limitations


Sandbox solution is a new feature introduced in SharePoint 2010. It's a secured wrapper around webparts and other elements with limitations. There is no thumb rule that every webpart in SharePoint 2010 belongs to Sandbox Solution. But it's recommended to develop webparts with Sandbox solution. It allows administrators to monitor the solutions and control as required. SharePoint Site Collection administrators can view the resource utilization of each solution and can block if it consumes too much resources. Usually when sites working slow, developers complain the server is slow whereas site/server administrators blame on Develepor code/solutions. Now Microsoft put a Full Stop to that. :)

Technically speaking SharePoint solutions run in seperate worker processes and not in w3wp.exe. So It doesn't require IIS Reset or Application Pool Recycling. Without disturbing the SharePoint site, Sandbox solutions can be deployed. Only thing while deploying new version of Sandbox solution over existing solution, SharePoint will display No Solution found error in Sandbox Webparts on the page. However within seconds sandbox solutions getting deployed and it'll start working. In SharePoint 2007, only farm administrators can install/deploy developer solutions. But Now site collection administrators can deploy solutions with web based interface. This reduces the dependency of Farm Administrator and improves rapid deployment.

Sandbox Processes
Here the processes which required for Sandbox solutions.
  1. SPUCWorkerprocess.exe - Sandbox Worker process service which is a Seperate Service Application which actually executes Sandbox code. It should be started in every farm to use Sandbox solutions.

  2. SPUCWorkerProcessProxy.exe - Sandbox Worker process proxy which is working as a proxy for Worker process and takes care of Sandbox code execution. It can also serve to other farms if configured. Basically it helps site administrator for load balancing.

  3. SPUCHostService.exe - Sandbox User Code Service takes care of user code in Sandbox amd it can be started in the farms where to use Sandbox solutions.
Sandbox Limitations
As I said before, Sandbox is a secured wrapper and it has restrictions on code to run in SharePoint environment. Few Key limitations which developers should know are listed below.
  1. No Security Elevation - RunWithElevatedPrivileges which runs the specified block of code in application pool account(typically System Account) context is not allowed in Sandbox code. SPSecurity class also not allowed to use in Sandbox.

  2. No Email Support - SPUtility.SendMail method has been blocked explicitly in Sandbox, However .Net mail classes can be used to send mails. Additionaly sandbox won't allow to read Farm SMTP address. So developers has to specify the SMTP address in code itself(may be some other workaround).

  3. No Support to WebPartPages Namespace - Sandbox won't allow to use Microsoft.SharePoint.WebPartPages namespace.

  4. No Support to external Webservice - Internet web service calls are not allowed to ensure security in Sandbox solutions. Allow Partially Trusted code also can't be accessed within Sandbox.

  5. No GAC Deployment - Sandbox solutions are not stored in File System(Physical path) and assemblies can't be deployed to Global Assembly Cache(GAC). But it's available on C:\ProgramData\Microsoft\SharePoint\UCCache at runtime. Note the ProgramData is a hidden folder.

  6. No Visual Webparts - Visual Studio 2010 by default won't allow to create Visual Webparts to deploy as sandbox solution. But with Visual Studio PowerTools extensions(downloadable from Microsoft MSDN website) Visual Webparts can be developed and deployed as sandbox Solutions.
SharePoint Online which is SharePoint environment provided by Microsoft to manage SharePoint Sites in internet accepts only Sandbox solutions. Because SharePoint Online sites are Windows Servers at Microsoft Datacenters, Microsoft won't allow GAC deployment or file system access. In future Sandbox solution will give more features for developers.

SharePoint - Cannot convert a primitive value to the expected type 'Edm.Double'. See the inner exception for more details If y...

Ad