Tuesday, November 10, 2009

TimeZone Conversion in C#

hi.
.Net framework have some powerful classes for Date conversion.some time we need to convert date between different time Zones in code behind.In some cases difference in Time Zone leads difference in Date between locations.

To make this conversion .Net have very easy way.Just Provide leg/lead difference of hour/minute/seconds as argument in built in Function.

Suppose you want to convert Current date time to EST(GMT-5). this can be done by code.

DateTime currentDt = DateTime.Now.ToUniversalTime();//Current Converted to UTC
currentDt = DateTime.SpecifyKind(currentDt, DateTimeKind.Utc);//Say to runtime that this date is UTC date.

/*
we can convert between timezones with referance to UTC(GMT) time.
.Net Provides TimeZoneInfo class which provides Statis functions to make easy conversion between Time Zones.

Though It Takes many arguments ,Key point is ConvertTime method and TimeSpan
we can specify TimeSpan as diferance between GMT to EST,GMT to PST etc.
*/

lblGMT.Text = TimeZoneInfo.ConvertTime(currentDt, TimeZoneInfo.CreateCustomTimeZone("1", new TimeSpan(-5, 0, 0), "EST", "EST", "EDT", new TimeZoneInfo.AdjustmentRule[] { })).ToString();

you can read more about TimeZone and TimezoneInfo at

http://www.danrigsby.com/blog/index.php/2008/08/24/timezone-vs-timezoneinfo-in-net/

http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx

hope this will help you.

thanks.

Saturday, November 7, 2009

Create XML document Using T-SQL Statement

Hi.

There are many ways in asp.net for generating RSS file.you can use string concatenation,loop iteration or using more advanced techniques you can Use LINQ-TO-XML for creating xml document for RSS feed.
i was searching a in SQL server by which i can generate RSS using T-SQL query. SQL Server is shiped with many new function and operators which help us to generate XML from SQL server.

There are many options Like RAW Mode ,AUTO Mode and EXPLICIT Mode.

auto and raw mode can be used for simple xml tag generation ,while Explicit mode is vary powerful mode to generate whole XML documents.

I Will show you the code how to Generate XML file for Rss Feed.

Let's say I have a table Name "myFeeds" which looks like:




Now i want to Create Rss Feed File Using data of this table ,which should look like:




and Here is The code which will give you content as xml which can be written Feed file.

Code:

select 1 as Tag,Null as parent,'2.0' as 'rss!1!version',Null as
'Link!2!rel',Null as [Channel!3!Title!element], Null as
[Channel!3!Link!element],null as [Channel!3!Description!element],Null as
[Channel!3!language!element], NULL as [Item!4!Title!element], NULL as
[Item!4!Url!element], NULL as [Item!4!PubDate!element]



UNION ALL



select 2,1,Null,'alternate' as 'Link!2!rel',Null as
[Channel!3!Title!element],Null as [Channel!3!Link!element], Null as
[Channel!3!Description!element],Null as [Channel!3!language!element],NULL as
[Item!3!Title!element], NULL as [Item!3!Url!element], NULL as
[Item!3!PubDate!element]



UNION ALL



SELECT 3,2,Null,Null, 'My Website feed channel title' as
[Channel!2!Title!element], 'http://www.dhameliya.blogspot.com' as
[Channel!2!Link!element], 'This is channel description' as
[Channel!2!Description!element], 'en-us' as [Channel!2!language!element], NULL
as [Item!3!Title!element], NULL as [Item!3!Url!element], NULL as
[Item!3!PubDate!element]



UNUNION ALL



SELECT 4, 3,Null,Null,Null,Null,Null,Null, sa.Title, sa.Url, sa.PubDate FROM
myFeeds sa



For XML EXPLICIT


--End of Code

at first site this is very complex code but when you run this without "For XML EXPLICIT" Statements.it is simple a transformation table which looks like :

Transformation Table:



When you look at Tag and Parent Column you can easily judge what actually happening in this query.


Hope will help you.

happy programming.

thanks.

Friday, November 6, 2009

How to select Top N Records from datatable

hi.
In a web application with asp.net, c# in i want to select Top N records fro datatable .this is possible in many ways.but preffered way are here.

We can select Top (N) records from data-table using LINQ.

