jump to navigation

Create a master-detail Windows Forms application with EF March 15, 2012

Posted by fofo in C#, Visual Studio 2008, Visual Studio 2010.
Tags: ,
16 comments

I have been teaching in the past few weeks many people on how to use Entity Framework. I have decided to provide some of the samples I am using in my classes.

In this post I will show you a step by step example on how to build a Windows Forms (Master – Details) application with C# and Entity Framework. Have a look in this post if you would like to see how to implement similar functionality with WPF.

First let’s try to define what EF is and why it is going to help us to create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of Object-relational impedance mismatch. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.

In my other development blog (ASP.Net blog) you can find many posts on Entity Framework.Have a look if you want.

We will need a database and a version of SQL Server.You can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample AdventureWorkLT database, click here

Let’s start with our hands-on example.

1) Launch Visual studio 2010 Express edition or any other edition you may have installed.

2) Create a new class library project and name it AWEFModel. Choose C# as your language of development.Ιn this project I will keep my Entities Data Model in a separate project and then I will consume this project from a separate application (Windows Forms)

3) Remove the Class1.cs file.Right – click on your project from the Solutions Explorer window and Add a new Item. From the available templates choose ADO.NET Entity data model. Give it the name ΑdventureWorksLTEntities.edmx and click the Add button.

4) Then the Wizard pops up. Choose “Generate from Database”. Have a look at the picture below

5) Click Next and Create a New Connection (as you see in the picture below) and hit the Continue button.

6) Then follow the instructions as shown in the picture below.Select the local installation of your SQL Server and the database name and then click OK.


7) After you complete the steps above you will see something like the picture below. You can see the Entity connection string and where these setting will be saved.Hit the Next button.Then click Finish

8) If you notice you will see that there is something called Entity connection string that points to the actual database.It is saved in the App.config file of the

9)  Now the wizard will identify the database objects and let us choose which database objects we want to include in our model.I included all the database objects.Hit the Finish button.Ι will include only some of the tables. Have a look at the picture below

Finally, Visual Studio will add the model to the project and will add the necessary references.

10) Have a look at your entity model as it is visualized in the Entity Model Designer. Have a look at the Entity classes and their relationships/associations.Have a look at the properties of each Entity class. Have also a look at the Navigation Properties of each entity class.Basically the entity framework generates classes for all the entities in the designer. You can have a look at the generated code if you want by opening the class file, which in my case is AdventureWorksLTEntities.Designer.cs.

11) Add a new project to your solution, a Windows Forms Application. Name it WindowsFormsEFMD. Add a reference to the System.Data.Entity  and the Entity Framework Model project (AWEFModel)

12) Copy paste the App.config file from the AWEFModel project to the WindowsFormsEFMD project.

13) We will add a datasource to the Windows Forms application (Data–> Add new Datasource). We will add a datasource for the Customer Entity. In the wizard that pops up (Choose a Data Source Type) select Object and then click Next.In the Select the Data Objects choose from the AEFModel(It is already in the there) the Customer class /entity. Change the Customer Entity from GridView to Details. Drag and drop the Customer Entity from the Data Sources to the Form1 window.

Have a look at the picture below to see what I mean

Drag and drop from the Data Sources (SalesOrdersHeaders) entity to the Form1 form.

Have a look at the picture below.

14) In the Form1_Load event handling routine type,


private void Form1_Load(object sender, EventArgs e)
{
var ctx = new AdventureWorksLTEntities();

var query = ctx.Customers.Where(c=>c.SalesOrderHeaders.Any());

customerBindingSource.DataSource = query.ToList();

}

15) Ι am querying the database to find only customers that have orders. Run your application.

16) I will show you how easy it is to make changes. Please note that all the changes are made to the entities in the memory and then are persisted back to the database.

17) Go to the customerBindingNavigator control in the Form1 design view.Select the “Save” button and enable it (right-click on it).

18) Then in the customerBindingNavigatorSaveItem_Click event handling routine type.


private void customerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{

      ctx.SaveChanges();
    }

I have made a very small change in the code. I have instantiated the context outside of the local scope

