Thursday 27 November 2014

Change the log file path in Microsoft.Practices.EnterpriseLibrary.Logging.Configuration

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;

namespace TestInterface
{
    internal class Program
    {
        internal static int ExitCode = 0;
        static void Main(string[] args)
        {
            string logFilePath = Environment.GetEnvironmentVariable("LogFile", EnvironmentVariableTarget.Process);
            SetupRuntimeConfiguration(logFilePath);

            ProcessData();
            Environment.Exit(ExitCode);
        }

        public static void SetupRuntimeConfiguration(string logFilePath)
        {
            string loggingConfigurationSectionName = "loggingConfiguration";

            //Create the Configuration object
            //System.Configuration.ExeConfigurationFileMap configFileMap = new System.Configuration.ExeConfigurationFileMap();

            //The ExeConfigFilename is the absolute path of the config file
            // configFileMap.ExeConfigFilename = enterpriseLibraryConfig;

            System.Configuration.Configuration entLibConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);


            //Open our configuration file instead of the default app configuration
            //Configuration entLibConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, System.Configuration.ConfigurationUserLevel.None);

            //Check if the configuration file exist
            if (!entLibConfig.HasFile)
            {
                return;
            }

            //Get the logging ConfigurationSection
            LoggingSettings settings = (LoggingSettings)entLibConfig.GetSection(loggingConfigurationSectionName);

            //Dynamically set the location of the trace listener to a directory
            //that allows Enterprise Library to read and write.
            //Handle the trace listeners that has a fileName property.
            foreach (TraceListenerData traceListernData in settings.TraceListeners)
            {
                FlatFileTraceListenerData flatFileTraceListener = traceListernData as FlatFileTraceListenerData;
                XmlTraceListenerData xmlTraceListener = traceListernData as XmlTraceListenerData;
                RollingFlatFileTraceListenerData rollingFileTraceListener =
                    traceListernData as RollingFlatFileTraceListenerData;

                if (flatFileTraceListener != null)
                {
                    flatFileTraceListener.FileName = logFilePath;
                }
                if (rollingFileTraceListener != null)
                {
                    rollingFileTraceListener.FileName = logFilePath;
                }
                if (xmlTraceListener != null)
                {
                    xmlTraceListener.FileName = logFilePath;
                }
            }
            //Make sure the configuration file is in a directory where the user have write permission.
            entLibConfig.Save();
        }      

        static void ProcessData()
        {
            try
            {
                Logger.Write(new LogEntry { Title = "ProcessData", Severity = TraceEventType.Verbose, TimeStamp = DateTime.Now, Message = "Message: SAP Data Refresh Started" });             


                Logger.Write(new LogEntry { Title = "ProcessData", Severity = TraceEventType.Verbose, TimeStamp = DateTime.Now, Message = "Message: SAP Data Refresh Completed" });
            }
            catch (Exception ex)
            {
                // if any exception write to the log file
                Logger.Write(new LogEntry { Title = "ProcessSAPDataRefresh:", Severity = TraceEventType.Error, TimeStamp = DateTime.Now, Message = "Message:" + ex.Message + " Stack Trace:" + ex.StackTrace });
                ExitCode = 20000;
            }
        }
   }
}

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
      <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
      <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
     <appSettings>
        </appSettings>
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
      <listeners>
        <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            fileName="C:\log1.log" formatter="Text Formatter"
            rollFileExistsBehavior="Increment" rollInterval="Day" />
      </listeners>
      <formatters>
        <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
            name="Text Formatter" />
      </formatters>
      <categorySources>
        <add switchValue="All" name="General">
          <listeners>
            <add name="Rolling Flat File Trace Listener" />
          </listeners>
        </add>
      </categorySources>
      <specialSources>
        <allEvents switchValue="All" name="All Events" />
        <notProcessed switchValue="All" name="Unprocessed Category" />
        <errors switchValue="All" name="Logging Errors &amp; Warnings">
          <listeners>
            <add name="Rolling Flat File Trace Listener" />
          </listeners>
        </errors>
      </specialSources>
    </loggingConfiguration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="YAX_READ_TABLEBinding" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    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>
            <customBinding>
              <binding name="Config1" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00">
                <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
                  messageVersion="Soap11" writeEncoding="utf-8">
                  <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                    maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                </textMessageEncoding>
                <httpTransport maxReceivedMessageSize="2147483647" authenticationScheme="Basic"
                  bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                  keepAliveEnabled="false" proxyAuthenticationScheme="Basic" realm=""
                  useDefaultWebProxy="true" />
              </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="http://../sap/bc/soap/rfc" binding="customBinding"
                bindingConfiguration="Config1" contract="YaxReadTable.YAX_READ_TABLEPortType"
                name="YAX_READ_TABLEPortType" />
          <!--<endpoint address="http://.../sap/bc/soap/rfc" binding="customBinding"
              bindingConfiguration="Config1" contract="YaxReadTable.YAX_READ_TABLEPortType"
              name="YAX_READ_TABLEPortType" />-->
        </client>
    </system.serviceModel>
