jump to navigation

Using the Process Component to launch applications from our .Net application December 3, 2008

Posted by fofo in .NET, VB 2005, VB 9.0, Visual Studio 2005, Visual Studio 2008.
Tags: , , ,
1 comment so far

In this post I will show with a simple example how to use the Process control to launch applications from a windows form application (vb version), with this control that was shipped with the .Net 2.0 version you can launch very easily all sort of applications.

Let’s get started then…

1) Launch Visual Studio 2008/2005-express editions will do

2) Create a windows form application. Choose VB as your development language.

3) Name your solution project with a name of your choice

4) Add 3 buttons on the form. Change the Text properties of the 3 button to “Launch Notepad”, “Launch Wordpad”, “Launch MS Paint”

5) Drag and Drop 3 Process controls from the ToolBox (Under  the Component tab) and name them “NotePadProcess”, “WordPadProcess”,”MSPaintProcess”

6) Add a reference to your project to the System.IO namespace from the Solutions explorer window, by right-clicking on your project name, then Properties, then Reference and select System.IO from the imported namespaces

7) Double Click on the button that is destined to launch Notepad. In the body of the routine type

mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
mypath = Path.Combine(mypath, “notepad.exe”)
NotepadProcess.StartInfo.FileName = mypath
NotepadProcess.Start()

the code is pretty straight forward.We get to the notepad.exe file by finding the path and then we start notepad

8) Run your application, click on the “Notepad” button and see notepad launching

9) Double click on the two other buttons on the form designer. In their respective event handling routines type

for the button the launches wordpad

Dim mypath As String
mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
mypath = Path.Combine(mypath, “Windows NT\Accessories\wordpad.exe”)
WordPadProcess.StartInfo.FileName = mypath
WordPadProcess.Start()

for the button the launches paint

Dim mypath As String
mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
mypath = Path.Combine(mypath, “mspaint.exe”)
MSPaintProcess.StartInfo.FileName = mypath
MSPaintProcess.Start()

10) Run your application and then click on all the buttons

11) If you need to close all these applications programmatically you can add another 3 buttons on the form and (names:CloseNotepad,CloseWordpad,CloseMsPaint).Double click on the buttons and type respectively

NotepadProcess.Kill()
WordPadProcess.Kill()
MSPaintProcess.Kill()

12) Run your application. In order for this example to work, click once on the buttons to launch all 3 applications and then click on the “close” buttons to close the applications

13) If you try to close “Notepad” without first launching notepad you will receive an error.If you want to avoid that and close all the notepad instances you opened

instead of

NotepadProcess.Kill()

type in the body of the event handling routine

Try
Dim npProc() As Process
npProc = Process.GetProcesses
For Each proc As Process In npProc
If proc.ProcessName.Equals(“notepad”) Then
proc.Kill()
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

14) Do the same for the remaing two event handling routines that close MsPaint,WordPad

15) Now if you want to capture the moment that notepad closes, for any reason you need to add this line of  code

NotepadProcess.EnableRaisingEvents = True

in the button click event that launches Notepad.

So the complete code for the button that launches Notepad is

Dim mypath As String
mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
mypath = Path.Combine(mypath, “notepad.exe”)
NotepadProcess.EnableRaisingEvents = True
NotepadProcess.StartInfo.FileName = mypath
NotepadProcess.Start()

16)  Find the NotepadProcess (if you called it like that) process and choose the event Exited from the code window. The complete code is this

Private Sub NotepadProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotepadProcess.Exited
MessageBox.Show(“Notepad Exited”)
End Sub

17) Run your application. Launch Notepad. If you close Notepad by either clicking on the respective button on your form or just close Notepad from the close button, the code within this event will run

That is all folks!!!!

If you need the source code email me or leave a message.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Advertisements

Using the FileUpload web server control in your asp.net website November 22, 2008

Posted by fofo in .NET, asp.net 2.0, C#, Visual Studio 2005, Visual Studio 2008.
Tags: , ,
7 comments

In this post i would like to talk about another web server control, FileUpload, which was a control included in  the ASP.Net 2.0 framework. I will try to demonstrate,as always with an example, how to upload one file and how to upload multiple files using the FileUpload control. Basically with this control you try to give the user the same functionailty with a ftp client.

For more information on this control have a look at the msdn reference, here

If you remember back in the days of ASP.NET 1.0 and ASP.NET 1.1 we had to use  the HTML FileUpload server control. This control put an <input type="file"> element on your Web page to enable the end user to upload files to the server. To make this work however, we had to add, enctype="multipart/form-data" to the page’s <form> element.

