Just another WordPress.com site

Silverlight 5 Features


Silverlight  

Silverlight 5 includes several new features that are based on customer suggestions. This topic introduces some of the new features and improvements in Silverlight 5.

 

This topic contains the following sections.

PivotViewer

The PivotViewer control enables you to display a large amount of data at once in a way that is easily consumable by the user. Users can browse the data in such a way that helps them see the trends and quickly find information they need. For more information see, PivotViewer.

DrawingSurface

DrawingSurface is a new control in Silverlight 5. DrawingSurface defines an area where 3-D content can be composed and rendered. You implement the rendering behavior through the event data of the Draw event. For more information, see 3-D Graphics Overview and Walkthrough: Creating and Animating a 3-D Textured Cube in Silverlight.

ItemsControl Text Search

A user can now search a list of items in an ListBox or ComboBox using keyboard input. You can specify the property that identifies an item for search purposes by setting the TextPath attached property. The list will scroll to the first item that matches.

Dialog Changes

OpenFileDialog and SaveFileDialog have new capabilities. You can use the InitialDirectory property to specify the initial directory when you open theOpenFileDialog. You can use the DefaultFileName property to specify a default file name when you open the SaveFileDialog.

Sound Effects

Silverlight 5 includes new classes for sound effects. You can use the classes in the Microsoft.Xna.Framework.Audio namespace to create and manage sound effects in your applications. Use the SoundEffect class to trigger low-latency sound.

Variable Playback Rate

Silverlight 5 includes the ability to check and change the playback rate of media. MediaElement now includes a PlaybackRate property and a RateChanged event.

Application-Restricted Media

Application-restricted media is a new feature in Silverlight 5 that enables content providers to ensure their content under digital rights management (DRM) is consumed only by Silverlight applications they authorize. This is ensured by requiring Silverlight client applications accessing restricted media to be signed with an Authenticode x.509 certificate. For more information about signing applications, see Application Signing. For more information about DRM, see Digital Rights Management (DRM).

Key Rotation

Silverlight 5 includes support for Live TV scenarios that have policies and licenses. A Silverlight 5 client manages the enforcement of changing policies for the developer. No special client application code is required. For more information, see Digital Rights Management (DRM).

Remote Control Support

Enables users to control media playback. For more information, see MediaCommand.

 

Graphics Stack

The graphics stack has been re-architected to add features such as independent animations.

3-D Graphics

Silverlight 5 introduces the ability to use hardware accelerated 3-D graphics in your Silverlight applications. This opens up a whole new set of scenarios that are possible in Silverlight, such as 3-D drawn controls, data visualizers, 3-D charts, scatter points, geographic overlays, and 3-D games and simulations.

The core of the XNA Games Studio 4.0 graphics libraries is now included in Silverlight 5. These libraries include render targets, XNA built-in effects, and surface composition settings for depth/stencil buffers and multi-sample anti-aliasing. Developers familiar with XNA will be able to quickly get up to speed with Silverlight 3-D graphics programming. For more information, see 3-D Graphics Overview and Walkthrough: Creating and Animating a 3-D Textured Cube in Silverlight.

Character Spacing

Silverlight 5 includes the ability to increase or decrease the amount of space in between characters in text. You can do this by using the CharacterSpacingproperty available in the ControlTextBlock, and TextElement classes.

Inter-line Spacing

Silverlight 5 enables you to increase or decrease the space between lines of text to increase readability or to change the look and feel of the body of text. You can do this by using the LineHeight and LineStackingStrategy properties available in the BlockTextBlockTextBox, and RichTextBox.

RichTextBlock and Displaying Overflow Content

Silverlight 5 includes a new RichTextBlock control that you can use to display rich text. You can display the content that does not fit in a RichTextBlock in aRichTextBlockOverflow control. For more information, see RichTextBlockOverflow.

Text Clarity

Silverlight 5 includes more support for OpenType fonts. It also includes support for pixel-snapped text. Both of these features improve text clarity. For more information, see TextFormattingMode.

Silverlight 5 includes the following enhancements for trusted applications. For more information, see Trusted Applications.

Access File System

Trusted applications can now access the local file system without restriction.

Multiple Windows

You can display multiple Window instances in trusted, out-of-browser applications. This enables you to create non-modal dialog boxes, tear-off windows, and user-adjustable layouts that can span multiple monitors. For more information, see the Window class.

In-Browser

System administrators can enable trusted applications to run inside the browser, simplifying enterprise deployment and application updates. This also enables you to use some previously out-of-browser-only features inside the browser, including the WebBrowser and NotificationWindow classes. For more information, see How to: Enable Trusted Applications to Run Inside the Browser.

Call Windows APIs

On computers running Windows, you can now call Windows native APIs and unmanaged code from Silverlight 5 applications. This is also referred to as platform invoke or PInvoke. This applies to trusted out-of-browser applications or trusted in-browser applications. For more information, see How to: Call Unmanaged Code from Trusted Applications.

Silverlight 4 added bitmap printing support. However, all content was rasterized as a bitmap. Silverlight 5 adds vector printing support, which improves printing quality and performance. For more information, see Printing.

Detecting Double-Clicks

Silverlight 5 adds a ClickCount event data property to the MouseButtonEventArgs event data class. You can use this property to detect double-clicks, based on platform settings for the time duration that two clicks should be considered a double-click.

Data Binding

Silverlight 5 enables you to debug data bindings by setting breakpoints on bindings in XAML. When a breakpoint is hit, you can use the Locals window to examine the state of a binding and identify any issues. For more information, see Data Binding.

Silverlight 5 also includes several data binding enhancements, some of which were previously available only in Windows Presentation Foundation (WPF). These enhancements enable you to do the following:

  • Use data bindings with styles. To do this, use the Setter.Value property as a binding target. You will typically do this in XAML using the binding markup extension.

  • Bind to ancestors in the visual tree. To do this, set the Binding.RelativeSource property to FindAncestor.

  • Associate bound objects to data templates implicitly by type instead of explicitly by template name. To do this, set the DataTemplate.DataType property for each implicit template instead of specifying x:Key values.

  • Bind to dynamically-generated properties. To do this, implement the ICustomTypeProvider interface on classes with dynamic properties.

  • The FrameworkElement.DataContextChanged event has been added. You can use this event to detect when the data context for an element has changed.

  • The UpdateSourceTrigger.PropertyChanged enumeration value has been added. This indicates to update the binding source whenever the binding target value changes. This can be helpful when the binding target is a TextBox. You can detect changes before the TextBox loses focus. Also, you do not have to handle the TextChanged event, which better supports the MVVM pattern.

Silverlight 5 now has a IMarkupExtension<T> interface. By implementing the ProvideValue method, you can define a custom markup extension, which can be understood and used by the Silverlight XAML parser. Services that are intended for markup extension service context enable several scenarios that were not possible in Silverlight 4 XAML. For example, it is now possible to implement a similar markup extension behavior to the x:Type markup extension from WPF XAML.

Certain structures that did not support an attribute syntax for setting their properties now support attribute syntax on properties. These structures are:CornerRadiusThicknessSize, and Rect.

You should see performance improvements because of the following changes.

  • Reduced network latency by using a background thread for networking. This is helpful for scenarios that use client HTTP web requests.

  • Improved XAML parser improvements for user controls and resource dictionaries.

  • Support for 64-bit browsers.

  • Increased performance of hardware decoding and presentation of H.264 media for unprotected content.

  • Support for multi-core JIT to improve start-up time for Silverlight applications.

Advertisements

Windows 8 OperatingSystem


 
Windows 8:Advantages:
  1. Windows 8 is able to work on the Tablet, Laptop and Desktop
  2. Everything was faster in Windows 8
  3. There is a Windows App Store on Windows 8
  4. Windows 8 is designed to support the touchscreen 
  5. Windows 8 has been designed for touch screens with ARM based processors in which current smartphones and tablets are run on .
Windows 8:Disadvantages
  1. Metro is able to work well on the tablet but the UI is not very compatible when used on the desktop 
  2. Metro multitasking is limited to 2 application only
  3. Very difficult to move between screens
  4. There is no option to turn tiles into icons
  5. Tiles caused crash

Building an N-Tier Application in .NET


Building an N-Tier Application in .NET

 

Summary: After reviewing the types of n-tier applications, you’ll learn how to create a typed dataset that can return data from a Web service and consume a Web service from a Windows application. (17 printed pages)

Objectives

  • Review the types of n-tier applications.
  • Review the goals of a good n-tier application.
  • Learn how to create a typed dataset that can return data from a Web service.
  • Consume a Web service from a Windows application.

Assumptions

  • You have developed an n-tier application.
  • You are very familiar with classes.
  • You have used the OleDbDataAdapter and DataSets.
  • You know how to create a Typed DataSet.
  • You can create a form in Microsoft® Visual Studio® .NET.
  • You are familiar with relational databases and Microsoft ADO.NET.
  • You have created a Web service in Microsoft® .NET.

Contents

Types of N-Tier Applications
Creating an N-Tier Application
What’s Different from Visual Basic 6.0?
Summary

Types of N-Tier Applications

