Archive for April, 2005

Single Instance of an application is not Exactly the Singleton Model .Because in singleton model we talk about a class having only a single insatnce at most per application.However in singleinstance the requirement is often a single application instance(many time an exe) per system.(may be network :often central flag based system used the same..that is put a db entry of on flag and check the same before start.The most sutable is though keep the same running in a single system).

Now coming to the requirement :In singleton often we need a singleinstance to be shared thru out the apps thsu we have to design a thread safe static/shared(in vb) class with synchronization.However for single instance we need to manipulate the process class and us emutex to run the apps instance and if the instance is runnig  let return the instance .

here are some example and links:-

Many ways of single instance apps

http://www.bobpowell.net/singleinstance.htm

http://www.codeproject.com/csharp/singleinstance.asp

http://www.ai.uga.edu/mc/SingleInstance.html

http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=711

In single system in vb.net

Imports System.Threading

 Module modMain

 Public mtx As Mutex

 Public Sub Main()

 Dim bCreated As Boolean

 mtx = New Mutex(False, "SingleInstanceApp", bCreated)

 If bCreated = True Then

Application.Run(New frmMain)

 Else

End

End If

End Sub

End Module

C#

[STAThread]static void Main() {     Application.Run(new Form1());}   Process aProcess = Process.GetCurrentProcess();    string aProcName = aProcess.ProcessName;                          if (Process.GetProcessesByName(aProcName).Length > 1)    {        MessageBox.Show("The application is already running!!","Test",MessageBoxButtons.OK,MessageBoxIcon.Stop);        Application.ExitThread();    }

Advertisements

VB Like c# MDI APPLICATION

Posted: April 24, 2005 in Uncategorized

Today i was asked  from a vb developer who recently  moves into c# how he can design a mdi application in c# which have same functionality as like vb.The problem was the instance and how to display it like the vb functionality.Luckily to debug soem old code i d installed vb and i craete a sampel vb app to study the mdi functionality he was talking about.Also i search the web and many people have impelmented many complicated flag set to achieve the same and further some are setting null to form and checking the same and many stuff.

I have design the same very simple code :-before giving the code let me write i have a mdi in which i have placed file menu and 4 submenu under it for 3 child and one close and heer is the code to set the mdi app

I know my vb friends are missing the default form and the forms collection badly.however soon ms is thinking of giving you ur old form collectiona nd default form..howveer until then here is the code you can do ur bit..

[STAThread]

static void Main()

{

Application.Run(

new frmMDI());

}

private bool isexist(string frmname)

{ foreach(Form frmcol in this.MdiChildren)

{

if (frmcol.Text ==frmname)

{

frmcol.BringToFront();

return true;

}

}

return false;

}

private void position(Form frm)

{ frm.Left=this.Left;

frm.Top =this.Top ;

frm.Width =this.Width-10;

frm.Height =this.Height-10;

}

private void menuItem1_Click(object sender, System.EventArgs e)

{

if (isexist("Form1")==false )

{ Form frm=new Form1 ();

frm.MdiParent =this;

position(frm);

frm.Show();

}

}

private void menuItem2_Click(object sender, System.EventArgs e)

{

if (isexist("Form2")==false )

{ Form frm=new Form2 ();

frm.MdiParent =this;

position(frm);

frm.Show();

}

}

private void menuItem3_Click(object sender, System.EventArgs e)

{

if (isexist("Form3")==false )

{ Form frm=new Form3 ();

frm.MdiParent =this;

position(frm);

frm.Show();

}

}

private void menuItem5_Click(object sender, System.EventArgs e)

{

this.Close();

}

agile developer

Posted: April 17, 2005 in Uncategorized

I like the agiledeveloper.com dotnet gotchas and the java integration of webservice and difference of c# and java material and quite a lot material to down load in pdf format.have a look http://www.agiledeveloper.com/download.aspx

 

Often you need requirement to implement callback with delagate and also to call some long runnign operation different from the main UI.THe requirement ofetn come to call a long database operation and still you want that to async way so that ur UI ll not hang.

Here is what the sample app is look like:-

here is a class named secondary and delegate declaration:go trhu the comment that is well enough.

 

namespace

threadtest

{

//delegate declaration for runnign the long task

delegate void testasync (int i);

//delaget declaration for processign task of main thread from sceondary thread

delegate void sendmessage(string msg);

public class secondary

{

//the long runnign method

public void methodonsecondary(int i)

{

for (int j=0;j<i;j++)

{

j=j+i;

}

i=i+1;

}

}

}

 

 

Now here goes he form code:-

testasync asy =

null;

private void button1_Click(object sender, System.EventArgs e)

