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
}
Friday, October 18, 2013
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)