//Suppose this is datatablse whic have 1000 records
DataTable dtAllRecords = new DataTable();
//(1)How to select Top 100
var AllRecords = from item in dtAllRecords.AsEnumerable()
select item;
var top100 = AllRecords.Take(100);
//(1)How To select Second 100 (records from 101 to 200)
var Second100 = AllRecords.Skip(100).Take(100);
/*
Using this Take and Skip method of LINQ we can easily select top N records from datatabse.
*/

Above code use two powerful methods of LINQ to select Top 100 and Second 100 records from datatabse. you can you Take and Skip methods to select Top(N) records from datatable

We can also select Top N records without using LINQ.
here is the sample code .

//Table with 20 records
DataTable dtDates = new DataTable();
dtDates.Columns.Add("Bdates");
for (int i = 0; i <>
{
dtDates.Rows.Add(DateTime.Now.AddDays(i));
}
//Want to select top 10 from above Datatatable
DataTable dtTop10 = dtDates.Clone();
Int32 N = 0;
while (N <>
{
dtTop10.ImportRow(dtDates.Rows[N]);
N++;
}


Hope this will help.

thanks.

Wednesday, November 4, 2009

How to read Feed from Remote path using Syndication

hi.
it is very hard task to read all type of Feeds and atoms Generically,because all feeds on web are not published with same standard.
Microsoft .Net framework 3.5 is shipped with new syndication library which provide very easy and reliable way to read this feeds in our system.

Then you can process them as you need using LINQ. here is the method the read feed as "SyndicationFeed".

Method to read Feed:

public SyndicationFeed ReadFeedFrom(string url)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.CheckCharacters = true;
settings.CloseInput = true;
settings.IgnoreComments = true;
settings.IgnoreProcessingInstructions = true;
settings.ProhibitDtd = false;

try
{
using (XmlReader reader = XmlReader.Create(url, settings))
{
SyndicationFeedFormatter GenericFeedFormatter = null;
Atom10FeedFormatter atom = new Atom10FeedFormatter();
Rss20FeedFormatter rss = new Rss20FeedFormatter();

if (reader.ReadState == ReadState.Initial)
{
reader.MoveToContent();
}
//If Atom can read it is Atom feed
if (atom.CanRead(reader))
{
GenericFeedFormatter = atom;
}
if (rss.CanRead(reader))
{
GenericFeedFormatter = rss;
}
if (GenericFeedFormatter == null)
{
return null;
}
GenericFeedFormatter.ReadFrom(reader);
return GenericFeedFormatter.Feed;

}
}
catch
{
return null;
}
}

If feeds is formatted according to Atom/Rss it will Choose proper formatter and returns you as SyndicationFeed . after that this class can be iterated using LINQ.

Process them with LINQ:

SyndicationFeed feed = ReadFeedFrom("http://feeds.feedburner.com/mobileburn/rss2");
var q = from t2 in feed.Items select new { Title = t2.Title.Text, Url = t2.Links[0].Uri.ToString(), pubDate = t2.PublishDate.DateTime };

then you can bind this LINQ variable to Grid or save them to database as per requirement.

Hope this will help.

thanks.

Tuesday, November 3, 2009

Perform UNION on Datatables in LINQ

hi.
some times we need to merge two tables in C#.we can use merge method of Data table.but if you have complex data and you want to perform some editional operations like sorting etc. before merging them you can use LINQ to dataset.

you can see working example below.
Table-1:

public DataTable GetTable1()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("BirthDate");
dt.Rows.Add("1", "Herry", "Thu, 18 Jan 2007 11:00:00 GMT");
dt.Rows.Add("1", "Mac", "Thu, 19 Jan 2007 11:00:00 GMT");
dt.Rows.Add("1", "Wisly", "Thu, 20 Jan 2007 11:00:00 GMT");
return dt;
}


Table-2:

public DataTable GetTable2()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("BirthDate");
dt.Rows.Add("1", "July", "1/19/2009 4:28:24");
dt.Rows.Add("1", "Anna", "1/20/2009 4:28:24");
dt.Rows.Add("1", "Jeniffer", "1/21/2009 4:28:24");
return dt;
}

Now you can join both tables using below code.

DataTable tmpDatatable = GetTable1().Clone();
var all = (from boys in GetTable1().AsEnumerable()
orderby boys["BirthDate"] descending
select boys).Union(from girls in GetTable2().AsEnumerable()
orderby girls["BirthDate"] descending
select girls);
all.CopyToDataTable(tmpDatatable, LoadOption.OverwriteChanges);
grvAll.DataSource = tmpDatatable;
grvAll.DataBind();

Thanks.