Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries for the ‘C#’ Category

Call web service via jQuery in asp.net

step 1. Add Web service, and you must add a [System.Web.Script.Services.ScriptService] to the service class

(in webservice.asmx.cs file)

   1: /// <summary>

   2: /// Summary description for WebService1

   3: /// </summary>

   4: [WebService(Namespace = "http://tempuri.org/")]

   5: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

   6: [System.ComponentModel.ToolboxItem(false)]

   7: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 

   8: [System.Web.Script.Services.ScriptService]

   9: public class WebService1 : System.Web.Services.WebService

  10: {

  11:     [WebMethod]

  12:     public string DeleteProduct(string id)

  13:     {

  14:         Thread.Sleep(800);

  15:         return "Hello World22: " + id;

  16:     }

  17: }

step 2. call webservice in aspx via jQuery

(in head of the page)

   1: <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

   2: <script type="text/javascript">

   3:     $(function () {

   4:         $('a').click(function () {

   5:             deleteProduct(111);

   6:         }); // end of  $('a').click(function () {

   7:  

   8:     });     // end of $(function () {

   9:  

  10:  

  11:  

  12:     function deleteProduct(id) {

  13:         $.ajax({

  14:             type: "POST",

  15:             url: "WebService1.asmx/DeleteProduct",

  16:             data: "{id: '" + id.toString() + "'}",

  17:             contentType: "application/json; charset=utf-8",

  18:             dataType: "json",

  19:             success: function (msg) {

  20:                 AjaxSucceeded(msg);

  21:             },

  22:             error: AjaxFailed

  23:         });

  24:     }

  25:     function AjaxSucceeded(result) {

  26:         alert(result.d);

  27:     }

  28:     function AjaxFailed(result) {

  29:         alert(result.status + ' - ' + result.statusText);

  30:     }  

  31: </script>

Use HttpRuntime.Cache to call asp.net Cache

In some scenario, you can’t visit asp.net cache, even via HttpContext.Current.Cache. For example, in Unit Test mode. In this case, you can use the HttpRuntime.Cache to access asp.net Cache.

Entity Framework Code First

The “EF Code-First” functionality provides a pretty nice code-centric way to work with data.

Advantage

  • ·         Develop without ever having to open a designer or define an XML mapping file, and start from a class
  • ·         Define your model objects by simply writing “plain old classes” with no base classes required
  • ·         Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • ·         Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping. columbus oh website design

Disadvantage

  • Mapping entities to the database is quite complex
  • There is no Model diagram

Static VS Dynamic Resources in WPF

In WPF A resource can be referenced as either a static resource or a dynamic resource. This is done by using either the StaticResource Markup Extension or the DynamicResource Markup Extension. A markup extension is a feature of XAML whereby you can specify an object reference by having the markup extension process the attribute string and return the object to a XAML loader. For more information about markup extension behavior, see Markup Extensions and WPF XAML.

When you use a markup extension, you typically provide one or more parameters in string form that are processed by that particular markup extension, rather than being evaluated in the context of the property being set. The StaticResource Markup Extension processes a key by looking up the value for that key in all available resource dictionaries. This happens during loading, which is the point in time when the loading process needs to assign the property value that takes the static resource reference. The DynamicResource Markup Extension instead processes a key by creating an expression, and that expression remains unevaluated until the application is actually run, at which time the expression is evaluated and provides a value.

When you reference a resource, the following considerations can influence whether you use a static resource reference or a dynamic resource reference:

  • The overall design of how you create the resources for your application (per page, in the application, in loose XAML, in a resource only assembly).
  • The application functionality: is updating resources in real time part of your application requirements?
  • The respective lookup behavior of that resource reference type.
  • The particular property or resource type, and the native behavior of those types.

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

So, Static resources are resolved at compile time, whereas dynamic resources are resolved at runtime. Use DynamicResources when the value of the resource could change during the lifetime of the Application. Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.

Routed Events in WPF

When you are first getting started with WPF, you will likely use routed events without even knowing you are using them. For example, if you add a button to your window in the Visual Studio® designer and name it myButton and then double-click on it, the Click event will get hooked up in your XAML markup and an event handler for the Click event will be added to the codebehind of your Window class. This should feel no different than hooking up events in Windows Forms and ASP.NET. It is actually a little closer to the coding model for ASP.NET but more like the runtime model of Windows Forms.

