Posts Tagged ‘C#’

Today’s post is a small code snippet for you to write byte array to an xml file using FileStream and Binary Writer class’s Write method.Hope this helps 🙂

private void ByteArrayToFile(string fileName, byte[] byteArray)
{
FileStream fs = new FileStream(fileName + ".xml", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode);
bw.Write(byteArray);
bw.Close();
fs.Close();
}

Advertisements

In one of my stored pocedure’s an input parameter accepts Guid value & every time I wanted to test it,I used to run class from C# with Guid.NewGuid().ToString() to copy value & add it to stored procedure.Quite weird right 🙂 Because I never knew how else I can generate a guid value.

Visual Studio External Tools come with a tool guidgen.exe that can help you create Guid in a specified format.

Path – C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\guidgen.exe

How to Use guidgen.exe?

  1. Run exe
  2. Select the format you want for the GUID.
  3. Click New GUID & then Copy.

The GUID is copied to the Clipboard so that you can paste it whereever you want.

If you want to generate another GUID, click New GUID

I decided to write a method utilizing Tuple which is newly introduced in VS 2010.I did not bother to open a new solution,just tried to add a new method of return type Tuple in an existing project’s class.

It took half an hour to figure out why it was giving a compilation error saying “The type or namespace name “Tuple” could not be found”.I rushed to msdn to figure out which namespace it referes to or any dll I need to refer.I found,it is added in System namespace which is already added to my cs file.I kept on googling for sometime & nothing helped.Finally figured out that though my solution is VS2010,Target Framework is not set to 4.0 & it’s still 3.5 😦 so simple it is,still took long time to track the exact issue.

Moral is,whenever you are implementing something newly introduced to framework,make sure that you check the target framework version & not the visual studio version :).

Did you know that LINQ simplifies working with XML data & you need not use Xpath or XQuery for reading XML?Below code queries the xml & populates the listbox with values of Subject node under Book.

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Books>
  <Book>
    <Subject>
      Social Science
    </Subject>
    <Content>
      History,Geography
    </Content>
  </Book>

  <Book>
    <Subject>
     General Science
    </Subject>
    <Content>
      Biology,Chemistry,Physics
    </Content>
  </Book>
  </Books>

var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book")
select nodes;
if (books != null)
{
foreach (var b in books)
{
listBox1.Items.Add(b.Element(“Subject”).Value.Trim());

}
}

It took sometime to figure out what went wrong when I was getting an Unauthorized Access Exception when trying to delete folder from C#.

UnAuthorizedAcess Exception when trying to delete a folder

There was a misleading factor that the folder was residing on our server & had an impression that authorization is not given to do so.I started thinking from a code perspective,when I could delete the folder manually & later via code when I manually changed the readonly attribute to false. So the problem was that readonly attribute gets set by itself while folder/file is getting created or copied via code hence it will not let you delete unless you remove the attributes.

I am adding the code snippet to delete the folder with the comments herewith

public void RemoveFolder(string[] FolderNames)
{
//Gets Path from web.config
string Path = ConfigurationManager.AppSettings[“Root”];
//Loops through all the folder names & form the DirectoryInfo Path
FolderNames.ToList().ForEach(foldername =>
{

DirectoryInfo Folder = new DirectoryInfo(Path + @”\” + foldername.Trim());
//Checks if folder exists in the Path provided
if (Folder.Exists)
{
//Sets attributes for the DirectoryInfo
Folder.Attributes = Folder.Attributes & ~System.IO.FileAttributes.ReadOnly;
//Gets all files inside the folder
FileInfo[] files = Folder.GetFiles();
//For each file,set the attributes so that it does not throw
//unauthorized access exception while trying to delete
Array.ForEach<FileInfo>(files, new Action<FileInfo>(
                            f =>
                            {
                                File.SetAttributes(f.FullName, FileAttributes.Normal);
                            }));

Folder.Delete(true);

}
});
}

Hope you find this post useful 🙂

It’s been few days since I wrote anything as I was enjoying my christmas vecation 🙂 Hope you all had a wonderful holiday time celebrating christmas.

What I am going to share today is about using extension methods in .Net.I faced this scenario recently & thought will make a note of this so that months later I can look back & remember what I learnt. Extension methods are a special kind of static method that enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

For example if you are using LINQ to read a OracleDataReader & want to check if a column exists in a DataReader object,we do not have a direct method that does so.Here comes the use of a custom extension method.These are the steps to follow

  • Define a static class to contain the extension method.
  • The class must be visible to client.
  • Implement the extension method as a static method with at least the same visibility as the containing class.
  • The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
  • namespace Helper
    {

    public static class Extension
    {

    public static bool HasColumn(this IDataRecord dr, string columnName)
    {
    for (int i = 0; i < dr.FieldCount; i++)
    {
    if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
    return true;
    }
    return false;
    }
    }
    }

  • In the calling code, add a using directive to specify the namespace that contains the extension method class.
  • Call the methods as if they were instance methods on the type.
  • Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.

    public void Format(OracleDataReader reader)
    {
    try
    {
    bool iscolumnexist = reader.HasColumn(“Description”);

    }
    catch (Exception ex)
    {

    throw;
    }
    }

    Hope you find this code snippet useful 🙂

    I beleive most of you know about overloading in oops.Well,to have some optional parameters some time before, we had to rely on overloading itself.But now things have changed & with the introduction of Optional Parameters in C#4.0,it’s going to be really easy. This is how it will look like.
    Eg:

    public void ExampleMethod(int required, string optionalstr = "default string",int optionalint = 10)

  • Each optional parameter has a default value as part of its definition.
  • If no argument is sent for that parameter, the default value is used. These default values must be constants.
  • Comma-separated gaps in the argument list are not supported.
  • The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second.

    ExampleMethod(3, ,4);

    However, if you know the name of the third parameter, you can use a named argument to accomplish the task.

    ExampleMethod(3, optionalint: 4);

  • Optional parameters can also be defined at the end of the parameter list, after any required parameters.
  • public void ExampleMethod(int required,int optionalint = 10,string optionalstr = "default string")

  • If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.