Let’s start a new project to demonstrate out example

1) Launch Visual Studio 2005/2008

2) Create a new asp.net web application in C#

3) Call it “uploadcontrol”

4) Drag and drop in the default.aspx page a FileUpload control from the Toolbox

5) If you run your application now , you will see a page that does not do much, just a textbox and “Browse” button that are part of the FileUpload control

6) Stop your application and place a button in the default.aspx page

7) Add a Label control in your application. Leave the default names for all the controls on the page.

8) Create a folder in the C drive and call it “myUploads”

9) Double click on the button and in the event handling routine and type

if (FileUpload1.HasFile) {
FileUpload1.SaveAs(“C:\\myUploads\\” + FileUpload1.FileName);
Label1.Text = “File name: ” +
FileUpload1.PostedFile.FileName + “<br>” +
FileUpload1.PostedFile.ContentLength + ” kb<br>” +
“Content type: ” +
FileUpload1.PostedFile.ContentType;
}
else
{
Label1.Text = “You have not selected a file or the file has not been found.”;
}

First of all let’s explain the lines above.

Initially we use the HasFile Property which returns a value indicating whether the FileUpload control contains a file.

10) Run your application again and try to upload a file

If that is true we append in the text property of the Label control , the following information

  • filename
  • file size
  • type of the document, e.g image,word document, e.t.c

We achieve that by using the PostedFile property , which holds the file that is being uploaded.

Before going to show more things regarding the FileUpload control, i will add a Try Catch statement in the code above to provide some sort of exception handling.

if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs(“C:\\myUploads\\” + FileUpload1.FileName);
Label1.Text = “File name: ” +
FileUpload1.PostedFile.FileName + “<br>” +
FileUpload1.PostedFile.ContentLength + ” kb<br>” +
“Content type: ” +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = “ERROR: ” + ex.Message.ToString();
}
else
{
Label1.Text = “You have not specified a file or the file has not been found.”;
}

Now let’s see how you can upload mutliple files from a single page.

1) Create a new .aspx page and add it to your project, by adding a new item from the Solutions window.

2) Place 3 FileUpload controls on the page. Also add a button and a label control.

3) double click on the button

4) In the event handling routine for the click event of the button, type

thefileupload(FileUpload1);
thefileupload(FileUpload2);
thefileupload(FileUpload3);

In order to upload the three files at once, I make 3 seperate calls to the method , thefileupload.

So I have created a method of my own which I call thefileupload. This is the code for the method

private void thefileupload(FileUpload upload)

{
if (upload.HasFile)
try
{
upload.SaveAs(“C:\\myUploads\\” + upload.FileName);

}
catch (Exception ex)
{
Label1.Text = “ERROR: ” + ex.Message.ToString();
}
else
{
Label1.Text = “You have not specified a file or the file has not been found.”;
}
}

There is nothing fancy about this code. It is exactly the same as the previous bits. I just placed this code inside a method.

If you want the file upload functionality to work make sure that the destination folder on the server is  writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder’s properties. If you want to permit your users to upload large files you should overwrite in the web.config file, the default size limitation which is 4MB (4096kb)

Hope it helps.

If you want the source code you can email me.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

.Net 4 Framework poster November 16, 2008

Posted by fofo in .NET.
Tags: , ,
add a comment

Brad Adams has created a very nice and cool poster with the new features in .Net Framework 3.5 SP1 and .Net Framework 4.0.

For more information click here

The poster is available in pdf version and in DeepZoom version.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Interfaces in C# July 22, 2008

Posted by fofo in .NET, asp.net, C#, c# 3.0.
Tags:
16 comments

I am currently teaching people from all walks of life about designing and implementing asp.net web applications with .net 3.5 and visual studio 2008. Everyone wants to develop a web application right away. But I keep encouraging them to find out more about the basics of OO. When it comes to the term Interface most novice developers are confused. In this post I will try though a practical example and some definitions to clear things….

So what is actually an interface? I will start with an example from real life. We use interfaces or interface all the time. When my dad told me how to dial my first telephone number from our home phone many years ago, I was pretty pleased. When we visited my uncle in their house I could use their phone just as easy.

Imagine if someone had to teach me all over again how to use the phone. I do not need to know how the interface is implemented for a phone. I can use the buttons in the panel (the interface in this case)  and know that the phone will subscribe to the general phone interface.

