Category Archives: C#

Reading Files For Windows Phone 7

I was writing some games using the windows phone 7 tools and I found out that its a pretty cool sdk with .Net framework 4.0. For games you can either do silverlight or XNA. The first decision that you will have to make is to whether go Silverlight or go XNA ? If you plan to have 3D graphics/ animation, extensive control on drawing and coloring, show lot of images or trying to process rapid user input then go with XNA, otherwise silverlight is also pretty powerful if all you have to do is to manipulate windows phone controls and write a little logic to create your app. What I found out is you will need to read data files as there is no support or built in database in the phone. For me its a good thing, I do not want to write database wrappers or start a war with entity framework. File processing and Handling is kind of neat and you can pretty much do everything 90% of the time that you would with a database. I don’t think it is a cool idea to write “Payroll Management System” for a cell phone, I mean common ? what is the computer for ??
So coming from the Web/desktop/laptop world its very simple to read a file in .Net. Here is what you would do normally in ASP.Net or a C# Windows Application.

// Assuming file is in the same directory or your project
StreamReader sr = new StreamReader(“file.txt”);
string str = sr.ReadLine();

Pretty Simple huh !! It is a little tricky with XNA 4.0. Primarily you should have the files in the ContentProject and not your game project. If you look at the Game project references, you will see a reference to the ContentProject. So place the files in the Content Project, then change the file properties. You should change the Build Action property to “NONE” and “Copy to Output directory” to “Copy always”. This would put the files in your executable’s path. XNA provides a TileContainer Class and you can call the static method OpenStream and pass in the path (Content Project).

Stream testpath = TitleContainer.OpenStream(“Content/Test.txt”);
StreamReader reader = new StreamReader(testpath);
string line = reader.ReadLine();

For silverlight since you do not have the content project and the files possibly are included in your project you can do:

Stream testpath = Application.GetResourceStream(new Uri(“Test.txt”, UriKind.Relative)).Stream;
StreamReader reader = new StreamReader(testpath);
string line = reader.ReadLine();

I found this the google way, just putting it out there, it may save some time for someone trying to read files in their windows 7 applications. You can pretty much apply the same logic for StreamWriter to create and write to files.

Happy Coding and Best of luck 🙂

3 Comments

Filed under C#

Getting started with AJAX in ASP.Net:

 

As a prerequisite you would require to have Microsoft Visual Studio 2008 installed on your system. Alternatively you can also have Microsoft Visual Studio 2005 with AJAX extensions for ASP.Net installed. This would be a very basic example just to get you started and will touch the basics of writing AJAX enabled web applications using Visual Studio and ASP.Net.

 

So What is AJAX  and what is the use ?

 

AJAX is the abbreviation of “Asynchronous JavaScript and XML”. It is a technique in web development that is used to greatly improve the responsiveness and performance of a web application thus resulting in a great user experience. To understand how it works you should understand how the old web applications worked, how it all started, what is java script and what do we exactly mean by AJAX?

 

As web applications were hosted and running on a web server, the browser simply accessed the application on a server and rendered the html produced for the user.

 

Ever wondered why it took a long time after you clicked a button and when you look at the status bar its slowly moving and after some time it comes back with the response”.

 

This was mostly the case not with static websites but web applications where a lot of processing was done on the server side based on events like pressing a button. The page would “postback” and provide the server the necessary input. On the event handler there would be some validations and then some processing and then typically another “postback” updating the user. As more users complained that the application was not responsive enough or too slow, more techniques evolved to process minor data on the client side using javascript. Typically these would be tasks like client side input validations, dynamic menus and conversions displaying time and things like that.

The end user liked the experience as the application was much more responsive and wont go back to the server to process each and every piece of information (postback) .

 

So this idea was refined and the AJAX technologies were introduced and including in all the major web development frameworks. If you are reading this off course you are not an AJAX Expert , you just want to know how you can use AJAX in your application to make it more responsive or just for the heck of it J .

 

So here is how you do it with ASP.Net using Visual Studio 2008.

 

1/  Create a new website and name it as AJAXExample. This can be achieved by File -> New -> Website and selecting ASP.Net Website from the installed templates.

 

2/  Visual Studio .Net will generate the basic skeleton application by generating the following files (pages):

 

Default.aspx

Default.aspx.cs

 

Default.aspx is the actual page where all the controls or (html elements are). The Visual Studio IDE enables you to switch between Design View and Source View. Design view is where you can look how the page looks like and the source view is the html view of the page.

 

3/ Be in the design view and the first control to be dragged and dropped on the page must be “ScriptManager”. This is located under “AJAX Extensions”. Visual studio will rename it as ScriptManager1 and will add the following code when you switch to source view:

 

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

</asp:ScriptManager>

 

Note: This should be the first control in the page. It tells the asp.net worker process that this application or page uses AJAX and the required “dlls” have to be loaded in memory.

 

4/ Add the controls whatever is required in your application. For the sake of simplicity I will add a textbox and 2 buttons in the design view. The visual studio will generate the following code in the source view.

 

<asp:Button ID=”Button1″ runat=”server” Text=”Hello” onclick=”Button1_Click” />

 

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

 

<asp:Button ID=”Button2″ runat=”server” onclick=”Button2_Click” Text=”Clear” />

 

5/ Define the event handlers in “Default.aspx.cs”.

 

protected void Button1_Click(object sender, EventArgs e)

{

    TextBox1.Text = “Hello”;

}

 

protected void Button2_Click(object sender, EventArgs e)

{

    TextBox1.Text = “”;

}

 

6/  Add the following code in your html before and after your controls code. So the controls you want to process without postbacks has to be wrapped around this block:

 

 

<asp:UpdatePanel id=up1 runat=server>

    <ContentTemplate>

 

// Controls here

 

</ContentTemplate>

</asp:UpdatePanel>

 

7/  Run the application and Enjoyeee ! In the same way you can put more controls in a page like gridViews comboboxes and list boxes or even databound controls and use it without causing the application to postback.

 

I am copying and pasting the contents of my code files:

 

 

Default.aspx

 

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

 

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

 

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

    <title>Untitled Page</title>

</head>

<body>

    <form id=”form1″ runat=”server”>

    <div style=”height: 295px”>

    <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

    </asp:ScriptManager>

    <asp:UpdatePanel id=up1 runat=server>

    <ContentTemplate>   

        <asp:Button ID=”Button1″ runat=”server” Text=”Hello” onclick=”Button1_Click” />

        <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

        <asp:Button ID=”Button2″ runat=”server” onclick=”Button2_Click” Text=”Clear” />

    </ContentTemplate>

    </asp:UpdatePanel>

    </div>

   

    </form>

</body>

</html>

 

Default.aspx.cs:

 

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        TextBox1.Text = “Hello”;

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        TextBox1.Text = “”;

    }

}

 

 

 

1 Comment

Filed under C#

Using Windows Communication Foundation WCF with Visual Studio 2008:

There is a lot of hype about new (not so new now) technologies from Microsoft and the new architectures that are now a part of Microsoft .Net development environment. These include Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF) and Workflow Foundation (WF).

I will give a brief introduction about what these are just in case you are not familiar. Anyways if you are then probably this article is no good J since I just started working with these. This will help you get a quick start in case you are a starter and I have gathered the info skimming through tutorials and I want to give you something quick and easy. So to start off “What is WPF?” WPF exclusively has everything to do with the UI or user interfaces. Till .Net 2005 the Graphics were GDI (Graphics device Interface) based and in WPF they are Direct X based thus utilizing the faster video card acceleration and fast memory access as compared to the GDI. Secondly this used to be an issue when clients wanted fancy UI e.g. Elliptical buttons, Window Layouts, Animated menus and colors in controls. Microsoft made it possible with user controls to some extent but off course the mainstream developers didn’t want to get in that mess and always wanted to use the default controls with some styling that the client wont like. Customers these days doesn’t want “just another windows button” there should be something innovative about it so WPF enables you to define your own controls with XAML pronounced as (zammel).

