Saturday, November 23, 2013
Copy splistitems with folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Configuration;
namespace Mercuria.HR.CopyListItemVersion
{
class Program
{
static Dictionary fieldMapping = new Dictionary
{
//{"GlobalID","PersonalNo"}
};
static void Main(string[] args)
{
try
{
string SrcSiteUrl = ConfigurationManager.AppSettings["srcSiteUrl"];
string srclistName = ConfigurationManager.AppSettings["srcListName"];
string destSiteUrl = ConfigurationManager.AppSettings["destSiteUrl"];
string destlistName = ConfigurationManager.AppSettings["destListName"];
string FolderName = ConfigurationManager.AppSettings["folderName"];
SPListItem folderItem;
using (SPSite site = new SPSite(SrcSiteUrl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList sourceList = web.Lists[srclistName];
SPWeb destweb = new SPSite(destSiteUrl).OpenWeb();
SPList destList = destweb.Lists[destlistName];
Console.WriteLine(string.Format("Total files to be move={0}", sourceList.ItemCount));
int i = 1;
folderItem = destList.Items.Add(destList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);
// set the folder name and update
folderItem["Title"] = FolderName;
folderItem.Update();
foreach (SPListItem sourceItem in sourceList.Items)
{
Console.WriteLine(string.Format(" {0} Item copied of {1}", i, sourceList.ItemCount));
Console.WriteLine(string.Format("{0} Item copied ", sourceItem["Global ID"]));
CopyItem(sourceItem, destList, folderItem);
i++;
}
Console.WriteLine(string.Format("Item copied completed."));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
public static void CopyItem(SPListItem sourceItem, SPList destinationList, SPListItem folderItem)
{
//create a listitem object to add item in the foler
SPListItem targetItem = destinationList.Items.Add(folderItem.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, null);
for (int i = sourceItem.Versions.Count - 1; i >= 0; i--)
{
//set the values into the target list
foreach (SPField sourceField in sourceItem.Fields)
{
SPListItemVersion version = sourceItem.Versions[i];
if ((!sourceField.ReadOnlyField) && (sourceField.InternalName != "Attachments") && (sourceField.Type != SPFieldType.Calculated) && !sourceField.TypeDisplayName.Contains("ESOP % 2011") && (sourceField.Type != SPFieldType.DateTime))
{
try
{
if (sourceField.InternalName == "Title0")
{
targetItem[Mapper(sourceField.InternalName)] = version[sourceField.InternalName];
}
else
{
targetItem[Mapper(sourceField.Title)] = version[sourceField.Title];
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Destination field={0} :: ", sourceField.Title));
Console.WriteLine(ex);
}
}
else if (sourceField.Title == "Created" ||
sourceField.Title == "Created By" ||
sourceField.Title == "Modified" ||
sourceField.Title == "Modified By")
{
try
{
targetItem[sourceField.Title] = version[sourceField.Title];
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
else if (sourceField.Type == SPFieldType.DateTime)
{
try
{
targetItem[sourceField.Title] = (DateTime.Parse(version[sourceField.Title].ToString(), null, System.Globalization.DateTimeStyles.AdjustToUniversal).AddDays(1));
}
catch
{
}
}
}
//update the target item and loop over the the next version
targetItem.Web.AllowUnsafeUpdates = true;
targetItem.Update();
targetItem.Web.AllowUnsafeUpdates = false;
}
// now check for attachments (not versioned) and copy
foreach (string fileName in sourceItem.Attachments)
{
SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
targetItem.Attachments.Add(fileName, file.OpenBinary());
}
targetItem.Web.AllowUnsafeUpdates = true;
// perform a systemupdate so that a new version is not created
targetItem.SystemUpdate();
destinationList.Update();
targetItem.Web.AllowUnsafeUpdates = false;
}
// updates the output fieldname if the destination list has different fields (must be the same type though!)
public static string Mapper(string fieldNameIn)
{
// if not in the mapping dictionary then use the infieldname as the field to write to.
string fieldNameOut = fieldNameIn;
//if (fieldMapping.ContainsKey(fieldNameIn)) fieldNameOut = fieldMapping[fieldNameIn];
return fieldNameOut;
}
}
}
Monday, November 18, 2013
Update Metadata field value using object model from TaxonomyWebTaggingControl
TaxonomyField managedFieldDept = (TaxonomyField)list.Fields["Department"];
TaxonomyFieldValueCollection DeptValues = new TaxonomyFieldValueCollection(String.Empty);
DeptValues.PopulateFromLabelGuidPairs(controlDept.Text);
TaxonomyFieldValue DeptValue = DeptValues[0];
managedFieldDept.SetFieldValue(itemSelected, DeptValue);
Friday, October 18, 2013
Daylight time value calculate in Sharepoint and Asp.Net
Below is the code to get the Daylight time .
Method
public static DateTime GetZoneBasedDateTime(TimezoneName zone)
{
try
{
string strzoneId = GetEnumStringValue(zone);
var dt = DateTime.UtcNow;
var tz = TimeZoneInfo.FindSystemTimeZoneById(strzoneId);
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
DateTime dtResult = utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)).DateTime;
return dtResult;
}
catch (Exception ex)
{
WriteLogToFile("GetZoneTime(TimZoneName zone)", ex.Message, null, true);
return DateTime.MinValue;
}
}
}
Enum
public enum TimezoneName
{
[StringValueAttribute("Singapore Standard Time")]
Asia = 1,
[StringValueAttribute("W. Europe Standard Time")]
Geneva = 2,
[StringValueAttribute("Central Standard Time")]
Hoston = 3,
[StringValueAttribute("None")]
None = 0
}
Enum with String Value Tagging
I have an requirement where I need to get a string value from Enum like KeyValue mapping.
Below is the process to use Enum like a KeyValue mapping and get the keyvalue passing enum name .
using System.Reflection;
Declare a custom class.
[AttributeUsage( AttributeTargets.Field )]
public sealed class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
Enum declaration.
public enum TimezoneName
{
[StringValueAttribute("Singapore Standard Time")]
Asia = 1,
[StringValueAttribute("W. Europe Standard Time")]
Geneva = 2,
[StringValueAttribute("Central Standard Time")]
Hoston = 3,
[StringValueAttribute("None")]
None = 0
}
Get string value from Enum.
public static string GetEnumStringValue(Enum evalue)
{
string output = null;
if (evalue != null)
{
Type type = evalue.GetType();
FieldInfo fi = type.GetField(evalue.ToString());
StringValueAttribute[] attrs =fi.GetCustomAttributes(typeof(StringValueAttribute),false) as StringValueAttribute[];
if (attrs.Length > 0)
{
output = attrs[0].Value;
}
}
return output;
}
Thursday, October 3, 2013
Write log for application
private void WriteLogToFile(string errorSource, string message, Exception exception, bool isNewLine)
{
try
{
//
FileStream fs = new FileStream(ConfigurationManager.AppSettings.Get("ErrorLog"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter errorLog = new StreamWriter(fs);
if (isNewLine)
errorLog.WriteLine("-".PadRight(100, '-'));
errorLog.WriteLine(DateTime.Now);
if (errorSource != null)
errorLog.WriteLine(errorSource);
if (message != null)
errorLog.WriteLine(message);
if (exception != null)
errorLog.WriteLine(exception);
errorLog.Close();
fs.Close();
fs.Dispose();
}
catch (Exception ex)
{
}
}
DateTime Filter in CAML
While filtering data on datetime field use SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.UtcNow) for sharepoint in CAML.
Subscribe to:
Posts (Atom)