csharp 0Logging.cs

StringExtensions.cs
public static class StringExtensions
{
    /// <summary>
    /// Formats string with the formatting passed in. This is a shortcut to string.Format().
    /// </summary>
    /// <param name="input">The input.</param>
    /// <param name="formatting">The formatting.</param>
    /// <returns>A formatted string.</returns>
    public static string FormatWith(this string input, params object[] formatting)
    {
        return string.Format(input, formatting);
    }

}
NullLogger.cs
/// <summary>
	///     Default logger 
	/// </summary>
	public class NullLogger : ILogger
	{
		public void Debug(string message)
		{
			
		}

		public void Error(string message)
		{
			
		}

		public void Error(string message, Exception exception)
		{
			
		}

		public void Fatal(string message)
		{
			
		}

		public void Fatal(string message, Exception exception)
		{
			
		}

		public void Info(string message)
		{
			
		}

		public void InitializeFor(string loggerName)
		{
			
		}

		public void Warning(string message)
		{
			
		}
	}
LoggingExtensions.cs

	/// <summary>
	/// Extensions to help make logging awesome
	/// </summary>
	public static class LoggingExtensions
	{
		/// <summary>
		/// Concurrent dictionary that ensures only one instance of a logger for a type.
		/// </summary>
		private static readonly Lazy<ConcurrentDictionary<string, ILogger>> _dictionary = new Lazy<ConcurrentDictionary<string, ILogger>>(() => new ConcurrentDictionary<string, ILogger>());

		
		public static ILogger Log<T>(this T type)
		{
			var objectName = typeof(T).FullName;
			return Log(objectName);
		}

		public static ILogger Log(this string objectName)
		{
			return _dictionary.Value.GetOrAdd(objectName, Logging.Log.GetLoggerFor);
		}

		public static void Debug(this ILogger logger, string message, params object[] args)
		{
			logger.Debug(string.Format(message,args));
		}

		public static void Info(this ILogger logger, string message, params object[] args)
		{
			logger.Debug(string.Format(message, args));
		}

		public static void Warning(this ILogger logger, string message, params object[] args)
		{
			logger.Debug(string.Format(message, args));
		}

		public static void Error(this ILogger logger, string message, params object[] args)
		{
			logger.Debug(string.Format(message, args));
		}

		public static void Fatal(this ILogger logger, string message, params object[] args)
		{
			logger.Debug(string.Format(message, args));
		}
	}
Log4NetLogger.cs
using System;
using log4net;
using log4net.Config;

[assembly: XmlConfigurator(Watch = true)]
namespace Some.Namespace {

/// <summary>
/// Log4net logger implementing special ILog class
/// </summary>
public class Log4NetLog : ILog, ILog<Log4NetLog>
{
    private global::log4net.ILog _logger;
    
    public void InitializeFor(string loggerName)
    {
        _logger = LogManager.GetLogger(loggerName);
    }

    public void Debug(string message, params object[] formatting)
    {
        if (_logger.IsDebugEnabled) _logger.DebugFormat(DecorateMessageWithAuditInformation(message), formatting);
    }

    public void Debug(Func<string> message)
    {
        if (_logger.IsDebugEnabled) _logger.Debug(DecorateMessageWithAuditInformation(message.Invoke()));
    }

    public void Info(string message, params object[] formatting)
    {
       if (_logger.IsInfoEnabled) _logger.InfoFormat(DecorateMessageWithAuditInformation(message), formatting);
    }

    public void Info(Func<string> message)
    {
        if (_logger.IsInfoEnabled) _logger.Info(DecorateMessageWithAuditInformation(message.Invoke()));
    }

    public void Warn(string message, params object[] formatting)
    {
       if (_logger.IsWarnEnabled) _logger.WarnFormat(DecorateMessageWithAuditInformation(message), formatting);
    }

    public void Warn(Func<string> message)
    {
        if (_logger.IsWarnEnabled) _logger.Warn(DecorateMessageWithAuditInformation(message.Invoke()));
    }

    public void Error(string message, params object[] formatting)
    {
        // don't need to check for enabled at this level
        _logger.ErrorFormat(DecorateMessageWithAuditInformation(message), formatting);
    }

    public void Error(Func<string> message)
    {
        // don't need to check for enabled at this level
         _logger.Error(DecorateMessageWithAuditInformation(message.Invoke()));
    }

    public void Fatal(string message, params object[] formatting)
    {
        // don't need to check for enabled at this level
        _logger.FatalFormat(DecorateMessageWithAuditInformation(message), formatting);
    }

    public void Fatal(Func<string> message)
    {
        // don't need to check for enabled at this level
        _logger.Fatal(DecorateMessageWithAuditInformation(message.Invoke()));
    }

    public string DecorateMessageWithAuditInformation(string message)
    {
        string currentUserName = ApplicationParameters.GetCurrentUserName();
        if (!string.IsNullOrWhiteSpace(currentUserName))
        {
            return "{0} - {1}".FormatWith(message, currentUserName);
        }

        return message;
    }

}
}
Log.cs
/// <summary>
	/// Logger type initialization
	/// </summary>
	public static class Log
	{
		private static Type _logType = typeof(NullDebugLogger);
		private static ILogger _logger;

		/// <summary>
		/// Sets up logging to be with a certain type
		/// </summary>
		/// <typeparam name="T">The type of ILog for the application to use</typeparam>
		public static void InitializeWith<T>() where T : ILogger, new()
		{
			_logType = typeof(T);
		}

		/// <summary>
		/// Sets up logging to be with a certain instance. The other method is preferred.
		/// </summary>
		/// <param name="loggerType">Type of the logger.</param>
		/// <remarks>This is mostly geared towards testing</remarks>
		public static void InitializeWith(ILogger loggerType)
		{
			_logType = loggerType.GetType();
			_logger = loggerType;
		}

		/// <summary>
		/// Initializes a new instance of a logger for an object.
		/// This should be done only once per object name.
		/// </summary>
		/// <param name="objectName">Name of the object.</param>
		/// <returns>ILog instance for an object if log type has been initialized; otherwise null</returns>
		public static ILogger GetLoggerFor(string objectName)
		{
			var logger = _logger;

			if (_logger == null)
			{
				logger = Activator.CreateInstance(_logType) as ILogger;
				if (logger != null)
				{
					logger.InitializeFor(objectName);
				}
			}

			return logger;
		}
	}
ILogger.cs
public interface ILogger
	{
		void Debug(string message);
		void Error(string message);
		void Error(string message, Exception exception);
		void Fatal(string message);
		void Fatal(string message, Exception exception);
		void Info(string message);
		void InitializeFor(string loggerName);
		void Warning(string message);
	}

	/// <summary>
	///     Ensures a default constructor for the logger type
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public interface ILogger<T> where T : new()
	{
	}
1TheBootStrapRegistration.cs
 Log.InitializeWith<Log4NetLog>();
0Logging.cs
public class SomeClass {

  public void SomeMethod() {
    this.Log().Info("Here is a log message with params which can be in Razor Views as well: '{0}'".FormatWith(typeof(SomeClass).Name));
  }

}

csharp Ashx回应了json POST的身体

Ashx回应了json POST的身体

