Specializations

Wednesday, November 21, 2012

File upload in AP.net


 Conditional base file uploading with database given path


private string Uploadfile()
        {
            string UPURL = string.Empty;
            if (fucFileUpload.HasFile)
            {
                try
                {
                    DataTable dt = dtImportCodes.Select("imp_cod_value='HLPFilePath'").CopyToDataTable();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        string filename = Path.GetFileName(fucFileUpload.FileName);
                        string fileType = "L";
                        dtImportCodes.AsEnumerable().Where(p => p["imp_cod_value"].ToString().Trim() == "HLPSource").ToList().ForEach(delegate(DataRow dr) { fileType = dr["directorypathFiled"].ToString(); });
                        if (fileType == "L")
                        {
                            string filePath = Server.MapPath(dt.Rows[0]["directorypathFiled"].ToString()) + "\\" + filename;
                            fucFileUpload.PostedFile.SaveAs(filePath);
                        }
                        else
                        {
                            fucFileUpload.SaveAs(dt.Rows[0]["directorypathFiled"].ToString() + "\\" + filename);
                        }
                        //fucFileUpload.SaveAs(dt.Rows[0]["directorypathFiled"].ToString() + "\\" + filename);
                       UPURL = filename;

                      
                    }
                }
                catch (Exception ex)
                {
                    LogError("GTKEntityHelp.UILayer.Security.Utilities", "Uploadfile", ex.GetBaseException().Message.ToString().Replace("\r\n", ""), UserCode, true);
                }

            }
            return UPURL;
        }

Tuesday, November 20, 2012

Global Trade Infor mation


Code                         Abrivation                                                    
HTS                        -Harmonized Tariff Schedule

SED                       

QP/WP                   -- Record idenitifier only 






ABI                           Automated Broker Interface

NAFTA                     Nort America Free Trade Agreement

CBP                         Customs and Border Protection


BOM                       Bill of Material


CBPF                     Customs Border Protection Form

Recon                      reconciliation


ACS                       Automate Commercial System

SCAC                     Standard Carier Alpha Code

AMS                        Automated Manifest System


Air Cargo Advanced Screening (ACAS) Initiative (PDF 320.58 KB)

Automated Export System (AES) Service

 

Excise Movement Control Systems (EMCS)

 

Import Control Systems (ICS)

 

Importer Security Filing (ISF) (PDF 267.8 KB)

ACE                     Automated Commercial Environment

Quality Performance

service bureaus (SB) 



GTK Foreign Trade Zone Product Features
GTkonnect FTZ software solution aims to automate your zone related data management and
transactions to the maximum possible extent by not only reconciling with your inventory BoM
data, but also by integrating with your other systems and your partners to reduce data entry.
Some salient features of GTKonnect FTZ software are:
 Ability to integrate your BoM data or your inventory consumption data to track inventory and
avoid manual entry and reconciliation
 Inventory reconciliation with your system on a daily basis
 High level of flexibility to accommodate your complex manufacturing processes and its use of
inventory towards products including exports, domestic, and ancillaries.
 High level of flexibility to integrate with your existing systems and unique identifiers for your
parts data to automate what falls within the zone purview.
 Ability to do weekly estimate tracking, anti-dumping tracking and combined NAFTA entries
 Comprehensive audit trail
 Unified web browser user interface and platform provides the ability to manage all zone
operations for a either single site or multiple subzones, as well as multiple customers in a
general purpose zone or any combination
 Automatically populate Advanced Shipment Notification (ASN) data by integrating with your
partners including carriers, freight forwarders, vessel operators etc.
 Integration with your CHB
 Ability to do individual and weekly Entries (CBPF 3461 and CBPF 7501)
 Ability to generate annual CBP Reconciliation Reports and FTZ Board Report
 Generate Quarterly Harbor Maintenance Fee Data Report
 Supports CBPF 7512 (in-bond documentation) and QP/WP transmissions
 Provides the ability to generate other custom reports
 Direct submission of e-214
 Direct submission of QP/WP (electronic in-bond transactions)
 ABI and ACE approved