Let’s see interface characteristics in the “code world”

  • An iterface defines only the properties and method signatures and not the actual implementation. I mean that in a class declaration we implement fields,properties,methods and events. In an interface we just define what properties/methods the class should have.
  • Requires that classes which implement an interface must “honour” the property and method signatures. Basically are like contracts for classes. Classes which implement an interface must implement the methods and the properties of the interface
  • Many classes can implement a particular interface method, in their own way
  • An interface may inherit from multiple base interfaces
  • A class may implement-inherit from multiple interfaces
  • A C# class may only inherit from one class

Let’s see a simple example

1) Create a asp.net web application with C#

2) Add a new item to your project, a class file, called Human.cs.

3) Let’s define an Interface, called IHuman.

Just above this line of code

public class Human

type the following

 

interface IHuman
{
    void Read();
    void Write(object obj);
    int Height { get; set; }
    int Weight { get; set; }

}

here we define properties and methods that the class that subscribes to this interface must implement.

We prefix the name of the Interface with an “I”. Just a widely accepted convention…

4) Now let’s implement the class

Here we declare (sign a contract so to speak, that the Human class will Implement the IHuman Interface)

public class Human:IHuman

Right after the line above type

private int height;
        private int weight;

    public Human(string s)
         {
             MessageBox.Show(s);
      
         }

         // implement the Read method
         public void Read()
         {
             MessageBox.Show(
                 “Implementing the Read Method for IHuman”);
         }

         // implement the Write method
         public void Write(object o)
         {
             MessageBox.Show(
                 “Implementing the Write Method for IHuman”);
         }
         // implement the property Height
         public int Height
         {
             get { return height; }
             set { height = value; }
         }

// implement the property Weight

public int Weight
         {
             get{ return weight; }
             set{ weight = value; }
         }

As i said before the class must “honour” its contract with the interface.

Before you go on try to comment this code out

public void Read()
    {
        MessageBox.Show(
            “Implementing the Read Method for IHuman”);
    }

Try to build your application. Well as you see from the error message below, someone is not honouring his contract….

Human’ does not implement interface member ‘IHuman.Read()’

5) From our Page_Load event of the defaul.aspx page we can create a new instance of the Human class

 Human myperson = new Human(“fofo”);
        myperson.Read();
        myperson.Weight = 78;
        myperson.Height = 88;
        Response.Write(myperson.Weight);
        Response.Write(“</br>”);
        Response.Write(myperson.Height);

Please note that i could have a Boy class that could implement the IHuman interface.

public class Boy:IHuman

each class (boy,human) should implement the Read method of the IHuman interface. But each class was free to implement it in its own way. 

We could define the IHuman interface above as an abstract class.And then had our class inheriting from our abstract class. But if changed slighlty the implementation of our abstract class then the referencing classes would fail and so our application would fail. If we work with Interfaces and we are commited to follow good practices like, never to alter the Interface implementation after they have been deployed, we will not run into such problems.

Read this article from msdn to see when to use interfaces

Read this article from msdn to see when to use Inheritance

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

How to use .NET Delegates and event handling using delegates July 22, 2008

Posted by fofo in .NET, C#, c# 3.0.
Tags:
10 comments

One of the issues that troubles most novice developers is the concept of “delegates”. In this post I will try through definitions and practical examples to explain delegates and what is the relation of delegates and events. If you come from a C/C++ environment you can think delegates as function pointers. Basically function pointers are variables that hold the memory address of a function. So when we invoke that variable, a call is made to the underlying function.

In the .Net world we can simply say that delegates are type-safe .NET objects (like everything else) which points to a method that matches its specific signature.Delegates derive from the System.Delegate class.

In order to see how delegates work we will review a simple example.I would like to point out that i am talking about single cast delegates. A single cast delegate can invoke a single method.

 1) Create a simple asp.net web application with C#

 2) Add a new item, a class file, and call it delegate (delegate.cs)

 3) In this class file add this public function

public int addnumbers(int myfirstnum, int mysecondnum)
    {
        int result;
        result = myfirstnum + mysecondnum;
        return result;
    } 

4) In the Page Load event of the default.aspx add the code below

delegateclass theDelegate = new delegateclass();
myDelegate delegateAddition = new myDelegate(theDelegate.addnumbers);

int addition = delegateAddition(10, 89);

Response.Write(“</br>”);

Response.Write(addition.ToString());

5) Place the code below which declares a delegate that takes two integer type as arguments and returns an integer as return type, just above your Page_Load event handler method

public delegate int myDelegate(int thefirst,int thesecond);

I will try to explain what the code does.