handler.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace TheHashProject
{
    public class Ajax : IHttpHandler
    {
        private HttpContext context;
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            context.Response.ContentType = "application/json";
            string req = new StreamReader(context.Request.InputStream).ReadToEnd();
            if (!String.IsNullOrEmpty(req))
            {
                JObject jsonRequest = JObject.Parse(req);

                Response(new{name="lupu"});
            }
        }

        public void Response(object obj)
        {
            context.Response.Write(JsonConvert.SerializeObject(obj, Formatting.None).ToString());
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

csharp 一组.NET和SharePoint 2010/2013特定用法的扩展方法的集合

一组.NET和SharePoint 2010/2013特定用法的扩展方法的集合

LS.Utilities.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.HtmlControls;
using LS.Extensions;
using Microsoft.Office.Server.Search.Query;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Workflow;
using TermGroup = Microsoft.SharePoint.Taxonomy.Group;

namespace LS.Utilities
{
	
	public static class Data
	{
		public static string HtmlEncode(string toEncode)
		{
			string encodedString = toEncode;

			encodedString = encodedString.Replace((char)0xff06, '&').Replace((char)0xff02, '"');
			encodedString = HttpContext.Current.Server.HtmlEncode(encodedString);

			encodedString = Regex.Replace(encodedString, @"
				# Match & that is not part of an HTML entity.
				&                  # Match literal &.
				(?!                # But only if it is NOT...
				  \w+;             # an alphanumeric entity,
				| \#[0-9]+;        # or a decimal entity,
				| \#x[0-9A-F]+;    # or a hexadecimal entity.
				)                  # End negative lookahead.",
				"&amp;",
				RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

			return encodedString;
		}

		/// <summary>
		/// Example usage: Utilities.Data.GetHivePath(@"TEMPLATE\FEATURES\BBC.Pitch_Site - Authenticated Site Nintex Workflows\MO_Authenticated Site Workflows\Invite Supplier.nwf")
		/// </summary>			
		public static string GetHivePath(string path)
		{
			return SPUtility.GetVersionedGenericSetupPath(path, 15);
		}

		public static string GetServerFileAsString(string path)
		{
			string output = File.ReadAllText(path);
			return output;
		}

		/// <summary>
		/// Upload a file on a form postback via an HTML file input control
		/// </summary>
		/// <param name="web">The SharePoint SPWeb</param>
		/// <param name="fileName">The destination file name</param>
		/// <param name="folder">The destination folder</param>
		/// <param name="fileInput">The HTML file input form control</param>
		/// <param name="maxFileSize">The maximum allowed file size in bytes</param>
		/// <param name="fileSize">The size of the file that the user attempted to upload</param>
		/// <returns>The URL of the uploaded file if the upload was successful or string.Empty if the file size exceeded maxFileSize</returns>
		public static string UploadFile(SPWeb web, string fileName, string folder, HtmlInputFile fileInput, int maxFileSize, out int fileSize)
		{
			string destUrl = string.Format("{0}/{1}/{2}", web.Url, folder, fileName);
			Stream fStream = fileInput.PostedFile.InputStream;
			byte[] contents = new byte[fStream.Length];
			fStream.Read(contents, 0, (int)fStream.Length);
			fStream.Close();

			fileSize = contents.Length;
			if (fileSize > maxFileSize)
			{
				return string.Empty;
			}

			EnsureParentFolder(web, destUrl);
			web.Files.Add(destUrl, contents, true); // overwrite existing

			if (destUrl.StartsWith("https"))
			{
				return destUrl;
			}
			else
			{
				return destUrl.Replace("http", "https");
			}

		}

		private static string EnsureParentFolder(SPWeb parentSite, string destinUrl)
		{
			destinUrl = parentSite.GetFile(destinUrl).Url;

			int index = destinUrl.LastIndexOf("/");
			string parentFolderUrl = string.Empty;

			if (index > -1)
			{
				parentFolderUrl = destinUrl.Substring(0, index);

				SPFolder parentFolder = parentSite.GetFolder(parentFolderUrl);

				if (!parentFolder.Exists)
				{
					SPFolder currentFolder = parentSite.RootFolder;

					foreach (string folder in parentFolderUrl.Split('/'))
					{
						currentFolder = currentFolder.SubFolders.Add(folder);
					}
				}
			}

			return parentFolderUrl;
		}

		public static string SanitiseFileName(string input)
		{
			return Regex.Replace(input, "[^A-Za-z0-9_-]", "");
		}
	}

	public static class Permissions
	{
		public static void CreatePermissionLevel(SPWeb web, string name, string description, SPBasePermissions basePermissions)
		{
			// Delete existing permission level
			List<SPRoleDefinition> existingPermissionLevels = (from SPRoleDefinition role in web.RoleDefinitions
															   where role.Name == name
															   select role).ToList();

			if (existingPermissionLevels.Count() > 0)
			{
				web.RoleDefinitions.Delete(name);
				web.Update();
			}

			// Create new permission level
			SPRoleDefinition newPermissionLevel = new SPRoleDefinition();
			newPermissionLevel.Name = name;
			newPermissionLevel.Description = description;
			newPermissionLevel.BasePermissions = basePermissions;
			web.RoleDefinitions.Add(newPermissionLevel);
			web.Update();
		}
	}

	public static class Reflection
	{
		public static string GetAssemblyFileVersion(Assembly assembly)
		{
			FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
			return fvi.ProductVersion;
		}
	}

	public static class Taxonomy
	{
		public static void ConnectTaxonomyField(SPSite site, string termGroupName, string termSetName, Guid taxonomyFieldId, Guid taxonomyNoteFieldId)
		{
			if (site.RootWeb.Fields.Contains(taxonomyFieldId))
			{
				TaxonomyField taxonomyField = site.RootWeb.Fields[taxonomyFieldId] as TaxonomyField;

				TaxonomySession session = new TaxonomySession(site);
				TermStore termStore = session.TermStores.FirstOrDefault();

				if (termStore != null)
				{
					Microsoft.SharePoint.Taxonomy.Group group = termStore.Groups.Where(g => g.Name == termGroupName).FirstOrDefault();
					TermSet termSet = group.TermSets.Where(g => g.Name == termSetName).FirstOrDefault();

					// Connect the field to the specified term set
					try
					{
						taxonomyField.SspId = termSet.TermStore.Id;
						taxonomyField.TermSetId = termSet.Id;
						taxonomyField.TargetTemplate = string.Empty;
						taxonomyField.AnchorId = Guid.Empty;
						taxonomyField.TextField = taxonomyNoteFieldId;
						taxonomyField.Open = false;
						taxonomyField.CreateValuesInEditForm = true;
						taxonomyField.Update();
					}
					catch (Exception ex)
					{
						throw ex;
					}
				}
				else
				{
					throw new ApplicationException(string.Format("Term store not found for site {0}", site.Url));
				}
			}
			else
			{
				throw new ArgumentException(string.Format("Field {0} not found in site {1}", taxonomyFieldId, site.Url), "taxonomyFieldId");
			}
		}

		/// <summary>
		/// Get the Term Group in the context of the current site collection
		/// </summary>
		public static TermGroup GetTermGroup(string termGroupName)
		{
			TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
			TermStore store = session.TermStores.FirstOrDefault();
			return store.Groups.FirstOrDefault(g => g.Name == termGroupName);
		}

		/// <summary>
		/// Get the Term Group in the context of the specified site collection
		/// </summary>
		public static TermGroup GetTermGroup(SPSite site, string termGroupName)
		{
			TaxonomySession session = new TaxonomySession(site);
			TermStore store = session.TermStores.FirstOrDefault();
			return store.Groups.FirstOrDefault(g => g.Name == termGroupName);
		}
	}

	public static class User
	{
		public static SPUser GetPeoplePickerUser(ClientPeoplePicker peoplePicker)
		{
			string username = ((PickerEntity)peoplePicker.ResolvedEntities[0]).Key;
			return SPContext.Current.Web.EnsureUser(username);
		}

		public static List<SPUser> GetPeoplePickerUsers(ClientPeoplePicker peoplePicker)
		{
			List<SPUser> users = new List<SPUser>();
			peoplePicker.ResolvedEntities.ForEach<PickerEntity>(p =>
			{
				users.Add(SPContext.Current.Web.EnsureUser(p.Key));
			});
			return users;
		}

		public static bool IsAuthenticatedUser()
		{
			return HttpContext.Current.Request.IsAuthenticated;
		}

		public static bool CheckUserProfileProperty(string loginName, string property, string value)
		{
			SPServiceContext serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);

			UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);

			UserProfile newUserProfile = userProfileMgr.GetUserProfile(loginName);

			string profilePropertyValue = GetUserProfileProperty(newUserProfile, property);

			if (string.Equals(profilePropertyValue, value, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		public static bool CheckUserProfileProperty(UserProfile user, string property, string value)
		{
			string profilePropertyValue = GetUserProfileProperty(user, property);

			if (string.Equals(profilePropertyValue, value, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// Gets the specified userprofile property for the Current User.
		/// </summary>
		/// <param name="profileProperty"></param>
		/// <returns></returns>
		public static string GetCurrentUserProfileProperty(string profileProperty)
		{
			UserProfile currentUserProfile = GetCurrentUserProfile();

			return GetUserProfileProperty(currentUserProfile, profileProperty);
		}

		/// <summary>
		/// Gets the specified user profile property for the specified User Profile
		/// </summary>
		/// <param name="userProfile"></param>
		/// <param name="profileProperty"></param>
		/// <returns></returns>
		public static string GetUserProfileProperty(UserProfile userProfile, string profileProperty)
		{
			var propertyNameObject = userProfile.GetProfileValueCollection(profileProperty).Value;

			if (propertyNameObject != null)
			{
				string profilePropertyString = propertyNameObject.ToString();

				return profilePropertyString;
			}
			else
			{
				return null;
			}

		}

		/// <summary>
		/// Returns the current user's user profile
		/// </summary>
		/// <returns></returns>
		public static UserProfile GetCurrentUserProfile()
		{
			UserProfile currentUserProfile = ProfileLoader.GetProfileLoader().GetUserProfile();

			return currentUserProfile;
		}

		/// <summary>
		/// Gets the login name from the specified email.
		/// </summary>
		/// <param name="userEmail"></param>
		/// <returns></returns>
		public static string DetermineLoginNameFromEmail(string userEmail, string emailManagedProperty, string accountNameManagedProperty, Guid peopleSearchGuid, string[] selectProperties)
		{
			KeywordQuery keywordQuery = new KeywordQuery(SPContext.Current.Site);

			keywordQuery.QueryText = emailManagedProperty + ":" + userEmail;

			//People Search Source Id.
			keywordQuery.SourceId = peopleSearchGuid;

			foreach (string property in selectProperties)
			{
				keywordQuery.SelectProperties.Add(property);
			}

			SearchExecutor searchExecutor = new SearchExecutor();

			ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);

			IEnumerable<ResultTable> resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);

			ResultTable resultTable = resultTables.FirstOrDefault();

			DataTable dataTable = resultTable.Table;

			DataRowCollection rows = dataTable.Rows;

			if (rows.Count > 0)
			{
				return rows[0][accountNameManagedProperty].ToString();
			}

			return null;
		}

		public static string GetUserProfilePropertyWithSearch(SPSite site, string filterPropertyName, string filterPropertyValue, string returnProperty, Guid peopleSearchGuid)
		{
			KeywordQuery keywordQuery = new KeywordQuery(site);

			keywordQuery.QueryText = filterPropertyName + ":" + filterPropertyValue;

			//People Search Source Id.
			keywordQuery.SourceId = peopleSearchGuid;

			string[] selectProperties = { returnProperty };

			foreach (string property in selectProperties)
			{
				keywordQuery.SelectProperties.Add(property);
			}

			SearchExecutor searchExecutor = new SearchExecutor();
			ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
			IEnumerable<ResultTable> resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);
			ResultTable resultTable = resultTables.FirstOrDefault();
			DataTable dataTable = resultTable.Table;
			DataRowCollection rows = dataTable.Rows;

			if (rows.Count > 0)
			{
				return rows[0][returnProperty].ToString();
			}

			return null;
		}

		public static UserProfile GetUserByEmail(SPSite site, string userEmail)
		{
			SPServiceContext svcContext = SPServiceContext.GetContext(site);

			UserProfileManager userProfileManager = new UserProfileManager(svcContext);

			ProfileBase[] searchResults = userProfileManager.Search(userEmail);

			if (searchResults.Length > 0)
			{
				return (UserProfile)searchResults[0];
			}

			return null;
		}

		/// <summary>
		/// Get site owner user token for use in SPSite constructor, i.e. using(SPSite site = new SPSite(url, userToken))
		/// </summary>			
		public static SPUserToken GetSiteOwnerUserToken(string siteUrl)
		{
			SPUserToken tokenWithContext = null;
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite elevatedSite = new SPSite(siteUrl))
				{
					tokenWithContext = elevatedSite.Owner.UserToken;
				}
			});
			return tokenWithContext;
		}
	}

	public static class Workflow
	{
		//public static void AttachWorkflowToSharePoint(SPWeb web, NintexWorkflow workflow)
		//{
		//    //Configure Nintex Workflow on the list
		//    //Read in the workflow package file into byte array
		//    byte[] nwfFile = File.ReadAllBytes(workflow.FilePath);

		//    //Construct Nintex Web Service url
		//    string webServiceUrl = Url.EnsureTrailingSlash(web.Url);
		//    webServiceUrl += "_vti_bin/nintexworkflow/workflow.asmx";

		//    if (workflow.WorkflowType == WorkflowType.Site)
		//    {
		//        AttachWorkflowToSite(web, workflow, nwfFile, webServiceUrl);
		//    }
		//    else
		//    {
		//        AttachWorkflowToLists(web, workflow, nwfFile, webServiceUrl);
		//    }
		//}

		//private static void AttachWorkflowToLists(SPWeb web, NintexWorkflow workflow, byte[] nwfFile, string webServiceUrl)
		//{
		//    NintexWorkflowWS.NintexWorkflowWS service = null;
		//    foreach (var listToDeployTo in workflow.ListAssociations)
		//    {
		//        try
		//        {
		//            //Call the NintexWorkflow Service to publish/save the workflow
		//            if (service == null)
		//            {
		//                service = new NintexWorkflowWS.NintexWorkflowWS();
		//                service.Url = webServiceUrl;
		//                service.Credentials = GetRunTimeCredentials(web);
		//            }

		//            service.PublishFromNWF(nwfFile, listToDeployTo, workflow.Title, true);

		//        }
		//        catch (SoapException sex)
		//        {
		//            //Oh no. No one likes an exception during sex.
		//            if (sex.Message.Contains("A workflow with this name already exists on the site"))
		//            {
		//                Logger.Log(sex);
		//                continue;
		//            }
		//            else
		//            {
		//                Logger.Log(sex);
		//                service.Dispose();
		//                throw sex;
		//            }
		//        }
		//        catch (Exception ex)
		//        {
		//            Logger.Log(ex);
		//            service.Dispose();
		//            throw ex;
		//        }
		//    }

		//    if (service != null)
		//        service.Dispose();
		//}

		//private static void AttachWorkflowToSite(SPWeb web, NintexWorkflow workflow, byte[] nwfFile, string webServiceUrl)
		//{
		//    NintexWorkflowWS.NintexWorkflowWS service = null;
		//    try
		//    {
		//        //Call the NintexWorkflow Service to publish/save the workflow
		//        service = new NintexWorkflowWS.NintexWorkflowWS();
		//        service.Url = webServiceUrl;
		//        service.Credentials = GetRunTimeCredentials(web);

		//        service.PublishFromNWF(nwfFile, null, workflow.Title, true);

		//    }
		//    catch (SoapException sex)
		//    {
		//        if (sex.Message.Contains("A workflow with this name already exists on the site"))
		//        {
		//            Logger.Log(sex);
		//        }
		//        else
		//        {
		//            Logger.Log(sex);
		//            throw sex;
		//        }
		//    }
		//    catch (Exception ex)
		//    {
		//        Logger.Log(ex);
		//        throw ex;
		//    }
		//    finally
		//    {
		//        if (service != null)
		//            service.Dispose();
		//    }
		//}

		//private static System.Net.ICredentials GetRunTimeCredentials(SPWeb web)
		//{
		//    Nintex.Workflow.WorkflowConstantCollection constants = Nintex.Workflow.WorkflowConstantCollection.GetWorkflowConstants(web.ID, web.Site.ID);
		//    Nintex.Workflow.CredentialValue credValue = constants.GetCredential(Constants.NintexWorkflowConstants.WebServiceCredentials);

		//    if (credValue == null)
		//        throw new ArgumentOutOfRangeException("Nintex Credential Constant Name", string.Format("Could not find a workflow constant called '{0}'.", Constants.NintexWorkflowConstants.WebServiceCredentials));

		//    return (credValue.Username.IndexOf("\\") > 0) ? new NetworkCredential(credValue.Username.Substring(credValue.Username.IndexOf("\\") + 1), credValue.Password, credValue.Username.Substring(0, credValue.Username.IndexOf("\\"))) :
		//        new NetworkCredential(credValue.Username, credValue.Password);
		//}

		public static void RemoveWorkflowAssociationFromListByName(SPList list, string workFlowNameToRemove)
		{
			if (list == null)
				throw new ArgumentNullException("list");
			if (string.IsNullOrEmpty(workFlowNameToRemove))
				throw new ArgumentNullException("workFlowNameToRemove");
			list.ParentWeb.AllowUnsafeUpdates = true;
			SPWorkflowAssociation workflowAssociation = list.WorkflowAssociations.GetAssociationByName(workFlowNameToRemove, CultureInfo.CurrentCulture);
			list.WorkflowAssociations.Remove(workflowAssociation);
			list.ParentWeb.AllowUnsafeUpdates = false;
		}

		public static SPWorkflowAssociation GetWebWorkflowAssociation(SPWeb web, string associationName)
		{
			if (web == null)
				throw new ArgumentNullException("web");
			if (string.IsNullOrEmpty(associationName))
				throw new ArgumentNullException("associationName");
			return web.WorkflowAssociations.GetAssociationByName(associationName, CultureInfo.CurrentCulture);
		}

		public static SPWorkflowAssociation GetListWorkflowAssociation(SPWeb web, string listName, string associationName)
		{
			if (web == null)
				throw new ArgumentNullException("web");
			if (string.IsNullOrEmpty(listName))
				throw new ArgumentNullException("listName");
			if (string.IsNullOrEmpty(associationName))
				throw new ArgumentNullException("associationName");
			return web.Lists[listName].WorkflowAssociations.GetAssociationByName(associationName, CultureInfo.CurrentCulture);
		}

		public static SPWorkflow StartWorkflow(SPSite site, Object objectContext, SPWorkflowAssociation workflowAssociation, string eventData, SPWorkflowRunOptions sPWorkflowRunOptions)
		{
			if (site == null)
				throw new ArgumentNullException("site");
			if (workflowAssociation == null)
				throw new ArgumentNullException("workflowAssociation");
			return site.WorkflowManager.StartWorkflow(objectContext, workflowAssociation, eventData, sPWorkflowRunOptions);
		}
	}

	public static class DateTimeUtilities
	{
		/// <summary>
		/// SharePoint stores its datetime fields in UTC time. The UI corrects datetime values according to local time.
		/// If working with search, you need to correct the datetime fields with the UTC offset you have locally.
		/// </summary>
		/// <param name="dueDate"></param>
		/// <returns></returns>
		public static DateTime GetDateWithOffSet(string dueDate)
		{
			//http://itblog.wolthaus.net/2011/09/sharepoint-stores-dates-in-utc-time/

			//KPI DueDate without Day Light Savings Offset
			DateTime kpiDueDateWithoutOffset = DateTime.ParseExact(dueDate, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

			DateTimeOffset currentOffset = new DateTimeOffset(kpiDueDateWithoutOffset);

			//KPI DueDate.
			DateTime kpiDueDate = kpiDueDateWithoutOffset.AddHours(currentOffset.Offset.Hours).AddMinutes(currentOffset.Offset.Minutes);

			return kpiDueDate;
		}

		public static DateTime ParseDateString(string date)
		{
			// "InvariantCulture is guaranteed to always exist on any machine and will always convert and parse back to the same values. CurrentCulture is the culture of the current thread. This can vary.." http://stackoverflow.com/a/14194950
			return DateTime.ParseExact(date, Format.DateFormat, CultureInfo.InvariantCulture);
		}
	}

	public static class Request
	{
		public static void RefreshPage()
		{
			HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString());
		}

		public static void RedirectToHomePage()
		{
			HttpContext.Current.Response.Redirect(SPContext.Current.Web.Url, true);
		}
	}

	public static class Lists
	{
		/// <summary>
		/// Returns the List instance based on the relative url
		/// </summary>
		/// <param name="web"></param>
		/// <param name="url"></param>
		/// <returns></returns>
		public static SPList GetList(SPWeb web, string url)
		{
			string sanitizedUrl = Url.EnsureTrailingSlash(web.ServerRelativeUrl);

			return web.GetList(sanitizedUrl + url);
		}

		public static void AddJSLink(SPSite site, string listName, string formName, string jsLinkUrl)
		{
			SPWeb web = site.RootWeb;
			SPFile file = web.GetFile(string.Format("Lists/{0}/{1}", listName, formName));

			file.CheckOut();
			using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
			{
				ListFormWebPart wp = wpm.WebParts[0] as ListFormWebPart;
				if (wp != null)
				{
					wp.JSLink = jsLinkUrl;
					wpm.SaveChanges(wp);
				}
			}
			file.CheckIn("Added JSLink to webpart");

		}
	}

	public static class Claims
	{

		public static SPClaim CreateClaimUpn(string type, string userPrincipalName, string claimsProviderIdentifier)
		{
			return new SPClaim(type,
								userPrincipalName,
								ClaimValueTypes.String,
								SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, claimsProviderIdentifier));

		}

		public static string GetEncodedClaimUpn(string type, string userPrincipleName)
		{
			string result = string.Empty;
			if (SPClaimProviderManager.Local != null)
			{
				SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
				SPClaim claim = CreateClaimUpn(type, userPrincipleName, claimMgr.TrustedClaimProviders.FirstOrDefault().Name);
				result = claimMgr.EncodeClaim(claim);
			}
			return result;
		}

		public static string GetEncodedClaim(string claimType, string claimValue, string claimValueDataType, string providerName)
		{
			SPClaimProviderManager claimMgr = GetClaimProviderManager();

			SPClaim claim = new SPClaim(claimType, claimValue, claimValueDataType, GetOriginalIssuer(providerName));

			string encodedClaim = claimMgr.EncodeClaim(claim);

			return encodedClaim;
		}

		internal static SPClaimProviderManager GetClaimProviderManager()
		{
			SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;

			if (claimMgr != null)
			{
				return claimMgr;
			}
			else
			{
				throw new Exception("Claim Provider Manager is null");
			}
		}

		internal static string GetOriginalIssuer(string providerName)
		{
			return SPOriginalIssuers.Format(SPOriginalIssuerType.ClaimProvider, providerName);
		}
	}

	public static class Url
	{
		/// <summary>
		/// Ensures that there is a "/" at the end of the url provided 
		/// </summary>
		/// <param name="url">The url to check</param>
		/// <returns></returns>
		public static string EnsureTrailingSlash(string url)
		{
			if (!url.EndsWith("/"))
			{
				return url += "/";
			}
			else
			{
				return url;
			}
		}
	}
	

	public static class Format
	{
		public const string DateFormat = "dd/MM/yyyy";
		public const string TimeFormat = "HH:mm";
	}
}