The styles, colors, shapes, data bindings and everything that is a part of the control can be done using XAML which is simple xml just defined somewhat like html ( I always see the elements and attributes notations) whenever I see XAML.

So WPF is for UIs and probably an effective solution for at least Windows Vista if not XP. Just as with the “User Interfaces” Microsoft realized that “Services Oriented Architectures” are gaining in popularity. With Central server centric applications and Microsoft efforts to support the SOA with applications like “BizTalk”, “SharePoint” e.t.c something also needed to be done to provide a standard platform for network programming using .Net. Microsoft came with WCF which is a powerful framework for writing and utilizing or consuming web services , windows services , .Net Remoting without needing to write a whole lot of socket interfaces. The implementation is hidden in the components constituting the WCF. WCF like WPF depends heavily on configurations and it is usually a good idea to separate the business logic from the configurations or the (app.config) file. In this article I will demonstrate writing a simple client server program using WCF which will give you some bare essentials for WCF and will help you to explore more in the ever growing world of emerging technologies.

By the way just to get you started if you are not familiar with the client server paradigm, client server application that I am going to develop would be basically two applications. A Server application will let many clients connect to it and say “Hi”. Keeping in mind this is not to tell you how to design better client server applications this is all about getting you up and running with WCF. Ok my friends so don’t get angry =] 

Designing the Client and Server with WCF:

Primarily while designing the application remembers there should be something common in the client and server. To explain this better ask yourself the question “How is client going to interact with the Server”? There should be some interface the server should provide to achieve this. If you are familiar with web services think of wsdl (web services description language) that exposes the web service API. So just like that the WCF Service also exposes interfaces. The clients can generate the proxy classes for the API and will call those API methods to communicate with the Server with underlying implementation of Sockets and communication mechanism). I will discuss “How to generate the proxy classes” but first things first “Decide what should the Server be like”? And “what functionality you want to expose”?

So just for the sake of simplicity just think that what the server wants to expose and client wants to consume is 1 single functionality called send message.

 

The First Step in Writing the Server: 

I consider adding the “system.servicemodel” reference a prerequisite to every WCF application so if you have not already added that do make sure the reference is included in the list of your references.

1/ Add a new interface to your solution. I named the solution as WCFServer so the namespace here is WCFServer. I named the interface as CommonInterface just to be clear what this does. This would be the API exposed for the client and would be executed on the server. Good naming convention for this would be to prefix the name of the class with an “I” so something like ICommonInterface but that’s something you know right.

namespace WCFServer

{

    [ServiceContract]

    public interface CommonInterface

    {

        [OperationContract]

        void SendMessage(string msg);

 

    }

}

Observe that there are two things here which might be new to you. The interface is marked as “ServiceContract” which is the attribute which specifies that this is the contract between the client and server.The other thing is the method is marked as “OperationContract”. For the time being just think that every method in this interface should be marked as an “OperationContract”. This method is what will be executed on the server and what the client will call from the “Client code”. 

Second Step is to implement the Interface with your server class:

Give a meaning to the interface by implementing it in your server side code.How to do that is declare a class in your program and name it appropriately and inherit it from this interface that we defined in step 1. For our sample application I defined the server class as shown in the definition below:

 

namespace WCFServer

{

    class Server : CommonInterface

    {

        public void SendMessage(string msg)

        {

            Console.WriteLine(“Message from client –> “ + msg);

        }

 

        static void Main(string[] args)

        {

            Console.WriteLine(“Starting the server …”);

            ServiceHost host = new ServiceHost(typeof(Server));           

            host.Open(); 

            Console.WriteLine(“Server started successfully at…Pressing a key would cause the server to shut down …”);

            Console.ReadLine();

            host.Close();

        }

    }

}

 

So if you look at the code closely you will find the implementation of the “SendMessage” function that will be called by the client and a message would be passed and displayed on the Server’s console window.

If you look at the Main function the first thing that we do is to declare a Service Host and specify the sever’s type. Then use the Open method of the service host to start the service.