There are many types of n-tier applications that programmers have developed over the years. Since classes were first introduced in Microsoft Visual Basic® 4.0, many programmers have attempted to come up with the definitive method of creating n-tier applications. Although all of them are clever, there has never been a consensus on how every n-tier application should be constructed. As many programmers as there are in the world, there seem to be that many methods of developing n-tier applications. Below is a list of some of the possible ways.

  • Create a component with one class that returns a disconnected ADO recordset for any SQL statement sent to it. All updates are performed in the ADO recordset, then passed back to the component for batch updating.
  • Create a component that has many classes based around business processes. All data for the business process is passed to this component. The component will update the appropriate tables from the data supplied. Another component would be used to return views of data needed to support the user interface for a business process.
  • Create one class per table using ADO embedded into the class. This is a logical n-tier model where both the EXE and the classes (in a DLL) are installed on the client machine.
  • Create one class per table using ADO on the client side. This client-side class passes SQL through DCOM to a server-side Data Class running under MTS that returns a disconnected ADO recordset to the client side.
  • Create two classes per table, one with properties that can be set from the client side EXE. These properties are then bundled into an XML string and passed across DCOM to a server-side class running under MTS. The XML contains instructions on how to gather or modify the data, and a disconnected ADO recordset is returned back to the client-side class.
  • Create one class per table using a DOMDocument object on the client side to process all the data. The client-side class bundles up properties into an XML string that is then sent to a server-side data class. The server side extracts the instructions (the SQL) from the XML and performs the appropriate action on the database server. The server-side class then returns XML to the client-side class to inform the client what happened on the database. In this scenario, there is only one data class for all tables.
  • Create one server-side class for all tables. The client side passes SQL to the server-side class and it returns a disconnected ADO recordset. All forms then use these ADO recordsets for processing data.
  • Create a client-side EXE that sends a SOAP request to a Web server for XML data. XML is processed on the client side using the DOMDocument object.

As you can see, there are many different methods for creating an n-tier application. They all work, and they each have advantages and disadvantages. The goal of this document is not to dispute any of these, nor to look at the advantages and disadvantages, but to simply present a way to create n-tier data classes within Visual Basic .NET.

In this document, you will learn to create a Typed DataSet using built-in tools in Visual Studio .NET. A Typed DataSet is inherited from the DataSet class in .NET. It also provides you with properties that match up to each column in the base table. You use a standard data adapter object to fill up the DataSet from the data source. The wizard that generates this Typed DataSet reads the schema information from the data source and maps these data types to each of the columns. This is why this is called a Typed DataSet.

A Typed DataSet will help you speed up your development process in a few ways. First, you no longer have to remember column names; you will have a Microsoft® InteliSense® list after creating an object from this DataSet class. This avoids run-time errors as column names can be checked at compile time. Second, you no longer have to see SQL in your front-end client application. All of the SQL is buried in the data adapter. By putting these Typed DataSets into a separate component, you are able to reuse these classes from multiple projects.

Goals of a Good N-Tier Application

N-tier design came about as a result of the failings of the client/server model. There are many goals that an n-tier application design should achieve. Here are some of them.

  • If you change the underlying data access methods, the client-side code should not have to change.
  • All data access routines should be exposed as objects instead of function calls. As an example, it is much easier to use ADO than the ODBC API calls.
  • SQL should be eliminated from the client-side code. The client code should just be concerned with methods and properties.
  • Table and column names should be eliminated from the client-side code. Typed datasets can present table and column names as properties, providing an IntelliSense list, as opposed to having to type in a string name. This means at compile time, checks can be made for data types and names of columns.
  • The client code should not care where the data comes from. It should just care that it can retrieve and modify the data in some object and the object will take care of the details.
  • The coding you need to do on the client side should be simplified. Instead of using many functions, your application should be able to use objects with properties and methods.
  • It becomes easier to create and use the classes than the function calls.
  • It becomes easier to add functionality to your applications, and change the functionality, without breaking the client-side code.

Disadvantages to N-Tier

Although there are many advantages to a good n-tier application, there are some disadvantages as well.

  • You end up creating a lot of classes. This can lead to maintenance issues and could even be a performance issue as it does take time to create a new class at run time.
  • N-tier does not work well when you do not know the structure of the tables from which you will be retrieving data. For example, in a Query By Example (QBE) application where the user may put together several columns from several tables, there is no way to generate classes on the fly to accomplish this.
  • Creating reports is not something that lends itself to a good n-tier design, as report writers do not use classes to get at data.

In the end, the advantages of a good n-tier design will far outweigh the disadvantages. In the cases where you simply cannot use n-tier, go ahead and use the typical client/server method of development. There is certainly nothing wrong with mixing both of these paradigms in the same application if appropriate.

Creating an N-Tier Application

When you talk about a true distributed n-tier type of application, you are talking about separating the components of the different tiers on different machines as well as in separate components. Figure 1 shows a typical example of an n-tier application with multiple components on each machine.

 

Figure 1. A distributed n-tier application has three physical tiers with one or more logical tiers on each machine

There are many different ways you could configure an n-tier application. For example, the business rules may go on a separate machine and you might use .NET Remoting to talk from the client application to the business rule tier as shown in Figure 2.

 

Figure 2. Business rules can be placed on a separate machine to facilitate ease of maintenance

You may also have a data input validation rule component on the client to check simple rules such as required fields and formatting. These are rules that you do not want to make a trip across the network just to check. You may then also add a business rule layer on the same tier as the data layer component to check complicated business rules that compare the data from one table to another.

These are just a few different configurations that you may utilize. Of course, you could come up with something unique that fits your specific situation. Regardless of how you structure the physical implementation of the components, make sure that the logical structure of the program is broken up into components as shown in the above figures.

Creating the User Interface

In the example you see in Figure 1, the client tier consists of a Windows application and a business rule component. The Windows application makes all requests for data, and all updates through the business rule component. This isolates the location of the data from the Windows application. The advantage of doing this is if you change where the data comes from, you do not need to make any changes to the client application, only to the business rule component.

 

Figure 3. This is a DataGrid that has been bound to the return result from the business rules component

Perform the following steps to build a simple Windows client application that will display employee information in a DataGrid control on a Windows Form.

  1. Create a new Windows Application project named EmpClient.
  2. Rename the default form (Form1.vb) file name to frmEmpInfo.vb.
  3. Set the form’s Name property to EmpInfo.
  4. Set the form’s Text property to Employee Information.
  5. Set the Startup Object in the Project Properties to EmpInfo.
  6. Drag a DataGrid onto this form. Set the Name property to grdEmps.
  7. Add a Button control to this form. Set the Name property to btnUpdate. Set the Text property to Update.

At this point, the user interface for your employee form is complete. Now it is time to start building the components so you can retrieve the data to populate this DataGrid.

Creating the Data Tier

The data tier is responsible for connecting to your data source, building a typed data set, and returning that data set from a method within this component.

Follow these steps to build a data tier component.

  1. In the Solution Explorer window, right-click the solution named EmpClient.
  2. On the shortcut menu, click Add, and then click New Project.
  3. Choose the Class Library template. Set the name of this class library to EmpData.
  4. Delete the class file named Class1.vb from the project.
  5. To add a new component to the project, on the Project menu, click Add Component. Set the name of the component to clsEmp.vb.
  6. View the code for this component and change the name of the class from clsEmp to Employees.
  7. In the design view, click and drag a SqlDataAdapter control from the Data tab of the toolbox onto the design surface of this component.
  8. Go through the steps of this wizard to connect to your SQL Server, pointing to the Northwind database on that server. Select all rows and columns from the Employee table within this database.
  9. Rename the SqlConnection object from SqlConnection1 to cnNorthwind. Rename the SqlDataAdapter object from SqlDataAdapter1 to daEmps.
  10. Click the daEmps object and, on the Data menu, click Generate DataSet. Set the name of the New DataSet to dsEmps.

At this point, you have a component with some data access objects on it. The reason to use a component instead of a regular class is that you need the ability to drag a Connection and DataAdapter object onto a design surface. A component will let you do this; a regular class will not. Of course, you could always just create your own data adapter and connection objects in code, but this way is much easier.

All that is left to do after adding this component is to add a couple of methods to the component. The first method, named GetData, returns a reference to the typed dataset filled with employee data. The second method, named Update, accepts a typed dataset as a parameter and submits the changes in this dataset to the backend data source.

The GetData Method in the Data Component

This method is responsible for declaring an object of the type dsEmps. Remember that this is the name of the typed dataset that you generated. This file is represented in the Solution Explorer window as dsEmps.xsd. This is the schema definition file for the Employees table from the Northwind database. The code behind this xsd file is the generated typed dataset named dsEmps.

Public Function GetData() As dsEmps

Dim dsData As dsEmps

 

Try

dsData = New dsEmps()

 

daEmps.Fill(dsData)

 

Return dsData

Catch

Throw

End Try

End Function

After creating the instance of the dsEmps object, you will use the SqlDataAdapter object to fill the dsEmps object with data from the Employees table. This typed dataset is then returned from the method to be consumed by some other component. You will learn how to consume this dataset in the next section.

The Update Method in the Data Component

