myfavoritemovies.us

June 22, 2008

Handling Resources in C#

Filed under: C# 3.0 — @ 12:41 am

Most of the people use resources when they want localize a product. Some other uses would be to use static reference files etc., For a month or two I have been use ResourceManager for one of my project. The requirement is very simple, I need to create a resource with bunch of files and then later build the same resource file into a C# project which when running would extract the files from the resource which was build in the previous step. Like any other simple C# coder, I approached the problem with our ResourceReader and ResourceWriter.

I first created a class called Writer as shown below, 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.IO;
 
namespace ResourceBuilder
{
    public class Writer
    {
        public void WriteFile(string resourceName, string fileName)
        {
            ResourceWriter writer = new ResourceWriter(resourceName);
            CreateFile(fileName);
            byte[] file = File.ReadAllBytes(fileName);
            writer.AddResource(fileName, file);
            writer.Generate();
            writer.Close();
        }
 
        private void CreateFile(string name)
        {
            using (StreamWriter wr = new StreamWriter(name))
            {
                for (int i = 0; i < 5; i++)
                    wr.WriteLine(i.ToString());
            }
        }
    }
}

 
Writer class has one method called WriteFile, which creates a simple resource file and then populate the resource with one text file. The text file is created dynamically.
 
Next I created a class called Reader which does nothing but read the information from the resource file and creates output file. There are two ways you can read the resource file and I created two separate methods to extract in both ways as shown below.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.IO;
using System.Reflection;
using System.Collections;
 
namespace ResourceBuilder
{
    public class Reader
    {
        public string ReadFiles(string resourceName, string fileName)
        {
            string outFile = "file1.txt";
            ResourceReader reader = new ResourceReader(resourceName);
            string resourceType;
            byte[] resourceData;
            reader.GetResourceData(fileName, out resourceType, out resourceData);
            File.WriteAllBytes(outFile, resourceData);
            return outFile;
        }
 
        public string ReadWithDictionary(string resourceName, string fileName)
        {
            string outFile = "file2.txt";
            string name;
            object value;
            ResourceReader myReader = new ResourceReader(resourceName);
            IDictionaryEnumerator readerWalker = myReader.GetEnumerator();
            while (readerWalker.MoveNext())
            {
                name = (string)(readerWalker.Key);
                if (name.Equals(fileName))
                {
                    value = readerWalker.Value;
                    File.WriteAllBytes(outFile, (byte[])value);
                    return outFile;
                }
            }
            return "";
        }
    }
}

The first read method ReadFile is the straight opposite of write method. This basically opens the resource file in resource reader mode and fetches the file we are interested in and write it out to a file.

The second method is little different. This still opens the resource file in resource reader mode and then instead of fetching object directory, cast it to IDictionaryEnumurator so that we can traverse the resource file to find out what are all the objects the current resource file has. So if you get a resource file and you would like to find out all the resources in the file, all you have to do is implement the second method, whola, now you can traverse the resource file and get the object by dictionary look up.

Now lets look at the main code which uses the reader and writer together to put all together.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace ResourceBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            Program pg = new Program();
            pg.CreateAndCompareResources();            
        }
 
        private void CreateAndCompareResources()
        {
            string resourceName = "temp.resource";
            string fileName = "file.txt";
            Writer wr = new Writer();
            wr.WriteFile(resourceName, fileName);
            Reader rd = new Reader();
            string outfile = rd.ReadFiles(resourceName, fileName);
            string outfile1 = rd.ReadWithDictionary(resourceName, fileName);
 
            string[] infilea = File.ReadAllLines(fileName);
            string[] outfilea = File.ReadAllLines(outfile);
            string[] outfile1a = File.ReadAllLines(outfile1);
            
            Console.WriteLine("First Match using ResourceReader/Writer is {0}", CompareArrays(infilea, outfilea));
            Console.WriteLine("First Match using ResourceReader/Writer is {0}", CompareArrays(infilea, outfile1a));
            Console.ReadKey();
        }
 
        private bool CompareArrays(string[] infile, string[] outfile)
        {
            if (infile.Length == outfile.Length)
            {
                for (int i = 0; i < infile.Length; i++)
                {
                    if (!infile[i].Equals(outfile[i]))
                        return false;
                }
                return true;
            }
            return false;
        }
    }
}

Now lets go through the program and see what are we trying to do;

1. We create Writer and request it to create a resource file called "temp.resource" and create a file called "file.txt" with following content

0

1

2

3

4

in it and then insert this file into the resource file.

2. We Create a reader class and then we call the first reader method to extract the "file.txt" from "temp.resource" and write the extracted content into a file called "file1.txt".

3. Then we call the same reader class but use the second extract method to extract the "file.txt" from "temp.resource" and write the extracted content into a file called "file2.txt".

4. Next we compare "file.txt" against "file1.txt" and write the match result.

5. Compare "file.txt" against "file2.txt" and write the match result.

Based on the documentation, (4) and (5) should return true.

Now if we run this program the result show be something like the following

image

To our surprise the first match returned false, if you would debug the code and see the content in the "file1.txt", the first four bytes are the size of the file and the "file2.txt" does not have the size of the file in it. That is the difference.  So beware of this difference.

I will research more on this to see why the first method put the size of the file in the beginning. If you know the answer, please post it here or send me a note at ksunair at yahoo.com

I developed the code on XP SP3 using Visual Studio 2008 Express for C# 3.0.

Thanks and happy coding…

May 29, 2008

Passing arguments to exec

Filed under: Nant — Tags: , , , — @ 1:56 pm

In one of my nant tasks I was expecting arguments through args element node. So I have a task like the following

.

.

.

<property arg1=”c:\temp\dir\” />

<property arg2 = “c:\temp\dir2\” />

<target name=”Pgm” description=”Run pgm.exe”>
     <exec program=”pgm.exe”>
  <arg value='”${arg1}” “${arg2}”‘ />
  </exec>
  </target>

But when I ran the program, it got only one argument instead of two. Obvious thing you do would be then is to display your command line arguments and this is what I got

c:\temp\dir\” c:\temp\dir2″

as you can see my first part fo the double quotes are gone. So after some trail and error (still didn’t hit the google though) I found out that, if I would change the argument to have two slashes instead of the problem is solved. So the modified arguments would look like the following…

<property arg1=”c:\\temp\\dir\\” />

<property arg2 = “c:\\temp\\dir2\\” />

 Thought of logging it for someone else looking…

May 28, 2008

Starting Web Services and IIS

Filed under: asp.net,iis — Tags: , , — @ 4:47 pm

I thought I log some of the problems that I faced during the demo of my web services.

 

First I installed IIS and then I opened VS2008 and created a Hello World ASP Web service project. I ran a test in IDE and it worked fine. After that I deployed it on the IIS.

 

Now I opened IE to test the web service using the url and I got a wired error that “%” is invalid. After some research I found out that, under the default web site properties ASP.Net does not have version selected. I choose the latest version and that error went away.

Now the second try and I got the following error

“Failed to access IIS metabase”

This is due to the fact, you have installed IIS after installing the .Net Frame work 2.0 Be default .Net 2.0 has default asp.net resigtry and that need to be reset with the new IIS install. This can be done by running the simple command

Aspnet_regiis –i

After resolving these two issues I was able to cruise along without any problems.

April 29, 2008

Compiler complains about ‘Linq’

Filed under: Linq — Tags: , , — @ 6:37 am

I developed an application using VS 2008 and build on the box and everything was good. Now we were implementing the code compile in the CI environment. Where I installed .Net framework 3.5.

Now when I try to compile the code in Ci environment I get an error ‘Linq’ is missing. I checked assemblies and found System.Xml.Linq is in the GAC. I even added that as a reference to in the compile task. That didn’t resolve the problem. After some research I found out that, it looks like System.Linq is in System.Core.dll and even though it is in the GAC, we must explicitly include that as a reference during compile. Once I added that as a part of reference, the Linq error went away.

So, be careful on this.

CAB and Dynamic Menuitem generation

There comes a time, when you are developing CAB application you may need to insert menu items on the run. CAB comes with a feature to add the menu items from the app.config instead of entering each menu item in the shell itself. I rather keep it in the XML than in the shell, that way shell will continue to be shell. This out of box method also gives you a feature to associate command the required menu item click event as well.

