Execute C# code from PowerShell Script – SharePoint Online

Are you looking for an example code to exeucte C# code from PS?

Hope you can get started with the below sample. As per your requirement change the DLL path, Site URL, UserName and Password parameters in the below example.

cls

# C# Source Code
$SourceCode = @”
using System;
using System.Management.Automation;
using System.Security;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;

namespace SPOperations
{
public class SPHelper
{
public static string getWebTitle(string siteUrl, string userName, string sitePassword)
{
using (ClientContext clientContext = new ClientContext(siteUrl))
{
SecureString passWord = new SecureString();
foreach (char c in sitePassword.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
return web.Title;
}
}
}
}
“@

try
{
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase

$TenantConfig = $scriptBase + “\” + “Configs\settings.xml”
$TenantConfigXML = [xml](Get-Content($TenantConfig));

$url = $TenantConfigXML.ConnectionString.Key.URL
$username = $TenantConfigXML.ConnectionString.Key.UserName
$password = $TenantConfigXML.ConnectionString.Key.Password

$assemblies = @(
“$scriptBase\DLL\Microsoft.SharePoint.Client.dll”,
“$scriptBase\DLL\Microsoft.SharePoint.Client.Runtime.dll”
“System.Core”
)
}
catch
{
Write-host “Error while loading the input parameters ” $_.Exception.Message -ForegroundColor Red
exit 1
}

try
{
#Add the Assembly
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $SourceCode -Language CSharp
}
catch
{
Write-host “Error while loading the Referenced Assemblies and Type Definition ” $_.Exception.Message -ForegroundColor Red
exit 1
}

try
{
$siteTitle = [SPOperations.SPHelper]::getWebTitle($url, $username, $password)
Write-Host $siteTitle
}
catch
{
Write-host “Error : ” $_.Exception.Message -ForegroundColor Red
exit 1
}

Display semicolon separated values in ASP.NET Label as new lines

Requirement:

As a part of your daily coding life at times you may have to split the input value with a value and show in newline as a read only value using a Label control.

If you come across this requirement, you can use the below code snippet. In this example I am splitting the input string with semicolon.

If your input value has any html inputs then you have to use Server.HtmlEncode when you bind the data as a new line.

Front End Code

<asp:Label ID=”lbl_PreviousApprover” runat=”server”>

<asp:Repeater ID=”rep_PreviousApprover” runat=”server”>

<ItemTemplate>

<%# Server.HtmlEncode( (string) (Container.DataItem) ) %><br />

</ItemTemplate>

</asp:Repeater>

</asp:Label>

Backend Code

List<string> list_PreviousApprover = new List<string>(((string.IsNullOrEmpty(str_Input) ? string.empty : str_Input).Split(new string[] { “;” }, StringSplitOptions.None)));

if (list_PreviousApprover.Count > 0)

{

for (int list_PreviousApprover_index = 0; list_PreviousApprover_index < list_PreviousApprover.Count; list_PreviousApprover_index++)

{

bool nullOrEmpty = string.IsNullOrEmpty(list_PreviousApprover[list_PreviousApprover_index].Trim());

if (nullOrEmpty)

{

list_PreviousApprover.RemoveAt(list_PreviousApprover_index);

–list_PreviousApprover_index;

}

}

rep_PreviousApprover.DataSource = list_PreviousApprover;

rep_PreviousApprover.DataBind();

}

else

{

lbl_PreviousApprover.Text = “-“;

}

Why do I get Auto-generated Permission Level 64b6593a-75eb-4031-ae23-0048de865fa3 instead of actual permission level name?

Problem

I am trying to create a new group and set a custom permission level(mask number is 196615) to that group with the following web services.