myDelegate delegateAddition = new myDelegate(theDelegate.addnumbers);

 I have created a delegate variable(delegateAddition) of type myDelegate. Using the delegate variable, I can point to any method that has the matching signature.

In the above example the method addnumbers has the same signature with the delegate variable. I use the new keyword to reference the delegate variable to the addnumbers method.

Then I call the function addnumbers by passing required parameters through the delegate.

int addition = delegateAddition(10, 89);

6) Run your application

In this second part of the post I would like to talk about delegates and events.

Some people do not understand why we need to use delegates in the event communication process.

Let’s imagine that we have a created/developed a multi-tier application for a supermarket. In our business logic layer we can have a class(productstock) that among other things checks the stock limit of any particular product. If the minimum of stock for any given product is reached this class should notify the other parts of the application. I can hear people saying, “Well, where is the problem? We do not need delagates. We simply call a normal method, that might call another method and so on…”

I think we can understand more about the scenario above if we see how events are raised and captured by applications.

We want to handle our events. That is why we write so much code in the event handlers like (e.g button_click). But how on earth knows our application that a button has been clicked?

Well the operating system, the moment the button_click happens, it fires an event.The operating system does not care who will capture this event. It just notifies everyone that “well guys out there, a button_click event has taken place”. Our code(event handling routine) can capture this event and do whaterver it must do.But any other programs can use this event now that they are notified.

In our productstock class, in our supermarket application, the application does not know what other applications need to know about the stock limit of a product running low. So it justs fires an event whenever stock is low for any product and notifies other application like, an application that sends an email to the manager of the supermarket informing him that stock is running low, an other application that may cancel or initiate another transaction.

Hopefully it is much clearer now.Let’s take the example above and explain it with .Net terms.

An event in the .NET Framework world enables objects of a class to notify other objects that an action has been performed and that they should react. The model on which the events in the .Net Framework are based is the publisher-subscriber model. The class that publishes the event is the publisher. The class that registers to the published event is the suscriber class.

In C#,VB any object can publish a set of events. Other applications can subscribe to these events. When the publishing class raises an event, all the subscribed applications are notified.But the publisher doesn’t know who is going to subscribe the event.  Delegates act as an intermediary between the publisher and the subscriber.

Let’s see another example

1) Create an ASP.Net web application with C#

2) We will create  a class that will publish the events. Add a new item to the project, a class file and call it Publisher.cs.

3) Add the code below inside the public class Publisher

  public event DelegateEvent theevent;
  public delegate void DelegateEvent(object from, EventArgs args);

  public void raiseEvent(EventArgs args)
  {
      theevent(this, args);
  }

   public Publisher()
   {
   

   }

public void SendTheEvent()
   {
         MessageBox.Show(“the event is fired here”);
         this.raiseEvent(new EventArgs());
   }

Let me explain what I do here.

First I declare the event

public event DelegateEvent theevent;

Use a delagate to publish our event

public delegate void DelegateEvent(object from, EventArgs args);

 We raise the event from the Publisher class

public void raiseEvent(EventArgs args)
{
theevent(this, args);
}

We trigger the event here 

 public void SendTheEvent()
    {
        MessageBox.Show(“the event is fired here”);
        this.raiseEvent(new EventArgs());
    }

Do not forget to add a reference to your project to the System.Windows.Forms namespace. At the beginning of the Publisher.cs file add this bit of code, using System.Windows.Forms.

4) Add another class file to the project and call it Subscriber.cs. Add the code below in the class Subscriber

public Subscriber()
 {

Publisher myclass = new Publisher();
     
myclass.theevent += new Publisher.DelegateEvent(handletheevent);

myclass.SendTheEvent();

}

Let me explain what I do here

We create an instance of the Publisher class

Publisher myclass = new Publisher();

We want to subscribe to this event delegate (DelegateEvent) of Publisher. So if the Publisher
raises any event, our method called the “handletheevent” is notified

myclass.theevent += new Publisher.DelegateEvent(handletheevent);

The event is fired here

myclass.SendTheEvent();

our event handler code goes here that responds to the event being fired

   private void handletheevent(object sender, EventArgs e)
   {
    
       MessageBox.Show(“Event handled in handletheevent of the Subscriber”);
    
     
       MessageBox.Show(“Who is the Sender?” + sender.GetType());
   }

Do not forget to add a reference to your project to the System.Windows.Forms namespace. At the beginning of the Subscriber.cs file add this bit of code, using System.Windows.Forms.

5) Run your application and see the results

Hope it helps!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl