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

How To Add Jquery In sharepoint 2010 Using visual studio

We Know how to add jquery in sharepoint master page using designer but how we add jquery using visual studio.

Using vs 2010 we have two option.
1). Farm Solution
2). Sandbox Solution 

1). Farm Solution
  • Open Visual Studio 2010.
  • Create an "Empty SharePoint Project".
  • Right click on the solution and click on Add =>Sharepoint "Layouts" Mapped Folder.
  • Copy your jquery file in layouts folder.
Now create new Usercontrol. open that control and add your jquery script like

<script language="javascript" type="text/javascript" src="/_layouts/ScriptPath"></script>


Add as much as jquery or css  you like
OK your work is done now create one Element file and add Usercontrol in MasterPage head using delegate control like this

<Control Id="AdditionalPageHead" ControlSrc="~/_controltemplates/path/your usercontrol .ascx"></Control>


Great work now deploy your project and find your jquery in firebug.
This technique is called delegate control how to edit master page using vs.

2). Sandbox Solution

    In sandbox solution there isn't layout folder so how you can add your jquery.
    for sandbox we have to create new documentlibrary which is hidden in sharepoint site.
    we add all our jquery in documentlibrary using module.

    lets start
    first of all add new list defination in your solution you have to select document library as list defination.
  
             <ListInstance Title="JsCode"
                OnQuickLaunch="False"
                TemplateType="101"
                FeatureId="00bfea71-e717-4e80-aa17-d0c71b360101"
                Url="Lists/JsCode"
                Hidden="True"
                Description="JsCode - Contains supporting files ">
             </ListInstance>

  know add new module in your solution and paste all jquery in module

    <Module Name="AddSupportingDocsModule" Url="Lists/JsCode">
     <File Path="AddSupportingDocsModule\Sample.js" Url="Sample.js" />
    </Module>

Done now deploy project and check your jquery in JsCode library.

Now add one Empty Element File and call jquery using customaction using below code

    <CustomAction
     ScriptSrc="~site/Lists/JsCode/yourjs.js"
     Location="ScriptLink"
     Sequence="100"
    >
    </CustomAction>


In this blog we can see both the method that how to add jquery in sharepoint 2010 using vs 2010.

Custom Properties in sharepoint 2010 visual webpart.



We know how to add custom properties in webpart. But is this same in visual webpart. No you have to create some more stuff for generate custom property in visual webpart.

Follow this steps for create custom properties in visual webpart.

  • Open Visual Studio 2010.
  • Create an "Empty SharePoint Project".
  • Right click on the solution and click on Add => New Item.
  • Select "Visual Web Part" template from SharePoint 2010 installed templates.

My visual webpart name is WordToPdf. You can see hole picture of my solution.







Now open wordToPdf.cs file and write following code within WordToPdf class.

        public string _DocLibraryName;
        [WebBrowsable(true),
        WebDisplayName("Document Library Name"),
        WebDescription(""),
        Personalizable(true),
        Category("Custom Properties"),
        DefaultValue("")]

        public string _Doclibrary
        {
            get { return _DocLibraryName; }
            set { _DocLibraryName = value; }

        }
Done your custom property added in custom properties group as string.
Now question is how we can get custom property value. So for that open WOrdToPdfUserControl.ascx.cs file and write following code

         public WordToPdf  WebPart { get; set; }  // here WordToPdf is your class name where custom property is defined

         this.WebPart = this.Parent as WordToPdf;
         var _Doclibrary = this.WebPart._Doclibrary;


OK you are able to get custom property value.In this example we only use string if you want to use droupdown list then add following code

       public enum ControlModes
        {
            Simple,
            Standard,
            Advanced
        }
        [DefaultValue(ControlModes.Standard)]
        [Description("Select a category from the dropdown list.")]
        [WebBrowsable(true)]
        [Personalizable()]
        [Category("Custom Properties")]

        public ControlModes ControlMode
        {
            get;
            set;
        }
If you want to add checkbox then use following code

 [DefaultValue(""),
        WebBrowsable(true),
        WebDisplayName("DisplayName"),
        WebDescription(""),
        Personalizable(true),
        Category("Custom Properties"),]
        public bool ch
        {
            get;
            set;
        }

You can also use DateTime and Integer. Hope this will help you
Thanks