Windows Forms Cross Threading Simple Solution

I found this article in the CodeProject Newsletter that presents an extension method that takes a delegate to run on the UI.

And this was my comment.

I have came across the same issue before, I was developing a windows forms application client used by more than 30 developer in the same time and the application was taking a lot of time just to access the UI from another thread.

I got ANTS Profiler to get for me the line of code that takes that much time, and it was this

if (form.InvokeRequired)
{
form.Invoke(code); //this
return;
}

I searched for a better solution and got this simple way with one line of code to access the UI.

SynchronizationContext syncContext;
syncContext = SynchronizationContext.Current; //in constrcutor
syncContext.Send(new SendOrPostCallback((s) => { this.myTextBox.Text = "some text"; }), null);

After running ANTS Profiler again I noticed a very big difference in the time spent to accomplish the same job!.

Categories: .NET Development

Simple tip to share only specified folders with Remote Desktop Connections

I was acessing the production server via explorer \\server\,  until the network team has disabled this feature for security issues, which got me annoyed I dont want to take a whole partition of my disk as a local resource with the remote desktop connection.

My freind Michael showed me how I can take only a specified folder by mapping a new network drive to the specified local folder on my machine, then take this drive as local resource with my remote desktop connection to the production server.

Categories: .NET Development

Easily Uninstall and Install Windows Services with batch file

I have spent some time editing a windows service after installing (and uninstalling) it for several times and I have to admit that this consumes time on the command line tool, so I have written a batch file to stop the service, uninstall it, install it, and start it again, and all what i need to do is to run the batch file.

Paste the following lines in a file.txt, replace the service name and the service path to match yours, and rename the file to file.bat.

@ECHO Stopping service..
net stop AlertsService
@ECHO service stopped.
@ECHO Uninstalling Service…
@SET PATH=%PATH%;C:Program FilesMicrosoft Visual Studio 9.0VC
“C:WINDOWSMicrosoft.NETFrameworkv2.0.50727installutil” -u “C:DebugAlertsWindowsService.exe”
@ECHO Uninstall Done.
@ECHO Reinstalling..
“C:WINDOWSMicrosoft.NETFrameworkv2.0.50727installutil” -i “C:DebugAlertsWindowsService.exe”
@ECHO Install Done.
@ECHO Starting Service..
net start AlertsService

Categories: .NET Development

Why using the using keyword instead of try/finally

April 20, 2009 1 comment

I was confused that they both accomplish the same mission, then why using ?!

Maybe with using I’ll write less lines of code..
Maybe with using I’ll write more maintainable code..

Well, That’s true. Let’s take an example of disposing a SqlConnection object,

This is the way you do it with try finally, the compiler won’t get out of the method blocks to return the value unless it executes the finally block to ensure closing the connection.

        private static string GetString2(string connectionString)
        {
            SqlConnection connection = null;
            SqlCommand cmd = null;

            try
            {
                connection = new SqlConnection(connectionString);
                cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT StringColumn FROM SomeTable";
                connection.Open();
                return Convert.ToString(cmd.ExecuteScalar());
            }
            finally
            {
                connection.Close();
            }
        }

Well, with using the compiler won’t get out of the using block unless it executes the Dispose() method on the resource object if it serves the IDisposable interface.

        private static string GetString(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT StringColumn FROM SomeTable";
                connection.Open();
                return Convert.ToString(cmd.ExecuteScalar());
            }
        }

Have you noticed any differences? This is the Code Metrics,
Code Metrics

So, how can I benefit from the using keyword to automatically free my resources when my object gets disposed?
Simply implement the IDisposable interface in your class, and use your class inside the using block.

    class Program
    {
        static void Main()
        {
            using (MyClass myClass = new MyClass())
            {

            }

            throw new InvalidOperationException();
        }
    }

    public class MyClass : IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

And off course the NotImplementedException will fire before the InvalidOperationException.

Hope this makes sense, Thanks!

Categories: .NET Development

Top Twitter Tools

If you haven’t seen them yet, I just liked this post so much.
http://zebolsen.com/top-twitter-tools-exposed-explained-at-lightning-speed/

Categories: .NET Development

Hello again!

Hello again folks!!

I’m sorry the last post was months ago, but lets just start over.

Off course I’m welcome to wordpress 😛 I know things are messy I’ve just moved from blogspot, imported my posts and comments just to find how easy and hard too to get my stuff here in the right way!.

