Gokul's Blog


Leave a comment

XSD to table generator

http://stackoverflow.com/questions/2628327/how-to-build-a-database-from-an-xsd-schema-and-import-xml-data

http://stackoverflow.com/questions/138575/how-can-i-create-database-tables-from-xsd-files

Creating Database from XSD file

http://stackoverflow.com/questions/403420/convert-xsd-into-sql-relational-tables


Leave a comment

UNC access in C#

Below code helps to access a UNC path with different credentials

Thanks to source article: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/0cbd77b7-5c6c-4a86-bc3a-e06eb888fa17
Usage:
UNCAccess uncAccess = new UNCAccess(uncPath,”username”, “domain”,”Password”);

Code for UNCAccess class:

public class UNCAccess
{
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
	internal struct USE_INFO_2
	{
		internal LPWSTR ui2_local;
		internal LPWSTR ui2_remote;
		internal LPWSTR ui2_password;
		internal DWORD ui2_status;
		internal DWORD ui2_asg_type;
		internal DWORD ui2_refcount;
		internal DWORD ui2_usecount;
		internal LPWSTR ui2_username;
		internal LPWSTR ui2_domainname;
	}

	[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
	internal static extern NET_API_STATUS NetUseAdd(
		LPWSTR UncServerName,
		DWORD Level,
		ref USE_INFO_2 Buf,
		out DWORD ParmError);

	[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
	internal static extern NET_API_STATUS NetUseDel(
		LPWSTR UncServerName,
		LPWSTR UseName,
		DWORD ForceCond);

	private string sUNCPath;
	private string sUser;
	private string sPassword;
	private string sDomain;
	private int iLastError;
	public UNCAccess()
	{
	}
	public UNCAccess(string UNCPath, string User, string Domain, string Password)
	{
		login(UNCPath, User, Domain, Password);
	}
	public int LastError
	{
		get { return iLastError; }
	}

	///
<summary> /// Connects to a UNC share folder with credentials
 /// </summary>
	///UNC share path
	///Username
	///Domain
	///Password
	/// True if login was successful
	public bool login(string UNCPath, string User, string Domain, string Password)
	{
		sUNCPath = UNCPath;
		sUser = User;
		sPassword = Password;
		sDomain = Domain;
		return NetUseWithCredentials();
	}
	private bool NetUseWithCredentials()
	{
		uint returncode;
		try
		{
			USE_INFO_2 useinfo = new USE_INFO_2();

			useinfo.ui2_remote = sUNCPath;
			useinfo.ui2_username = sUser;
			useinfo.ui2_domainname = sDomain;
			useinfo.ui2_password = sPassword;
			useinfo.ui2_asg_type = 0;
			useinfo.ui2_usecount = 1;
			uint paramErrorIndex;
			returncode = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex);
			iLastError = (int)returncode;
			return returncode == 0;
		}
		catch
		{
			iLastError = Marshal.GetLastWin32Error();
			return false;
		}
	}

	///
<summary> /// Closes the UNC share
 /// </summary>
	/// True if closing was successful
	public bool NetUseDelete()
	{
		uint returncode;
		try
		{
			returncode = NetUseDel(null, sUNCPath, 2);
			iLastError = (int)returncode;
			return (returncode == 0);
		}
		catch
		{
			iLastError = Marshal.GetLastWin32Error();
			return false;
		}
	}

}


Leave a comment

File Helpers to handle large text file

File Helpers to handle large text file

Sample Type
<pre>[Delimitedrecord("|")]
 public class SampleType
 {
	public string Field1;
	public int    Field2;
 }

For small files

FileHelperEngine&lt;SampleType&gt; engine = new FileHelperEngine&lt;SampleType&gt;();
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
_dataSet = engine.ReadFile(sourceFilePath).ToDataSet();

For large files
                    FileHelperAsyncEngine engine2 = new FileHelperAsyncEngine(typeof(SampleType));
                    engine2.BeginReadFile(sourceFilePath);

                    List&lt;SampleType&gt; records = new List&lt;SampleType&gt;();
                    int iCount = 0;
                    while (engine2.ReadNext() != null)
                    {
                        records.Add((SampleType)engine2.LastRecord);
                        if (iCount++ &gt; 10000)
                        {
                            //Put in a queue here and call the method to create dataset as follows
                            ///records.ToDataSet();
                            records = new List&lt;SampleType&gt;(); //rinse and repeat till all records are processed.
                        }
                        // put your code here !!!!
                        Console.WriteLine("Data " + records[0].Field1 + " , " + records[0].Field2.ToString());

                    }
Extension method to create Dataset from a list.
 #region Extension Classes
    static class Extensions
    {
        public static DataSet ToDataSet&lt;T&gt;(this IList&lt;T&gt; list)
        {
            Type elementType = typeof(T);
            DataSet ds = new DataSet();
            DataTable t = new DataTable(elementType.Name);
            ds.Tables.Add(t);

            //add a column to table for each public property on T
            foreach (var propInfo in elementType.GetProperties())
            {
                Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

                t.Columns.Add(propInfo.Name, ColType);
            }

            //go through each property on T and add each value to the table
            foreach (T item in list)
            {
                DataRow row = t.NewRow();

                foreach (var propInfo in elementType.GetProperties())
                {
                    row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                }

                t.Rows.Add(row);
            }

            return ds;
        }
    }
    #endregion


Leave a comment

Paging query helper C#

Code snippet which generates paging query 

int RecordCount = 3435354535647829;
int PageSize = 50000;
int MaxThreadCount = 5;
int PageSizebaseThreadSize = (RecordCount / MaxThreadCount) + 1;

PageSize = PageSizebaseThreadSize;

Console.WriteLine(PageSizebaseThreadSize);

int i = 0;
while(i i = i + PageSize;
}


Leave a comment

Generate XSD for a XML file

Original Link: http://www.gibmonks.com/c_sharp/csharpckbk2-CHP-15-SECT-13.html

[sourceode language=”csharp”]
public static void GenerateSchemaForDirectory(string dir)
{
// Make sure the directory exists.
if (Directory.Exists(dir))
{
// Get the files in the directory.
string[] files = Directory.GetFiles(dir, “*.xml”);
foreach (string file in files)
{
// Set up a reader for the file.
using (XmlReader reader = XmlReader.Create(file))
{
XmlSchemaSet schemaSet = new XmlSchemaSet();
XmlSchemaInference schemaInference =
new XmlSchemaInference();

// Get the schema.
schemaSet = schemaInference.InferSchema(reader);

string schemaPath = “”;
foreach (XmlSchema schema in schemaSet.Schemas())
{
// Make schema file path.
schemaPath = Path.GetDirectoryName(file) + @”\” +
Path.GetFileNameWithoutExtension(file) + “.xsd”;
using (FileStream fs =
new FileStream(schemaPath, FileMode.OpenOrCreate))
{
schema.Write(fs);
}
}
}
}
}
}
[/sourcecode]


Leave a comment

Working with XMLTextReader

Some good articles from MSDN on how to work with XMLTextReader. The below block of code can be used to iterate through the list of book in a XML list of books.

XmlTextReader reader = new XmlTextReader(@"C:\books.xml");

            XmlDocument doc;
            reader.MoveToContent();
            while (reader.Read())
            {
                Application.DoEvents();
                //if (reader.MoveToContent() == XmlNodeType.Element
                 // && reader.Name == "ns0:book")
                if (reader.Name == "ns0:book")
                {
                    doc = new System.Xml.XmlDocument();
                        XmlNode node = doc.ReadNode(reader);
                        txtStatus.Text = txtStatus.Text + node.OuterXml.ToString()
                                        + Environment.NewLine
                                         + "---Processed Node No:"
                                         + i++ + "---" + Environment.NewLine;
                   doc = null;
                }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }