Wednesday, October 24, 2012

State Management in Silverlight using Isolation Storage Help

            In ASP.Net, Silverlight has no concept of a session. To store session information we have to store the data in isolation storage. Suppose after login you have to display your log in name through several pages. SO the best way to store the data for displaying it is isolation storage and then you can retrieve it later.

            Now in this example below I will enter a user name and when I press submit it will store it in the isolation storage and also display it in the label by getting the value from the isolation storage.

            Create a new Silver light Application name "isolationwrittingfile".


            Now in the page.xaml paste the code below:<UserControl x:Class="isolationwritting_file.MainPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d"    d:DesignHeight="300" d:DesignWidth="400"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <Grid x:Name="LayoutRoot" Background="White">        <TextBox Height="23" HorizontalAlignment="Left" Margin="152,37,0,0" Name="textBox1"VerticalAlignment="Top" Width="120" Text="" />        <sdk:Label Height="28" HorizontalAlignment="Left" Margin="26,37,0,0" Name="label1"VerticalAlignment="Top" Width="120" Content="UserName" />        <sdk:Label Height="28" HorizontalAlignment="Left" Margin="26,105,0,0" Name="label2"VerticalAlignment="Top" Width="120" />        <Button Content="Submit" Height="23" HorizontalAlignment="Left" Margin="278,37,0,0"Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />    </Grid>
</
UserControl>
It will look like Figure 1:

StateMgmt1.gif

Now in the Page.xaml.cs paste the code below:using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using System.IO.IsolatedStorage;using System.IO;
namespace isolationwritting_file
{
    public partial class MainPage : UserControl    {
        public MainPage()
        {
            InitializeComponent();
            //SaveData("Hello There", "MyData.txt");             //string test = LoadData("MyData.txt");            //textBox1.Text = test.ToString();        }
        private void SaveData(string data, string fileName)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) 
            { 
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName,FileMode.Create, isf))
                { 
                    using (StreamWriter sw = new StreamWriter(isfs)) 
                    { sw.Write(data); sw.Close(); }
                } 
            }
        }
        private string LoadData(string fileName)
        { string data = String.Empty;
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) 
            { 
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName,FileMode.Open, isf))
                {
                    using (StreamReader sr = new StreamReader(isfs)) 
                    {
                        string lineOfData = String.Empty; 
                        while ((lineOfData = sr.ReadLine()) != null)   
                            data += lineOfData; 
                    } 
                } 
            } 
            return data;
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SaveData(textBox1 .Text , "MyData.txt");
            string test = LoadData("MyData.txt");
            label2.Content = "Your UserName is" + test.ToString();
        }
    }
}

In the SaveData method under the button click I am passing the "textBox1 .Text" parameter and also the ""MyData.txt" file name which will be created in the isolation storage.

The Method "LoadData()" retrieves the value from the isolation storage.

Now run the program; it will look like Figure 2:

StateMgmt2.gif

Figure 2:

When you enter the user name and press submit button it will look like Figure 3:

StateMgmt3.gif

Figure 3:

Conclusion: So in this article we have learned about using isolation storage for maintaining the state management in Silverlight.

Tuesday, October 23, 2012

What is the difference between transaction and query?


QUERY:
A query is a single SQL statement that does Select, Update, Insert or Delete of rows.


Transaction:
A transaction is a consecutive sequence of SQL statements (from the application viewpoint) that have the "ACID" properties:
  • Atomicity: All statements or none are executed.
  • Consistency: Data integrity is always maintained.
  • Isolation: Transaction A can never affect Transaction B.
  • Durability: Changes that are committed by a transaction persist, even in event of system failure.

Understanding Basics of UI Design Pattern MVC, MVP and MVVM


Introduction

This is my first article and I hope you will like it. After reading this article, you will have a good understanding about "Why we need UI design pattern for our application?" and "What are basic differences between different UI patterns (MVC, MVP, MVVP)?”.
In traditional UI development - developer used to create a View using window or usercontrol or page and then write all logical code (Event handling, initialization and data model, etc.) in code behind and hence they were basically making code as a part of view definition class itself. This approach increased the size of my view class and created a very strong dependency between my UI and data binding logic and business operations. In this situation, no two developers can work simultaneously on the same view and also one developer's changes might break the other code. So everything is in one place is always a bad idea for maintainability, extendibility and testability prospective. So if you look at the big picture, you can feel that all these problems exist because there is a very tight coupling between the following items.
  1. View (UI)
  2. Model (Data displayed in UI)
  3. Glue code (Event handling, binding, business logic)
Definition of Glue code is different in each pattern. Although view and model is used with the same definition in all patterns.
In case of MVC it is controller. In case of MVP it is presenter. In case of MVVM it is view model.
If you look at the first two characters in all the above patterns, it remain same i.e. stands for model and view. All these patterns are different but have a common objective that is “Separation of Duties"
In order to understand the entire article, I request readers to first understand the above entity. A fair idea about these will help you to understand this article. If you ever worked on UI module, you can easily relate these entities with your application.
MVC (model view controller), MVP (model view presenter) and MVVM (model view view model) patterns allow us to develop applications with loss coupling and separation of concern which in turn improve testability, maintainability and extendibility with minimum effort.
MVVM pattern is a one of the best solutions to handle such problems for WPF and Silverlight application. During this article, I will compare MVC, MVP and MVVM at the definition level.

MVP & MVC

Before we dig into MVVM, let’s start with some history: There were already many popular design patterns available to make UI development easy and fast. For example, MVP (model view presenter) pattern is one of the very popular patterns among other design patterns available in the market. MVP is a variation of MVC pattern which is being used for so many decades. Simple definition of MVP is that it contains three components: Model, View and presenter. So view is nothing but a UI which displays on the screen for user, the data it displays is the model, and the Presenter hooks the two together (View and model).
View,Model,Presenter,Model
The view relies on a Presenter to populate it with model data, react to user input, and provide input validation. For example, if user clicks on save button, corresponding handling is not in code behind, it’s now in presenter. If you wanted to study it in detail, here is the MSDN link.
In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View basically calls to a Controller along with an action. In web application, each action is a call to a URL and for each such call there is a controller available in the application who respond to such call. Once that Controller has completed its processing, it will return the correct View.
In case of MVP, view binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation. It means while implementing this pattern, we have to write some code in code behind of view in order delegate (register) to the presenter. However, in case of MVC, a view does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. Since controller itself returns view while responding to URL action, there is no need to write any code in view code behind file.

MVC Steps

Step 1: Incoming request directed to Controller.
View,Model,Presenter,Model
Step 2Controller processes request and forms a data Model.
View,Model,Presenter,Model
Step 3Model is passed to View.
View,Model,Presenter,Model
Step 4View transforms Model into appropriate output format.
View,Model,Presenter,Model
Step 5: Response is rendered.
View,Model,Presenter,Model
So now you have basic understanding of MVC and MVP. Let’s move to MVVM.

MVVM (Model View ViewModel)

The MVVM pattern includes three key parts:
  1. Model (Business rule, data access, model classes)
  2. View (User interface (XAML))
  3. ViewModel (Agent or middle man between view and model)
View,Model,ViewModel
Model and View work just like MVC and “ViewModel” is the model of the View.
  • ViewModel acts as an interface between model and View.
  • ViewModel provides data binding between View and model data.
  • ViewModel handles all UI actions by using command.
In MVVM, ViewModel does not need a reference to a view. The view binds its control value to properties on a ViewModel, which, in turn, exposes data contained in model objects. In simple words, TextBox text property is bound with name property in ViewModel.
In View:
<TextBlock Text="{Binding Name}"/> 
In ViewModel:
public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                this.OnPropertyChanged("Name");
            }
        }
ViewModel reference is set to a DataContext of View in order to set view data binding (glue between view and ViewModel model).
Code behind code of View:
public IViewModel Model
        {
            get
            {
                return this.DataContext as IViewModel;
            }
            set
            {
                this.DataContext = value;
            }
        }
If property values in the ViewModel change, those new values automatically propagate to the view via data binding and via notification. When the user performs some action in the view for example clicking on save button, a command on theViewModel executes to perform the requested action. In this process, it’s the ViewModel which modifies model data, View never modifies it. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model doesn’t have any idea about ViewModel and view exists.

Where to Use What in the .NET World

  • Model-View-Controller (MVC) pattern
    • ASP.NET MVC 4 Link
    • Disconnected Web Based Applications
  • Model-View-Presenter (MVP) pattern
    • Web Forms/SharePoint, Windows Forms
  • Model-View-ViewModel (MVVM) pattern
    • Silverlight, WPF Link
    • Data binding

MVC Basics

The ASP.NET MVC Framework is a web application framework that implements the model-view-controller pattern. Based on ASP.NET, it allows software developers to build a Web application as a composition of three roles:

ModelView and Controller

model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the application.

controllerhandles interactions and updates the model to reflect a change in state of the application, and then passes information to the view.

view accepts necessary information from the controller and renders a user interface to display that


View - just the UI (HTML), there's no much logic there only logic for taking data from the Model. View just take a Model and render it's content on the page. There's no code behind, no .aspx.vb or .aspx.cs

Model - contains all data that view needs to display

Controller - is the boss, the controller handling HTTP requests for web page and it's role is to create a model (read data from DB, bussiness logic etc) and selects proper view for render. Controller never interacts with the user interface, it's job of the View. And never holds any data or statements, it's job of the Model.

Folder structure of app:
image_thumb1

  • "Controllers" folder is the place where the controllers are placed. The name convention is the controller name must end with "Controller" word, for eg.: HomeController -> Home is the name of the controller. And "Controller" is required postfix. In the code you using just a name (for eg. Home) but controller classes needs the have there the Controller postfix to be properly handled by MVC engine.
  • "Views" is the place for views.
    When the view represents action result (for eg. aspx page) then view name needs to match with action names used for.
    When view is usercontrol you can name it whatever you what.Under Views folder you will have list of folders with controller names and the one called Shared. The folders with the controller names are there just because the view is somehow associated with the controller. Another words when the controller return views that's the place where the MVC is looking for particular view that needs to be renders. The "Shared" folder is the place for user controls, master pages etc. The "Shared" folder contains views used by multiple controllers.
  • "Models" - place for object definitions that will be populated with the Controller and used by View for rendering.