{

//create an instance of the class whose method is a longrunnig app

secondary sec=

new secondary();

//create an instance of the delegate and pass the long runnign method

asy=

new testasync(sec.methodonsecondary);

//declare async callback and pass the callback method which will be raised when the long

//runnign app in secondary thread ll be completed

AsyncCallback callback=

new AsyncCallback(callbackmethod);

//invoke the long runnign app passing callback and value for the param

asy.BeginInvoke(500,callback,

null);

//YOU CAN WRITE ANY OTHER METHOD OF EXECUTIO HERE ITWILL BE EXECUTED AS PREV CALL IS ASYNC

}

private void callbackmethod(IAsyncResult ar)

{

try

{

//this method called once the secondary THREAD Complete

//call endinvoke pass the async result

//you can recd the ret value in an object array here if you want to manip the ret value of callback

asy.EndInvoke(ar);

//here goes our logic for updating main thread from secondary

//i am simply displayign a message here you can set some value that could be displayed in ur label

//or progress abar etc

UpdateUI("completee");

MessageBox.Show ("comp");

}

catch(Exception ex)

{

string msg="";

msg="error :"+ ex.Message.ToString();

UpdateUI(msg);

}

}

private void UpdateUI (string StatusMessage)

{

//if invoke is reqd on the thread

if (this.InvokeRequired )

{

//create delegate and pass the showmessage method

sendmessage handler=

new sendmessage(this.ShowMessage);

//arguments array to be passed to invoke method

Object[] args= {StatusMessage};

//invoke the method

this.BeginInvoke(handler,args);

}

else

{

ShowMessage(StatusMessage);

}

}

private void ShowMessage(string StatusMessage)

{

//show the result back to main thread

MessageBox.Show(StatusMessage);

}

private

void Form1_Load(object sender, System.EventArgs e)

{

string connString = @"Integrated Security=SSPI;Packet Size=4096;Data Source=shreeman;Tag with column collation when possible=False;Initial Catalog=test;Use Procedure for Prepare=1;Auto Translate=True;Persist Security Info=False;Provider=SQLOLEDB.1;Workstation ID=SHREEMAN;Use Encryption for Data=False";

string sqlString = "SELECT * FROM emp";

OleDbDataAdapter dataAdapter =

null;

DataSet _dataSet =

null;

try

{

// Connection object

OleDbConnection connection =

new OleDbConnection(connString);

// Create data adapter object

dataAdapter =

new OleDbDataAdapter(sqlString, connection);

// Create a dataset object and fill with data using data adapter’s Fill method

_dataSet =

new DataSet();

dataAdapter.Fill(_dataSet, "emp");

connection.Close();

}

catch(Exception ex)

{

MessageBox.Show("Problem with DB access-\n\n connection: "

+ connString + "\r\n\r\n query: " + sqlString

+ "\r\n\r\n\r\n" + ex.ToString());

this.Close();

return;

}

// Create a table style that will hold the new column style

// that we set and also tie it to our customer’s table from our DB

DataGridTableStyle tableStyle =

new DataGridTableStyle();

tableStyle.MappingName = "emp";

// since the dataset has things like field name and number of columns,

// we will use those to create new columnstyles for the columns in our DB table

int numCols = _dataSet.Tables["emp"].Columns.Count;

DataGridNoActiveCellColumn aColumnTextColumn ;

for(int i = 0; i < numCols; ++i)

{

aColumnTextColumn =

new DataGridNoActiveCellColumn();

aColumnTextColumn.HeaderText = _dataSet.Tables["emp"].Columns[i].ColumnName;

aColumnTextColumn.MappingName = _dataSet.Tables["emp"].Columns[i].ColumnName;

tableStyle.GridColumnStyles.Add(aColumnTextColumn);

}

// make the dataGrid use our new tablestyle and bind it to our table

dataGrid1.TableStyles.Clear();

dataGrid1.TableStyles.Add(tableStyle);

dataGrid1.DataSource = _dataSet.Tables["emp"];

}

}

public class DataGridNoActiveCellColumn : DataGridTextBoxColumn

{

private int SelectedRow = -1;

protected override void Edit(System.Windows.Forms.CurrencyManager

source,

int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string

instantText,

bool cellIsVisible)

{

//make sure the selectrow is valid before trying to unselect

if(SelectedRow > -1 && SelectedRow < source.List.Count + 1)

this.DataGridTableStyle.DataGrid.UnSelect(SelectedRow);

SelectedRow = rowNum;

this.DataGridTableStyle.DataGrid.Select(SelectedRow);

}

}

I found hasselman have some good set of qusetions for .net dev.check it out here