  • AddGroup using usergroup.asmx
  • AddPermission using permissions.asmx

Everything is working fine but the Permission Level name is updated with “Auto-generated Permission Level 64b6593a-75eb-4031-ae23-0048de865fa3” instead of the name I have given while creating the permission level.

I am using the below SOAP

AddPermission

<?xml version=”1.0″ encoding=”utf-16″?>

<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;

<soap:Body>

<AddPermissionxmlns=”http://schemas.microsoft.com/sharepoint/soap/directory/”&gt;

<objectName>Site54</objectName>

<objectType>Web</objectType>

<permissionIdentifier>Site54</permissionIdentifier>

<permissionType>group</permissionType>

<permissionMask>1011028719</permissionMask>

</AddPermission>

</soap:Body>

</soap:Envelope>

If  I assign this custom permission level to a new SharePoint group through SharePoint UI then I am getting the exact name what I gave for the custom permission level. I am facing this issue only when I try to set the permission through web service

I am getting the below XML when I ran the GetPermissionCollectionweb method. Here I am setting my custom permission level to the “Custom Joseph Group“ SharePoint group.

<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;

<soap:Body>

<GetPermissionCollectionResponsexmlns=”http://schemas.microsoft.com/sharepoint/soap/directory/”&gt;

<GetPermissionCollectionResult>

<GetPermissionCollection>

<Permissions>

<Permission MemberID=”2″ Mask=”-1″MemberIsUser=”True” MemberGlobal=”False” UserLogin=”Domain\\joseph” />

<Permission MemberID=”4″ Mask=”138612801″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Viewers” />

<Permission MemberID=”5″ Mask=”134287360″MemberIsUser=”True” MemberGlobal=”False” UserLogin=”NT AUTHORITY\authenticated users” />

<Permission MemberID=”6″ Mask=”-1″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Joseph R&amp;D Works Owners” />

<Permission MemberID=”7″ Mask=”138612833″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Joseph R&amp;D Works Visitors”/>

<Permission MemberID=”8″ Mask=”1006834407″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Joseph R&amp;D Works Members”/>

<Permission MemberID=”10″ Mask=”134287360″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Style Resource Readers” />

<Permission MemberID=”11″ Mask=”1012866047″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Designers” />

<Permission MemberID=”12″ Mask=”2129075183″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Hierarchy Managers” />

<Permission MemberID=”13″ Mask=”1011028991″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Approvers” />

<Permission MemberID=”14″ Mask=”196641″MemberIsUser=”False” MemberGlobal=”True” GroupName=”Restricted Readers” />

<Permission MemberID=”54″ Mask=”134287360″MemberIsUser=”True” MemberGlobal=”False” UserLogin=”Domain\smarappan” />

<Permission MemberID=”94″ Mask=”196615″MemberIsUser=”False” MemberGlobal=”True” GroupName=”WIKI Site Owners” />

<Permission MemberID=”1073741823″Mask=”134287360″ MemberIsUser=”True” MemberGlobal=”False”UserLogin=”SHAREPOINT\system” />

</Permissions>

</GetPermissionCollection>

</GetPermissionCollectionResult>

</GetPermissionCollectionResponse>

</soap:Body>

</soap:Envelope>

Solution 

The following thread has similar issue about this

http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopmentlegacy/thread/e14dfed9-21c4-423d-872b-dc3c03ba8156

The conclusion of the above thread is to create custom web service to fix this issue.

Now I tried setting the role to the SharePoint group using object model APIs. Its working perfectly

Please find the sample code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace CustomPermissionService
{
    class Program
    {
        static void Main(string[] args)
        {

            AddCustomSitePermission("http://ServerName/sites/JRDW/Site54", "WIKI Site Owners", "group", "Custom Joseph");

            AddCustomListPermission("http://ServerName/sites/JRDW/Site54","Domain\\joseph","user", "Custom Joseph", "test");               

        }

        private static void AddCustomListPermission(string siteName, string userAccountOrGroupName, string entityName, string roleName, string listName)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //check site exist or not
                SPSite site = new SPSite(siteName);
                SPWeb web = site.OpenWeb();
                //check list exist or not
                SPList list = web.Lists[listName];
                if (isGroupAlreadyExist(web, userAccountOrGroupName) == true)
                {
                    SPGroup group = site.RootWeb.SiteGroups[userAccountOrGroupName];
                    AddCustomPermissionToList(web, list, group, roleName);

                }
                else if (isUserAlreadyExist(web, userAccountOrGroupName) == true)
                {
                    SPUser user = site.RootWeb.SiteUsers[userAccountOrGroupName];
                    AddCustomPermissionToList(web, list, user, roleName);
                }
                else
                {
                    //throw exception.
                }
            });
        }

        private static void AddCustomSitePermission(string siteName, string userAccountOrGroupName, string entityName, string roleName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //check site exist or not
                SPSite site = new SPSite(siteName);
                SPWeb web = site.OpenWeb();

                if (isGroupAlreadyExist(web, userAccountOrGroupName) == true)
                {
                    SPGroup group = site.RootWeb.SiteGroups[userAccountOrGroupName];
                    AddCustomPermissionToSite(web, group, roleName);

                }
                else if (isUserAlreadyExist(web, userAccountOrGroupName) == true)
                {
                    SPUser user = site.RootWeb.SiteUsers[userAccountOrGroupName];
                    AddCustomPermissionToSite(web, user, roleName);
                }
                else
                {
                    //throw exception.
                }

            });
        }

        public static void AddCustomPermissionToSite(SPWeb web, SPPrincipal entity, string roleName)
        {
            SPRoleAssignment roleAssignment = new SPRoleAssignment(entity);
            SPRoleDefinition byType = web.ParentWeb.RoleDefinitions[roleName];
            roleAssignment.RoleDefinitionBindings.Add(byType);
            web.RoleAssignments.Add(roleAssignment);
        }

        public static void AddCustomPermissionToList(SPWeb web, SPList list, SPPrincipal entity, string roleName)
        {
            SPRoleAssignment roleAssignment = new SPRoleAssignment(entity);
            SPRoleDefinition byType = web.ParentWeb.RoleDefinitions[roleName];
            roleAssignment.RoleDefinitionBindings.Add(byType);
            list.RoleAssignments.Add(roleAssignment);

        }

        public static bool isGroupAlreadyExist(SPWeb web, string groupName)
        {
            bool isExist = false;

            try
            {
                SPGroup group = web.ParentWeb.SiteGroups[groupName];
                isExist = true;
            }
            catch (SPException)
            {
                isExist = false;
            }
            catch (Exception)
            {
                isExist = false;
            }
            return isExist;
        }

        public static bool isUserAlreadyExist(SPWeb web, string loginName)
        {
            bool isExist = false;

            try
            {
                SPUser user = web.ParentWeb.SiteUsers[loginName];
                isExist = true;
            }
            catch (SPException)
            {
                isExist = false;
            }
            catch (Exception)
            {
                isExist = false;
            }
            return isExist;
        }
    }
}