</configuration>

Wednesday 26 November 2014

Change a web application URL for SharePoint 2013


Unlike typical IIS applications, you cannot simply use IIS Manager or other IIS metabase tools to modify the bindings of IIS web applications that have been extended with SharePoint 2013.

If you modify the IIS bindings of a web application by adding a host header binding or SSL port or by changing a port number, SharePoint 2013 will not be aware of these changes and will not update the web application's alternate access mapping URLs.
If you update the web application's alternate access mappings to change a host header, switch to an SSL URL, or change a port number, SharePoint 2013 will not automatically update your IIS bindings to match.
To update the URL or IIS bindings of a web application, unextend and reextend the web application and reconfigure the alternate access mapping URLs or IIS website bindings.
We do not recommend reusing the same IIS website for your HTTP and SSL hosting. Instead, extend a dedicated HTTP and a dedicated SSL website, with each assigned to its own alternate access mapping zone and URLs.


Create the Host name
1.     Open the hosts file from the following location: C:\Windows\System32\drivers\etc 
2.     Enter the following line into it and save the file:
127.0.0.1 q.apps.org-intra.net

3.     Repeat steps (1) and (2) for all the servers in the farm.
Remove SharePoint form IIS Site
1.     SharePoint Central Administration website à Application Management à Click Manage web applications.
2.     On the Web Applications menu à Click Delete à Click Remove SharePoint from IIS Web Site.
3.     On the Remove SharePoint from Web site page à Click the web application we want to remove from IIS Site.
4.     In Select IIS Web site and zone to remove list à Click the IIS website and zone we want to remove.
5.     In the Delete IIS Web sites section à Click Yes
6.     Click OK. This action does not delete the web application, nor does it delete the content databases of the web application.

Re-extend the webapplication
1.     On the SharePoint Central Administration à Application Management à Click Manage web applications.
2.     Click the web application we want to extendà on the ribbon, click Extend.
3.     In the IIS Web Site section à click the Create a new IIS Web site option 
     Enter the name “HOT_Q_F08_Apps
4.     In the Port sectionà Enter ‘80’
5.     In the Host Header section à Enterq.apps.org-intra.net
6.     In Public URL section à Enter “http://q.apps.org-intra.net
7.     In Public URL section, in the Zone listà Select the zone “Default”.
8.     Click OK.

Update the alternate mapping URLs
9.     Ensure that internal URLs are updated in the alternate access mappings to reflect the new IIS bindings.
Redeploy solutions
10.  Redeploy all the solutions which are deployed to that specific web application in central admin site.

Ref: http://technet.microsoft.com/en-us/library/cc262366%28v=office.15%29.aspx

Tuesday 25 November 2014

Creating Host Name for Webapplication in SharePoint


This article explains how to setup a Host name for the web application.
Create the Host name 
Open the hosts file from the following location:
C:\Windows\System32\drivers\etc 
Enter the following line into it and save the file:
127.0.0.1 myApp.corp.com

Host file looks like below,

















2. Create web application:
Open the SharePoint Central Administration and create a new web application.
Please note to set the following properties:
            Port: 80

            Host Header: myApp.corp.com