Our server at this point is up and running and waiting for the clients to say “Hi”. How to write the clients will be discussed in the next article. Hope this helps getting you a quick start of essentially what it is and if you have any ideas, observations I would love to hear from you in the form of comments.Stay tuned for more and thanks for reading.Happy Coding !!

Here are the Configurations necessary for the configurations: 

<?xml version=1.0 encoding=utf-8?>

<configuration>

  <system.serviceModel>

    <services>

      <service name=WCFServer.Server>

        <endpoint address=net.tcp://localhost:5555/Server binding=netTcpBinding

            bindingConfiguration=“” contract=WCFServer.CommonInterface />

      </service>

    </services>

  </system.serviceModel>

</configuration>

 You can use the “svcconfigeditor.exe” to generate this so you don’t have to memorize this simply go through a wizard and save the file as app.config and copy and paste.The svccinfigeditor can be found at “C:\Program Files\Microsoft Visual Studio 8\Common7\IDE

 

1 Comment

Filed under C#

ADO.Net Explained step by Step

In this tutorial I would be talking about integrating databases in your .Net Applications specifically C# applications. ADO.Net is a .Net framework’s library which is essentially the same for ASP.Net for web development and other desktop applications using C#.Net or VB.Net. In my experience the database that was used most frequently was Ms-SQL Server, off course because both are Microsoft products. .Net seems to integrate with SQL Server very easily and gives better performance.  (ADO.Net provides a Namespace specifically for SQL Server which might result in better performance with SQL Server. It is prescribed to use System.Data.SqlClient when using SQL Server as your back end instead of System.Data.OLEDB)  Having said that .Net can connect to all the major databases systems. The ones I have worked with include Oracle, Sybase SQL Anywhere, MySQL and MS-Access. For the sake of discussion I would be connecting to SQL Server Database here to show how to connect to databases using ADO.Net and do the routine operations.In many books I have seen hard coding of ADO.Net objects and configuring the data sources and some properties of ADO.Net objects which pisses me off. Simply ask yourself the question How are you going to deploy such software? Is it easy to replicate your development environment on the Target client machine? NO !! Not at all!! It’s a nightmare. So setting all the properties in code and all the configurations in a configuration file is the mostly used conventional way of doing things.

Prerequisites for this are some knowledge of C# and I would assume that you have a DBMS available that you wish to use for your practice or running sample code against.

Connecting to Database:
The easiest way to ensure database connection is through a UDL (universal data link) file. Simply create a new text file on your desktop, open it and from the file menu choose the “Save As” Option. In the “Save As” dialogue for file type select “All files” and for file name specify “abc.udl” and save the file. When you close the file you should have a new file called abc.udl. UDL FILES are a Microsoft proprietary file format that is used to configure data sources.

Simply enter your Database info and select the “Test Connection” Button. Once you see the message box that says “Test Connection Succeeded” close the dialogue by clicking “OK” and close the “Data Link File”. Open the file with notepad or any text editor and the third line in the file is the connection string.

 An Alternative approach to connection:

If the above mentioned process sounded too complicated which it is not the following connection strings can be used:

 For SQL Server use: 
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

 For MS-Access use:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;

 For Oracle use:
Provider=msdaora;Data Source=MyOracleDB;User Id=myUsername;Password=myPassword; 

 For MySQL use
Provider=MySQLProv;Data Source=mydb;User Id=myUsername;Password=myPassword; 

The first step to talk to databases is to include a reference to ADO.Net library in your code. You don’t need to do it explicitly. Simply use the following statements in the beginning of your code.

 using System.Data;
using System.Data.OleDb; 

Once you have decided what database you want to connect and what connection string you have to use then your C# code starts. I would make a small method that returns an instance of System.Data.Oledb.OLEDBConnection if a successful connection is established else returns a null. 