public partial class Form1 : Form
{      AdventureWorksLTEntities ctx = new AdventureWorksLTEntities();

public Form1()
{
InitializeComponent();
}

19) The ctx.SaveChanges() method persists the changes to the database.Run your application and make some changes in the Customers Grid. Click the Save button to persist the changes back to the database. Launch SQL Profiler to see what actually happens in the database.

Leave a comment if you need the source code.

Hope it helps!!!!

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

Manage files,folders, special folders with VB.Net and window forms December 1, 2008

Posted by fofo in general .net, VB 2005, VB 9.0, Visual Studio 2005, Visual Studio 2008.
Tags: , , , , ,
8 comments

Hello all !!!

I came across a project today that it was required that we manage files,folders,special folders through windows forms.

Basically that specific functionality was already implemented with scripts. Some of the tasks required were implemented with WMI and some using the Windows Script Host FileSystemObject

If you want to find more scripts like that visit the Script Center

In this post I will show you how to implement file,folder related tasks, by merely using the classes and methods that are already written for us in the FCL in .Net and reside in the System.IO namespace.

I will create an example so we can follow step by step how to accomplish a similar task

1) Launch Visual Studio 2005/2008.

2) Create a new Windows Forms project and choose VB as your development language.

3) Save your project-solution with a name of your choice.

4) Add a reference to the System.IO namespace from your project

5) Add a button and a listbox from the Toolbox on the form. Name the button “FindFiles”

6) In this first example we will see what methods to use to retrieve all files from a folder

7) Double click the button and in the event handling routine that is automatically created type this code

Dim thefiles() As String
‘change the path to a path that exists in your machine
thefiles = Directory.GetFiles(“C:\Acer\Empowering Technology”)
Me.ListBox1.DataSource = thefiles

If you wanted to get files with a specific type e.g all .dll in tha folder you can replace this line

thefiles = Directory.GetFiles(“C:\Acer\Empowering Technology”)

with this

thefiles = Directory.GetFiles(“C:\Acer\Empowering Technology”, “*.dll”)

8)Build your solution and then run your application. Click on the button and see all the files from this particular folder to get listed inside the ListBox control. We use the Directory Class and the GetFiles method of this class.

9) Add another button in the for. Name it “FindFolders”. As you can imagine we will find all the subfolders inside that folder.Double click the button and in the event handling routine that is automatically created type this code

Dim thefolders() As String
thefolders = Directory.GetDirectories(“C:\Acer\Empowering Technology”)
Me.ListBox1.DataSource = thefolders

10) Run your application. Click on the “FindFolders” button and see all the subfolders from this particular folder to get listed inside the ListBox control

11) Let’s see now how we can access special folders like “My Pictures”, “My Documents”.Add another button in your form and name it “GetSpecialFolders”.We will try to get all the files inside the My Documents special folder.

12) Double click the button and in the event handling routine that is automatically created type this code

Dim thefiles() As String
Dim specialfolder As String
specialfolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
thefiles = Directory.GetFiles(specialfolder)
Me.ListBox1.DataSource = thefiles

As you can see we use the Environment.SpecialFolder.MyDocuments toget access to that special folder.

13) In this final example I want to show you how to find information like file size for all the files that are inside the “C:\Acer\Empowering Technology” folder. We need to find the file size, the time the file was created and the extension of the file.

In order to to do that we must place 3 textboxes and 3 labels on our form. Change the text property of the first label to “FileSize” .Change the text property of the second label to “File Created” .Change the text property of the third label to “Extension”.

We will place the values we find for each file inside the textboxes.

We will use the SelectedIndexChanged event of the ListBox control to write our code. Just click on the Listbox control from the Form Designer. In the event routine that is created type the following lines.

Dim theselectedfile As String
theselectedfile = Me.ListBox1.SelectedItem.ToString
Dim myfile As New FileInfo(theselectedfile)
Me.TextBox1.Text = myfile.Length.ToString()
Me.TextBox2.Text = myfile.CreationTime.ToString()
Me.TextBox3.Text = myfile.Extension.ToString()

14) Run your application and click on the button “FindFiles”. See the listbox populated with files. Just click on several files and see the results for each file inside the textboxes.

That is all folks!!! Hope it helps.Make sure you explore the other methods and classes in the System.IO namespace.

If you need the source code then you can email me or just leave a comment.

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

Follow

Get every new post delivered to your Inbox.

Join 1,788 other followers