Routed events normally appear as pair. The first is a tunneling event called PreviewMouseDown and the second is the bubbling called MouseDown. They don’t stop routing if the reach an event handler. To stop routing then you have to set e.Handled = true;

  • Tunneling The event is raised on the root element and navigates down to the visual tree until it reaches the source element or until the tunneling is stopped by marking the event as handeld. By naming convention it is called Preview... and appears before corresponding bubbling event.
  • Bubbling The event is raised on the source element and navigates up to the visual tree until it reaches the root element or until the bubbling is stopped by marking the event as handled. The bubbling event is raised after the tunneling event.
  • Direct The event is raised on the source element and must be handled on the source element itself. This behavior is the same as normal .NET events.

You can think about routed events either from a functional or implementation perspective. Both definitions are presented here, because some people find one or the other definition more useful.

Functional definition: A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

Implementation definition: A routed event is a CLR event that is backed by an instance of the RoutedEvent class and is processed by the Windows Presentation Foundation (WPF) event system.

A typical WPF application contains many elements. Whether created in code or declared in XAML, these elements exist in an element tree relationship to each other. The event route can travel in one of two directions depending on the event definition, but generally the route travels from the source element and then "bubbles" upward through the element tree until it reaches the element tree root (typically a page or a window). This bubbling concept might be familiar to you if you have worked with the DHTML object model previously.

A code snippet

   1: <StackPanel Orientation="Horizontal" Button.Click="ButtonCLickHandler">

   2:   <Button Name="btnYes" Width="Auto" >Yes</Button>

   3:   <Button Name="btnNo" Width="Auto" >No</Button>

   4:   <Button Name="btnCancel" Width="Auto" >Cancel</Button>

   5: </StackPanel>

As an application developer, you do not always need to know or care that the event you are handling is implemented as a routed event. Routed events have special behavior, but that behavior is largely invisible if you are handling an event on the element where it is raised.

Where routed events become powerful is if you use any of the suggested scenarios: defining common handlers at a common root, compositing your own control, or defining your own custom control class.

Routed event listeners and routed event sources do not need to share a common event in their hierarchy. Any UIElement or ContentElement can be an event listener for any routed event. Therefore, you can use the full set of routed events available throughout the working API set as a conceptual "interface" whereby disparate elements in the application can exchange event information. This "interface" concept for routed events is particularly applicable for input events.

Routed events can also be used to communicate through the element tree, because the event data for the event is perpetuated to each element in the route. One element could change something in the event data, and that change would be available to the next element in the route.

Other than the routing aspect, there are two other reasons that any given WPF event might be implemented as a routed event instead of a standard CLR event. If you are implementing your own events, you might also consider these principles:

    Certain WPF styling and templating features such as EventSetter and EventTrigger require the referenced event to be a routed event. This is the event identifier scenario mentioned earlier.

    Routed events support a class handling mechanism whereby the class can specify static methods that have the opportunity to handle routed events before any registered instance handlers can access them. This is very useful in control design, because your class can enforce event-driven class behaviors that cannot be accidentally suppressed by handling an event on an instance.

Each of the above considerations is discussed in a separate section of this topic.

MVVM in WPF

Key characteristics of VIEW
? The view is a visual element, such as a window, page, user control, or data template. The view defines the controls contained in the view and their visual layout and styling.
? The view references the view model through its DataContext property. The controls in the view are data bound to the properties and commands exposed by the view model.
? The view may customize the data binding behavior between the view and the view model. For example, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.
? The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.
? The view’s code-behind may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view.

Key characteristics of’ ‘VIEWMODEL’
? The view model is a non-visual class and does not derive from any WPF or Silverlight base class. It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model.
? The view model typically does not directly reference the view. It implements properties and commands to which the view can data bind. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
? The view model coordinates the view’s interaction with the model. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
? The view model may define logical states that the view can represent visually to the user.

Key characteristics of ‘MODEL’
? Model classes are non-visual classes that encapsulate the application’s data and business logic. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
? The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
? The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. This allows them to be easily data bound in the view. Model classes that represent collections of objects typically derive from the ObservableCollection<T> class.
? The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
? The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.