LS.Extensions.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Xml; // requires System.Xml reference
using System.Xml.Linq; // requires System.Xml.Linq reference
using Microsoft.SharePoint; // requires Microsoft.SharePoint reference
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Deployment;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Workflow;

namespace LS.Extensions
{
    public static class ControlExtensions
    {
        /// <summary>
        /// Get all child Control objects recursively as a flat generic List
        /// </summary>
        public static List<Control> GetRecursive(this ControlCollection controls)
        {
            var controlList = new List<Control>();
            return GetRecursive(controls, controlList).ToList();
        }

        private static List<Control> GetRecursive(this ControlCollection controls, List<Control> controlList)
        {
            controls.ForEach<Control>(c =>
            {
                controlList.Add(c);

                if (c.HasControls()) // get children
                    controlList = GetRecursive(c.Controls, controlList);
            });

            return controlList;
        }

        /// <summary>
        /// Add an array of Control objects to a ControlCollection
        /// </summary>
        public static void Add(this ControlCollection controls, Control[] controlsToAdd)
        {
            controlsToAdd.ForEach<Control>(c =>
            {
                controls.Add(c);
            });
        }
    }

    public static class StringExtensions
    {
        public static string RemoveHtmlTags(this string input)
        {
            char[] array = new char[input.Length];
            int arrayIndex = 0;
            bool inside = false;

            for (int i = 0; i < input.Length; i++)
            {
                char let = input[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }

        public static string ConvertLineBreaksToBR(this string input)
        {
            Regex regex = new Regex(@"\n");
            return regex.Replace(input, "<br />");
        }

        public static string ReplaceIgnoreCase(this string input, string match, string replacement)
        {
            return Regex.Replace(input, match, replacement, RegexOptions.IgnoreCase);
        }

        public static string GetCharacters(this string text, int characters)
        {
            return text.Length <= characters ? text : text.Substring(0, characters);
        }
    }

    public static class GenericMethods
    {
        /// <summary>
        /// Returns a generic list of object property values that match the supplied type
        /// </summary>
        /// <typeparam name="T">The type of property values to return</typeparam>        
        /// <returns>A generic list of property values that match the supplied type</returns>
        public static List<T> GetPropertiesOfType<T>(this Object classInstance)
        {
            return classInstance.GetType()
                .GetProperties()
                .Where(p => p.PropertyType == typeof(T)) // filter by type
                .Select(p => p.GetValue(classInstance, null)) // get values
                .Cast<T>() // cast to appropriate type
                .ToList(); // output as List<T>
        }

        /// <summary>
        /// Return true if the collection contains an element matching the predicate, otherwise return false
        /// </summary>        
        public static bool Contains<T>(this IEnumerable collection, Func<T, bool> predicate)
        {
            return collection.Cast<T>().Any(predicate);
        }

        /// <summary>
        /// Cast the collection to a generic List and perform the supplied action on each item in the list.
        /// </summary>        
        public static void ForEach<T>(this IEnumerable collection, Action<T> action)
        {
            collection.Cast<T>().ToList().ForEach(action);
        }

        public static void ReverseForEach<T>(this IEnumerable collection, Action<T> action)
        {
            var list = collection.Cast<T>().ToList();
            for (int i = list.Count - 1; i >= 0; i--)
            {
                var item = list[i];
                action(item);
            }
        }
    }

    public static class SharePointMethods
    {
        #region Taxonomy
        public static TermSet GetTermSet(this TermSetCollection termSets, string termSetName)
        {
            return termSets.FirstOrDefault(t => t.Name == termSetName);
        }
        #endregion

        #region SPWorkflowCollection methods
        /// <summary>
        /// Cancel all workflows in the SPWorkflowCollection.
        /// </summary>        
        public static void CancelWorkflows(this SPWorkflowCollection wfs)
        {
            foreach (SPWorkflow w in wfs)
                SPWorkflowManager.CancelWorkflow(w);
            //wfs.ForEach<SPWorkflow>(w => SPWorkflowManager.CancelWorkflow(w));
        }
        #endregion

        #region SPLimitedWebPartCollection methods
        /// <summary>
        /// Get the first web part from the collection that matches the supplied typeName
        /// </summary>        
        public static WebPart GetWebPartByTypeName(this SPLimitedWebPartCollection webParts, string typeName)
        {
            return webParts.Cast<WebPart>().Where(w => w.GetType().ToString().Contains(typeName)).SingleOrDefault();
        }

        /// <summary>
        /// Get all web parts from the collection that match the supplied typeName
        /// </summary>        
        public static List<WebPart> GetWebPartsByTypeName(this SPLimitedWebPartCollection webParts, string typeName)
        {
            return webParts.Cast<WebPart>().Where(w => w.GetType().ToString().Contains(typeName)).ToList();
        }
        #endregion

        #region ContentEditorWebPart methods
        /// <summary>
        /// Sets the HTML contents of a ContentEditorWebPart. In order to persist these changes, don't forget to either call 'SaveChanges(cewp)' on the SPLimitedWebPartManager instance (for an existing CEWP) or 'AddWebPart(cewp, [zone], [index])' (for a new CEWP).
        /// </summary>
        /// <param name="cewp"></param>
        /// <param name="contents"></param>
        public static void SetContents(this ContentEditorWebPart cewp, string contents)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement xmlElement = xmlDoc.CreateElement("Root");
            xmlElement.InnerText = contents;
            cewp.Content = xmlElement;
            cewp.Content.InnerText = xmlElement.InnerText;
        }
        #endregion

        #region SPWorkflowAssociation methods
        /// <summary>
        /// Remove all workflow associations from the collection.
        /// </summary>        
        public static void RemoveAll(this SPWorkflowAssociationCollection wfc)
        {
            while (wfc.Count > 0)
                wfc.Remove(wfc[0]);
            //wfc.ForEach<SPWorkflowAssociation>(w => wfc.Remove(w));
        }
        #endregion

        #region SPContentType methods
        /// <summary>
        /// Remove all workflow associations from all content types in the content type collection.
        /// </summary>
        /// <param name="contentTypes"></param>
        public static void RemoveWorkflowAssociations(this SPContentTypeCollection cts)
        {
            foreach (SPContentType ct in cts)
                ct.WorkflowAssociations.RemoveAll();
            //cts.ForEach<SPContentType>(c => c.WorkflowAssociations.RemoveAll());
        }
        #endregion

        #region SPRoleAssignmentCollection methods
        /// <summary>
        /// Remove all role assignments from the collection (does not break role inheritance first).
        /// </summary>        
        public static void RemoveAll(this SPRoleAssignmentCollection roles)
        {
            while (roles.Count > 0)
                roles.Remove(0);
        }

        /// <summary>
        /// Remove all role assignments from the collection (optionally break role inheritance first).
        /// </summary>        
        public static void RemoveAll(this SPRoleAssignmentCollection roles, bool breakRoleInheritance)
        {
            if (breakRoleInheritance)
            {
                SPSecurableObject parent = roles.ParentSecurableObject;
                if (parent is SPWeb)
                {
                    if (!((SPWeb)parent).IsRootWeb)
                    {
                        parent.BreakRoleInheritance(false);
                        roles.RemoveAll();
                    }
                }
                else
                {
                    parent.BreakRoleInheritance(false);
                    roles.RemoveAll();
                }
            }
        }
        #endregion

        #region SPList methods
        /// <summary>
        /// Delete WorkflowStatus fields from the list. 
        /// </summary>        
        public static void RemoveWorkflowFields(this SPList list)
        {
            List<SPField> wfFields = list.Fields.Cast<SPField>().Where(f => f.Type == SPFieldType.WorkflowStatus).ToList();
            wfFields.ForEach(f =>
            {
                f.ReadOnlyField = false;
                f.Update(true);
                f.Delete();
            });
        }

        /// <summary>
        /// Delete WorkflowStatus fields from the list that match a predicate (such as field name). For example: list.RemoveWorkflowFields(f => f.Title == "SomeFieldTitle");
        /// </summary>        
        public static void RemoveWorkflowFields(this SPList list, Func<SPField, bool> predicate)
        {
            List<SPField> wfFields = list.Fields.Cast<SPField>().Where(f => f.Type == SPFieldType.WorkflowStatus).Where(predicate).ToList();
            wfFields.ForEach(f =>
            {
                f.ReadOnlyField = false;
                f.Update(true);
                f.Delete();
            });
        }

        public static void EnsurePermissions(this SPList list, string groupName, string[] permissionLevels, SPPrincipal owner)
        {
            if (!list.HasUniqueRoleAssignments)
            {
                list.BreakRoleInheritance(false);
                list.RoleAssignments.RemoveAll();
            }

            SPWeb web = list.ParentWeb;
            SPGroup group = web.EnsureGroup(groupName, null);

            // get the role definitions corresponding to the permission level names
            List<SPRoleDefinition> permissionLevelDefinitions = new List<SPRoleDefinition>();
            foreach (string permissionLevel in permissionLevels)
                permissionLevelDefinitions.Add(web.RoleDefinitions[permissionLevel]);

            if (permissionLevelDefinitions.Count > 0)
            {
                // check for existing role assignment for this group on the list
                SPRoleAssignmentCollection roleAssignments = list.RoleAssignments;
                SPRoleAssignment listRoleAssignment = null;
                foreach (SPRoleAssignment roleAssignment in roleAssignments)
                    if (roleAssignment.Member.LoginName == groupName)
                        listRoleAssignment = roleAssignment;

                // create it if necessary
                if (listRoleAssignment == null)
                {
                    listRoleAssignment = new SPRoleAssignment(group);
                    listRoleAssignment.RoleDefinitionBindings.RemoveAll();
                    foreach (SPRoleDefinition def in permissionLevelDefinitions)
                        listRoleAssignment.RoleDefinitionBindings.Add(def);
                    list.RoleAssignments.Add(listRoleAssignment);
                }
                else // update if existing
                {
                    listRoleAssignment.RoleDefinitionBindings.RemoveAll();
                    foreach (SPRoleDefinition def in permissionLevelDefinitions)
                        listRoleAssignment.RoleDefinitionBindings.Add(def);
                    listRoleAssignment.Update();
                }
            }

            list.Update();
        }

        /// <summary>
        /// Populate a list from a tab separated values file.
        /// </summary>                
        /// <param name="path">The path to the tab separated values file.</param>
        /// <param name="uniqueField">The 'index' field in the list in which all items have a unique value (required)</param>
        public static void PopulateFromTabSeparatedValues(this SPList list, string path, string uniqueField)
        {
            SPQuery query = new SPQuery(); // get list item collection without loading items
            query.RowLimit = 0;
            SPListItemCollection items = list.GetItems(query);

            // get fields from first line of file
            List<string> fields = GetFields(path);

            // create items if they don't already exist, based on one unique identifying column
            CreateItems(items, fields, uniqueField, path);
        }

        /// <summary>
        /// Get a list of field names from the headers of a tab separated values file
        /// </summary>
        /// <param name="path">The location of the file</param>
        /// <returns>A generic list of field names</returns>
        private static List<string> GetFields(string path)
        {
            List<string> fields = new List<string>();
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                int lineCount = 0;
                while ((line = sr.ReadLine()) != null && lineCount < 1) // only read the header row
                {
                    char[] delimiters = new char[] { '\t' };
                    string[] parts = line.Split(delimiters, StringSplitOptions.None);
                    for (int i = 0; i < parts.Length; i++)
                    {
                        fields.Add(parts[i]);
                    }
                    lineCount++;
                }
            }

            return fields;
        }

        /// <summary>
        /// Create list items based on a tab separated values file rows, if they don't already exist
        /// </summary>
        /// <param name="items">The item collection to populate</param>
        /// <param name="fields">The field names to populate, based on the headers of the tab separated values file</param>
        /// <param name="uniqueField">The internal name of the field that should only contain unique values</param>
        /// <param name="fileUrl">The url of the tab separated values file</param>
        private static void CreateItems(SPListItemCollection items, List<string> fields, string uniqueField, string path)
        {
            // add all item unique values to a generic list, for comparison to the tab separated values file
            List<string> itemKeys = new List<string>();
            items.ForEach<SPListItem>(item =>
            {
                string uniqueValue = item[uniqueField] != null ? (string)item[uniqueField] : string.Empty;
                if (uniqueValue != string.Empty)
                    itemKeys.Add(uniqueValue.Trim(new char[] { ' ', '\t' }));
            });

            int indexOfUniqueField = fields.IndexOf(uniqueField);
            if (indexOfUniqueField < 0)
                throw new Exception("Tab separated values file " + path + " does not contain the header " + uniqueField);

            // open the tab separated values file, and create items based on its contents
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                int lineCount = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    if (lineCount > 0) // skip the header row
                    {
                        char[] delimiters = new char[] { '\t' };
                        string[] parts = line.Split(delimiters, StringSplitOptions.None);
                        if (parts.Length != fields.Count)
                            throw new Exception("Error parsing " + path + " - number of headers does not match number of columns for line " + lineCount.ToString() + " - headers:" + fields.Count + ", columns:" + parts.Length);

                        // if the list doesn't contain an item matching this row of the tab separated values file, create the row
                        if (!itemKeys.Contains(parts[indexOfUniqueField].Trim(new char[] { ' ', '\t' })))
                        {
                            SPListItem newItem = items.Add();
                            for (int i = 0; i < parts.Length; i++) // for each value in the row
                            {
                                string fieldName = fields[i];
                                string fieldValue = parts[i];
                                newItem[fieldName] = fieldValue; // set the field value in the list                                
                            }
                            newItem.Update();
                        }
                    }
                    lineCount++;
                }
            }
        }

        /// <summary>
        /// Break role inheritance, remove all role assignments then give Everyone 'Read' access to the list.
        /// </summary>
        public static void SetReadOnlyAllUsers(this SPList list)
        {
            list.BreakRoleInheritance(false);
            list.RoleAssignments.RemoveAll();
            SPWeb web = list.ParentWeb;
            web.AllowUnsafeUpdates = true;
            string permissionLevel = "Read";
            SPUser allAuthenticatedUsers = web.EnsureUser("c:0(.s|true");
            SPRoleAssignment ra = new SPRoleAssignment(allAuthenticatedUsers);
            ra.RoleDefinitionBindings.Add(web.RoleDefinitions[permissionLevel]);
            list.RoleAssignments.Add(ra);
        }

        /// <summary>
        /// Ensures that an SPGroup matching the supplied 'groupName' string exists, and gives members of that group 'Contribute' access to the list (does not break role inheritance first).
        /// </summary>        
        public static void EnsureGroupHasContributeAccess(this SPList list, string groupName, string groupDescription)
        {
            SPWeb web = list.ParentWeb;
            web.AllowUnsafeUpdates = true;
            SPGroup group = web.EnsureGroup(groupName, groupDescription); // ensure that the group exists
            string permissionLevel = "Contribute";
            SPRoleAssignment ra = new SPRoleAssignment(group);
            ra.RoleDefinitionBindings.Add(web.RoleDefinitions[permissionLevel]);
            list.RoleAssignments.Add(ra);
        }

        public static void EnsureField(this SPList list, string internalName, SPFieldType type, bool required)
        {
            list.EnsureField(internalName, type);

            if (required)
            {
                SPField field = list.Fields[internalName];
                field.Required = true;
                field.Update();
            }
        }

        public static void EnsureField(this SPList list, string internalName, SPFieldType type)
        {
            if (!list.Fields.ContainsFieldWithStaticName(internalName))
            {
                SPField field = new SPField(list.Fields, type.ToString(), internalName);
                list.Fields.Add(field);
            }
        }

        public static void EnsureContentType(this SPList list, string contentTypeName, bool removeOtherContentTypes)
        {
            using (SPSite site = new SPSite(list.ParentWeb.Site.RootWeb.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Get content type from site
                    SPContentType webContentType;
                    if (web.ContentTypes.Contains<SPContentType>(c => c.Name == contentTypeName))
                        webContentType = web.ContentTypes[contentTypeName];
                    else
                        throw new Exception("Web does not contain the content type " + contentTypeName);

                    // If list does not contain the content type, add it
                    if (!list.ContentTypes.Contains<SPContentType>(c => c.Name == contentTypeName))
                    {
                        list.ContentTypes.Add(webContentType);
                        list.Update();
                        //web.Update();
                    }

                    // if the list contains other content types that you want to remove...
                    if (removeOtherContentTypes && list.ContentTypes.Count > 1)
                    {
                        // Get content types that don't match the name of the content type you've added
                        List<SPContentType> otherContentTypes = list.ContentTypes.Cast<SPContentType>().Where(c => c.Name != contentTypeName).ToList<SPContentType>();
                        otherContentTypes.ForEach(c => c.Delete()); // delete them
                        list.Update();
                    }
                }
            }
        }

        /// <summary>
        /// Export the list (and its contents) to a location on disk (adapted from http://amitkumarmca04.blogspot.co.uk/2010/10/exportimport-sharepoint-listdocument.html)
        /// </summary>                
        /// <param name="folderPath">The folder path to save the list data to. Data will be saved in a subfolder named according to the Date/Time the export was initiated.</param>
        /// <param name="folderName">The string to store the full export path (including the Date/Time subfolder).</param>        
        public static void Export(this SPList list, string folderPath, ref string folderName)
        {
            SPExportObject exportObj = new SPExportObject();
            exportObj.Id = list.ID;
            exportObj.Type = SPDeploymentObjectType.List;

            SPExportSettings settings = new SPExportSettings();
            settings.SiteUrl = list.ParentWeb.Url;
            settings.ExportMethod = SPExportMethodType.ExportAll;
            folderName = folderPath + "\\" + DateTime.Now.ToString("yyyyMMdd_HHmmss");
            settings.FileLocation = folderName;
            settings.FileCompression = false;
            settings.IncludeSecurity = SPIncludeSecurity.All;
            settings.ExcludeDependencies = true;

            settings.ExportObjects.Add(exportObj);

            SPExport export = new SPExport(settings);
            export.Run();
        }

        /// <summary>
        /// Check if the list contains at least one item that matches the supplied CAML query
        /// </summary>		
        /// <returns>true if one or more items are returned by the query, otherwise false</returns>
        public static bool ContainsItem(this SPList list, string camlQuery)
        {
            SPQuery spQuery = new SPQuery();
            spQuery.Query = camlQuery;
            spQuery.RowLimit = 1;
            spQuery.ViewFields = "<FieldRef Name='ID' />";
            spQuery.ViewFieldsOnly = true;
            return list.GetItems(spQuery).Count > 0;
        }
        #endregion

        #region SPWeb methods
        /// <summary>
        /// Ensure that a group with the supplied group name exists and that it has the permission levels listed in the permissionLevels array
        /// </summary>
        /// <param name="web"></param>
        /// <param name="groupName"></param>
        /// <param name="permissionLevels"></param>
        /// <param name="owner"></param>
        public static void EnsurePermissions(this SPWeb web, string groupName, string[] permissionLevels, SPPrincipal owner)
        {
            if (!web.HasUniqueRoleAssignments && !web.IsRootWeb)
            {
                web.BreakRoleInheritance(false);
                web.RoleAssignments.RemoveAll();
            }

            SPGroup group = web.EnsureGroup(groupName, null);

            // get the role definitions corresponding to the permission level names
            List<SPRoleDefinition> permissionLevelDefinitions = new List<SPRoleDefinition>();
            foreach (string permissionLevel in permissionLevels)
                permissionLevelDefinitions.Add(web.RoleDefinitions[permissionLevel]);

            if (permissionLevelDefinitions.Count > 0)
            {
                // check for existing role assignment for this group on the web
                SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                SPRoleAssignment groupRoleAssignment = null;
                foreach (SPRoleAssignment roleAssignment in roleAssignments)
                    if (roleAssignment.Member.LoginName == groupName)
                        groupRoleAssignment = roleAssignment;

                // create it if necessary
                if (groupRoleAssignment == null)
                {
                    groupRoleAssignment = new SPRoleAssignment(group);
                    groupRoleAssignment.RoleDefinitionBindings.RemoveAll();
                    foreach (SPRoleDefinition def in permissionLevelDefinitions)
                        groupRoleAssignment.RoleDefinitionBindings.Add(def);
                    web.RoleAssignments.Add(groupRoleAssignment);
                }
                else // update if existing
                {
                    groupRoleAssignment.RoleDefinitionBindings.RemoveAll();
                    foreach (SPRoleDefinition def in permissionLevelDefinitions)
                        groupRoleAssignment.RoleDefinitionBindings.Add(def);
                    groupRoleAssignment.Update();
                }
            }

            web.Update();
        }

        /// <summary>
        /// Ensure that the permission level exists for the web. If the permission level already exists it will be updated.
        /// </summary>        
        public static void EnsurePermissionLevel(this SPWeb web, string permissionLevelName, SPBasePermissions permissions)
        {
            if (!web.RoleDefinitions.Contains<SPRoleDefinition>(r => r.Name == permissionLevelName))
            {
                SPRoleDefinition newDef = new SPRoleDefinition();
                newDef.Name = permissionLevelName;
                newDef.BasePermissions = permissions;
                web.RoleDefinitions.Add(newDef);
            }
            else
            {
                SPRoleDefinition existingDef = web.RoleDefinitions[permissionLevelName];
                existingDef.BasePermissions = permissions;
                existingDef.Update();
            }
        }

        /// <summary>
        /// Imports a list (and its contents) from a set of files created by the SPList.Export extension method to the web (adapted from http://amitkumarmca04.blogspot.co.uk/2010/10/exportimport-sharepoint-listdocument.html).
        /// </summary>
        /// <param name="folderPath">The location of the export files.</param>        
        public static void ImportList(this SPWeb destinationWeb, string folderPath)
        {
            Exception ex = null;
            SPWebApplication webApp = destinationWeb.Site.WebApplication;

            try
            {
                destinationWeb.AllowUnsafeUpdates = true;
                webApp.FormDigestSettings.Enabled = false;
                webApp.FormDigestSettings.Expires = false;

                SPImportSettings settings = new SPImportSettings();
                settings.SiteUrl = destinationWeb.Site.Url;
                settings.WebUrl = destinationWeb.Url;
                settings.FileLocation = folderPath;
                settings.FileCompression = false;
                settings.RetainObjectIdentity = false;

                SPImport import = new SPImport(settings);
                import.Run();
            }
            catch (Exception e)
            {
                ex = e;
            }
            finally
            {
                destinationWeb.AllowUnsafeUpdates = false;
                webApp.FormDigestSettings.Enabled = true;
                webApp.FormDigestSettings.Expires = true;

                if (ex != null)
                {
                    throw ex.InnerException;
                }
            }
        }

        /// <summary>
        /// Check if an SPGroup exists in a site collection and if not, create the group
        /// </summary>        
        public static SPGroup EnsureGroup(this SPWeb sourceWeb, string groupName, string groupDescription)
        {
            using (SPSite site = new SPSite(sourceWeb.Url)) // get an SPSite object, so that we can get the SPSite.Owner property
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroup group = sourceWeb.SiteGroups.TryGetGroup(groupName);
                    if (group == null)
                        web.SiteGroups.Add(groupName, site.Owner, site.Owner, groupDescription);
                    return group;
                }
            }
        }
        #endregion

        #region SPGroup methods
        /// <summary>
        /// Return the SPGroup if it exists in the list of site groups, otherwise return null
        /// </summary>        
        public static SPGroup TryGetGroup(this SPGroupCollection groups, string groupName)
        {
            return groups.Cast<SPGroup>().Where(g => g.Name == groupName).SingleOrDefault();
        }
        #endregion

        #region SPFeatureCollection methods
        /// <summary>
        /// Activate a feature, with a specified feature definition scope (i.e. Farm/Site(SPWeb))
        /// </summary>
        /// <param name="features">The feature collection</param>
        /// <param name="featureGuid">The GUID of the feature you wish to activate</param>
        /// <param name="scope">The feature scope. Use the overload with no scope parameter for site collection features.</param>
        public static void ActivateFeature(this SPFeatureCollection features, Guid featureGuid, SPFeatureDefinitionScope scope, bool force)
        {
            if (!features.Any(f => f.DefinitionId == featureGuid))
                features.Add(featureGuid, force, SPFeatureDefinitionScope.Site);
        }
        public static void ActivateFeature(this SPFeatureCollection features, string featureGuidString, SPFeatureDefinitionScope scope, bool force)
        {
            ActivateFeature(features, new Guid(featureGuidString), scope, force);
        }

        /// <summary>
        /// Activate a feature
        /// </summary>
        /// <param name="site"></param>
        /// <param name="featureGuid"></param>
        public static void ActivateFeature(this SPFeatureCollection features, Guid featureGuid, bool force)
        {
            if (!features.Any(f => f.DefinitionId == featureGuid))
                features.Add(featureGuid, force);
        }
        public static void ActivateFeature(this SPFeatureCollection features, string featureGuidString, bool force)
        {
            ActivateFeature(features, new Guid(featureGuidString), force);
        }
        #endregion

        #region SPFeatureReceiverProperties methods
        /// <summary>
        /// Extension method for handling file updates in SharePoint modules from http://johanleino.wordpress.com/2009/04/22/howto-handling-file-updates-in-sharepoint/
        /// </summary>        
        public static void UpdateFilesInModule(this SPFeatureReceiverProperties instance)
        {
            var modules = (from SPElementDefinition element in instance.Feature.Definition.GetElementDefinitions(CultureInfo.CurrentCulture)
                           where element.ElementType == "Module"
                           let xmlns = XNamespace.Get(element.XmlDefinition.NamespaceURI)
                           let module = XElement.Parse(element.XmlDefinition.OuterXml)
                           select new
                           {
                               Url = module.Attribute("Url").Value,
                               Path = Path.Combine(element.FeatureDefinition.RootDirectory, module.Attribute("Path").Value),
                               Files = (from file in module.Elements(xmlns.GetName("File"))
                                        select new
                                        {
                                            Url = file.Attribute("Url").Value,
                                            Properties = (from property in file.Elements(xmlns.GetName("Property"))
                                                          select property).ToDictionary(
                                            n => n.Attribute("Name").Value,
                                            v => v.Attribute("Value").Value)
                                        }).ToList()
                           }).ToList();

            using (SPWeb web = (instance.Feature.Parent as SPSite).OpenWeb())
            {
                modules.ForEach(module =>
                {
                    module.Files.ForEach(file =>
                    {
                        try
                        {
                            string hivePath = Path.Combine(module.Path, file.Url); // in 15-hive
                            string virtualPath = string.Concat(web.Url, "/", module.Url, "/", file.Url); // in SharePoint

                            if (File.Exists(hivePath))
                            {
                                using (StreamReader sr = new StreamReader(hivePath))
                                {
                                    SPFile virtualFile = web.GetFile(virtualPath);
                                    bool CheckOutEnabled = virtualFile.Item.ParentList.ForceCheckout;
                                    bool NeedsApproval = virtualFile.Item.ParentList.EnableModeration;

                                    if (CheckOutEnabled)
                                    {
                                        virtualFile.CheckOut();
                                    }

                                    virtualFile = web.Files.Add(virtualPath, sr.BaseStream, new Hashtable(file.Properties), true);

                                    if (CheckOutEnabled)
                                    {
                                        virtualFile.CheckIn("Updated", SPCheckinType.MajorCheckIn);
                                    }

                                    if (NeedsApproval)
                                    {
                                        virtualFile.Approve("Updated");
                                    }

                                    virtualFile.Update();
                                }
                            }
                        }
                        catch { }
                    });
                });
            }

        }

        /// <summary>
        /// Ensure root web content type definition matches the XML definition in the feature
        /// </summary>        
        public static void PushContentTypeDefinitionChangesToSite(this SPFeatureReceiverProperties properties, SPWeb web)
        {
            using (SPSite site = new SPSite(web.Url))
            {
                var query = from SPElementDefinition element in properties.Feature.Definition.GetElementDefinitions(CultureInfo.CurrentCulture)
                            where element.ElementType == "ContentType"
                            let xlmns = XNamespace.Get(element.XmlDefinition.NamespaceURI)
                            let ContentTypeXml = XElement.Parse(element.XmlDefinition.OuterXml)
                            let ContentTypeId = new SPContentTypeId(ContentTypeXml.Attribute("ID").Value)
                            let ContentType = web.ContentTypes[ContentTypeId]
                            select new
                            {
                                WebContentType = ContentType,
                                FieldLinks = (from fieldref in ContentTypeXml.Descendants(xlmns.GetName("FieldRef"))
                                              select fieldref.Attribute("ID").Value).ToList()
                            };

                var queryToList = query.ToList();
                foreach (var result in queryToList)
                {
                    SPContentType webCT = result.WebContentType;
                    bool updated = false;
                    foreach (string ctFieldLink in result.FieldLinks)
                    {
                        // does web content type contain the field links defined in the content type definition xml?
                        if (!webCT.FieldLinks.Cast<SPFieldLink>().Any<SPFieldLink>(f => f.Id == new Guid(ctFieldLink)))
                        {// if not, add them
                            webCT.FieldLinks.Add(new SPFieldLink(web.Fields[new Guid(ctFieldLink)]));
                            updated = true;
                        }
                    }
                    if (updated)
                        webCT.Update();
                }
            }
        }

        /// <summary>
        /// Ensure that all Site Columns referenced by all Content Types deployed by the supplied feature are updated
        /// </summary>
        public static void PushContentTypeDefinitionChangesToList(this SPFeatureReceiverProperties properties, SPWeb web)
        {
            using (SPSite site = new SPSite(web.Url))
            {
                // ensure list fields
                // ensure list field schema is up to date
                // ensure list content type field links

                #region Get content types defined in this feature, the lists they are used in and the related field definitions
                var query = from SPElementDefinition element in properties.Feature.Definition.GetElementDefinitions(CultureInfo.CurrentCulture)
                            where element.ElementType == "ContentType"
                            let xlmns = XNamespace.Get(element.XmlDefinition.NamespaceURI)
                            let ContentTypeXml = XElement.Parse(element.XmlDefinition.OuterXml)
                            let ContentTypeId = new SPContentTypeId(ContentTypeXml.Attribute("ID").Value)
                            let ContentTypeName = ContentTypeXml.Attribute("Name").Value
                            from usage in SPContentTypeUsage.GetUsages(web.ContentTypes[ContentTypeId])
                            where usage.IsUrlToList == true
                            select new
                            {
                                ContentTypeName = ContentTypeName,
                                UrlToList = usage.Url,
                                SiteColumns = (from fieldref in ContentTypeXml.Descendants(xlmns.GetName("FieldRef"))
                                               select web.Fields[new Guid(fieldref.Attribute("ID").Value)]).ToList()
                            };
                var queryToList = query.ToList();
                #endregion

                foreach (var result in queryToList)
                {
                    using (SPWeb parentWeb = site.OpenWeb(result.UrlToList))
                    {
                        SPList list = web.GetList(result.UrlToList);
                        SPContentType listCT = list.ContentTypes[result.ContentTypeName];

                        foreach (SPField webField in result.SiteColumns)
                        {
                            // ensure list contains a copy of the related fields
                            if (!list.Fields.Contains(webField.Id))
                                list.Fields.Add(webField);
                            SPField listField = list.Fields[webField.Id];

                            // ensure the list field definitions are up to date
                            if (listField.SchemaXml != webField.SchemaXml)
                            {
                                listField.SchemaXml = webField.SchemaXml;
                                listField.Update();
                            }

                            // ensure content type contains relevant field links
                            if (!listCT.FieldLinks.Cast<SPFieldLink>().Any(c => c.Id == listField.Id))
                                listCT.FieldLinks.Add(new SPFieldLink(listField));
                        }

                        list.Update();
                    }
                }
            }
        }
        #endregion
    }
}

csharp HttpPost

HttpPost

gistfile1.cs
public static string GetHtmlPage(string _url)
{
  String strResult;
  WebResponse objResponse;
  WebRequest objRequest = HttpWebRequest.Create(_url);
  objResponse = objRequest.GetResponse();
  using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
  {
    strResult = sr.ReadToEnd();
    sr.Close();
  }
  return strResult;
}


public static string HttpPostRequest(string _url, string post)
{
  var encoding = new ASCIIEncoding();
  byte[] data = encoding.GetBytes(post);
  WebRequest request = WebRequest.Create(_url);
  request.Method = "POST";
  request.ContentType = "application/x-www-form-urlencoded";
  request.ContentLength = data.Length;
  Stream stream = request.GetRequestStream();
  stream.Write(data, 0, data.Length);
  stream.Close();
  WebResponse response = request.GetResponse();
  String result;
  using (var sr = new StreamReader(response.GetResponseStream()))
  {
    result = sr.ReadToEnd();
    sr.Close();
  }
  return result;
}