/// <summary>/// Open the Database Connection/// There should be an entry for “Database” in the app.config
/// </summary>///
<returns></returns>
public System.Data.OleDb.OleDbConnection OpenConnection()
{
    OleDbConnection conn;
    string connectionString = ConfigurationSettings.AppSettings[“Database”];
    try
       {
           conn = new OleDbConnection(connectionString);
           conn.Open();
           return conn; 
     
}
    catch (Exception ex)
    {
        return null;
    }           

 }

 Executing an SQL Statement:Whenever you are designing or developing a database centric application, you have to perform database operations ( Select , Insert , Delete , Update) from various places within your application. Here we would discuss about the most common scenarios like there is a dropdown list from where the user selects one or more items. How to populate the Combo box? . We want to show the user search results in a datagrid or a datagridView  in a windows forms or a web form. ? We want to add new records in the database How to do it ? Below you will find answers to all such questions. For the sake of discussion let us consider we have a table in our database called Student and the columns/attributes of the table are Name,ID,Date_Of_Birth,Address,Email , Phone and SSN. I will show you how to manipulate the table from our application using ADO objects and give you some example code to play around. 

Executing a Select Statement for a dropdown list:
 Suppose you have a form where you want to update the students record.You have a dropdown where you will display all the SSN of the existing student. When the user selects the SSN the form gets filled automatically by selected students information. The user can then make changes and click a button and the changes are saved to the database. 

