Tuesday, 8 May 2012

Sharepoint 2010 Find out Current Site access by Anonymous User Using Javascript

 
Using Ecma script we can find out user is logged in sharepoint site or not.
 
 
ExecuteOrDelayUntilScriptLoaded(getWebUserData, "SP.js");

function getWebUserData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
this._currentUser = web.get_currentUser();
context.load(this._currentUser);
context.load(web, 'EffectiveBasePermissions');
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),   Function.createDelegate(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args) {

   // Put your jquery logic for Successfully login
}
function onfaiuremethod(sender, args) {
   alert('Anonymous User');
}
 
You can also get current user details using this code
 
ExecuteOrDelayUntilScriptLoaded(getWebUserData, "SP.js");
function getWebUserData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
var userObject = web.get_currentUser();   
alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());  
}

Create an Event Receiver for a Specific List Instance programmatically

Here we learn how to apply event receiver to list or library programmatically.

1. open vs 2010 

2. New project -> Empty Sharepoint Project 
    Name of your solution project  "AddEventReceiver"



3. Select Farm solution as deployment.And click on Finish.
4. Now add new item Event Receiver Name "DynamicReceiver".


5.Choose List Item Events and custom List with Event you want to add.


 6. After adding event receiver you must remove that from feature so it is not attached to list automatically.



All steps to add receiver is done now just run this code to attach event receiver to list or library.
For that you have to add your dll in gac so simply deploy your project.Now
Go to "run" write assembly in run and click ok. One window open and then find your assembly. In this example find  "AddEventReceiver.dll". Just right click on dll and click on property.
Copy this information.
assembly name and  PublicKeyToken.

Write this code in webpart or appication page to attach event receiver

SPWeb oWeb = SPContext.Current.Web;
string _classname = "AddEventReceiver.DynamicReceiver.DynamicReceiver";
string _assname = "
AddEventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4500d411c00104bb";
                oWeb.Lists["ListName"].EventReceivers.Add(SPEventReceiverType.ItemAdded, _assname, _classname);
                oWeb.Lists["
ListName"].EventReceivers.Add(SPEventReceiverType.ItemUpdated, _assname, _classname);
                oWeb.Lists["
ListName"].EventReceivers.Add(SPEventReceiverType.ItemDeleted, _assname, _classname);

Add,Update,Delete sharepoint list data programmatically


Follow this code to perform insert,Update delete in sharepoint list.

using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
            oSPWeb.AllowUnsafeUpdates = true;
 
            // Fetch the List
            SPList list = oSPWeb.Lists["ListName"];
                   
            //Add a new item in the List
            SPListItem itemToAdd = list.Items.Add();
            itemToAdd["Title"] = "Test Title";
            itemToAdd.Update();
 
            // Get the Item ID
            listItemId = itemToAdd.ID;
 
            // Update the List item by ID
            SPListItem itemToUpdate = list.GetItemById(listItemId);
            itemToUpdate["Title"] = "Changed Title";
            itemToUpdate.Update();
 
            // Delete List item
            SPListItem itemToDelete = list.GetItemById(listItemId);
            itemToDelete.Delete();
 
            oSPWeb.AllowUnsafeUpdates = false;
       }
}

Get sharepoint list data using Javascript

Using Javasctipt Script  getting sharepoint list data


            var clientContext = null;
      var web = null;

      ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");

        function Initialize()
        {
         clientContext = new SP.ClientContext.get_current();
         web = clientContext.get_web();
         this.list = web.get_lists().getByTitle("ListName");
         clientContext.load(list, 'Title', 'Id');
         clientContext.executeQueryAsync(Function.createDelegate(this,        this.onListLoadSuccess),

       Function.createDelegate(this, this.onQueryFailed));
        }

        function onListLoadSuccess(sender, args) {
         alert("List title : " + this.list.get_title() + "; List ID : "+  this.list.get_id());
        }

        function onQueryFailed(sender, args) {
          alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }​


This technique is called client object model using ECMA script

We can also get list data using web-service



$(document).ready(function()
{
    var soapEnv =
        "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
            <soapenv:Body>
                 <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
                    <listName>ListName</listName>
                    <viewFields>
                        <ViewFields>
                           <FieldRef Name='Title' />
                       </ViewFields>
                    </viewFields>
                </GetListItems>
            </soapenv:Body>
        </soapenv:Envelope>";

    $.ajax({
        url: "http://my_site/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset="utf-8""
    });
});

function processResult(xData, status) {
    $(xData.responseXML).find("z\:row").each(function() {
        alert($(this).attr("ows_Title"));

    });
}

Sharepoint 2010 Get list data Different technique

We can access sharepoint list data using
1). Object model
2).Client object model

1). Object model

Using object model get sharepoint list data.

      using(SPSite site = new SPSite(SPContext.Current.Web.Url))
      {

          using (SPWeb _web = site.OpenWeb())
            {

                SPList _list = _web.Lists["ListName"];
                SPListItemCollection collection = _list.Items;
                foreach (SPListItem item in collection)
                {
                        string title =     item["Title"] ;
                }
           }
      }

It is very easy to get data from sharepoint list but only we use in sharepoint environment. what about other?
If we want to use in silverlight application or in console application.
for that we use Client object model.

2).Client Object Model

