C# Code Snippets

Sending an email from SharePoint Web Part

Many a times we need to send an email by code from the SharePoint Web Part. The following function shall help you in doing so.

private static void sendEmail(string subject, string Body, string _siteUrl, string _ToEmailAddress)
{
try
{
using (SPSite site = new SPSite(_siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.SendEmail(web, false, false, _ToEmailAddress, subject, Body);
});
}
}
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("PHM Portal Event: ", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}

C# Code Snippets

Function to fetch value from Property Bag

Many a times there is a requirement to allow some values to be configurable. This can be achieved using custom list and an inbuilt option available for this is the Property Bag.

We need to configure the Property Bag in the central admin and the particular site for using it.

The following is the function that assists us to fetch value from the property bag:


public string getProperty(string propertyName)
{
try
{
SPWeb siteCollectionWeb = SPContext.Current.Site.RootWeb;
SPPropertyBag props = siteCollectionWeb.Properties;
Boolean propertyExist = props.ContainsKey(propertyName);
string value = null;
if (propertyExist)
{
value = siteCollectionWeb.AllProperties[propertyName].ToString();
}
value = siteCollectionWeb.AllProperties[propertyName].ToString();
return value;
}
catch (Exception ex)
{
string msg = ex.Message;//LeaveLogFileLocation
TextWriter tw1 = new StreamWriter(getProperty("LeaveLogFileLocation"), true);
tw1.WriteLine("getPropertyEvent : " + DateTime.Now);
tw1.WriteLine(ex.StackTrace);
tw1.Close();
throw ex;
}
}

In order to fetch the values from the Property Bag we just need to call this function by passing the key as the parameter to the function.

Ex: getProperty(“LeaveLogFileLocation”), true)

Here “LeaveLogFileLocation” is the key.

Commands

Some points to be kept in mind while working with Timer Job:

I have been working with timer job since a long time and I have listed some points that one needs to keep in mind while working on it.

The following are some of the points that we need to keep in mind:

  • In order to consume a wcf service in timer job, we need to add an endpoint in the owstimer.exe.config file of the web application.
  • owstimer.exe.config is the config file for timer jobs. It is very similar to the web.config for the web applications.
  • One can declare the global variables for multiple timer jobs over here like one does in the web.config file.
  • The owstimer.exe.config is located at the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN location.
  • It is advisable to save a backup of this file before making any changes to it so that if one messes up the file we can recover it from the backup.
  • The following is the code to be added in the file:

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />
<bindings>
<basicHttpBinding>
<binding name=”BasicHttpBinding_Iapi” closeTimeout=”00:01:00″ openTimeout=”00:01:00″ receiveTimeout=”00:10:00″ sendTimeout=”00:01:00″ allowCookies=”false” bypassProxyOnLocal=”false” hostNameComparisonMode=”StrongWildcard” maxBufferSize=”2147483647″ maxBufferPoolSize=”2147483647″ maxReceivedMessageSize=”2147483647″ messageEncoding=”Text” textEncoding=”utf-8″ transferMode=”Buffered” useDefaultWebProxy=”true”>
<readerQuotas maxDepth=”32″ maxStringContentLength=”8192″ maxArrayLength=”16384″ maxBytesPerRead=”4096″ maxNameTableCharCount=”16384″ />
<security mode=”None”>
<transport clientCredentialType=”None” proxyCredentialType=”None” realm=”” />
<message clientCredentialType=”UserName” algorithmSuite=”Default” />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address=”url” binding=”basicHttpBinding” bindingConfiguration=”BasicHttpBinding_Iapi” contract=”ContractName.Iapi” name=”BasicHttpBinding_Iapi” />
<endpoint address=”url” binding=”basicHttpBinding” bindingConfiguration=”BasicHttpBinding_Iapi” contract=”WCFServiceReference.Iapi” name=”BasicHttpBinding_Iapi” />
</client>
</system.serviceModel>

  • Add theĀ <system.serviceModel> tag after the <runtime>.
  • Here contract name is the name of the namespace that is obtained from the app.config file of the timer job.
  • In order to add multiple end points, add the tag as per requirement.
  • Always set the scope to Web Application.
  • Many a times during the deployment we encounter an error where we are told to force the deployment. For that we need to add the AlwaysForceInstall=”TRUE” in Manifest.xml file
  • The file looks something like the one shown below:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Feature xmlns=”http://schemas.microsoft.com/sharepoint/&#8221;
AlwaysForceInstall=”TRUE” >
</Feature>

 

 

Commands

Get User Details from User Profile Service Application

The following code helps us to get the required data from the User Profile Service Application programmatically.

SPServiceContext serviceContext = SPServiceContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(serviceContext);

UserProfile profile = profileManager.GetUserProfile(currentLoggedinUser);

UserProfile currentUserProfile = profileManager.GetUserProfile(System.Web.HttpContext.Current.User.Identity.Name);

//Getting Department Name
departmentName = (string)currentUserProfile[“department”].Value.ToString();

//Getting Emp Code (Custom Column)
empCode = Convert.ToInt32(profile[“EmpCode”].Value);