OK, the easiest way to load a combo box or a drop down list is by using an OLEDBDataReader object. The method with the code is shown below:

 public OleDbDataReader ExecuteDataReader(string query)
{
     try 
       
{
 
    
         OleDbDataReader reader;
              OleDbConnection conn = OpenConnection();
              OleDbCommand cmd = new OleDbCommand(query, conn);
              reader = cmd.ExecuteReader();
              return reader;
        } 
      
catch (Exception ex)
 
      
{
              return null;
        }
} 
You can call the method , get the data reader and then loop through all the items this would be something like on the form_load event of your form: // This is how you call the ExecuteDataReader Method
OleDbDataReader dr;
dr = ExecuteDataReader(“Select SSN from student”);
cmbStudents.Items.Clear();        
while (dr.Read())
{
  comboBox1.Items.Add(dr[0].ToString().ToString());
 
Executing a Select Statement to show in a datagrid or DataGridView:
The process of showing some rows of the database on a datagrid or a datagridview is essentially the same process with slightly different objects and the ways you use them.I am really pretty much against hardcoding stuff in the datagrid , the conventions you find in your first C# Book probably.I learned the fact, the hard way and believe me its no good at all. Probably good to make u understand what are the properties and what objects are closely connected or work together in the architecture.Always try to set the properties from your code instead of the designer view when it comes to ADO.Net objects like DataSet,DataReader,DataAdapter,DataGrid,Connection,Command e.t.c. Whenever you want to use Datagrids or DataGridView , the essential property is the “datasource”.This requires an instance of the dataset which has the results of the query passed in. The essential ADO.Net objects here are DataSet,DataAdapter and the DataGridView itself and that is it !!Following is the example of how to use: 
/// <summary>/// Given a query executes a dataset and returns the dataset
/// Ideal when to be shown on a Grid View for searching or display
/// </summary>
/// <param name=”query”>The Select query that returns a dataset when executed</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string query)
{
    DataSet ds = new DataSet();
    try
    {
        OleDbConnection conn = OpenConnection();
        OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
        da.Fill(ds);
        conn.Close();
        return ds;
    }
    catch (Exception ex)
    {
        return null;
    }
} 
This is the calling code from where this method would be called:
 DataSet ds = ExecuteDataSet(“Select * from Student”);
 
dataGridView1.DataSource = ds.Tables[0]; 
Note: You would also have to use dataGridView1.DataBind() if you are programming in ASP.Net 
Executing an SQL statement that updates a table:
Here we are not selecting any rows from the database rather we want to run an insert , delete or update sql statement so we don’t want anything back from the database.So the OLEDBCommand instance is treated in a slightly different way. Below is a sample method which might be used to execute and update a database table: 

/// <summary>
/// executes a given insert query and returns true if query is executed ok/// </summary>
/// <param name=”query”>The insert query which does not return any dataset</param>
/// <returns></returns>
public bool ExecuteInsertUpdateQuery(string query)
{
    bool toReturn = false;
    try
    {
        OleDbConnection conn = OpenConnection();
        OleDbCommand cmd = new OleDbCommand(query, conn);
    
   cmd.ExecuteNonQuery();
        toReturn = true;
        conn.Close();
        return toReturn;
    }
    catch (OleDbException dx)
    {
        throw dx;
 
   }
   catch (Exception ex)
   {
        return false;
   }
}
This method can be used as:  string insertQuery = “insert into student values(‘1’,’2’,’3’);
bool status = ExecuteInsertUpdateQuery(insertQuery); In a similar way delete and update queries can be passed in and the method would return a true or a false indicating whether the statement was executed properly or not. So this was a brief brief introduction and a short tutorial, I would say “ADO.Net Crash Course” and I think there is much more to ADO than what I showed. Keeping in mind these are the essentials which you should know if you want to enter the database applications world with Microsoft.Net.  If you make any additions to this article or simply provide feedback so I can make the required changes, or you want free consultation with your design, leave your comments as feedback.All your feedback is warmly welcomed and I would try my best to address your issues.   

5 Comments

Filed under C#

Microsoft Message Queue Example and Overview with C#

Many enterprise applications today require reliable message delivery mechanism. This is absolutely essential in financial transactions. There are a number of techniques available to achieve this including a Custom made Queuing server, the underlying protocol in that case would be Transfer Control Protocol TCP and it has to be made reliable by wrapping it in a layer of requests and acknowledgements, persisting all the requests and acknowledgements of a transaction in a database and applying rules for “Transaction Processing” as in a database. So the transaction is literally atomic and has many phases.This is sometimes difficult to achieve since implementing Sockets is itself a difficult proposition, it comes with the issues of Server client synchronization , memory management with multiple threads and usually the proprietary protocol that’s used for message passing or a custom developed API which needs to be configured for server and clients.
I have recently used MSMQ and was able to achieve all this without the need to develop long API or a lot of development. Integrating it with C# was very easy and the message passing has been very reliable. All the threads, queue management and connection are in built into MSMQ .In this article I would describe the basic things that you need to do to integrate MSMQ into your projects. Before using any of the sample code makes sure that MSMQ is installed on your system. If not it can be installed from the Add/Remove Windows component option. Once it is installed it is displayed in the administrative applications list and then you can use the code similar to one described in various sections. Make sure you add following references in your application:
System.Messaging
System.Messaging.Formatters
Writing Strings or Formatted Objects to MSMQ:
The sample code below would create a Message Queue in the private queues list with the name TestMSMQ. All messages that you post would be posted in this queue. // Name of the Private Queu you want to post data to
String queueName = “.\private$\TestMSMQ”; // The string message tou want to send// The  objects of user defined classes can also be sent
// MSMQ holds the serizlized version when received the body // should be converted to the same class object again
String messageToSend = “This is a test message”; // the message object that would be send
System.Object obj = messageToSend; // Create a MSMQ message queuing transaction.
MessageQueueTransaction msgTran = new MessageQueueTransaction(); // Begin a MSMQ transaction.// If the Queue doesn’t exist create it Using API
msgTran.Begin(); if (MessageQueue.Exists(queueName))   
    msgQueue = new MessageQueue(queueName);
else   
    msgQueue = MessageQueue.Create(queueName);  

msgQueue = new MessageQueue(queueName); 
Message msg = new Message(); 
// Assign the message to the BODY Property
msg.Body = obj; // Associate a binary or an XML formatter
msg.Formatter = new System.Messaging.BinaryMessageFormatter();
 // Send the Message
msgQueue.Send(msg, msgTr);  // Commit the transaction.
msgTran.Commit(); 
Reading from MSMQ: 

Receiving a Message from the Message Queue is Simple. If a user defined datatype resides in the body of the message and the Message queue is accessed from different applciations, services the same type should exist in both the services , applications. This can be done by placing them in a project and adding a reference to the project in both the applications , then converting the object returned by the Body of the message to an instance of the required Type. Note:Receiving a message would dequeue the Message from MessageQueue. If you want to make sure that whenever a message is removed from the message queue a copy of it is saved  you can use the Journal queue by setting the use journal queue flag while posting to the message queue. However if you don’t want to dequeue the message an Enumerator can be obtained and be processed with a loop that peeks the Message Queue messages. Use Peek instead of Receive and Receive only when absolutely certain about removing the message from the queue. // process the online messages here
string onlineQueueName = .\private$\TestMSMQ”;              // initialize the Message Queue instance
MessageQueue msgQueue;msgQueue = new MessageQueue(onlineQueueName); System.Messaging.Message Msg = nullMsg = olMq.Receive();Note : If you might be interested in  working code for MSMQ or have some design and architecture ideas feel free to discuss or email me at hiasad@hotmail.com

11 Comments

Filed under C#

Responsive User Interfaces with UI Threads

Have you ever seen this exception and wondered “Huh !! wtf is that suppose to mean ?”

exception.jpg

Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on.”?? Or you want to update a UI of a windows based application in real time. The classis scenario for this is the stock market applications or processing credit cards from windows based application or while making web service calls synchronously where at many places the real time updates to the UI is absolutely essential.As an application developer / designer you might have encountered situations where The UI of the application gets updated After a COM Component Call or a Web service call or some extensive processing with the data. If this takes too long the User Interface of your application stops responding and hangs which is the first thing people notice and criticize in spite of the efficient code you have written in the business logic for processing complex data !! One possible solution of handling all such scenarios is to update the UI of your Application from a separate thread. The thread would be responsible to update any UI on your forms and another thread would be processing the data simultaneously.I had this idea and when I tried to access windows controls from the newly created thread I had the exception which I have mentioned. I did some research on this and realized that “A control cannot be accessed from any other thread but the thread they were created on “. So for accessing UI elements from a different thread I have made a small framework which you can also use..Net provides a mechanism for this and it’s extremely simple. I think in the upcoming versions of .Net the background worker control would be more powerful and synchronization would be an included feature. So we don’t have to worry about any of it.For now I would just indicate how to update or access the UI from a different thread other than the main Application thread. My sample application is a VC# windows application compiled with .Net 2005 IDE and uses .Net 2 frameworks.I would just give you a step by step description instead of excerpts to make it more easy and understandable.The first thing we need to do is to create a System.Threading.Thread instance. It may be good to make it a form level variable since it might be accessed from different places on your form.ui.jpg

System.Threading.Thread  myThread;In the Constructor or any other suitable place initialize the Thread instance. The constructor is overloaded and I mostly use that takes the ThreadStart instance so I pass a new instance like: 

myThread = new Thread(new ThreadStart(ThreadProc));

 Note: Thread Start is a delegate and requires a target method which it points to and can be called once the thread is running.Now make a no argument method with the same name as you passed in the ThreadStart constructor:
public void ThreadProc()
{

   try
   {

        int count = 0;

        MethodInvoker mi;
        mi= MethodInvoker
(Updater);   

while (globalcount  < 300) 
  
{
         
     this.BeginInvoke(mi);

     Thread.Sleep(500);
         
  }
    
}

catch (Exception ex)    { // do nothing    }

}

We observe that we use another delegate “Method Invoker” which is the key basically. We make an instance of MethodInvoker delegate and pass a no argument method from which we access the UI of the form. After that we call the “BeginInvoke” of our main form and pass the instance of method Invoker.Note: As Method Invoker is also a delegate, we also need to specify the target method. In this case this would be the method from where UI is accessed. 

public void Updater()
{
   this.Text = globalcount.ToString();            
}

Once we are done with all of that all we have to do is to start the thread, so we would just call myThread.Start( ) ,and we are all set up.This way of updating the UI is also efficient in the sense that it is performed asynchronously instead of updating on timers or some other undesirable synchronous way.

 Want more sample code / applications feel free to contact me 🙂 If you have some good design ideas, I would love to hear it!! also post ur comments if there is something specific u r looking for , thanks . If you need examples with C# or java where you wanna update your UI from a different threads I have the code available for you … fell free to discuss here or if this was of any use or not , i would appreciate your feedback !!

My email address is hiasad@hotmail.com

18 Comments

Filed under C#