The Client Object Model is really three separate object models, one for the .NET CLR, one for Silverlight, and one for JavaScript. The .NET CLR version is used to create applications such as WinForms, Windows Presentation Foundation (WPF), and console applications, as well as PowerShell scripts. The Silverlight version works with both in-browser and out-of-browser Silverlight applications. The JavaScript version enables your Ajax and jQuery code to call back to SharePoint.

For client object model u have to add reference  Microsoft.SharePoint.Client.dll
then add reference

using Microsoft.SharePoint.Client;
 
        ClientContext clientContext = new ClientContext("http://ServerName");
        List list = clientContext.Web.Lists.GetByTitle("ListName");
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "<View/>";
        ListItemCollection listItems = list.GetItems(camlQuery);
        clientContext.Load(list);clientContext.Load(listItems);
        clientContext.ExecuteQuery();
        foreach (ListItem listItem in listItems)
            Console.WriteLine("Id: {0} Title: {1}", listItem.Id, oListItem["Title"]); 
   
 For more details on client object model please check this MSDN
 We see this is .net client object model code for getting list data in console application.
 How to get List data using Javascript.

Using Javasctipt ECMA Script for getting sharepoint list data

            var clientContext = null;
      var web = null;

      ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");

        function Initialize()
        {
         clientContext = new SP.ClientContext.get_current();
         web = clientContext.get_web();
         this.list = web.get_lists().getByTitle("ListName");
         clientContext.load(list, 'Title', 'Id');
         clientContext.executeQueryAsync(Function.createDelegate(this,        this.onListLoadSuccess),

       Function.createDelegate(this, this.onQueryFailed));
        }

        function onListLoadSuccess(sender, args) {
         alert("List title : " + this.list.get_title() + "; List ID : "+  this.list.get_id());
        }

        function onQueryFailed(sender, args) {
          alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }​



Create Managed MetaData Service Programmatically

Managed metadata is a hierarchical collection of centrally managed terms that you can define, and then use as attributes for items in Microsoft SharePoint Server 2010.

To create Managed metadata service add one feature receiver and write below code in featureActivate method.

        TaxonomySession oTaxSession;
        TermStore oTermStore;
        Group oTermGroup;
        TermSet oTermSet;
        Term oTerm;
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {


            SPWeb oSite = properties.Feature.Parent as SPWeb;
            oTaxSession = new TaxonomySession(oSite.Site);
            oTermStore = oTaxSession.DefaultSiteCollectionTermStore;

// or  oTermStore = oTaxSession.TermStores["Name of termstore like "Managed Metadata Service""];
            try
            {
                oTermGroup = oTermStore.Groups["New Group"];
            }
            catch (ArgumentOutOfRangeException ex)
            {
                oTermGroup = oTermStore.CreateGroup("New Group");
                oTermGroup.Description = "New Group Description";
            }

            try
            {
                oTermSet = oTermGroup.TermSets["New TermSet"];
            }
            catch (ArgumentOutOfRangeException ex)
            {
                oTermSet = oTermGroup.CreateTermSet("New TermSet");
                oTermSet.Description = "New TermSet Description";
            }

            try
            {
                oTerm = oTermSet.Terms["New Term"];
            }
            catch (ArgumentOutOfRangeException ex)
            {
                oTerm = oTermSet.CreateTerm("New Term", oTermStore.DefaultLanguage);
                oTerm.SetDescription("New Term Description", oTermStore.DefaultLanguage);
                oTerm.CreateLabel("New Term Label", oTermStore.DefaultLanguage, false);
            }

            oTermStore.CommitAll();     
      }
How to use that managed metadata service programmatically?
I am creating one site column with Managed Metadata type. add this code in above method.


bool fieldExists = oSite.Fields.ContainsField("ManagedTest");

            if (!fieldExists)
            {
                SPContentType contentTypeOfficeDetails = oSite.ContentTypes["MyContaintype"];

                TaxonomyField field = oSite.Fields.CreateNewField("TaxonomyFieldType", "ManagedTest") as TaxonomyField;

                field.SspId = oTermSet.TermStore.Id;

                field.TermSetId = oTermSet.Id;

                field.TargetTemplate = string.Empty;

                field.AllowMultipleValues = true;

                field.CreateValuesInEditForm = true;

                field.Open = true;

                field.AnchorId = Guid.Empty;

                field.Group = "Taxonomy Fields";

                //Add the taxonomy field to site columns

                oSite.Fields.Add(field);

                oSite.Update();

            }

Monday, 7 May 2012

Apply custom masterpage in sharepoint 2010 programmatically

It's been very easy to apply master page in sharepoint 2010 using C#

Follow this steps.

Add new sharepoint empty project.
After that Add new feature with feature receiver.


add this code in FeatureActivated method like so

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            //Get Parent Web
            SPWeb Web = properties.Feature.Parent as SPWeb;
            Web.AllowUnsafeUpdates = true;
            string strRelativeURL = (Web.ServerRelativeUrl.EndsWith("/") ? Web.ServerRelativeUrl : Web.ServerRelativeUrl + "/");

            //Apply default and custom masterpage URL
            Web.MasterUrl = strRelativeURL + "_catalogs/masterpage/masterpage.master";
            Web.CustomMasterUrl = strRelativeURL + "_catalogs/masterpage/masterpage.master";

            //Apply the alternate css
            Web.AlternateCssUrl = css path;

            //Confirm the version
            Web.UIVersion = 4;
            Web.Update();
            Web.AllowUnsafeUpdates = false;
      }