String Formatting in C#

String Formatting in C#

I couldn’t find a quick reference to .NET string formatting using the String.Format() function, so I created this one (which has also spawned this String Formatting FAQ).
When I started working with the .NET framework, one thing puzzled me. I couldn’t find sprintf(). sprintf() is the C function that takes an output buffer, a format string, and any number of arguments, and builds a string for you. For example:
char szError[256];
sprintf(szError, “Error %d occurred.\n”, nError);
This would write “Error 12 occurred.” into the szError buffer (assuming nError was 12). It’s a basic part of C programming and most C++ programmers still use it though better functionality is available in the STL because sprintf is simple to use and clear. The STL equivalent would be:
str << “Error ” << nError << ” occurred.” << endl;
Or something close to that. It’s type-safe, and more OO than sprintf, but not as easy to read and not as easy to localize.
The .NET framework handles strings very nicely – but it takes some getting used to. The rough equivalent of sprintf in .NET is the static String.Format function, which takes a format string and some arguments, and generates an output string. (This is a nice improvement over sprintf since there’s no chance you’ll overflow the output buffer). For example:
string errorString = String.Format(“Error {0} occurred.”, nError);
Teeming with metadata, the .NET environment doesn’t need the format string to say what type of data you’re formatting, just where you want it. (A common sprintf bug is supplying the wrong data type – there’s no protection from using %s instead of %d and having your program crash when sprintf is called).
The {0} in the string above is replaced with the value of nError, but what if you want to specify the number of digits to use? Or the base (hexadecimal etc)? The framework supports all this, but where it seemed confusing is that it’s not the String.Format function that does the string formatting, but rather the types themselves.
Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself – in the String.Format call, the formatting string is passed after the position, for example, “{0:##}”
The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.

Strings

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call.
Sample Generates
String.Format(“->{1,10}<-”, “Hello”); -> Hello<-
String.Format(“->{1,-10}<-”, “Hello”); ->Hello <-

Numbers

Basic number formatting specifiers:
Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90
Custom number formatting:
Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below
The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:

Dates

Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.
Specifier Type Example (Passed System.DateTime.Now)
d Short date 10/12/2002
D Long date December 10, 2002
t Short time 10:11 PM
T Long time 10:11:29 PM
f Full date & time December 10, 2002 10:11 PM
F Full date & time (long) December 10, 2002 10:11:29 PM
g Default date & time 10/12/2002 10:11 PM
G Default date & time (long) 10/12/2002 10:11:29 PM
M Month day pattern December 10
r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
s Sortable date string 2002-12-10T22:11:29
u Universal sortable, local time 2002-12-10 22:13:50Z
U Universal sortable, GMT December 11, 2002 3:13:50 AM
Y Year month pattern December, 2002
The ‘U’ specifier seems broken; that string certainly isn’t sortable.
Custom date formatting:
Specifier Type Example Example Output
dd Day {0:dd} 10
ddd Day name {0:ddd} Tue
dddd Full day name {0:dddd} Tuesday
f, ff, … Second fractions {0:fff} 932
gg, … Era {0:gg} A.D.
hh 2 digit hour {0:hh} 10
HH 2 digit hour, 24hr format {0:HH} 22
mm Minute 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month abbreviation {0:MMM} Dec
MMMM Full month name {0:MMMM} December
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} PM
yy Year, 2 digits {0:yy} 02
yyyy Year {0:yyyy} 2002
zz Timezone offset, 2 digits {0:zz} -05
zzz Full timezone offset {0:zzz} -05:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002

Enumerations

Specifier Type
g Default (Flag names if available, otherwise decimal)
f Flags always
d Integer always
x Eight digit hex.

Some Useful Examples

String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, value);
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.
String.Format(“{0:(###) ###-####}”, 8005551212);
This will output “(800) 555-1212″.

224 Responses to “String Formatting in C#”

  1. stevex » Blog Archive » Different Theme Says:
    [...] In case anyone reads this on the main page instead of in an aggregator.. I’m trying out a different theme. It’s wider, so code snippets don’t wrap. I wanted to make my String Formatting in C# page look good since searching for how to do sprintf type formatting in C# is how most people find this site. [...]
  2. pwalls Says:
    Great resource! This is definitely a handy reference page I’ve added to my favorites. However, I did notice a minor error.
    The following:
    String.Format(“{0:(###) ###-####}”, 18005551212);
    Produces (1800) 555-1212 and not (800) 555-1212.
    Otherwise, great information.

Formatting in C#

String Formatting in C#

I couldn’t find a quick reference to .NET string formatting using the String.Format() function, so I created this one (which has also spawned this String Formatting FAQ).
When I started working with the .NET framework, one thing puzzled me. I couldn’t find sprintf(). sprintf() is the C function that takes an output buffer, a format string, and any number of arguments, and builds a string for you. For example:
char szError[256];
sprintf(szError, “Error %d occurred.\n”, nError);
This would write “Error 12 occurred.” into the szError buffer (assuming nError was 12). It’s a basic part of C programming and most C++ programmers still use it though better functionality is available in the STL because sprintf is simple to use and clear. The STL equivalent would be:
str << “Error ” << nError << ” occurred.” << endl;
Or something close to that. It’s type-safe, and more OO than sprintf, but not as easy to read and not as easy to localize.
The .NET framework handles strings very nicely – but it takes some getting used to. The rough equivalent of sprintf in .NET is the static String.Format function, which takes a format string and some arguments, and generates an output string. (This is a nice improvement over sprintf since there’s no chance you’ll overflow the output buffer). For example:
string errorString = String.Format(“Error {0} occurred.”, nError);
Teeming with metadata, the .NET environment doesn’t need the format string to say what type of data you’re formatting, just where you want it. (A common sprintf bug is supplying the wrong data type – there’s no protection from using %s instead of %d and having your program crash when sprintf is called).
The {0} in the string above is replaced with the value of nError, but what if you want to specify the number of digits to use? Or the base (hexadecimal etc)? The framework supports all this, but where it seemed confusing is that it’s not the String.Format function that does the string formatting, but rather the types themselves.
Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself – in the String.Format call, the formatting string is passed after the position, for example, “{0:##}”
The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.

Strings

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call.
Sample Generates
String.Format(“->{1,10}<-”, “Hello”); -> Hello<-
String.Format(“->{1,-10}<-”, “Hello”); ->Hello <-

Numbers

Basic number formatting specifiers:
Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90
Custom number formatting:
Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below
The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:

Dates

Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.
Specifier Type Example (Passed System.DateTime.Now)
d Short date 10/12/2002
D Long date December 10, 2002
t Short time 10:11 PM
T Long time 10:11:29 PM
f Full date & time December 10, 2002 10:11 PM
F Full date & time (long) December 10, 2002 10:11:29 PM
g Default date & time 10/12/2002 10:11 PM
G Default date & time (long) 10/12/2002 10:11:29 PM
M Month day pattern December 10
r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
s Sortable date string 2002-12-10T22:11:29
u Universal sortable, local time 2002-12-10 22:13:50Z
U Universal sortable, GMT December 11, 2002 3:13:50 AM
Y Year month pattern December, 2002
The ‘U’ specifier seems broken; that string certainly isn’t sortable.
Custom date formatting:
Specifier Type Example Example Output
dd Day {0:dd} 10
ddd Day name {0:ddd} Tue
dddd Full day name {0:dddd} Tuesday
f, ff, … Second fractions {0:fff} 932
gg, … Era {0:gg} A.D.
hh 2 digit hour {0:hh} 10
HH 2 digit hour, 24hr format {0:HH} 22
mm Minute 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month abbreviation {0:MMM} Dec
MMMM Full month name {0:MMMM} December
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} PM
yy Year, 2 digits {0:yy} 02
yyyy Year {0:yyyy} 2002
zz Timezone offset, 2 digits {0:zz} -05
zzz Full timezone offset {0:zzz} -05:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002

Enumerations

Specifier Type
g Default (Flag names if available, otherwise decimal)
f Flags always
d Integer always
x Eight digit hex.

Some Useful Examples

String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, value);
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.
String.Format(“{0:(###) ###-####}”, 8005551212);
This will output “(800) 555-1212″.

224 Responses to “String Formatting in C#”

  1. stevex » Blog Archive » Different Theme Says:
    [...] In case anyone reads this on the main page instead of in an aggregator.. I’m trying out a different theme. It’s wider, so code snippets don’t wrap. I wanted to make my String Formatting in C# page look good since searching for how to do sprintf type formatting in C# is how most people find this site. [...]
  2. pwalls Says:
    Great resource! This is definitely a handy reference page I’ve added to my favorites. However, I did notice a minor error.
    The following:
    String.Format(“{0:(###) ###-####}”, 18005551212);
    Produces (1800) 555-1212 and not (800) 555-1212.
    Otherwise, great information.



<%= String.Format("{specifier}", DateTime.Now) %>
Specifier Description Output
d Short Date 08/04/2007
D Long Date 08 April 2007
t Short Time 21:08
T Long Time 21:08:59
f Full date and time 08 April 2007 21:08
F Full date and time (long) 08 April 2007 21:08:59
g Default date and time 08/04/2007 21:08
G Default date and time (long) 08/04/2007 21:08:59
M Day / Month 08 April
r RFC1123 date Sun, 08 Apr 2007 21:08:59 GMT
s Sortable date/time 2007-04-08T21:08:59
u Universal time, local timezone 2007-04-08 21:08:59Z
Y Month / Year April 2007
dd Day 08
ddd Short Day Name Sun
dddd Full Day Name Sunday
hh 2 digit hour 09
HH 2 digit hour (24 hour) 21
mm 2 digit minute 08
MM Month 04
MMM Short Month name Apr
MMMM Month name April
ss seconds 59
tt AM/PM PM
yy 2 digit year 07
yyyy 4 digit year 2007
: seperator, e.g. {0:hh:mm:ss} 09:08:59
/ seperator, e.g. {0:dd/MM/yyyy} 08/04/2007

conversion methods in c#.net


How to: Convert a string to an int (C# Programming Guide)



These examples show some different ways you can convert a string to an int. Such a conversion can be useful when obtaining numerical input from a command line argument, for example. Similar methods exist for converting strings to other numeric types, such as float or long. The table below lists some of those methods.
Numeric Type Method
decimal ToDecimal(String)
float ToSingle(String)
double ToDouble(String)
short ToInt16(String)
int ToInt32(String)
long ToInt64(String)
ushort ToUInt16(String)
uint ToUInt32(String)
ulong ToUInt64(String)


This example calls the ToInt32(String) method to convert an input string to an int . The program catches the two most common exceptions that can be thrown by this method, FormatException and OverflowException. If the number can be incremented without overflowing the integer storage location, the program adds 1 to the result and prints the output.
static void Main(string[] args)
{
    int numVal = -1;
    bool repeat = true;

    while (repeat == true)
    {
        Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");

        string input = Console.ReadLine();

        // ToInt32 can throw FormatException or OverflowException. 
        try
        {
            numVal = Convert.ToInt32(input);
        }
        catch (FormatException e)
        {
            Console.WriteLine("Input string is not a sequence of digits.");
        }
        catch (OverflowException e)
        {
            Console.WriteLine("The number cannot fit in an Int32.");
        }
        finally
        {
            if (numVal < Int32.MaxValue)
            {
                Console.WriteLine("The new value is {0}", numVal + 1);
            }
            else
            {
                Console.WriteLine("numVal cannot be incremented beyond its current value");
            }
        }
        Console.WriteLine("Go again? Y/N");
        string go = Console.ReadLine();
        if (go == "Y" || go == "y")
        {
            repeat = true;
        }
        else
        {
            repeat = false;
        }
    }
    // Keep the console open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();    
}
// Sample Output: 
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive). 
// 473 
// The new value is 474 
// Go again? Y/N 
// y 
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive). 
// 2147483647 
// numVal cannot be incremented beyond its current value 
// Go again? Y/N 
// Y 
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive). 
// -1000 
// The new value is -999 
// Go again? Y/N 
// n 
// Press any key to exit.
Another way of converting a string to an int is through the Parse or TryParse methods of the System.Int32 struct. The ToUInt32 method uses Parse internally. If the string is not in a valid format, Parse throws an exception whereas TryParse does not throw an exception but returns false. The examples below demonstrate both successful and unsuccessful calls to Parse and TryParse.
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded 
// and stores the result in the specified variable. 
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105
try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

// Output: Int32.TryParse could not parse 'abc' to an int. 
 
 
 
LINQ to Datatable 


private static DataTable JoinDataTablesWithLinq()
    {
    var query = from inv in _tblInvoice.AsEnumerable()
                join item in _tblLineItem.AsEnumerable()
                    on inv["InvoiceId"] equals item["InvoiceId"]
                select new
                        {
                            CustomerName = inv["CustomerName"],
                            ItemName = item["ItemName"],
                            Quantity = item["Quantity"]
                        };
 
    return query.CopyToDataTable();
    }
 
 
 
LINQ TO DATATABLE EXAMPLE:
 
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
     DataTable dtReturn = new DataTable();
     // column names 
     PropertyInfo[] oProps = null;

     if (varlist == null) return dtReturn;     foreach (T rec in varlist)
     {
          // Use reflection to get property names, to create table, Only first time, others
          will follow 
          if (oProps == null)
          {
               oProps = ((
Type)rec.GetType()).GetProperties();               foreach (PropertyInfo pi in oProps)
               {
                    Type colType = pi.PropertyType;                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()                          ==typeof(Nullable<>)))
                     {
                         colType = colType.GetGenericArguments()[0];
                     }

                    dtReturn.Columns.Add(
new DataColumn(pi.Name, colType));
               }
          }
          DataRow dr = dtReturn.NewRow();          foreach (PropertyInfo pi in oProps)
          {
               dr[pi.Name] = pi.GetValue(rec,
null) == null ?DBNull.Value :pi.GetValue               (rec,null);
          }

          dtReturn.Rows.Add(dr);
     }
     return dtReturn;
}
 
 
 
 
Another way to convert linq to data table
 
public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query){     if (query == null)
     {          throw new ArgumentNullException("query");
     }     
     IDbCommand cmd = ctx.GetCommand(query as IQueryable);     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (SqlCommand)cmd;     DataTable dt = new DataTable("sd");
     try     {
          cmd.Connection.Open();
          adapter.FillSchema(dt, SchemaType.Source); 
          adapter.Fill(dt);
     }     finally     {
          cmd.Connection.Close();     }     return dt;
} 
 
 
 
Another way using linq to conversion
 
var vrCountry = from country in objEmpDataContext.CountryMaster                         select new {country.CountryID,country.CountryName};
DataTable dt = LINQToDataTable(objEmpDataContext,vrCountry);
 

To implement the custom CopyToDataTable<T> methods in your application

 
 
 public class ObjectShredder<T>
{
    private System.Reflection.FieldInfo[] _fi;
    private System.Reflection.PropertyInfo[] _pi;
    private System.Collections.Generic.Dictionary<string, int> _ordinalMap;
    private System.Type _type;

    // ObjectShredder constructor.
    public ObjectShredder()
    {
        _type = typeof(T);
        _fi = _type.GetFields();
        _pi = _type.GetProperties();
        _ordinalMap = new Dictionary<string, int>();
    }

    /// <summary>
    /// Loads a DataTable from a sequence of objects.
    /// </summary>
    /// <param name="source">The sequence of objects to load into the DataTable.</param>
    /// <param name="table">The input table. The schema of the table must match that 
    /// the type T.  If the table is null, a new table is created with a schema 
    /// created from the public properties and fields of the type T.</param>
    /// <param name="options">Specifies how values from the source sequence will be applied to 
    /// existing rows in the table.</param>
    /// <returns>A DataTable created from the source sequence.</returns>
    public DataTable Shred(IEnumerable<T> source, DataTable table, LoadOption? options)
    {
        // Load the table from the scalar sequence if T is a primitive type.
        if (typeof(T).IsPrimitive)
        {
            return ShredPrimitive(source, table, options);
        }

        // Create a new table if the input table is null.
        if (table == null)
        {
            table = new DataTable(typeof(T).Name);
        }

        // Initialize the ordinal map and extend the table schema based on type T.
        table = ExtendTable(table, typeof(T));

        // Enumerate the source sequence and load the object values into rows.
        table.BeginLoadData();
        using (IEnumerator<T> e = source.GetEnumerator())
        {
            while (e.MoveNext())
            {
                if (options != null)
                {
                    table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
                }
                else
                {
                    table.LoadDataRow(ShredObject(table, e.Current), true);
                }
            }
        }
        table.EndLoadData();

        // Return the table.
        return table;
    }

    public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOption? options)
    {
        // Create a new table if the input table is null.
        if (table == null)
        {
            table = new DataTable(typeof(T).Name);
        }

        if (!table.Columns.Contains("Value"))
        {
            table.Columns.Add("Value", typeof(T));
        }

        // Enumerate the source sequence and load the scalar values into rows.
        table.BeginLoadData();
        using (IEnumerator<T> e = source.GetEnumerator())
        {
            Object[] values = new object[table.Columns.Count];
            while (e.MoveNext())
            {
                values[table.Columns["Value"].Ordinal] = e.Current;

                if (options != null)
                {
                    table.LoadDataRow(values, (LoadOption)options);
                }
                else
                {
                    table.LoadDataRow(values, true);
                }
            }
        }
        table.EndLoadData();

        // Return the table.
        return table;
    }        

    public object[] ShredObject(DataTable table, T instance)
    {

        FieldInfo[] fi = _fi;
        PropertyInfo[] pi = _pi;

        if (instance.GetType() != typeof(T))
        {
            // If the instance is derived from T, extend the table schema
            // and get the properties and fields.
            ExtendTable(table, instance.GetType());
            fi = instance.GetType().GetFields();
            pi = instance.GetType().GetProperties();
        }

        // Add the property and field values of the instance to an array.
        Object[] values = new object[table.Columns.Count];
        foreach (FieldInfo f in fi)
        {
            values[_ordinalMap[f.Name]] = f.GetValue(instance);
        }

        foreach (PropertyInfo p in pi)
        {
            values[_ordinalMap[p.Name]] = p.GetValue(instance, null);
        }

        // Return the property and field values of the instance.
        return values;
    }

    public DataTable ExtendTable(DataTable table, Type type)
    {
        // Extend the table schema if the input table was null or if the value 
        // in the sequence is derived from type T.            
        foreach (FieldInfo f in type.GetFields())
        {
            if (!_ordinalMap.ContainsKey(f.Name))
            {
                // Add the field as a column in the table if it doesn't exist
                // already.
                DataColumn dc = table.Columns.Contains(f.Name) ? table.Columns[f.Name]
                    : table.Columns.Add(f.Name, f.FieldType);

                // Add the field to the ordinal map.
                _ordinalMap.Add(f.Name, dc.Ordinal);
            }
        }
        foreach (PropertyInfo p in type.GetProperties())
        {
            if (!_ordinalMap.ContainsKey(p.Name))
            {
                // Add the property as a column in the table if it doesn't exist
                // already.
                DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
                    : table.Columns.Add(p.Name, p.PropertyType);

                // Add the property to the ordinal map.
                _ordinalMap.Add(p.Name, dc.Ordinal);
            }
        }

        // Return the table.
        return table;
    }
}
 
 
 public static class CustomLINQtoDataSetMethods
{
    public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
    {
        return new ObjectShredder<T>().Shred(source, null, null);
    }

    public static DataTable CopyToDataTable<T>(this IEnumerable<T> source,
                                                DataTable table, LoadOption? options)
    {
        return new ObjectShredder<T>().Shred(source, table, options);
    }

}
 
 
 
 
 Convert datatable to list
 
STEP 1:
  List<MyClassObject> liMyClassObject=myConvesionObject.GetDetails(yourdatatable);
 
 
 STEP 2:
 
class myConvesionObject
{ 
 public List<MyClassObject> GetDetails(DataTable dtDetails)
        {
            return MyConversionClass.ConvertToList<MyClassObject>(dtDetails);
        }
} 
 
STEP 3:  my conversion class

 public static class MyConversionClass
    {
       /// <summary>
       /// Convert DataTable ToList
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="table"></param>
       /// <returns></returns>
        public static List<T> ConvertToList<T>(this DataTable table) where T : new()
        {
            Type t = typeof(T);

            // Create a list of the entities we want to return
            List<T> returnObject = new List<T>();

            // Iterate through the DataTable's rows
            foreach (DataRow dr in table.Rows)
            {
                // Convert each row into an entity object and add to the list
                T newRow = dr.ConvertToEntity<T>();
                returnObject.Add(newRow);
            }

            // Return the finished list
            return returnObject;
        }
       /// <summary>
       /// ConvertTo Entity
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="tableRow"></param>
       /// <returns></returns>
        public static T ConvertToEntity<T>(this DataRow tableRow) where T : new()
        {
            // Create a new type of the entity I want
            Type t = typeof(T);
            T returnObject = new T();

            foreach (DataColumn col in tableRow.Table.Columns)
            {
                string colName = col.ColumnName;

                // Look for the object's property with the columns name, ignore case
                PropertyInfo pInfo = t.GetProperty(colName.ToUpper(),
                    BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                // did we find the property ?
                if (pInfo != null)
                {
                    object val = tableRow[colName];

                    // is this a Nullable<> type
                    bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null);
                    if (IsNullable)
                    {
                        if (val is System.DBNull)
                        {
                            val = null;
                        }
                        else
                        {
                            // Convert the db type into the T we have in our Nullable<T> type
                            val = Convert.ChangeType
                    (val, Nullable.GetUnderlyingType(pInfo.PropertyType));
                        }
                    }
                    else
                    {
                        // Convert the db type into the type of the property in our entity
                        val = Convert.ChangeType(val, pInfo.PropertyType);
                    }
                    // Set the value of the property with the value from the db
                    pInfo.SetValue(returnObject, val.ToString().Trim().ToUpper(), null); 

                    //pInfo.SetValue(returnObject, val.ToString().ToUpper(), null);
                }
            }

            // return the entity object with values
            return returnObject;
        }
        /// <summary>
        /// Convert DataRow[]  ToList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static List<T> ConvertToList<T>(this DataRow[] dtRows) where T : new()
        {
            Type t = typeof(T);

            // Create a list of the entities we want to return
            List<T> returnObject = new List<T>();

            // Iterate through the DataTable's rows
            foreach (DataRow dr in dtRows)
            {
                // Convert each row into an entity object and add to the list
                T newRow = dr.ConvertToEntity<T>();
                returnObject.Add(newRow);
            }

            // Return the finished list
            return returnObject;
        }
        public static List<EntityClass> ConvertGridEntity<T>(this List<T> liValues, int Pno, int RecPage, List<string> listr) where T : new()
        {

            Type t = typeof(T);
            Type Et = typeof(EntityClass);
            // Create a list of the entities we want to return
            List<EntityClass> returnObject = new List<EntityClass>();
            Type gType = typeof(T);
            int licount = liValues.Count;
            int StartInd = ((Pno) * RecPage + 1);
            int EndInd = Convert.ToInt32(((Pno + 1) * RecPage) > licount ? licount : ((Pno + 1) * RecPage));
            for (int ind = StartInd; ind <= EndInd; ind++)
            {
                T genType = liValues[ind - 1];
                EntityClass EC = new EntityClass();
                PropertyInfo[] EntitypropInfo = EC.GetType().GetProperties();
                //EntityClass E = new EntityClass();
                PropertyInfo[] propInfo = genType.GetType().GetProperties();




                Array.Sort(propInfo, new DeclarationOrderComparator());
    
                int j = 0;
                foreach (string str in listr)
                {
                    int i = Convert.ToInt32(str);
                    j = j + 1;
                    if (!string.IsNullOrEmpty(string.Format("{0}", propInfo[i].GetValue(genType, null)))&&j<16)
                    {
                        var value = propInfo[i].GetValue(genType, null).ToString().ToUpper();
                        // Look for the object's property with the columns name, ignore case
                     
                        PropertyInfo pInfo = Et.GetProperty("C" + j + "",
                        BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                      
                        //pInfo.SetValue(genType, value, i);
                        pInfo.SetValue(EC, value, null);

                    }
                }
                returnObject.Add(EC);
            }

            // Return the finished list
            return returnObject;
        }
       
    }
   public class DeclarationOrderComparator : IComparer
   {
       int IComparer.Compare(Object x, Object y)
       {
           PropertyInfo first = x as PropertyInfo;
           PropertyInfo second = y as PropertyInfo;
           if (first.MetadataToken < second.MetadataToken)
               return -1;
           else if (first.MetadataToken > second.MetadataToken)
               return 1;

           return 0;
       }
   }
 
 
 
LIST TO XML CONVETIONS 
 
 
STEP 1:
List<myListClass> mylistObjects=new  List<myListClass>(); 
string mystringxml=myclassconversion.PrepareSaveXml(mylistObjects) 
 
STEP 2:
 
class myclassconversion
{
  public string PrepareSaveXml(List<myListClass> liValues)
        {
            return ListToXMLCLass.GetXml<myListClass>(liValues, "RootNode", "ChildNode");
        }
 
} 
 
STEP 3:
 
 
 public static class ListToXMLCLass
    {
        /// <summary>
        /// Preparing Save XML string with GenericType
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="liValues"></param>
        /// <param name="parentRoot"></param>
        /// <param name="childRoot"></param>
        /// <returns></returns>
        public static string GetXml<T>(List<T> liValues,string parentRoot,string childRoot)
        {
            XDocument xDoc = new XDocument();
            var partentRoot = new XElement(parentRoot);
           
            foreach (T genType in liValues)
            {
                PropertyInfo[] propInfo = genType.GetType().GetProperties();
                var childroot = new XElement(childRoot);
                foreach (PropertyInfo prop in propInfo)
                {
                    if (prop.PropertyType.FullName.ToUpper() == typeof(System.String).ToString().ToUpper() || prop.PropertyType.FullName.ToUpper() == typeof(System.Int32).ToString().ToUpper() || prop.PropertyType.FullName.ToUpper() == typeof(System.Double).ToString().ToUpper())
                    {
                        if (prop.Name.ToLower() != "parentrootnode" && prop.Name.ToLower() != "parentnode" && prop.Name.ToLower() != "childnode")
                        {
                            if (!string.IsNullOrEmpty(string.Format("{0}", prop.GetValue(genType, null))))
                                childroot.SetAttributeValue(prop.Name, GTKString.ToEscapeSpecialChars(prop.GetValue(genType, null).ToString()));
                        }
                    }
                }
                 partentRoot.Add(childroot);
             }
            xDoc.Add(partentRoot);
            return xDoc.ToString();
         }

        public static XElement GetEntityXml<T>(T genClass, string RootNode)
        {
            XDocument xDoc = new XDocument();
            PropertyInfo[] propInfo = genClass.GetType().GetProperties();
            var childroot = new XElement(RootNode);
            foreach (PropertyInfo prop in propInfo)
            {
                if (prop.Name.ToLower() != "parentrootnode" && prop.Name.ToLower() != "parentnode" && prop.Name.ToLower() != "childnode")
                {
                    if (!string.IsNullOrEmpty(string.Format("{0}", prop.GetValue(genClass, null))))
                        childroot.SetAttributeValue(prop.Name, GTKString.ToEscapeSpecialChars(prop.GetValue(genClass, null).ToString()));
                }
            }
//
            xDoc.Add(childroot);
            return childroot;
        }
    }