I can’t hide my love to wordpress with all the themes, widgets, etc. I must say I liked it so much, except that I’ll have to edit most of the posts to make them look nice with the current theme.

I’ll be writing a series of posts on What do I learn in DashSoft, so don’t miss it 😉

Categories: .NET Development

Xmlawy – XML Framework-C# freindly

January 6, 2009 2 comments


Introduction

This framework provides an easy way to access XML files with support for inserting,
updating, deleting, and selecting by querying the XML like querying SQL.

Using the code

I’ll start by writing simple lines of code that demonstrate the operations of inserting,
updating, deleting, and selecting, and then show the results in an XML file.

Here is how we create an XML file and access an object:

            static void Main(string[] args)
            {
                BaseDataAccess access = new BaseDataAccess("D:/xmltest.xml", "Objects");
            }
            

Simple inserting

The Insert method takes an object of type BaseDataObject
as a parameter, which contains the name of the node, the value, the attributes,
and a list of children which are of the same type as well.

            access.Insert(new BaseDataObject("type", "human")).Execute();
            access.Insert(new BaseDataObject("type", "animal")).Execute();
            


Simple selecting

You can query the XML to select specific nodes:

            List<BaseDataObject> dataList = access.Select("type").
                                       Where("type").
                                       IsEqualTo("animal").
                                       ExecuteSelect<BaseDataObject>();

            for (int i = 0; i &lt; dataList.Count; i++)
            {
                Console.WriteLine(dataList[i].Name + " : " + dataList[i].Value);
            }
            


Updating

It is also easy to update specific nodes:

            access.Update("type").
               Set("type").
               EqualTo("animal").
               Where("type").
               IsEqualTo("human").
               Execute();
            


Deleting

And here is how we delete:

            access.Delete("type").Where("type").IsEqualTo("animal").Execute();
            


Advanced inserting

The way to insert children of children is to make a list of BaseDataObjects
and insert them in the list of the children of another BaseDataObject.
(The best way to do this is recursively.) The following code inserts three levels
of children in depth:

                static void Main(string[] args)
                {
                    // ACCESS
                    BaseDataAccess access = new BaseDataAccess("test.xml", "objects");

                    // INSERTING 3 LEVELS IN DEPTH
                    List<BaseDataObject> parents = new List<BaseDataObject>();

                    for (int i = 0; i < 5; i++)
                    {
                        parents.Add(new BaseDataObject("Parent", MakeChilds(5)));
                    }

                    BaseDataObject parentOfParents = new BaseDataObject("GrandParent", parents);
                    access.Insert(parentOfParents).Execute();

                    Console.WriteLine(access.XmlString);

                    Console.ReadLine();
                }

                private static List<BaseDataObject> MakeChilds(int count)
                {
                    List<BaseDataObject> childs = new List<BaseDataObject>();
                    for (int i = 0; i < count; i++)
                    {
                        childs.Add(new BaseDataObject("N" + i.ToString(), "V " + i.ToString()));
                    }
                    return childs;
                }
            


Advanced selecting

Here is how we select any child in the selected objects, recursively, with the method
PrintObject(obj):

            static void Main(string[] args)
            {
                // ACCESS
                BaseDataAccess access = new BaseDataAccess("test.xml", "objects");

                // INSERTING 3 LEVELS IN DEPTH
                List<BaseDataObject> parents = new List<BaseDataObject>();
                for (int i = 0; i < 5; i++)
                {
                    parents.Add(new BaseDataObject("Parent", MakeChilds(5)));
                }
                BaseDataObject parentOfParents = new BaseDataObject("GrandParent", parents);
                access.Insert(parentOfParents).Execute();

                // SELECTING
                List<BaseDataObject> objects =
                  access.Select("GrandParent").ExecuteSelect<BaseDataObject>();
                for (int i = 0; i < objects.Count; i++)
                {
                    PrintObject(objects[i]);
                }

                Console.ReadLine();
            }

            private static List<BaseDataObject> MakeChilds(int count)
            {
                List<BaseDataObject> childs = new List<BaseDataObject>();
                for (int i = 0; i < count; i++)
                {
                    childs.Add(new BaseDataObject("N" + i.ToString(),
                               " V" + i.ToString() + " "));
                }
                return childs;
            }

            private static void PrintObject(BaseDataObject obj)
            {
                if (obj.Childs.Count > 0)
                {
                    Console.WriteLine(obj.Name + " >");
                    for (int i = 0; i < obj.Childs.Count; i++)
                    {
                        PrintObject(obj.Childs[i]);
                    }
                }
                else
                {
                    Console.WriteLine(obj.Name + " : " + obj.Value);
                }
            }
            