Customizing ListItem Forms Using RenderingTemplates

When you open New/Edit/Display form the rendering template that is displayed by default is ListForm and can be found at SharepointRoot\TEMPLATE\CONTROLTEMPLATES\DefaultTemplates.ascx. Default template shows almost all fields. You can define your own templates depending on your requirement.

How to create Custom Form Template?

  • Open Visual Studio 2010 and create new “Empty SharePoint Project”. Select the site you want to use for debugging and most important select “Deploy as farm Solution” and click Finish.

  • Add New Item “Empty Element” to the Project. We will use this to create Fields. Open Elements.xml file and create fields.

  • Add new “Content Type” and edit “Elements.xml” file. Add the fields declared above.

  • CustomListForm is the id of the custom rendering template that we will create in coming step.
  • Add new Mapped Folder “ControlTemplates” in current project. Add new user control in control templates and name it CustomForm.ascx. Design your form as required.
  • Add new user control to design your new rendering template (CustomTemplates.ascx). Open user control in Source Mode and add the following code

<SharePoint:RenderingTemplate id=”CustomListForm” runat=”server”>

   <Template>

          <span id=’part1′>

                 <SharePoint:InformationBar ID=”InformationBar1″ runat=”server”/>

                 <div id=”listFormToolBarTop”>

                 <wssuc:ToolBar CssClass=”ms-formtoolbar” id=”toolBarTbltop” RightButtonSeparator=”&amp;#160;” runat=”server”>

                               <Template_RightButtons>

                                      <SharePoint:NextPageButton runat=”server”/>

                        <JRDCustomButton:SaveButtonCustom ID=”SaveButtonCustom1″ TemplateName=”SaveButtonCustom”

                            runat=”server” />

                                      <%–<SharePoint:SaveButton runat=”server”/>–%>

                                      <SharePoint:GoBackButton runat=”server”/>

                               </Template_RightButtons>

                 </wssuc:ToolBar>

                 </div>

                 <SharePoint:FormToolBar ID=”FormToolBar1″ runat=”server”/>

                 <SharePoint:ItemValidationFailedMessage ID=”ItemValidationFailedMessage1″ runat=”server”/>

                 <table style=”margin-top: 8px;” border=”0″ cellpadding=”0″ cellspacing=”0″ width=”100%”>

                 <SharePoint:ChangeContentType ID=”ChangeContentType1″ runat=”server”/>

                 <SharePoint:FolderFormFields ID=”FolderFormFields1″ runat=”server”/>

           

            <JRD:Custom ID=”JRDFormNew” runat=”server”></JRD:Custom>

 

                 <%–<SharePoint:ListFieldIterator ID=”ListFieldIterator1″ runat=”server”/>–%>

                 <SharePoint:ApprovalStatus ID=”ApprovalStatus1″ runat=”server”/>

                 <SharePoint:FormComponent ID=”FormComponent1″ TemplateName=”AttachmentRows” runat=”server”/>

                 </table>

                 <table cellpadding=”0″ cellspacing=”0″ width=”100%”><tr><td><img src=”/_layouts/images/blank.gif” width=’1′ height=’1′ alt=”” /></td></tr></table>

                 <table cellpadding=”0″ cellspacing=”0″ width=”100%” style=”padding-top: 7px”><tr><td width=”100%”>

                 <SharePoint:ItemHiddenVersion ID=”ItemHiddenVersion1″ runat=”server”/>

                 <SharePoint:ParentInformationField ID=”ParentInformationField1″ runat=”server”/>

                 <SharePoint:InitContentType ID=”InitContentType1″ runat=”server”/>

                 <wssuc:ToolBar CssClass=”ms-formtoolbar” id=”toolBarTbl” RightButtonSeparator=”&amp;#160;” runat=”server”>

                               <Template_Buttons>

                                      <SharePoint:CreatedModifiedInfo runat=”server”/>

                               </Template_Buttons>

                               <Template_RightButtons>

                    <JRDCustomButton:SaveButtonCustom ID=”SaveButtonCustom2″ TemplateName=”SaveButtonCustom”

                            runat=”server” />

                                      <%–<SharePoint:SaveButton runat=”server”/>–%>

                                      <SharePoint:GoBackButton runat=”server”/>

                               </Template_RightButtons>

                 </wssuc:ToolBar>

                 </td></tr></table>

          </span>

          <SharePoint:AttachmentUpload ID=”AttachmentUpload1″ runat=”server”/>

   </Template>

</SharePoint:RenderingTemplate>

 

<SharePoint:RenderingTemplate ID=”SaveButtonCustom” runat=”server” >

    <Template>

        <table cellpadding=”0″ cellspacing=”0″ width=”100%”>

            <tr>

                <td align=”<SharePoint:EncodedLiteral runat=’server’

                    text='<%$Resources:wss,multipages_direction_right_align_value%>’ EncodeMethod=’HtmlEncode’/>”

                    width=”100%”>

 

                    <asp:Button UseSubmitBehavior=”false” ID=”diidIOSaveItem” CommandName=”SaveItem”

                        Text=”<%$Resources:wss,tb_save%>” AccessKey=”<%$Resources:wss,tb_save_AK%>”

                        target=”_self” runat=”server” />

                       

                </td>

            </tr>

        </table>

    </Template>

</SharePoint:RenderingTemplate>

  •  Here SaveButtonCustom Template is to override the existing button submit
  • See the id of rendering template CustomListForm, its same as we defined in content type.
  • Find the code for the same on the below link

Customizing ListItem Forms Using RenderingTemplates

  • Deploy the project and see it working.

Thank you Pawan Ashish, you helped me a lot to understand this concept.

Passing variable values between Nintex workflows

There may be a requirement to pass certain workflow variables between workflows when you split a larger process into small workflows.

