Search This Blog

Saturday, December 24, 2016

How to install an App in SharePoint 2013 programmatically using c#

The below method is used to install the app in the sharepoint site programmatically using C#

InstallAppPart("http://sharepoint2013/site/","d:\\SampleApp\TestApp.app")

public void InstallAppPart(string WebURL, string AppFullPath)
{
   Guid appId = Guid.Empty;

    using(site = new SPSite(WebURL))
   {
       using(web = site.OpenWeb())
       {
            Stream package = null;
            try
           {
              //This code is used to start installing the app
              package = File.OpenRead(AppFullPath);
              SPAppInstance appInstance = web.LoadAndInstallApp(package);
              if (appInstance != null && appInstance.Status == SPAppInstanceStatus.Initialized)
             {
                //Your App is started installing now
                 appId = appInstance.Id;
             }
 
           //This code is used to check the app completeley installed in the sharepoint site
          SPAppInstance newAppInstance = null;
          int maxTry = 150;
          int count = 0;
          do
          {
              Thread.Sleep(1000);
              newAppInstance = web.GetAppInstanceById(appId);
              count++;
          }
          while (newAppInstance != null && newAppInstance.Status != SPAppInstanceStatus.Installed             && count  < maxTry);

         if(newAppInstance != null && newAppInstance .Status == SPAppInstanceStatus.Installed)
         {
                  Console.WriteLine("App installation complete. App URL:" +                localInstance.AppWebFullUrl.ToString());
         }
     }
     finally
     {
        if (package != null)
           package.Close();
     }
   }
 }
}

Sunday, December 11, 2016

Create Promoted Links/My Report Library/Asset Library list in SharePoint 2013 using Client Object Model C#

using Microsoft.SharePoint.Client;

//use one of the templateName that suits your purpose
string templateName = "Promoted Links";
string templateName = "Report Library";
string templateName = "Asset Library";
string templateName = "Custom List";

ClientContext ctx = new ClientContext(weburl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

Web web = ctx.Web;

// Get the list template by name
ListTemplate listTemplate = web.ListTemplates.GetByName(templateName);

ctx.Load(listTemplate);
ctx.ExecuteQuery();

// Create a new object for ListCreationInformation class - used to specify the // properties of the new list
ListCreationInformation creationInfo = new ListCreationInformation();

// Specify the title of your List
creationInfo.Title = "My Custom List";

// Specify the list description, if any
creationInfo.Description = "Description";

// Set a value that specifies the feature identifier of the feature 
// that contains the list schema for the new list.
creationInfo.TemplateFeatureId = listTemplate.FeatureId;

// Set a value that specifies the list server template of the new list
creationInfo.TemplateType = listTemplate.ListTemplateTypeKind;

web.Lists.Add(creationInfo);
ctx.ExecuteQuery();

Attach Event Receiver to SharePoint List using CSOM (Client Side Object Model)

using Microsoft.SharePoint.Client;
using System;
using System.Net;
 
private static void AttachEventReceiver()
{
            var userName = "<<UserNameWithoutDomainName>>";
            var password = "<<Password>>";
            string domain = "<<DomainName>>";
            string webUrl = "<<WebUrl>>";
 
            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new NetworkCredential(userName, password, domain);
                var list = context.Web.Lists.GetByTitle("<<ListName>>");
                var eventReceivers = list.EventReceivers;
                context.Load(eventReceivers);
                context.ExecuteQuery();
 
                EventReceiverType eventType = EventReceiverType.ItemUpdated;    //event type (ItemAdded / ItemUpdated)
                string receiverAssembly = "<<FullyQualifiedAssemblyName>>";     //Example: <<AssemblyName>>, Version=<<AssemblyVersion>>, Culture=neutral, PublicKeyToken=<<PublicKeyToken>>
                string receiverClass = "<<ReceiverClassNameStartingWithNamespaceName>>";    //Example: <<NamespaceName>>.<<ClassName>>
                string receiverName = "<<ReceiverName>>";       //you can give any name
 
                bool isEventReceiverAlreadyAssociated = false;
                foreach (var eventReceiver in eventReceivers)
                {
                    if (eventReceiver.EventType == eventType
                            && string.Compare(eventReceiver.ReceiverAssembly, receiverAssembly, StringComparison.OrdinalIgnoreCase) == 0
                            && string.Compare(eventReceiver.ReceiverClass, receiverClass, StringComparison.OrdinalIgnoreCase) == 0
                            && string.Compare(eventReceiver.ReceiverName, receiverName, StringComparison.OrdinalIgnoreCase) == 0
                        )
                    {
                        isEventReceiverAlreadyAssociated = true;
                    }
                }
 
                if (!isEventReceiverAlreadyAssociated)
                {
                    EventReceiverDefinitionCreationInformation eventReceiver
                                       = new EventReceiverDefinitionCreationInformation
                                         {
                                               EventType = eventType,
                                               ReceiverAssembly = receiverAssembly,
                                               ReceiverClass = receiverClass,
                                               ReceiverName = receiverName,
                                          };
 
                    list.EventReceivers.Add(eventReceiver);
                    context.ExecuteQuery();
                }
            }
 }  

Adding Remote Event Receivers To An Exisiting List In Office 365

// This Below method is used to build creation information for the event receiver.

public static EventReceiverDefinitionCreationInformation CreateGenericEventRecieverWithoutEventType()
{
string remoteAppurl = HttpContext.Current.Request["RemoteAppUrl"];
string remoteEventEndPointUrl = String.Format("{0}/ServiceName.svc", remoteAppurl);
EventReceiverDefinitionCreationInformation eventReceiver = new EventReceiverDefinitionCreationInformation();
eventReceiver.ReceiverName = "Give Your Receiver Name";
eventReceiver.ReceiverUrl = remoteEventEndPointUrl;
eventReceiver.SequenceNumber = 5000;
eventReceiver.ReceiverClass = "Fully qualified Path To RER Assembly";
eventReceiver.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName;
return eventReceiver;
}

// The below method is used to check whether the event receiver is already exists in the lists or not

public static bool DoesEventReceiverDefintionExistBasedOnCreationInfo(EventReceiverDefinitionCreationInformation info, List list)
{
bool exists = false;
list.Context.Load(list, x => x.EventReceivers);
list.Context.ExecuteQuery();
foreach (EventReceiverDefinition eventReceiverDefinition in list.EventReceivers)
{
string innerDefId = eventReceiverDefinition.ReceiverClass;
string outerDefId = info.ReceiverClass;
if (innerDefId.Equals(outerDefId, StringComparison.InvariantCultureIgnoreCase))
{
exists = true;
break;
}
}
return exists;
}

// Since the receivers were built without a specific event type, you can specify as many receiver capture behaviors as you want, as demonstrated in the below example.

public static void AttachEventReceiver(ClientContext context, List list)
{
EventReceiverDefinitionCreationInformation eventReceiver =CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemAdded;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
eventReceiver = CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemUpdated;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
eventReceiver = CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemDeleted;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
eventReceiver = CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemFileMoved;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
context.ExecuteQuery();
}

//The below method is used to delete event receivers in the list 

public static void DeleteEventReceiver(ClientContext context, List list)
{
EventReceiverDefinitionCollection eventReceiverDefinitionCollection = list.EventReceivers;
context.Load(eventReceiverDefinitionCollection);
context.ExecuteQuery();
List<Guid> ids = eventReceiverDefinitionCollection.Select(eventReceiverDefinition => eventReceiverDefinition.ReceiverId).ToList();
foreach (EventReceiverDefinition definition in ids.Select(eventReceiverDefinitionCollection.GetById))
{
definition.DeleteObject();
context.ExecuteQuery();
}
}