Inserting simple objects

If you want to quickly save the properties of an object in XML (simple serialization),
there is another generic Insert method which takes any object as a
parameter and inserts all the properties of type string or
int in the XML file.

            class MyClass
            {
                public MyClass()
                {
                    Age = 20;
                    FirstName = "Islam";
                    LastName = "Eldemery";
                    Address = "Egypt, Cairo, bla bla bla";
                }

                public int Age { get; set; }
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public string Address { get; set; }

            }

            class Program
            {
                static void Main(string[] args)
                {
                    MyClass obj = new MyClass();

                    // ACCESS
                    BaseDataAccess access = new BaseDataAccess("test.xml", "objects");

                    // INSERT
                    access.Insert<MyClass>(obj).Execute();

                    Console.WriteLine(access.XmlString);
                    Console.ReadLine();
                }
            }
            


So far so good, let’s dig deeper..

Overriding the virtual methods in the base class

Imagine you want to encrypt the XML after inserting, and decrypt it before selecting.
This can be easily done by overriding the base methods as follows:

            class XmlAccess : BaseDataAccess
            {
                XMLEncryptor encryptor;

                public XmlAccess(string path, string rootElement)
                    : base(path, rootElement)
                {
                    encryptor = new XMLEncryptor(path);
                }

                public override bool Execute()
                {
                    bool executed = base.Execute();

                    ///////////////////////////////////////////////////
                    // ENCRYPTOR GOES HERE
                    encryptor.Encrypt(base._objectToInsert.Name, "myKey");
                    ///////////////////////////////////////////////////

                    return executed;
                }

                public override List<T> ExecuteSelect<T>()
                {
                    ///////////////////////////////////////////////////
                    // ENCRYPTOR GOES HERE
                    encryptor.Decrypt("myKey");
                    ///////////////////////////////////////////////////

                    return base.ExecuteSelect<T>();
                }
            }
            

Select From

            // ACCESS
            // True will delete the file if exist (for debugging purposes)
            BaseDataAccess access = new BaseDataAccess(@"test4.xml", "doc", true);

            // Initialize 6 childs
            List<BaseDataObject> childs = new List<BaseDataObject>();
            for (int i = 0; i < 6; i++)
            {
                childs.Add(new BaseDataObject("Name" + i.ToString(), "Value" + i.ToString()));
            }

            // Insert
            access.Insert(new BaseDataObject("Human", childs)).Execute();
            access.Insert(new BaseDataObject("Animal", childs)).Execute();

            // Select
            List<BaseDataObject> selected = access.Select("Human").Where("Name2").IsEqualTo("Value2").ExecuteSelect<BaseDataObject>();
            // (Prints 1)
            Console.WriteLine(selected.Count);
            // selected[0] is the Human osbject and holds 6 childs objects

            // Select
            List<BaseDataObject> selectedN = access.Select("Name2").From("Human").Where("Name3").
                  IsEqualTo("Value3").ExecuteSelect<BaseDataObject>();
            // (Prints 1)
            Console.WriteLine(selectedN.Count);
            // selected[0] is the child osbject
            

Select all nodes

You can also select all the nodes in the root node with all children and children
of children, in one line of code:

            List<BaseDataObject> objects = access.SelectAll<BaseDataObject>();
            

And again, this is to loop on them recursively:

            static void Main(string[] args)
            {
                // ACCESS
                BaseDataAccess access =
                  new BaseDataAccess(@"D:\XmlFiles\StructureMap.xml",
                                     "doesntMatter");

                // SELECTING
                List<BaseDataObject> objects = access.SelectAll<BaseDataObject>();

                // DISPLAYING
                for (int i = 0; i < objects.Count; i++)
                    PrintObject(objects[i]);

                Console.ReadLine();
            }

            private static void PrintObject(BaseDataObject obj)
            {
                if (obj.Childs.Count > 0)
                {
                    Console.WriteLine(obj.Name + " >");

                    for (int i = 0; i < obj.Childs.Count; i++)
                        PrintObject(obj.Childs[i]);
                }
                else
                    Console.WriteLine(obj.Name + " : " + obj.Value);
            }
            

History

The code in the library is fully commented. This is version 1. I hope we can add
more and more features in the future.

Categories: .NET Development