To do this the target workflow can be configured with start data variables. These start data variables can then automatically be populated when the workflow is started through the nintex web service.

Create a new workflow as normal and select Workflow Settings then variables and then create a new variable.

In this example 2 workflow variables were created as start data.

EmpID                   –             Single line of text

LeaveREQ            –             Number

To test starting a workflow with these variables automatically set when the workflow starts using web service method. In this example the StartWorkflowOnListItem method will be used.

The first step is to use a build dynamic string action to create the association Data XML that will be required.

The format for the association data parameter is as follows:

<Data>

<StartDataItem1>value1</StartDataItem1>

<StartDataItem2>value2</StartDataItem2>

<StartDataItem3>value3</StartDataItem3>

</Data>

Based on the workflow we are attempting to start there are 2 start data items EmpID and LeaveREQ.

The association data will be as follows:

<Data>

<EmpID>x067900</EmpID>

<LeaveREQ>4</LeaveREQ>

</Data>

This will set the variable EmpID to x067900 and LeaveREQ to 4.

The best method to use when creating a start data variable is to build the value first using a build dynamic string action

To use this start data within a call web service action the configuration is as follows

Please ensure Encode inserted tokens is selected.

That’s it you are done. Happy Nintexing 🙂

How to configure Incoming Email Enabled Libraries in SharePoint using Exchange Server in an Active Directory Domain

Prior to the release of Exchange Server 2007, Microsoft announced that the future of public folders was in question, and that SharePoint libraries would take their place. Microsoft quickly changed its stance and continues to support Exchange public folders, but there still might be a number of compelling reasons why you would want to consider storing incoming messages in SharePoint document libraries — instead of public folders.

SharePoint can enable incoming mail on lists and libraries. It also offers several out-of-the-box features like Alerts, Enterprise Search and Information Management policies, all of which provide for a richer collaborative experience.

One instance where these features are valuable actually has to do with technical newsletters. Many SharePoint users subscribe to various email-based technical newsletters and forward those messages to team members. Email-enabled document libraries provide a central location to store these newsletters, removing the administrative burden of manually sharing the information with other team members.

This feature also allows users to subscribe to the document library via SharePoint Alerts. These alerts can be set to immediate, daily or weekly summary notifications.

Newsletter subscriptions that are automatically delivered to an email-enabled document library form part of SharePoint’s full-text index. Employees can search this index at a later date using SharePoint’s

Go through the step by step guide

How to configure Incoming Email Enabled Libraries in MOSS 2007 RTM using Exchange Server in an Active Directory Domain

Write data into the web.config file using C#

Some times you may need to allow the end user to update the data into Asp.net or SharePoint web.config file . To do this you must ensure that the Network Service user (or the ASP.NET user on WinServer 2003 or earlier) has modify permissions on your website root folder.

If the permission is not correct you will get the following error:
An error occurred loading a configuration file: Access to the path ‘c:\inetpub\wwwroot\yourwebsitefolder\py39wsfg.tmp’ is denied.

Assuming you have setup the correct permissions this code below will allow your web app to write to the web.config file.

// update the SiteName tag in web.config with a new value
Configuration config = WebConfigurationManager.OpenWebConfiguration(“~”);
config.AppSettings.Settings[“SiteName”].Value = “New Site Name Value”;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);