The Update method accepts a typed dataset from a calling program, and performs the Update method on the SqlDataAdapter object to send any changes in the dataset to the Employees table. It also returns this same dataset back to the calling program so any updated fields, like TimeStamps or Identity fields, can be merged back into the dataset in the calling program.

Public Function Update(ByVal dsData As dsEmps) As dsEmps

Try

‘ Update Data In Table

daEmps.Update(dsData)

 

Catch

‘ Throw any exceptions back to client

Throw

 

End Try

 

Return dsData

End Function

Notice the use of the structured exception handling in both of these methods. If any errors are encountered, the exceptions are simply thrown back to the calling component for handling. No errors will be handled in these components.

Creating the Web Service

In Figure 1, you can see that the Data Tier is called from the Web service. You will now create the Web service project that calls the EmpData component that you just created.

  1. In the Solution Explorer window, click the solution named EmpClient.
  2. Right-click and on the shortcut menu, click Add, and then click New Project.
  3. Select the ASP.NET Web service template and set the Name of this project to EmpWS.
  4. Delete the Service1.asmx file from the project.
  5. To add a new Web service file, on the Project menu, click Add Web service. Set the name of this new Web service to Employees.asmx.
  6. Click the EmpWS project and add a reference to the EmpData project.

Now that you have created the Web service named Employees, you can create the two methods that will consume the dataset from the data component. You name these two methods the same name as the methods in the data component for consistency.

The GetData Method in the Web Service

The GetData method in the Web service creates a reference to the EmpData.Employees class. Once you have created this new object, invoke the GetData method on this object and return the dataset from this Web method.

<WebMethod()> Public Function GetData() _

As EmpData.dsEmps

Dim dc As EmpData.Employees

 

Try

dc = New EmpData.Employees()

 

Return dc.GetData

 

Catch

‘ Throw any exceptions back to client

Throw

 

End Try

End Function

Remember from the diagram in Figure 1 that the business rule component retrieves the data from this Web service. The reason you don’t just create the typed data set in the Web service project is that you want the flexibility to use the data component directly from a Windows application if you are not going to be doing a true distributed application. So just by eliminating the Web service project, you can change the code in the business rule layer to talk directly to the data component instead of the Web service, and you do not have to change any other code.

The Update Method

The Update method in this Web service project simply passes the dataset that was passed in as an argument directly to the data component’s Update method.

<WebMethod()> Public Function Update( _

ByVal dsData As EmpData.dsEmps) As EmpData.dsEmps

Dim dc As EmpData.Employees

 

Try

dc = New EmpData.Employees()

 

dc.Update(dsData)

 

Catch

‘ Throw any exceptions back to client

Throw

 

End Try

 

Return dsData

End Function

Creating the Business Rules Component

Now it is time to bring all of the projects together by hooking up the business rule component to the Windows application, and having the business rule component make the call to the Web service to retrieve the data.

Follow the steps below to create the component that acts as the interface between the Windows application and the data tier.

  1. In the Solution Explorer window, right-click the EmpClient solution, and on the shortcut menu, click Add, and then click New Project.
  2. Select the Class Library template and set the Name of this new project to EmpBusRule.
  3. Rename the Class1.vb file to clsEmployee.vb.
  4. Change the name of the Public Class from Class1 to Employees.
  5. To ensure that the solution compiles and to also build the Web service files needed for referencing, on the Build menu, click Build Solution.
  6. Click the EmpBusRule project and add a Web Reference to the EmpWS.vsdisco file.

Note   If you cannot set a reference to the vsdisco file, set a reference to the Employees.asmx file instead.

  1. Expand the Web References folder in this project and rename the LocalHost item (or whatever the name of your Web Server is) to EmpService.

The GetData Method in the Business Rules Component

The GetData method in the business rule component simply accesses the Web service component to request the data from the data tier. Although this seems to be an indirect approach to getting the data, it allows us to create a truly distributed approach to our n-tier application.

Public Function GetData() As EmpService.dsEmps

Dim ws As EmpService.Employees

 

Try

ws = New EmpService.Employees()

 

Return ws.GetData

 

Catch

Throw

 

End Try

End Function

The Update Method in the Business Rules Component

The Update method is responsible for taking the dataset of changes, checking to make sure that the business rules are not violated, and then pushing the data back across the HTTP interface to the Web service component.

Public Function Update( _

ByVal dsData As EmpService.dsEmps) As EmpService.dsEmps

Dim ws As EmpService.Employees

 

Try

ws = New EmpService.Employees()

 

‘ Check business Rules

Me.Check(dsData)

 

‘ Update Data In Table

ws.Update(dsData)

 

Catch

‘ Throw any exceptions back to client

Throw

 

End Try

 

Return dsData

End Function

The Check Method in the Business Rules Component

The Check method is where you put in any appropriate business rules that you need to check prior to inserting or updating any rows in the dataset.

Public Sub Check(ByVal dsData As EmpService.dsEmps)

Dim strMsg As String

Dim row As EmpService.dsEmps.EmployeesRow

 

‘ Check business rules

For Each row In dsData.Employees.Rows

If row.RowState = DataRowState.Added Or _

row.RowState = DataRowState.Modified Then

If row.FirstName.Trim() = “” Then

strMsg &= “First Name must be filled in” & _

ControlChars.CrLf

End If

If row.LastName.Trim() = “” Then

strMsg &= “Last Name must be filled in” & _

ControlChars.CrLf

End If

If row.HireDate < row.BirthDate Then

strMsg &= “Hire Date must be greater

than Birth Date” & _

ControlChars.CrLf

End If

End If

Next

 

If strMsg <> “” Then

‘ Throw a new ApplicationException

‘ with our custom error message in it

Throw New ApplicationException(strMsg)

End If

End Sub

Notice that you should check the RowState property to see whether the row has been added or updated. You do not need to check the row if it has been deleted. During the Check method you can see the benefit of using Typed Datasets. Instead of referencing a column name through an index in a Dataset you have an actual property name. This enforces type safety and gives you an IntelliSense list of column names so you do not have to look them up in your database.

Consuming the Data from the Windows Application

Now that you have all of the components hooked up together, it is time to make the Windows application consume data from the business rules component. Follow the steps below to make this work.

  1. In the Solution Explorer window, click the EmpClient project.
  2. Add a reference to the EmpBusRule project.
  3. Bring up the code for the form and add the Private mdsEmps variable, as shown in the code below.
  1. Public Class EmpInfo
  2.     Inherits System.Windows.Forms.Form
  3.     Private mdsEmps As EmpBusRule.EmpService.dsEmps

This member variable on this form is a typed dataset that represents the Employees table in the Northwind database. You use this variable to fill the DataGrid control on the employee form.

Loading Data into the DataGrid

Next, you need to create the routine to load the DataGrid. First, you add code to the form’s Load event procedure.

  1. Double-click the form to display the Load event procedure.
  2. Add the following code:
  1. Private Sub EmpInfo_Load( _
  2.  ByVal sender As System.Object, _
  3.  ByVal e As System.EventArgs) Handles MyBase.Load
  4.     GridLoad()
  5. End Sub
  6. Public Sub GridLoad()
  7. Dim br As EmpBusRule.Employees
  8. Try
  9. br = New EmpBusRule.Employees()
  10. ‘ mdsEmps is a typed dataset on this form
  11. mdsEmps = br.GetData
  12. grdEmps.DataMember = “Employees”
  13. grdEmps.DataSource = mdsEmps
  14. Catch exp As Exception
  15. MsgBox(exp.Message)
  16. End Try
  1. Create the GridLoad procedure immediately below the Load event procedure.

25.End Sub

The GridLoad procedure declares a new business rule object. It then uses the GetData method in the business rule object to assign the new typed dataset mdsEmps. You assign the table name to the DataMember and the dataset object to the DataSource property of the DataGrid control.

You should now be able to run this application, and if you have done everything correctly, the DataGrid should be loaded with employee data.

  1. Set the EmpClient project as the Startup Project if it is not already.
  2. Press F5 to run the application.

You should now see employee data in the list box that looks like Figure 2.

Updating Data from the DataGrid

You will now create the procedure under the Update button on the form to take any changes you make to the data in the grid and push them back to the data tier. Of course, you will first push the changes to the DataSet through the business rules component, which then sends the data through the Web service component, and then finally to the data tier component. The data tier component then connects up to the SQL Server and pushes the changes to the server.

Private Sub btnUpdate_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnUpdate.Click

Dim br As New EmpBusRule.Employees()

Dim dsChanges As New EmpBusRule.EmpService.dsEmps()

Dim strMsg As String

 

Try

If mdsEmps.HasChanges Then

dsChanges.Merge(mdsEmps.GetChanges())

 

MsgBox(“Count = ” & _

CStr(dsChanges.Employees.Rows.Count))

 

‘ Update the Data on the Server

dsChanges = br.Update(dsChanges)

 

MsgBox(“Data Has Been Updated Successfully”)

 

‘ You can either merge the changes back

‘ in and accept the changes, or you can

‘ reload the data from the table. I prefer

‘ reloading as it gets all the other

‘ changes by all other users.

‘mdsEmps.Merge(dsChanges)

‘mdsEmps.AcceptChanges()

 

‘ If everything is OK, refresh all data

‘ from the web service.

GridLoad()

Else

MsgBox(“No changes have been made

to the data”)

End If

 

Catch exp As ApplicationException

MsgBox(exp.Message)

 

Catch exp As Exception

MsgBox(exp.Message)

 

End Try

End Sub

The first part of this event procedure checks to see whether any changes have even been made to the DataSet. If they have, you get the changed data rows by using the GetChanges method of the DataSet class. This will return just those rows that were changed in the DataGrid.

Once you have this short list of rows from the dataset you can submit that to the Update method of the business rule component. The business rule component then sends it to the Web service component, which sends it on to the data tier component, and finally updates SQL Server. If any changes are made to the rows in the dataset (such as a TimeStamp field updating, or an identity field updating), these rows are passed back to this procedure. You can then either merge the data back into the main dataset, or you could simply reload the entire dataset directly from the database (going through the components of course).

When attempting to submit the changes to the back end, there could be a business rule that is violated. For example, if someone deletes the first name of an employee, the business rule that checks for the existence of the first name in a row of data will fail. This will be thrown as an ApplicationException object. You should check for this type of exception first, then display the error message returned, as that will be the description of the business rule or rules that are in violation.

The last thing you have to check for is any generic exceptions. For example, the database server might be down, and thus a regular exception might be thrown. Or maybe a concurrency exception is thrown because you updated a row and another user updated a row just before you did.

What’s Different from Visual Basic 6.0?

Although the concepts for designing an n-tier application are pretty much the same as they have always been, the implementation is quite different. You should find that the amount of code you have to write is significantly reduced due to the advancements in Web services and ADO.NET.

Building an N-Tier Application in VB.NET, in 8 Steps

Introduction

Many People googled for an Article or a Tutorial that shows how to create N-Tier Applications step by Step in VB.NET and for Windows Application.But never found one. In this Article i will show you Step by Step on how to do it.i made an example from one of the Small Projects in did in N-Tier. i have included ways to reaquest Data pass Data between Tiers. This is a Good Practise and its Simple to mantain your code if its in tiers. Imagine having your Business Layer, Data Layer in the Presentation Layer(your VB form,ASP page). Your Code will be a Spageti code that is time consuming when it has to be maintined. Before we start coding, lets Explain what is N-Tier and why is it used.

Background

N-Tier is a Client-Server Architecture in which User interface (Presentation Layer), Business Rules(Business Logic Layer), Data Access(Data Layer) are separated in Layers, maintained and Developed Indipendently. The Applicatin will be broken into Tiers. Presentation Layer will be your Form or ASP.NEt page, Busines Layer will be the Classes that will Check if the Business Rules have not been Violeted, and the Data Access layer will Accept the Validated Data from the Business Logic layer and run the SQl commands on the Actual Database.

When reading this Article, i assume that you know how –

Getting Started

Make sure that your table is in Place and and it has a Primary key. because if you are using an Adapter, you cannot not update a table that has no Primary key, you will only select.

Step1(Adding PL and BLL)

In the First Step we are going create a Solution. you can call it anything meaningfull, in my case i called it “Pro_Client”. This will be will be your Presentation Layer, that is where the user will interact with the Actual data that we are going to Consume later in the Article.

Step 2(Adding PL and BLL)

In the Solution Explorer, select your Solution “Prop_Client” and right Click, in the menu select “Add” and “New Project.” An Addnew Project Dialogbox will appear and you must select “Class Library” because we are going to use this Project as our BLL(Business Logic Layer) and name it “Prop_BLL” or something meaningfull that will show you that its a BLL. rename the “Class1” into “clsPropertyBLL”, or something else meaningfull. and Double click on the renamed class or view the code. you will Notice that the “Class1” is still there. Change it to something meaning fulll, if you are working with Employees use “Employees” in my case “Properties”. Then you are done with you BLL, we will visit it Later again.

Step 3(Adding DAL to a Solution)

In this Step, we are going to Add our DAL in the same Solution. Select your Solution “Prop_Client” and right Click, in the menu select “Add” and “New Project.” An Addnew Project Dialogbox will appear and you must select “Class Library” and name it “PropDAL”, or something meaningfull to show you that this is your DAL. After you have done that, Delete “Class1” from your Dal project we will not use it. The next thing is to Add a Component, for a Beginner you will not use a Class directly, i want you to drag and drop some adapters from the Toolbox. Now to add a Component into our DAL , you must right Click on the DAL project in my case “PropDAL” and select “Add” and “Add Component” and give it a meaningfull name, in my case i have named it “Property_DAL”. Double click the Component and you will see that the name of the Component is the same as the Class name. use the name for the class you used in your BLL, in my case “Properties”. That means the code in your component will look like this.

Collapse | Copy Code

Public Class Properties

Inherits System.ComponentModel.Component

End Class

Now Our Solution will look like the one in Figure1 the Structure.

 

Figure1

Step 4(Adding DAL Componets)

In this Step we are going to Add an Adapter. On your DAl Project, Double click on the Component “Property_DAL” in my case and select your toolbox section of “DATA”. In the Toolbox select an SQLdataAdapter. and the Adapter dialog box will appear, click on “Next”, Select the Connection. note that if its the First time you do this, you will have to Create a Connection like this Example. Click next when the Connection is established, in the “Query type” , for now lets select “Use SQl Statement” , and Click next. and you will get a Space where you can type in your SQl statement or Use a Query Builder to let Visual Studio Build a Query for you. Lets type our SQl state like this.

Collapse | Copy Code

select * from Clients  where Client_name = @Clientname

This is a parameterized query. sometimes we dont know what Display until runtime and we might decide to display something else at runtime. Then in this case we use a parameterized query. The above sql query will be your commandtext in the adapter. when you are finished, you will click next,then the Report about your adapter will appear. If you see a yellow Exclamation mark on the Update,you should know that,it might be that you did not set a Primary Key in your table. If no Errors in your Adapter, click on Finish and your adapter will be created for you and note that the Connection object will appear on your Component. Right click and rename the connection object to “cnProperties” and you adapter to “daProperties”. If you are using SQl, on the Properties of you connection, click on Connection string and enter the password after the user ID and your Connectionstring will look like this.

Collapse | Copy Code

user id=sa; Password=topman;data source=Myserver;persist security info=False;initial catalog=ValRollClients

Next step is to Right click on the Adapter “daProperties” and Generate a dataset. Name your dataset as “dsProperties”. and check the Option “Add this Dataset to the Designer” to visualy see it on top of the Component after that click ok.

Now everything had been setup. Our Data source if fine then lets go back to Presentation Layer.

Step 5(Presentation Layer)

Now in this Step we have to do small Adjustments. first add a datagrid into your Form and name it dgproperties and add four buttons like this.

 

Figure 2

and forget to rename your form to “frmsearch”

Step 6(Function in DAL)

Lets go back again to our DAL Project. we are going to give our data to BLL from DAL and BLL will give the data to the Frontend(PL)

 

Figure3

now lets create a Function that will return a Dataset and takes a parameter. now Double Click on your Component and enter the Following code to inside a Class.

Collapse | Copy Code

Public Function Getdat(ByVal strname As String) As dsProperties

Dim dsdata As dsProperties

Try

dsdata = New dsProperties

‘We are Accepting an input parameter

daproperties.SelectCommand.Parameters(“Clients”).Value = strname

‘filling the dataset

daproperties.Fill(dsdata)

Catch Throw

‘In this Layer we dont Display Error or Exceptions. BLl will take care of that

‘we are throwing the Exception to be handled by the Calling Function End Try

‘Here we are returning a dataset filled with requested data

Return dsdata

End Function

Remember we have to save changes too, so we are going to create another Sub procedure that will Save the changes into the Database. So for saving,create this sub procedure in your Component Class. After the First one like this.

Collapse | Copy Code

Public Sub SaveData(ByVal dsdata As dsProperties)

Try

daproperties.Update(dsdata)

Catch

Throw

‘In this Layer we dont Display Error or Exceptions. BLl will take care of that

‘we are throwing the Exception to be handled by the Calling Function

End Try

End Sub

 

Now everything Has been Added to our DAL, so we are going to call this Function and Sub Procedure in the BLL (Business Ligic Layer)

Step 7(Calling DAL Functions in BLL)

Now we are going to call DAL Function when Data is Requested from Business Logic layer from the Presentation Layer . Go to the BLL Project and Double click on the “clsPropertyBLL” to view the code. First thing we need to create is a Function that will request the Data from the DAL and a Save Function that will send data to the BLL and some Business Rules Check Before we save to the actual database. Before we start coding. Add the a reference to the DAL on the BLL. Right click on the BLL and select Add Reference, in the Dialogbox select the Project tab and click on your DaL Project and click ok.

In the Class Properties of the BLL , Add the Following code.

Collapse | Copy Code

Public Function GetData(ByVal strname As String) As Prop_DAL.dsProperties

Dim dsdata As Prop_DAL.dsProperties

‘Creating an Object of a Class Properties in the Dal layer

Dim objgetdal As Prop_DAL.Properties

Try

dsdata = New Prop_DAL.dsProperties

objgetdal = New Prop_DAL.Properties

‘Calling the Function of DAL and Passing Arguments to the Function

dsdata = objgetdal.Getdata(strname)

If dsdata.Tables(“Clients”).Rows.Count = 0 Then

MsgBox(“No record with that Name was Found”)

Else

‘return a dataset with Data

Return dsdata

End If

Catch ex As SqlClient.SqlException

MsgBox(ex.Message)

End Try

End Function

 

The next Sub Should save and a Sub to Check if the Business Rules have been Violated.

Collapse | Copy Code

Public Function SaveData(ByVal dsdata As Prop_DAL.dsProperties) As Prop_DAL.dsProperties

Dim objDal As Prop_DAL.Properties

Try

objDal = New Prop_DAL.Properties

Me.CheckRules(dsdata)

 

‘saving the Data

 

objDal.SaveData(dsdata)

 

Catch ex As Exception

End Try

End Function

in the Above Function we will check the Rules using a Sub that will come Below. if the Rules are not Violated, then we can save the data, by calling a Dal Function through a Dal object “objDAL”. The Following code is the for Checking the Business Rules.

Collapse | Copy Code

Private Sub CheckRules(ByVal dsdata As Prop_DAL.dsProperties)

Dim strMsg As String

Dim row As Prop_DAL.dsProperties.ClientsRow

‘Iterating through the Dataset and Checking the Rules

For Each row In dsdata.Clients.Rows

If row.RowState = DataRowState.Added Or _

row.RowState = DataRowState.Modified Then

‘Start Checking the Rules now

If row.Client_Name.Trim = “” Then

MsgBox(“Name Cannot be Empty”)

End If

If row.Client_Address = “” Then

MsgBox(“Address Cannot be Empty”)

End If

If row.Client_ID.ToString.Length > 13 Then

MsgBox(“ID number must less than 13”)

End If

End If

Next

If strMsg <> “” Then

‘throw a new ApplicationException

‘with our Custom Error message in it

Throw New ApplicationException(strMsg)

End If

End Sub

Now Everything is done, your BLL can now Communicate with your DAL and your PL will Communicate with your DAL through your BLL. the Next is to call your BLL Functions from your PL . Add a reference to your BLL Project in the PL Project as i did when i added a reference to DAl in the BLL Project.

Step 8(Call BLL functions from a PL)

This is the Last Step of our Article. In this Step we are going to Call the BLL Functions. Firstly bouble click on your Form and declare a module level dataset like this

Collapse | Copy Code

Public Class Form1

 

Inherits System.Windows.Forms.Form

 

Dim mdsProperty As Prop_DAL.dsProperty

 

 

 

 

Note that this should not be inside your Form load, but outside, because its a Module level declaration that we want. On your Search button insert the Following code.

Collapse | Copy Code

Dim objBll As Prop_BLL.Properties Dim strsearch As String = CStr(txtsearch.Text)

btnClear.Enabled = True

Try

mdsProperty = New Prop_DAL.dsProperty

objBll = New Prop_BLL.Properties

mdsProperty = objBll.GetData(strsearch)

‘Binding the Datagrid

dgProperties.DataMember = “Clients”

dgProperties.DataSource = mdsProperty

 

Catch ex As SqlClient.SqlException

MessageBox.Show(ex.Message)

End Try

And in the Button Clear , you will Enter the Following code to Clear the Grid.

Collapse | Copy Code

mdsProperty.Clear()

btnClear.Enabled = False

And the last Button, will be the Exit Button, you can Enter your own code to Exit the Application or Form. So your N-Tier Application should be done now with 8 Steps.

Conclusion

Designing your Application in an N-Tier Application helps you to trace Bugs and helps you to improve your application at ease, than trying to trace a small bug in one mixed Application having all Subjects in one Place. i would like to learn more from anyone who has Suggestion and more knowledge on N-tier Applications. My Next Article will be on Web services. I want make the Subject Broad by Biulding an Example of a Windows N-tier Application that uses Web services. To those who know me,you know that this is not my First Article. Thanks for every e-mail i got People Asking Questions about Article and how to implement it in their Situations. IF Thank me for this Article Vote for it and mail me at vuyiswam@tshwane.gov.za

 

Code Example ADO.NET Entity Framework “Insert Update Delete” data in MVC application


 

Code Example ADO.NET Entity Framework “Insert Update Delete” data in MVC application

 

How we can use ASP.NET MVC Framework check this post

http://www.dotnetissues.com/2011/04/code-example-for-aspnet-mvc20.html

 

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)

Now In this post I ‘ll Insert and Update Data in Student_Marks table(Student_id,Marks)in One More view

Using ADO.NET Entity framework.

 

1.) Creating the ADO.NET Entity Data Model 

     Check the below post to create ADO.NET Entity Data Model.

 

ASP.Net MVC Sample Application using ADO.Net Entity Framework

How we can use ASP.NET MVC Framework check this post
http://www.dotnetissues.com/2011/04/code-example-for-aspnet-mvc20.html

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)
Now In this post I ‘ll add one more view Where To Select the records from the above table I ‘ll
use ADO.NET Entity framework.

1.)Creating the ADO.NET Entity Data Model
In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.
Follow these steps:

1)Right-click the Models folder in the Solution Explorer window and select the menu option Add, New Item.
2)In the Add New Item dialog, select the Data category
3)Select the ADO.NET Entity Data Model template, give the Entity Data Model the name Model1.edmx,

4)Click the Add button. Clicking the Add button launches the Data Model Wizard.
5)In the Choose Model Contents step, choose the Generate from a database option and click theNext button

6)In the Choose Your Data Connection step, select the MoviesDB.mdf database connection, enter the entities connection settings name TestMVEntities3, and click the Next button

8)In the Choose Your Database Objects step, select the TestMVC database table and click the Finishbutton

After you complete these steps, the ADO.NET Entity Data Model Designer (Entity Designer) opens.

Model1.designer.cs will be automatically generated and It will Map the Database and the tables as the
entity classes and To Communicate with the DB now we can Communicate with The entity classes objects
We can use EntitySQl query syntax or LINQ to Sql Below is the code sample for both.

To Select Records from student table using entity sql I added below highlighted code in StudentController.cs

Controllers/StudentController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestMVCapplication.Models;
using System.Data;
using System.Data.SqlClient;
using System.Data .Objects ;

namespace TestMVCapplication.Controllers
{
public class StudentController : Controller
{
SqlConnection connObj = new SqlConnection();
DataSet ds;
SqlCommand objCommand;
SqlDataAdapter objAdapter;

// GET: /Student/
public ActionResult GetStudent()
{
return View();
}



        public ActionResult Viewstudent()
        {


            TestMVCEntities3 DBobj = new TestMVCEntities3();
               
             
                    //ENTITY SQL QUERY SYNTAX
                    ObjectQuery query = DBobj.CreateQuery<Student>(“Select value s from student as s”);
                    var res = query.Execute(MergeOption.NoTracking) as IEnumerable<Student>;
                    int i=0;
                    foreach (Student  c in res)
                    {
                      // Response .Write (c.Name);
                       ViewData[“name”+i.ToString()] = c.Name;
                       ViewData[“email” + i.ToString()] = c.Email;
                       ViewData[“comment” + i.ToString()] = c.Comment;
                       i++;
                    }




                     //LINQ TO ENTITY QUERY
                     //var query1 = from Student  c in DBobj.Student
                     //               select c;


                     //foreach (Student  c in query1)
                     //       {
                     //          Response .Write (c.Name);
                     //       }


            return View();
        }

[HttpPost]

public ActionResult GetStudent(StudentModel model)
{
Response.Write(model.Name + model.Comment + model.Email);
//code to insert data in DB using ADO.NET
connObj.ConnectionString = “Data Source=.\\sqlexpress;Initial Catalog=TestMVC;Integrated Security=True”;
connObj.Open();
SqlCommand comm = new SqlCommand(“insert into student(name,email,comment) values(@name,@email,@comment)”, connObj);

comm.Parameters.Add(“@name”, SqlDbType.VarChar , 50).Value =model .Name ;
comm.Parameters.Add(“@email”, SqlDbType.VarChar, 50).Value = model.Comment;
comm.Parameters.Add(“@comment”, SqlDbType.VarChar, 50).Value = model.Email;

int result = comm.ExecuteNonQuery();
if (result != 0)
Response.Write(” added”);
else
Response.Write(“Error”);

return View();
}

}

}

From the above Viewstudent I selected records from the Student Table and
Inserted those iv ViewData to able to access them in the Viewstudent View
I added one View named Viewstudent.aspx in in views/Student

views/student/Viewstudent.aspx
<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>
Viewstudent
</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>Viewstudent</h2>
<% for (int i = 0; i <= ViewData.Count;i++ )
{ %>

Name: <%= ViewData [“name”+i.ToString ()]%>
<br />
Email:<%= ViewData [“email”+i.ToString ()]%>
<br />
Comment:<%= ViewData [“comment”+i.ToString ()]%>
<br />

<hr />
<% } %>

</asp:Content>

 

 

To Link this View in Previous MVC Example’s view I added the below highlighted line of code there

 

Views/Student/GetStudent.aspx

 
<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentModel>” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>
GetStudent
</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

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

<h2>GetStudent</h2>

<% Html.EnableClientValidation(); %>
<% using (Html .BeginForm() ){%>
<%= Html.ValidationSummary(true, “A few fields are still empty”) %>
 <%= Html.ActionLink(“ViewstudentData”, “Viewstudent”, “Student”)%>
&nbsp;<fieldset>
<legend>Student Detail</legend>
<div>
<%= Html.LabelFor(m => m.Name) %>
</div>
<div>
<%= Html.TextBoxFor(m => m.Name) %>
<%= Html.ValidationMessageFor(m => m.Name) %>
</div>
<div>
<%= Html.LabelFor(m => m.Email) %>
</div>
<div>
<%= Html.TextBoxFor(m => m.Email) %>
<%=Html.ValidationMessageFor(m => m.Email) %>
</div>
<div>
<%= Html.LabelFor(m => m.Comment) %>
</div>
<div>
<%= Html.TextAreaFor(m => m.Comment, 10, 25, null) %>
<%= Html.ValidationMessageFor(m => m.Comment) %>

</div>
<p>
<input type=”submit” value=”Submit” />
</p>
</fieldset>
<p id=”result”><%=TempData[“Message”] %></p>
<% } %>
</form>
</asp:Content>

Now Run the application again and Click On Student Menu Link

Click On ViewStudentData Link
and you ll get the selected records in the view

 

 

2.) We will Add Our Form AddStudentMarks within the same App

3.)Right click on Models Add new class StudentmarksModel.cs
4.)Code On StudentMarksModel.cs Create property corresponding to each Form Field + Write the Validation

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace TestMVCapplication.Models
{
public class StudentMarksModel
{

[DisplayName(“Marks”)]
[Required(ErrorMessage = “* Required”)]
public string  Marks { get; set; }

public string Student_Id { get; set; }

public IEnumerable<SelectListItem> StudentList { get; set; }

}
}

 

 

5.)We’ll then add a “StudentMarksController.cs” controller class to our project’s Controllers folder that exposes two “AddStudentMarks” action methods.

The first action method is called when an HTTP-GET request comes for the /StudentMarks/Create URL.  It will display a blank form for entering Student data.

The second action method is called when an HTTP-POST request comes for the /Studentmarks/Create URL.  It maps the posted form input to a StudentMarks object, verifies that no binding errors occurred, and if it is valid will eventually save it to a database(Business Logic)

 

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Data.Objects;

using TestMVCapplication.Models;

 

 

 

namespace TestMVCapplication.Controllers

{

public class StudentMarksController : Controller

{

//

// GET: /StudentMarks/

[HttpGet]

public ActionResult AddStudentMarks()

{

TestMVCEntities3 DBobj = new TestMVCEntities3();

 

//ViewData[“StudentList”] = new SelectList(DBobj.Student, “Student_Id”, “Name”);

 

//return View();

 

//To set the Student Names in DropdownList

var model = new StudentMarksModel();

model.StudentList = new SelectList(DBobj.Student, “Student_Id”, “Name”);

return View(model);

}

 

 

 

[HttpPost]

 

public ActionResult AddStudentMarks(StudentMarksModel model)

{

//Add Data Using Entity Framework in ADO.NET

 

TestMVCEntities3 DBobj = new TestMVCEntities3();

 

int StudentId = Convert.ToInt32(model.Student_Id);

 

 

//Check If the reord exists with the Dropdownlist selcted value as Student_Id

var record = DBobj.Student_Marks.FirstOrDefault(m => m.Student_Id == StudentId);

//If record exists update it with the value entered in marks textbox

if (record != null)

{

Student_Marks e = (from e1 in DBobj.Student_Marks

 

where e1.Student_Id == StudentId

 

select e1).First();

e.Marks = int.Parse(model.Marks);

DBobj.SaveChanges();

 

}

 

//If record doesn’t exists Insert the new record

else

{

Student_Marks sMarks = new Student_Marks();

 

sMarks.Student_Id = int.Parse(model.Student_Id);

sMarks.Marks = int.Parse(model.Marks);

 

 

 

DBobj.AddToStudent_Marks(sMarks);

DBobj.SaveChanges();

}

 

 

//To set the Student Names in DropdownList

var modelsend = new StudentMarksModel();

modelsend.StudentList = new SelectList(DBobj.Student, “Student_Id”, “Name”);

 

 

return View(modelsend);

}

 

}

}

 

7.)After we’ve implemented our controller, we can right-click within one of its action methods and choose the “Add View” command within Visual Studio – which will bring up the “Add View” dialog

Add  AddStudentMarks.aspx view file for us under the \Views\StudentMarks\

8.)Design the form on AddStudentMarks.aspx using HTMlHelper Class

 

 
<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentMarksModel>” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>
AddStudentMarks
</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>AddStudentMarks</h2>

<form id=”form1″ runat=”server”>
<% Html.EnableClientValidation(); %>
<% using (Html .BeginForm() ){%>
<%= Html.ValidationSummary(true, “A few fields are still empty”) %>
<fieldset>
<div>
<%= Html.DropDownListFor(x => x.Student_Id,Model.StudentList)%>
<%= Html.ValidationMessageFor(m => m.Student_Id) %>
</div>

<div>
<%= Html.TextBoxFor(m => m.Marks) %>
<%= Html.ValidationMessageFor(m => m.Marks) %>
</div>
<p>
<input type=”submit” value=”Submit” />
</p>
</fieldset>
<p id=”result”><%=TempData[“Message”] %></p>
<% } %>
</form>
</asp:Content>

 

 

9)Add The link for Student in Site.Master

10) Run the app

11.)Click StudentMarks

 

StudentList will be filled up from Student table in DropDownlist

 

12)select the name and insert Marks if The student_id already Exists in Student_Marks It will

update the record if it does not exist it will add new record with the selected Student_Id from drop Down and input marks

 

13.) See the Updated Record in DB

 

Difference between 3.5 and 4.0?


Difference between 3.5 and 4.0?

Microsoft .NET Framework 3.5 vs .NET Framework 4.0

.NET framework 3.5 and 4.0 are two versions of the Microsoft .NET framework. Microsoft always comes up with various applications and frameworks so that the application development is more advanced and enhanced. Microsoft .NET Framework is a framework which is designed for Windows operating system. It has a large library and supports various programming languages. It also supports interoperability and NET library is available to all programming languages which are supported by .NET. In year 2007, .NET 3.5 was released which had included more features that .NET 2.0 and .NET 3.0 could not stay in the industry for long time as it has various issues. However, .NET 4.0 was released in April 2010.

.NET 3.5 Framework

Microsoft .NET 3.5 Framework has various technologies which are able to help application developers solve the issues while developing applications. Some technologies were available in .NET 3.0 while some other technologies have been added in .NET 3.5. Some of the new technologies are mentioned as below:

ASP.NET AJAX– The technology supports creation of web applications with much more advanced features. It is much easier for developers to develop AJAX applications.

Language- Integrated Query- With the introduction of LINQ; the developers can create and maintain .NET Framework applications that can work well with the data.

Windows Communication Foundation– In .NET 3.5 Framework, various challenges are addressed via Windows Communication Foundation (WCF) which is service-oriented approach.

.NET 4.0 Framework

.NET 4.0 Framework will work side by side along with older versions of .NET. The applications which run with older versions will continue to run with this version. In this version, there are new features that have been implemented are as follows:

• The CLR (Common Language Runtime) and Base Class Library (BCL) have been improved.

• New Numeric types and memory mapped files have also been introduced.

• Data Access and Modeling Improvements

• Enhancements in ASP.NET

• Improved Windows Presentation Foundation(WPF)

• Various dynamic features such as entity templates, new query filters and validation features.

• Task Parallel Support and Parallel Loop Support

Difference between .NET 3.5 and .NET 4.0

› The web installers for .NET 4.0 are below 1MB in size and faster internet connection is required to download the bits.

› In .NET 3.5, there is no direct method for accessing data whereas there is an in-built feature for data access in .NET 4.0.

› Enableviewstage property has two values in .NET 3.5 as “True” and “False” whereas in .NET 4.0, this property has three values as Inherit, Disable and Enable.

› .NET 4.0 is the most improved version of .NET 3.5 and now it is widely used in IT industry by large organizations.

Despite of having differences, these frameworks have helped developers to use technologies for creating web-based applications. In case, you want to have more information about the features of these frameworks, you can get online and download tutorials as they are available for free. It is highly recommended to check the system requirements before installing it on your machine. Microsoft .NET Framework has created revolution in IT industry.
Read more: http://www.differencebetween.com/difference-between-microsoft-net-framework-3-5-and-net-framework-4-0/#ixzz1ckdVoXjT

 

.Net Framework 4.0 comes up with some of major changes as compare to previous versions of .Net Framework 3.5 and 2.0

Following are list of Major Changes in .Net 4.0

  • ControlRenderingCompatabilityVersion Setting in the Web.config File
  • ClientIDMode Changes
  • HtmlEncode and UrlEncode Now Encode Single Quotation Marks
  • ASP.NET Page (.aspx) Parser is Stricter
  • Browser Definition Files Updated
  • System.Web.Mobile.dll Removed from Root Web Configuration File
  • ASP.NET Request Validation
  • Default Hashing Algorithm Is Now HMACSHA256
  • Configuration Errors Related to New ASP.NET 4 Root Configuration
  • ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications
  • ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed
  • The HttpRequest.FilePath Property No Longer Includes PathInfo Values
  • ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd
  • Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation
  • MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved
  • Output Caching Changes to Vary * HTTP Header
  • System.Web.Security Types for Passport are Obsolete
  • The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4
  • Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When Paths Contain Backslashes

 

Data validation – Silverlight versus WPF


Data validation – Silverlight versus WPF part 2

In a previous blog post I pointed out that quite a difference between data validation between Silverlight and WFP. As I don’t think adding data validation in the UI is a good thing I focused on validation in the business object by throwing an exception when the value was not acceptable. As Beth pointed out WPF also supports the IDataErrorInfo interface as she demonstrates here.

I think using the IDataErrorInfo interface is superior to throwing exceptions. After all exceptions should be exceptional and users entering invalid data in real applications is not very exceptional  . However Silverlight only contains a subset of the .NET framework and doesn’t include the IDataErrorInfo interface.

So using the IDataErrorInfo in Silverlight will option will not work right?

Wrong, it is a very simple interface and we can just add it ourselves. We can even add it using the same namespace System.ComponentModel to when the interface gets added to Silverlight we can just remove our copy .

So this is my Silverlight implementation of the IDataErrorInfo interface:

namespace System.ComponentModel

{

// Summary:

//     Provides the functionality to offer custom error information that a user

//     interface can bind to.

public interface IDataErrorInfo

{

// Summary:

//     Gets an error message indicating what is wrong with this object.

//

// Returns:

//     An error message indicating what is wrong with this object. The default is

//     an empty string (“”).

string Error { get; }

 

// Summary:

//     Gets the error message for the property with the given name.

//

// Parameters:

//   columnName:

//     The name of the property whose error message to get.

//

// Returns:

//     The error message for the property. The default is an empty string (“”).

string this[string columnName] { get; }

}

}

I just copied this code by right clicking the IDataErrorInfo in my WPF application and selecting all the code shown.

So how do WPF and Silverlight compare when using the IDataErrorInfo interface?

 

The sample business object is the same person as in the pervious blog post. Only this time I did implement both the IDataErrorInfo and the INotifyPropertyChanged interface. The INotifyPropertyChanged is not really needed in WPF here, it will work just as well without it, but is a good practice to do every time.

public class Person : IDataErrorInfo, INotifyPropertyChanged

{

private string _firstName;

public string FirstName

{

get { return _firstName; }

set

{

_firstName = value;

if (string.IsNullOrEmpty(_firstName))

_errors[“FirstName”] = “The first name cannot be empty.”;

else

_errors[“FirstName”] = null;

OnPropertyChanged(“FirstName”);

}

}

 

private string _lastName;

public string LastName

{

get { return _lastName; }

set

{

_lastName = value;

if (string.IsNullOrEmpty(_lastName))

_errors[“LastName”] = “The last name cannot be empty.”;

else

_errors[“LastName”] = null;

OnPropertyChanged(“LastName”);

}

}

 

private Dictionary<string, string> _errors = new Dictionary<string, string>();

public string Error

{

get

{

StringBuilder sb = new StringBuilder();

foreach (var item in _errors)

if (item.Value != null)

sb.AppendLine(item.Value);

 

return sb.ToString();

}

}

 

public string this[string columnName]

{

get

{

string result = null;

_errors.TryGetValue(columnName, out result);

 

return result;

}

}

 

protected void OnPropertyChanged(string propertyName)

{

if (PropertyChanged != null)

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

}

 

public event PropertyChangedEventHandler PropertyChanged;

The WPF application

The XAML in the WPF application is simple, even simpler as previous blog post and looks like this:

<Grid>

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”150″/>

<ColumnDefinition />

<ColumnDefinition />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”Auto”/>

</Grid.RowDefinitions>

<TextBlock Text=”Firstname:” Grid.Row=”0″ Grid.Column=”0″/>

<TextBox Text=”{Binding FirstName, ValidatesOnDataErrors=True}”

Grid.Row=”0″ Grid.Column=”1″/>

<TextBlock Text=”Lastname:”

Grid.Row=”1″ Grid.Column=”0″/>

<TextBox Text=”{Binding LastName, ValidatesOnDataErrors=True}”

Grid.Row=”1″ Grid.Column=”1″/>

<Button Content=”Close” Grid.Row=”2″ Grid.Column=”0″/>

</Grid>

Nice, no longer do we need to add the ValidationRules collection and add the ExceptionValidationRule to it, instead all we have to do it set the ValidatesOnDataErrors to true. Much nicer .

 

 

How about the Silverlight application?

The Silverlight XAML isn’t much more complicated and looks like this:

<Grid x:Name=”LayoutRoot” Background=”White”>

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”150″/>

<ColumnDefinition />

<ColumnDefinition  Width=”20″/>

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”Auto”/>

</Grid.RowDefinitions>

<TextBlock Text=”Firstname:” Grid.Row=”0″ Grid.Column=”0″/>

<TextBox Text=”{Binding FirstName, Mode=TwoWay}”

Grid.Row=”0″ Grid.Column=”1″/>

<local:ErrorStatus PropertyName=”FirstName”  Grid.Row=”0″ Grid.Column=”2″/>

<TextBlock Text=”Lastname:” Grid.Row=”1″ Grid.Column=”0″/>

<TextBox Text=”{Binding LastName, Mode=TwoWay}”

Grid.Row=”1″ Grid.Column=”1″/>

<local:ErrorStatus PropertyName=”LastName” Grid.Row=”1″ Grid.Column=”2″/>

<Button Content=”Close” Grid.Row=”2″ Grid.Column=”0″ Click=”Button_Click” />

</Grid>

The main difference is the addition of two local:ErrorStatus elements. Most of the extra complexity is in this control which is needed because Silverlight has no default way to display validation errors. Please note that there is no longer a BindingValidationError handler involved, everything the app needs is done in XAML, much better than the approach when throwing exceptions. Also note that all I need to do is set the PropertyName attribute to indicate which property validation to display. When run this page looks like this:

 

 

The ErrorStatus control

All “magic” happens inside of the ErrorStatus control. This is a real simple user control. Now if I wanted to create a reusable control I would need to put some more work into it and use the VisualStateManager with the States&Parts model but this simple control is enough to demonstrate the solution.

The ErrorStatus.xaml looks like this:

<UserControl x:Class=”SilverlightApplication5.ErrorStatus”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

Width=”16″ Height=”16″>

<Grid x:Name=”LayoutRoot” >

<Ellipse Fill=”Red”/>

<TextBlock Foreground=”White”

HorizontalAlignment=”Center”

VerticalAlignment=”Stretch”

FontWeight=”Bold” >!</TextBlock>

</Grid>

</UserControl>

Real simple, just a red circle with a white exclamation mark in it.

The code is not very complex either. Most of it is related to either checking if the DataContext changed, see this post for an explanation, and when a property value has changed.

public partial class ErrorStatus : UserControl

{

public ErrorStatus()

{

InitializeComponent();

SetBinding(MyDataContextProperty, new Binding());

}

 

public static readonly DependencyProperty MyDataContextProperty =

DependencyProperty.Register(“MyDataContext”,

typeof(object),

typeof(ErrorStatus),

new PropertyMetadata(DataContextChanged));

 

public static readonly DependencyProperty PropertyNameProperty =

DependencyProperty.Register(“PropertyName”,

typeof(string),

typeof(ErrorStatus),

null);

 

private static void DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)

{

INotifyPropertyChanged person;

ErrorStatus errorStatus = (ErrorStatus)sender;

 

person = e.OldValue as INotifyPropertyChanged;

if (person != null)

person.PropertyChanged -= errorStatus.person_PropertyChanged;

 

person = e.NewValue as INotifyPropertyChanged;

if (person != null)

person.PropertyChanged += errorStatus.person_PropertyChanged;

 

errorStatus.UpdateStatus(e.NewValue);

}

 

public string PropertyName

{

get { return (string)GetValue(PropertyNameProperty); }

set { SetValue(PropertyNameProperty, value); }

}

 

private void person_PropertyChanged(object sender, PropertyChangedEventArgs e)

{

if (e.PropertyName == PropertyName)

UpdateStatus(sender);

}

 

private void UpdateStatus(object sender)

{

IDataErrorInfo person = sender as IDataErrorInfo;

if (person != null)

{

string errorText = person[PropertyName];

if (string.IsNullOrEmpty(errorText))

Opacity = 0;

else

Opacity = 100;

 

ToolTipService.SetToolTip(this, errorText);

}

}

}