After entering all the details click the Save button.  Wait for the operation to be completed and you can try entering the url in the browser.         
http://myApp.corp.com








Step 3: Disable Loopback

If you get a prompt for the user and you may face the following issues:

    There is continuous prompt for the credentials
    HTTP 401.1 error

This shows that there is a problem with the Loopback configuration.  This case should occur only when we access the application from the server machine.

For fixing the problem we have to disable Loopback value inside registry.

Open Registry Editor (regedit.exe) and locate the following key:
Collapse | Copy Code

            HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa

Create a new Key Value of type DWORD inside it and set the value to 1.Restart the server.




Friday 7 November 2014

Generic class file to create the site columns in SharePoint site


This is a common file is used to create 'n' number of site columns in SharePoint site.

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

namespace SPHelper
{
public class SiteColumn
{
/// <summary>
/// Determine if field exists as a site column in the web site
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <returns></returns>
public static bool IsExist(SPWeb web, string internalName, string displayName)
{
bool isExist = false;
try
{
// check to see if field exist by using passed internal name
if (!string.IsNullOrEmpty(internalName)) { isExist = web.Fields.ContainsField(internalName); }

// now check by field's display name, but only if couldn't already find the field using internal name,
// and the displayname is not null, and the display name is different from the internalname
if (!isExist && !string.IsNullOrEmpty(displayName) && displayName != internalName)
{ isExist = web.Fields.ContainsField(displayName); }
}
catch (Exception ex)
{
Log.WriteError("rthdytkyttdyrdrtjesr4e6esr", ex, "internal name: " + internalName);
}
return isExist;
}


/// <summary>
/// Create a new site column
/// </summary>
/// <param name="web">website to add column to (should bee root site!)</param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="type"></param>
/// <param name="isRequired"></param>
/// <param name="group"></param>
/// <param name="defaultValue"></param>
/// <param name="description"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, SPFieldType type, string defaultValue,
bool isHidden, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal Name for new site column cannot be null"); }
if (string.IsNullOrEmpty(group)) { throw new Exception("Custom site column group name is not defined"); }


// determine if field already exists
bool isExist = IsExist(web, internalName, displayName);

if (!isExist)
{
// create field
string fieldName = web.Fields.Add(internalName, type, true);
f = web.Fields[fieldName];

// group
f.Group = group;

// required?
f.Required = isRequired;

// default value
if (!string.IsNullOrEmpty(defaultValue)) { f.DefaultValue = defaultValue; }

// description
if (!string.IsNullOrEmpty(description)) { f.Description = description; }

// public title
if (!string.IsNullOrEmpty(displayName)) { f.Title = displayName; }

// hidden?
if (isHidden) { f.Hidden = isHidden; }

// update
f.Update();
}
else if (isThrowErrorIfFieldAlreadyExists)
{
throw new Exception("Site column: " + internalName + " already exists");
}
}
catch (Exception ex)
{
Log.WriteError("ette6idtyidrtsdrrdy", ex, "field internalName: " + internalName);
f = null;
}
return f;
}


public static SPField CreateTextSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, string defaultValue, int? displaySize,
bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Text,
null, false, isThrowErrorIfFieldAlreadyExists);

if (f != null)
{
// default value
if (!string.IsNullOrEmpty(defaultValue)) { ((SPFieldText)f).DefaultValue = defaultValue; }

// display size
if (displaySize != null) { ((SPFieldText)f).DisplaySize = displaySize.Value.ToString(); }

// update
((SPFieldText)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("r6eutrddfresr55t", ex, "internal name: " + internalName);
f = null;
}
return f;
}

/// <summary>
/// Create a multiline text box site column
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="defaultValue"></param>
/// <param name="numberOfLines"></param>
/// <param name="displaySize"></param>
/// <param name="isRichText"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateMultiLineTextSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, string defaultValue, int? numberOfLines, int? displaySize,
bool isRichText, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// call original
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Note,
defaultValue, false, isThrowErrorIfFieldAlreadyExists);

if (f != null)
{
// display size
if (displaySize != null) { ((SPFieldMultiLineText)f).DisplaySize = displaySize.Value.ToString(); }

// number of lines
if (numberOfLines != null) { ((SPFieldMultiLineText)f).NumberOfLines = numberOfLines.Value; }

// is rich text?
((SPFieldMultiLineText)f).RichText = isRichText;
if (isRichText) { ((SPFieldMultiLineText)f).RichTextMode = SPRichTextMode.FullHtml; }

// update
((SPFieldMultiLineText)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("56dfdsssetfdcd", ex, "internal name: " + internalName);
f = null;
}
return f;
}

/// <summary>
/// Create a dateTime site column
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="defaultValue"></param>
/// <param name="displayFormat"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateDateSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, DateTime? defaultValue, SPDateTimeFieldFormatType displayFormat,
bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.DateTime,
null, false, isThrowErrorIfFieldAlreadyExists);

if (f != null)
{
// default value
if (defaultValue != null && defaultValue != DateTime.MinValue)
{
string _defaultValue = defaultValue.Value.ToShortDateString();
if (displayFormat == SPDateTimeFieldFormatType.DateTime)
{
_defaultValue += " " + defaultValue.Value.ToShortTimeString();
}
((SPFieldDateTime)f).DefaultValue = _defaultValue;
}

// display format
((SPFieldDateTime)f).DisplayFormat = displayFormat;

// update
((SPFieldDateTime)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("et6fhtdfewrer", ex, "internal name: " + internalName);
f = null;
}
return f;
}


public static SPField CreateCurrencySiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, SPNumberFormatTypes currencyFormat, double? defaultValue, double? minValue,
double? maxValue, int? displaySize, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (defaultValue != null)
{
if (minValue != null && defaultValue < minValue) { throw new Exception("default value is less than the minimum value"); }
if (maxValue != null && defaultValue > maxValue) { throw new Exception("default value is greater than the maximum value"); }
}


// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Currency,
null, false, isThrowErrorIfFieldAlreadyExists);

if (f != null)
{
// display format
((SPFieldCurrency)f).DisplayFormat = currencyFormat;

// min value
if (minValue != null) { ((SPFieldCurrency)f).MinimumValue = minValue.Value; }

// max value
if (maxValue != null) { ((SPFieldCurrency)f).MaximumValue = maxValue.Value; }

// display size
if (displaySize != null) { ((SPFieldCurrency)f).DisplaySize = displaySize.Value.ToString(); }

// default value
if (defaultValue != null) { ((SPFieldCurrency)f).DefaultValue = defaultValue.Value.ToString(); }

// update
((SPFieldCurrency)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("euuerrsterres", ex, "internal name: " + internalName);
f = null;
}
return f;
}

/// <summary>
/// Create number site column
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="numberFormat"></param>
/// <param name="defaultValue"></param>
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <param name="displaySize"></param>
/// <param name="isShowAsPercentage"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateNumberSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, SPNumberFormatTypes numberFormat, double? defaultValue, double? minValue,
double? maxValue, int? displaySize, bool isShowAsPercentage, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (defaultValue != null)
{
if (minValue != null && defaultValue < minValue) { throw new Exception("default value is less than the minimum value"); }
if (maxValue != null && defaultValue > maxValue) { throw new Exception("default value is greater than the maximum value"); }
}


// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Number,
null, false, isThrowErrorIfFieldAlreadyExists);

if (f != null)
{
// display format
((SPFieldNumber)f).DisplayFormat = numberFormat;

// min value
if (minValue != null) { ((SPFieldNumber)f).MinimumValue = minValue.Value; }

// max value
if (maxValue != null) { ((SPFieldNumber)f).MaximumValue = maxValue.Value; }

// display size
if (displaySize != null) { ((SPFieldNumber)f).DisplaySize = displaySize.Value.ToString(); }

// default value
if (defaultValue != null) { ((SPFieldNumber)f).DefaultValue = defaultValue.Value.ToString(); }

// percent?
((SPFieldNumber)f).ShowAsPercentage = isShowAsPercentage;

// update
((SPFieldNumber)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("t6uftdfxgdfrddrt", ex, "internal name: " + internalName);
f = null;
}
return f;
}