If you are beginning to work on this item, I would recommend you to download Microsoft patterns and practices Composite Application Block Hands on Lab. This particular item was discussed in lab 3. If you follow the instruction in the lab you will understand how easy to add menu items dynamically from XML.

I would like to point out couple of things when you are adding the feature to your application;

1. Please remember to add the new section for ‘shellitems’ in the app.config. If you are wondering where it is used, it is used in the LoadFromConfig (UIElementBuilder).

(more…)

NUnit in VS2008

Filed under: Tips and Tricks — Tags: , — @ 2:58 am

Even though VS2008 comes with Microsoft version of the unit testing, I still prefer NUnit. The real reason is one less to learn and on the other hand NUnit does gives me all the good things required for my TDD. I can imagine Microsoft test suite might give lot of nice integration with VS2008, NUnit can be integrated nicely to get what you want. There are third party tools you can buy that will integrate NUnit nicely into Visual Studio but I am not sure about VS2008 and if you are a person like me, I do not like to spend money on a tool if there is a way you can do it. By the way, if I spend money I spend it on book 🙂

My first approach and easy approach is to attach NUnit process to my Debug process and put break point in the line of code where I want to debug and everything goes well. Well, let me explain what I meant by this. Here are my steps, this can change based on your preference;

(more…)

Building WPF application through console

Filed under: WPF — Tags: , , — @ 2:52 am

I build a simple WPF application using VS2008 and everything was ok. I needed to do little bit more outside the application (like adding a dynamic resource file to the WPF) so I decided to compile the application outside the IDE. I tried to compile it with the information provided in the MSDN page and it proved little difficult because of all the dlls I need to include during compile. So if you are like me trying to build WPF application through command line, the shortcut is, first build it through IDE. After the build is successful look at the output tab (at the bottom on the IDE), the first command is command line compiler call to build the application. So just cut and past it from there to a notepad or other editor where you would like to investigate what are all the required components for building the application.

Couple of things you have to remember, if you are going to compile the application from a location other than the project location, make sure all the source code files are converted to absolute path instead of relative path as in the IDE.

Once you make the change, now you can put it in a notepad and create a batch program and try running the batch program whola! you got yourself the exe.

Here is an excellent documentation on how to build wpf application from MS.

C# 3.0

Filed under: C# 3.0 — Tags: , , — @ 2:51 am

Recently I started using C#3.0 and I am loving all the new features MS has added to this fantastic language. One thing I was trying to do over time was to learn the functional programming. As you can imagine it is completely different paradigm shift. When I switched from COBOL to C++, I had to go through the same. Jumping from procedural to object oriented concept. It looks like with 3.0 there will be another shift I am very happy to do, jumping to functional programming, it is going to happen sometime soon for me. I wanted to learn functional programming while I thought it is going to take some extra effort from my side, C#3.0 kind of made my life easy by adding Lambda expressions in its arsenals. Now you all know why I am so hyped about 3.0. Enough said, let me go through what are the main new concepts added in 3.0

(more…)

April 24, 2008

Finding a pattern in a string

Filed under: regex,Tips and Tricks — Tags: , — @ 7:52 pm

It is easier to use Regex to find the string pattern you are looking for in a string using C#. If you are not sure how to use them, please use this link.

If you are trying to find a string with control characters please remeber to use ‘\’ character in front of it. Most of the time, you may not be looking for a string with special characters in it. If you are then make user you use correct character.

For example, I have a string x = “$\John\Mary”

I need to replace $\John\ with say blank, I want only Mary from that string. Then you need to do the following

string result = Regex.Replace(x, @”/$/\John/\”, “”);

With this each control character is preceded by / so that, regex will use that as a normal character otherwise, regex will try to interpret them as special character and you will not find the match.

Finding string from an array

Filed under: Linq,Tips and Tricks — Tags: , , , — @ 2:26 pm

I ran into a situation where, I need to find a string from a string array where I know only the part of the string I am looking for. So if I would be writing the code in C#2.0 the code would be something like the following;

string[] array = {“help”,”Csharp rocks”,”I am learning”};

string findString = “rocks”;

string matchedString=””;

foreach(string str in array)

{

if (str.Contains(findString))

{

matchedString = str;

break;

}

}

if (matchedString.Length > 0)

{

// the code to handle the logic goes here.

}

(more…)

« Older Posts

Powered by WordPress