The real work happens in the UpdateStatus() function right at the bottom. This function is called every time the target property changes or the DataContext is set. Basically it checks if there are any errors and makes the control visible or invisible depending on the result. Besides the control’s visibility it also sets the tooltip text to the error. The only other thing worth mentioning is that I make the control invisible by using the Opacity instead of the Visibility property. The reason is that I do not want to change the layout of the controls on the page just because the validation status changed. WPF has a Visibility option of Visibility.Hidden but unfortunately Silverlight doesn’t support this. Not a big problem as making a control transparent is just a good in this case.

 

WPF MVVM Pattern: A Simple Tutorial for Absolute Beginners


WPF MVVM Pattern: A Simple Tutorial for Absolute Beginners

 

As part of learning MVVM pattern I tried to search many sites and blogs and found most of them are explained in a complicated manner. After some research I cracked the very basic steps in MVVM pattern, and then trying to write MVVM tutorials for absolute beginners.

 

I don’t think much more time or words spend for explaining various part of MVVM and the relationship  between MVVM and WPF. If you go to the depth of WPF you will realize that MVVM is the best suitable pattern for WPF (You might not understand the difference between these two) .

 

As a formal procedure I am giving a simple diagram and definition for MVVM

 

 

 

I start this tutorial with two examples, i.e WpfSimple.csproj and WpfMvvmTest.csproj

 

For the sake of simplicity, the first project (WpfSimple.csproj) avoids the Model object (an example with Model will come later).

 

In the example WpfSimple, the view contains only a Button and no code behind, but its click event is loosely bound with ViewModel. The bindings between view and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a view. If property values in the ViewModel change, those new values automatically propagate to the view via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action.

 

The View

 

 

The following code snippets are coming from WpfSimple application (available with tutorial)

 

<Window x:Class=”WpfSimple.MainWindow”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

xmlns:local=”clr-namespace:WpfSimple”

Title=”MainWindow” Height=”150″ Width=”370″>

<Window.DataContext>

<local:MainWindowViewModel/>

</Window.DataContext>

<Grid>

<Button Content=”Click”

Height=”23″

HorizontalAlignment=”Left”

Margin=”77,45,0,0″

Name=”btnClick”

VerticalAlignment=”Top”

Width=”203″

Command=”{Binding ButtonCommand}”

CommandParameter=”Hai” />

</Grid>

</Window>

 

ViewModel class used here is MainWindowViewModel, which is the object set as the DataContext of a view.

 

xmlns:local=”clr-namespace:WpfSimple”

<Window.DataContext>

<local:MainWindowViewModel/>

</Window.DataContext>

 

The ViewModel

 

ViewModel  class used over here is  MainWindowViewModel.cs

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Input;

using System.Windows;

 

namespace WpfSimple

{

class MainWindowViewModel

{

private ICommand m_ButtonCommand;

public ICommand ButtonCommand

{

get

{

return m_ButtonCommand;

}

set

{

m_ButtonCommand = value;

}

}

public MainWindowViewModel()

{

ButtonCommand=new RelayCommand(new Action<object>(ShowMessage));

}

public void ShowMessage(object obj)

{

MessageBox.Show(obj.ToString());

}

}

}

 

You can see an empty code behind file. If you click on the button it will prompt a message box, despite the lack of event handling methods in the views. When the user clicks on buttons, the application reacts and satisfies the user’s requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel’s functionality from a view declared in XAML.

 

Command=”{Binding ButtonCommand}”

CommandParameter=”Hai”

 

RelayCommand

 

In this example RelayCommand class is used for implementing ICommad object. I think it’s a simple and standard approach. One more common approach is also available by using nested inner class (will  explain later).

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Input;

 

namespace WpfSimple

{

class RelayCommand : ICommand

{

private Action<object> _action;

public RelayCommand(Action<object> action)

{

_action = action;

}

#region ICommand Members

public bool CanExecute(object parameter)

{

return true;

}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)

{

if (parameter != null)

{

_action(parameter);

}

else

{

_action(“Hello World”);

}

}

#endregion

}

}

 

Next, I am going to discuss MVVM with an example having the Model object. So I like talk bit about INotifyPropertyChanged Interface

 

INotifyPropertyChanged

 

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, which a property value has changed. The INotifyPropertyChanged interface contains an event called PropertyChanged. Whenever a property on a ViewModel / Model  object has a new value, it can raise the PropertyChanged event to notify the WPF binding system of the new value. Upon receiving that notification, the binding system queries the property, and the bound property on some UI element receives the new value

 

From the example WpfMvvmTest project I am  taking the following code

 

public class Product:INotifyPropertyChanged

{

private int m_ID;

private string m_Name;

private double m_Price;

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)

{

if (PropertyChanged != null)

{

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

}

}

#endregion

 

public int ID

{

get

{

return m_ID;

}

set

{

m_ID = value;

OnPropertyChanged(“ID”);

}

}

public string Name

{

get

{

return m_Name;

}

set

{

m_Name = value;

OnPropertyChanged(“Name”);

}

}

public double Price

{

get

{

return m_Price;

}

set

{

m_Price = value;

OnPropertyChanged(“Price”);

}

}

}

 

Another  approach for binding ViewModel object  as datacontext of View

 

public partial class App : Application

{

protected override void OnStartup(StartupEventArgs e)

{

base.OnStartup(e);

WpfMvvmTest.MainWindow window = new MainWindow();

ProductViewModel VM = new ProductViewModel();

window.DataContext = VM;

window.Show();

}

}

 

In the following code snippet used inner class approach for implementing ICommand interface i.e create a private nested class within the ViewModel class, so that the command has access to private members of its containing ViewModel and does not pollute the namespace.

 

The disadvantage of this approach is that it requires creation of a nested class that implements ICommand for each command exposed by a ViewModel which will increase the size of the ViewModel class.

 

class ProductViewModel

{

private IList<Product> m_Products;

public ProductViewModel()

{

m_Products = new List<Product>

{

new Product {ID=1, Name =”Pro1″, Price=10},

new Product{ID=2, Name=”BAse2″, Price=12}

};

}

public IList<Product> Products

{

get

{

return m_Products;

}

set

{

m_Products = value;

}

}

private ICommand mUpdater;

public ICommand UpdateCommand

{

get

{

if (mUpdater == null)

mUpdater = new Updater();

return mUpdater;

}

set

{

mUpdater = value;

}

}

private class Updater : ICommand

{

#region ICommand Members

public bool CanExecute(object parameter)

{

return true;

}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)

{

}

#endregion

}

}

 

From the following view XAML you can understand how to bind a collection of object to the list control.

 

<Window x:Class=”WpfMvvmTest.MainWindow”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

Title=”MainWindow” Height=”350″ Width=”525″>

<Grid Height=”314″>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

<RowDefinition Height=”Auto”/>

</Grid.RowDefinitions>

<ListView Name=”ListViewEmployeeDetails” Grid.Row=”1″ Margin=”4,109,12,23″  ItemsSource=”{Binding Products}”  >

<ListView.View>

<GridView x:Name=”grdTest”>

<GridViewColumn Header=”ID” DisplayMemberBinding=”{Binding ID}”  Width=”100″/>

<GridViewColumn Header=”Name” DisplayMemberBinding=”{Binding Name}”  Width=”100″ />

<GridViewColumn Header=”Price” DisplayMemberBinding=”{Binding Price}” Width=”100″ />

</GridView>

</ListView.View>

</ListView>

<TextBox Grid.Row=”1″ Height=”23″ HorizontalAlignment=”Left” Margin=”80,7,0,0″ Name=”txtID”VerticalAlignment=”Top” Width=”178″ Text=”

Binding ElementName=ListViewEmployeeDetails,Path=SelectedItem.ID}” />

<TextBox Grid.Row=”1″ Height=”23″ HorizontalAlignment=”Left” Margin=”80,35,0,0″ Name=”txtName”VerticalAlignment=”Top” Width=”178″ Text=”{Binding ElementName=ListViewEmployeeDetails,Path=SelectedItem.Name}” />

<TextBox Grid.Row=”1″ Height=”23″ HorizontalAlignment=”Left” Margin=”80,61,0,0″ Name=”txtPrice”VerticalAlignment=”Top” Width=”178″ Text=”{Binding ElementName=ListViewEmployeeDetails,Path=SelectedItem.Price}” />

<Label Content=”ID” Grid.Row=”1″ HorizontalAlignment=”Left” Margin=”12,12,0,274″ Name=”label1″ />

<Label Content=”Price” Grid.Row=”1″ Height=”28″ HorizontalAlignment=”Left” Margin=”12,59,0,0″ Name=”label2″VerticalAlignment=”Top” />

<Label Content=”Name” Grid.Row=”1″ Height=”28″ HorizontalAlignment=”Left” Margin=”12,35,0,0″ Name=”label3″VerticalAlignment=”Top” />

<Button Content=”Update” Grid.Row=”1″ Height=”23″ HorizontalAlignment=”Left” Margin=”310,40,0,0″Name=”btnUpdate”

VerticalAlignment=”Top” Width=”141″

Command=”{Binding Path=UpdateCommad}”

/>

</Grid>

</Window>

 

So…  I hope you can get a small insight about MVVM from this article.