// BROKEN FOR SOME REASON, GET ERROR: The node to be inserted is from a different document context.
///// <summary>
///// Create a choices site column
///// http://niral.net/blog/create-sharepoint-content-type-programmatically
///// </summary>
///// <param name="web"></param>
///// <param name="internalName"></param>
///// <param name="displayName"></param>
///// <param name="isRequired"></param>
///// <param name="group"></param>
///// <param name="choices"></param>
///// <param name="defaultValue"></param>
///// <param name="description"></param>
///// <param name="isThrowErrorIfFieldAlreadyExists"></param>
///// <returns></returns>
//public static SPField CreateChoiceSiteColumn(SPWeb web, string internalName, string displayName, string description,
//    string group, bool isRequired, string[] choices, string defaultValue, bool isThrowErrorIfFieldAlreadyExists)
//{
//    SPField f = null;
//    try
//    {
//        // call original
//        f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Choice,
//            null, false, isThrowErrorIfFieldAlreadyExists);

//        // if didn't already exist and no errors
//        if (f != null)
//        {
//            // site column successfully created, now set choice specific properties
//            if (choices != null && choices.Length > 0)
//            {
//                Log.WriteInformation("about to add choices");
//                bool isDefaultFound = false;
//                int defaultIndex = 0;
//                int i = 0;
//                foreach (string choice in choices)
//                {
//                    // a.) add choice option
//                    Log.WriteInformation("about to add choice: " + choice);
//                    ((SPFieldChoice)f).Choices.Add(choice);
//                    if (choice == defaultValue)
//                    {
//                        // b.) default choice found
//                        isDefaultFound = true;
//                        defaultIndex = i;
//                    }
//                    i++;
//                }

//                if (!isDefaultFound)
//                {
//                    if (!string.IsNullOrEmpty(defaultValue)) { throw new Exception("Default value: " + defaultValue + " was not found in array of choices passed"); }
//                    ((SPFieldChoice)f).DefaultValue = string.Empty;
//                }

//                // update the site column
//                Log.WriteInformation("about to update");
//                ((SPFieldChoice)f).Update();
//                Log.WriteInformation("successfully updated");

//                // set default
//                if (isDefaultFound)
//                {
//                    ((SPFieldChoice)f).DefaultValue = defaultIndex.ToString();
//                    Log.WriteInformation("about to update again after setting the default value to: " + defaultIndex.ToString());
//                    ((SPFieldChoice)f).Update();
//                }
//            }
//        }
//    }
//    catch (Exception ex)
//    {
//        Log.WriteError("rh6tthsGGhdrsrt", ex, "field internalName: " + internalName);
//        f = null;
//    }
//    return f;
//}

/// <summary>
/// Create a lookup site column
/// http://niral.net/blog/create-sharepoint-content-type-programmatically
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="lookupListId">SPList.ID</param>
/// <param name="lookupField"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateLookupSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, Guid lookupListId, string lookupField, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passes is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
if (lookupListId == null || lookupListId == Guid.Empty) { throw new Exception("Invalid list GUID passed to lookup against"); }
if (string.IsNullOrEmpty(lookupField)) { throw new Exception("Lookup Field passed is null"); }


// determine if site column already exists
if (IsExist(web, internalName, displayName))
{
if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("site column already exists: " + internalName); }
}
else
{
// create lookup site column
string fieldname = web.Fields.AddLookup(displayName, lookupListId, isRequired);
f = web.Fields[fieldname];
if (f == null) { throw new Exception("Failed to create lookup list: " + internalName); }
else
{
// remote lookup field
((SPFieldLookup)f).LookupField = lookupField;

// update
((SPFieldLookup)f).Update();
}
}
}
catch (Exception ex)
{
Log.WriteError("tek7rdthddr", ex, "internal name: " + internalName);
f = null;
}
return f;
}


/// <summary>
/// Create new image field
/// http://blog.beckybertram.com/Lists/Posts/Post.aspx?ID=67
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="group"></param>
/// <returns></returns>
public static Microsoft.SharePoint.Publishing.Fields.ImageField CreateImageSiteColumn(SPWeb web, string internalName,
string displayName, string description, string group, bool isThrowErrorIfFieldAlreadyExists)
{
Microsoft.SharePoint.Publishing.Fields.ImageField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
if (string.IsNullOrEmpty(group)) { throw new Exception("Custom site column group name is not defined"); }


if (IsExist(web, internalName, displayName))
{
if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("Site column already exists: " + internalName); }
}
else
{
f = new Microsoft.SharePoint.Publishing.Fields.ImageField(web.Fields, "Image", displayName);
f.Group = group;
f.StaticName = internalName;
f.Title = displayName;
f.RichText = true;
f.RichTextMode = SPRichTextMode.FullHtml;
web.Fields.Add(f);
}
}
catch (Exception ex)
{
Log.WriteError("5ek7itytdrhdfdf", ex);
f = null;
}
return f;
}


/// <summary>
/// Create new link url field
/// http://blog.beckybertram.com/Lists/Posts/Post.aspx?ID=67
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="group"></param>
/// <returns></returns>
public static Microsoft.SharePoint.Publishing.Fields.LinkField CreateLinkSiteColumn(SPWeb web, string internalName,
string displayName, string description, string group, bool isThrowErrorIfFieldAlreadyExists)
{
Microsoft.SharePoint.Publishing.Fields.LinkField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
if (string.IsNullOrEmpty(group)) { throw new Exception("Custom site column group name is not defined"); }


if (IsExist(web, internalName, displayName))
{
if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("Site column already exists: " + internalName); }
}
else
{
f = new Microsoft.SharePoint.Publishing.Fields.LinkField(web.Fields, "Link", displayName);
f.Group = group;
f.StaticName = internalName;
f.Title = displayName;
//f.RichText = true;
//f.RichTextMode = SPRichTextMode.FullHtml;
web.Fields.Add(f);
}
}
catch (Exception ex)
{
Log.WriteError("76ritfgdfdedrt", ex);
f = null;
}
return f;
}

// NOT WORKING: Simply creates text fields. Why?!?
///// <summary>
///// Create Managed Metadata site columns
///// The first SPField in the collection is the managed metadata column.
///// The second SPField in the collection is the hidden note field that must also be added
///// http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.taxonomyfield.aspx
///// http://social.technet.microsoft.com/Forums/en/sharepoint2010programming/thread/310692d3-49f2-4c0f-b911-735f24b769b3
///// </summary>
///// <param name="web"></param>
///// <param name="internalName"></param>
///// <param name="displayName"></param>
///// <param name="description"></param>
///// <param name="group"></param>
///// <param name="isRequired"></param>
///// <param name="defaultValue"></param>
///// <param name="isAllowMultipleValues">Allow multiple terms to be selected?</param>
///// <param name="isCreateValuesInEditForm">Allowed to create new terms into the termset?</param>
///// <param name="isAllowFillInChoices">Allowed to add keywords? (added to the item, but not to the term store)</param>
///// <param name="termSet"></param>
///// <param name="termTargetTemplate">Relative url that is used to display the term when clicked on</param>
///// <param name="isThrowErrorIfFieldAlreadyExists"></param>
///// <returns></returns>
//public static List<SPField> CreateMetadataSiteColumn(SPWeb web, string internalName, string displayName, string description,
//    string group, bool isRequired, string defaultValue, bool isAllowMultipleValues,
//    bool isCreateValuesInEditForm, bool isAllowFillInChoices,
//    TermSet termSet, string termTargetTemplate, bool isThrowErrorIfFieldAlreadyExists)
//{
//    List<SPField> taxonomySiteColumns = null;
//    try
//    {
//        // init
//        if (web == null) { throw new Exception("SPWeb passed is null"); }
//        if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
//        if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
//        if (string.IsNullOrEmpty(group)) { group = "NEMA"; }
//        if (termSet == null) { throw new Exception("TermSet passed is null"); }
//        TaxonomyField f = null;
//        taxonomySiteColumns = new List<SPField>();


//        // exist?
//        if (IsExist(web, internalName, displayName))
//        {
//            if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("Duplicate column already exists: " + internalName); }
//        }
//        else
//        {
//            // create field
//            f = web.Fields.CreateNewField("TaxonomyFieldTypeMulti", displayName) as TaxonomyField;

//            // internal name
//            f.StaticName = internalName;

//            // description
//            if (!string.IsNullOrEmpty(description)) { f.Description = description; }

//            // group
//            f.Group = group;

//            // is required?
//            f.Required = isRequired;

//            // default value
//            if (!string.IsNullOrEmpty(defaultValue)) { f.DefaultValue = defaultValue; }

//            // allow multiple values?
//            f.AllowMultipleValues = isAllowMultipleValues;

//            // is allowed to create new terms in the terms store edit form?
//            f.CreateValuesInEditForm = isCreateValuesInEditForm;

//            // user allowed to create new terms
//            f.Open = isAllowFillInChoices;

//            //////////////////////////////////////////////////////
//            //////////////////////////////////////////////////////
//            // termstore
//            //////////////////////////////////////////////////////
//            //////////////////////////////////////////////////////

//            // anchor term
//            // If this is set to a GUID of a term only terms that are descendents of the term can be picked
//            f.AnchorId = Guid.Empty;

//            // term store id
//            f.SspId = termSet.TermStore.Id;

//            // term set id
//            f.TermSetId = termSet.Id;

//            // term target url (relative)
//            if (!string.IsNullOrEmpty(termTargetTemplate)) { f.TargetTemplate = termTargetTemplate; }

//            // create Note site column to be linked to this site column
//            string noteInternalName = Taxonomy.FormatNoteFieldInternalName(internalName);
//            SPField noteSiteColumn = null;
//            try
//            {
//                noteSiteColumn = web.Fields.GetField(noteInternalName);
//                if (noteSiteColumn != null) { Log.WriteInformation("regwegtwge", "Hidden Note field already exists: " + noteInternalName); }
//            }
//            catch { }
//            if (noteSiteColumn == null)
//            {
//                // note field doesn't already exist, create it
//                noteSiteColumn = CreateSiteColumn(web, noteInternalName, internalName + "_0",
//                    null, group, false, SPFieldType.Note, null, true, false);
//            }
//            if (noteSiteColumn == null) { throw new Exception("Failed to find or create an accompanying hidden note field for this metadata column"); }

//            // link to notes field
//            f.TextField = noteSiteColumn.Id;

//            // update
//            f.Update();

//            // add to collection, the first being the taxonomy field, the 2nd being the note field
//            // IMPORTANT: BOTH need to be added to the content type!
//            taxonomySiteColumns.Add(f);
//            taxonomySiteColumns.Add(noteSiteColumn);
//        }
//    }
//    catch (Exception ex)
//    {
//        Log.WriteError("6uydrtserrH", ex, "internal name: " + internalName);
//        taxonomySiteColumns = null;
//    }
//    return taxonomySiteColumns;
//}


public static bool DeleteSiteColumn(SPWeb web, string displayName)
{
bool isSuccessful = false;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(displayName)) { throw new Exception("Site Column display name passed is null"); }


// get internal name
string internalName = Field.ConvertDisplayNameToInternalName(displayName);

// get site column object
SPField siteColumnToDelete = web.Fields.GetFieldByInternalName(internalName);
if (displayName == null) { throw new Exception("Failed to find site column using internal name: " + internalName); }

// can't delete these types
if (siteColumnToDelete is TaxonomyField) { throw new Exception("Cannot handle deleting managed metadata fields"); }
if (siteColumnToDelete is SPFieldLookup) { throw new Exception("Cannot handle deleting lookup fields"); }

// delete
siteColumnToDelete.Delete();
isSuccessful = true;
}
catch (Exception ex)
{
Log.WriteError("shrjsfhasert43srth", ex, "display name: " + displayName);
isSuccessful = false;
}
return isSuccessful;
}
}
}