Monday, November 22, 2010

Silverlight First Sample Application With Database Common Operation

1. Create a Table and Storeprocedure in Database

--Table Script
CREATE TABLE [dbo].[PracticalTest](
       [ID] [int] IDENTITY(1,1) NOT NULL,
       [ModelName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
       [CarName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
       [CarPrice] [numeric](18, 2) NOT NULL,
       [ManufactureDate] [datetime] NOT NULL,
       [Status] [int] NOT NULL,
 CONSTRAINT [PK_PracticalTest] PRIMARY KEY CLUSTERED
(
       [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

--Procedure
CREATE PROCEDURE [dbo].[Practical]
      
@Task int = 0,
@ID int = 0,
@ModelName varchar(50) = " ",
@CarName varchar(50) = " ",
@CarPrice numeric(18,2) = 0,
@ManufactureDate datetime = " ",
@Status int = 0


AS
BEGIN
      
if(@Task = 1)
INSERT INTO PracticalTest(ModelName,CarName,CarPrice,ManufactureDate,Status)
VALUES (@ModelName,@CarName,@CarPrice,@ManufactureDate,@Status)

else if(@Task = 2)
SELECT     ID, ModelName, CarName, CarPrice, ManufactureDate,
Status as Status
FROM         PracticalTest

else if(@Task = 3)
DELETE FROM PracticalTest where ID=@ID

else if(@Task = 4)
SELECT * FROM PracticalTest where ID=@ID

else if(@Task = 5)
UPDATE PracticalTest
   SET ModelName = @ModelName
      ,CarName = @CarName
      ,CarPrice = @CarPrice
      ,ManufactureDate = @ManufactureDate
      ,Status= @Status
 WHERE ID=@ID
END



2 . UPage3.xaml  Code – For Desing the Page

<UserControl x:Class="Shaneesh.UPage3"
    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"
                xmlns:slv="clr-namespace:Silverlight.Validators;assembly=Silverlight.Validators"
             xmlns:slvf="clr-namespace:Silverlight.Validators.Filters;assembly=Silverlight.Validators"
    d:DesignHeight="1000" d:DesignWidth="1000" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
   
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100 "/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="125"/>
            <ColumnDefinition Width="175"/>
            <ColumnDefinition Width="100 "/>
            <ColumnDefinition Width="400*" />
        Grid.ColumnDefinitions>
       
        <Grid.RowDefinitions>
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="33" />
            <RowDefinition Height="102" />
            <RowDefinition Height="601*" />
        Grid.RowDefinitions>
        <sdk:Label Height="28" HorizontalAlignment="Left" Name="lblModelName" VerticalAlignment="Top" Width="87" Content="Model Name" Grid.Column="1"  Grid.Row="1" Margin="0,5,0,0" />
        <TextBox Height="23" HorizontalAlignment="Left"  Name="txtModelName" VerticalAlignment="Top" Width="100" Grid.Column="2"  Grid.Row="1" TabIndex="1" Margin="7,4,0,0">
            <slv:ValidatorService.Validator>
                <slv:RequiredValidator ManagerName="Group1"    ErrorMessage="Enter Charge Type"/>
            slv:ValidatorService.Validator>
        TextBox>
        <sdk:Label Height="28" HorizontalAlignment="Left" Name="lblCarName" VerticalAlignment="Top" Width="87" Content="Car Name" Grid.Column="1"  Grid.Row="2" Margin="0,9,0,0" Grid.RowSpan="2" />
        <TextBox Height="23" HorizontalAlignment="Left"  Name="txtCarName" VerticalAlignment="Top" Width="100" Grid.Column="2"  Grid.Row="2" TabIndex="2" Margin="6,5,0,0">
            <slv:ValidatorService.Validator>
                <slv:RequiredValidator ManagerName="Group1"    ErrorMessage="Enter Charge Type"/>
            slv:ValidatorService.Validator>
        TextBox>
        <sdk:Label Content="Car Price" Grid.RowSpan="2" Height="28" HorizontalAlignment="Left" Margin="0,10,0,0" Name="label1" VerticalAlignment="Top" Width="87" Grid.Column="1" Grid.Row="3" />
        <TextBox Height="23" HorizontalAlignment="Left" slvf:TextBoxFilterService.Filter="PositiveDecimal"  Name="txtCarPrice" VerticalAlignment="Top" Width="100" Grid.Column="2"  Grid.Row="3" TabIndex="3" Margin="6,10,0,0">
            <slv:ValidatorService.Validator>
                <slv:RequiredValidator ManagerName="Group1"    ErrorMessage="Enter Charge Type"/>
            slv:ValidatorService.Validator>
        TextBox>
        <sdk:Label Height="28" HorizontalAlignment="Left" Name="Active" VerticalAlignment="Top" Width="87" Content="Status" Grid.Column="1"  Grid.Row="5" Margin="0,4,0,0" />
        <CheckBox Content="Active" Height="16" HorizontalAlignment="Left" Name="chkActive" TabIndex="5" VerticalAlignment="Top" Grid.Column="2" Grid.Row="5" Margin="0,6,0,0" Width="100" />
        <sdk:Label Content="ManufactureDate" Height="28" HorizontalAlignment="Left" Margin="0,5,0,0" Name="label2" VerticalAlignment="Top" Width="87" Grid.Column="1" Grid.Row="4" />
        <sdk:DatePicker Grid.ColumnSpan="2" Height="23" HorizontalAlignment="Left" Margin="7,10,0,0" Name="dtpManufactDate" VerticalAlignment="Top" Width="158" Grid.Column="2" Grid.Row="4" >
            <slv:ValidatorService.Validator>
                <slv:RequiredValidator ManagerName="Group1"    ErrorMessage="Enter Date"/>
            slv:ValidatorService.Validator>
        sdk:DatePicker>
        <Button Content="New" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="25,10,0,0" Name="New" VerticalAlignment="Top" Width="75" Click="New_Click" Grid.Column="1" />
        <Button Content="Edit" Grid.Column="2" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="25,10,0,0" Name="Edit" VerticalAlignment="Top" Width="75" Click="Edit_Click" />
        <Button Content="Delete" Grid.Column="3" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="120,10,0,0" Name="Delete" VerticalAlignment="Top" Width="75" Click="Delete_Click" Grid.ColumnSpan="2" />
        <Button Content="Save" Grid.Column="3" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="25,10,0,0" Name="Save" VerticalAlignment="Top" Width="75" Click="Save_Click" />

        <sdk:DataPager  Name="pagerCarModel" VerticalAlignment="Center"
        Source="{Binding Path=ItemsSource,ElementName=dtgCarModel}" Grid.Column="1"  DisplayMode="PreviousNext"
                       NumericButtonCount="10"  Grid.ColumnSpan="5" Grid.Row="13" Height="26" HorizontalAlignment="Left"
                      PageSize="10" Width="629" Margin="0,0,0,7" />

        <sdk:DataGrid AutoGenerateColumns="False" Grid.Column="1" Grid.ColumnSpan="5" Grid.Row="9" Grid.RowSpan="2"
                      Height="266" HorizontalAlignment="Left" Name="dtgCarModel" VerticalAlignment="Top" Width="629"
                      SelectionChanged="dtgCarModel_SelectionChanged" IsReadOnly="True">
            <sdk:DataGrid.Columns >
                <sdk:DataGridTextColumn Binding="{Binding ModelName}" Header="Modle Name" MinWidth="100" />
                <sdk:DataGridTextColumn Binding="{Binding CarName}" Header=" Car Name" MinWidth=" 100"/>
                <sdk:DataGridTextColumn Binding="{Binding CarPrice}" Header="Car Price" />
                <sdk:DataGridTextColumn Binding="{Binding Manufactdate}" Header ="Manufacture Date" MinWidth = "100"/>
                <sdk:DataGridTextColumn Binding="{Binding Flag}" Header="Status" MinWidth="100" />
            sdk:DataGrid.Columns>

        sdk:DataGrid>
    Grid>
UserControl>



3. Web Config File Add in Project for Connection String

xml version="1.0"?>


<configuration>
    <connectionStrings>
        <add name="TESTConnectionString" connectionString="Data Source=ntech5;Initial Catalog=TEST;User ID=sa;Password=12345"
            providerName="System.Data.SqlClient" />
    connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    system.web>

    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                behavior>
            serviceBehaviors>
        behaviors>
        <bindings>
            <customBinding>
                <binding name="Shaneesh.Web.srTest.customBinding0">
                    <binaryMessageEncoding />
                    <httpTransport />
                binding>
                <binding name="Shaneesh.Web.Service1.customBinding0">
                    <binaryMessageEncoding />
                    <httpTransport />
                binding>
            customBinding>
        bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
            multipleSiteBindingsEnabled="true" />
        <services>
            <service name="Shaneesh.Web.srTest">
                <endpoint address="" binding="customBinding" bindingConfiguration="Shaneesh.Web.srTest.customBinding0"
                    contract="Shaneesh.Web.srTest" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            service>
            <service name="Shaneesh.Web.Service1">
                <endpoint address="" binding="customBinding" bindingConfiguration="Shaneesh.Web.Service1.customBinding0"
                    contract="Shaneesh.Web.Service1" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            service>
        services>
    system.serviceModel>
configuration>


4. UPage3.xaml.cs file – Code For Page



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;

#region
using Shaneesh.srTest;
using System.Windows.Data;
#endregion

namespace Shaneesh
{
    public partial class UPage3 : UserControl
    {
        int ID = 0;
        //Page pvc;
        PagedCollectionView pvc;
        Pagestatus status;

        int operation;

        public UPage3()
        {
            InitializeComponent();
            SetControl(false);
            LoadGrid();
        }

        #region set and Clear Controls

        private void ClearControls()
        {
            txtCarName.Text = "";
            txtModelName.Text = "";
            txtCarPrice.Text = "";
            dtpManufactDate.Text = "";
            chkActive.IsChecked = false;
        }

        public void SetControl(Boolean value)
        {
            txtCarName.IsReadOnly = !value;
            txtModelName.IsReadOnly = !value;
            txtCarPrice.IsReadOnly = !value;
            dtpManufactDate.IsEnabled = value;
            chkActive.IsEnabled = value;
           
        }


        #endregion


        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            //operation = 2;
            status = Pagestatus.EditMode;
            txtModelName.Focus();
            SetControl(true);
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {

            SaveData();
            ClearControls();
            SetControl(false);
           
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            //operation = 5;
            status = Pagestatus.Delete ;
            DeleteData();
        }

        private void New_Click(object sender, RoutedEventArgs e)
        {
            status = Pagestatus.AddMode;
            operation = 1;
            ClearControls();
            txtModelName.Focus();
            SetControl(true);
        }  

        #region Method & load the Class
       private void DeleteData()
        {

            try
            {
                //if (operation == 5)
                if(status == Pagestatus.Delete)
                {
                    srTestClient srTestClient = new srTestClient();
                    Skpatel objskpatel = new Skpatel();
                    objskpatel.ID = ID;
                    srTestClient.DELETECompleted += new EventHandler<DELETECompletedEventArgs>(srTestClient_DELETECompleted);
                    srTestClient.DELETEAsync(objskpatel);
                  


                }


            }
            catch (Exception ex)
            {
                throw;
            }


        }

       void srTestClient_DELETECompleted(object sender, DELETECompletedEventArgs e)
       {

           if (e.Error == null)
           {
               ClearControls();
               SetControl(false);
               LoadGrid();
               General.Delete();
           }
           else
           {
               txtModelName.Focus();

           }
       }
        private void SaveData()
        {
            try
            {
                if (status == Pagestatus.AddMode)
                //if (operation == 1)
                {
                    srTestClient srTestClient = new srTestClient();
                    Skpatel objSkpatel = LoadObject();
                    srTestClient.INSERTCompleted += new EventHandler<INSERTCompletedEventArgs>(srTestClient_INSERTCompleted);
                    srTestClient.INSERTAsync(objSkpatel);
                }
                else if (status == Pagestatus.EditMode)
                //else if (operation == 2)
                {
                    if (ID != 0)
                    {
                        srTestClient srTestClient = new srTestClient();
                        Skpatel objSkpatel = LoadObject();
                        srTestClient.UPDATECompleted += new EventHandler<UPDATECompletedEventArgs>(srTestClient_UPDATECompleted);
                        objSkpatel.ID = ID ;
                        srTestClient.UPDATEAsync(objSkpatel);
                    }
                    ID = 0;
                }


            }
            catch (Exception ex)
            {
                throw ;
            }

        }


        void srTestClient_UPDATECompleted(object sender, UPDATECompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ClearControls();
                SetControl(false);
                LoadGrid();
                General.Update();
            }
            else
            {
                txtModelName.Focus();

            }

        }

        void srTestClient_INSERTCompleted(object sender, INSERTCompletedEventArgs e)
        {

            if (e.Error == null)
            {
                ClearControls();
                SetControl(false);
                LoadGrid();
                General.Save();
            }
            else
            {
                txtModelName.Focus();
               
            }


        }


        private Skpatel LoadObject()
        {
            try
            {
                Skpatel objSkpatel = new Skpatel();
                objSkpatel.ModelName = txtModelName.Text.Trim();
                objSkpatel.CarName = txtCarName.Text.Trim();
                objSkpatel.CarPrice = Convert.ToDouble(txtCarPrice.Text.Trim());
                objSkpatel.Manufactdate = Convert.ToDateTime(dtpManufactDate.Text.ToString()); ;
                objSkpatel.Flag =Convert.ToInt32(chkActive.IsChecked);
                return objSkpatel;
            }
            catch (Exception ex)
            {

                throw ex;    
            }
        }



        #endregion
        private void LoadGrid()
        {
            try
            {
                Skpatel objSkpatel = new Skpatel();
                srTestClient srTest = new srTestClient();
                srTest.SelectCompleted += new EventHandler<SelectCompletedEventArgs>(srTest_SelectCompleted);
                srTest.SelectAsync(objSkpatel);

            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

        void srTest_SelectCompleted(object sender, SelectCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Count > 0)
                {
                    pvc = new PagedCollectionView(e.Result);
                    dtgCarModel.ItemsSource = "";
                    dtgCarModel.ItemsSource = pvc;
                }
                else
                {
                    MessageBox.Show(e.Error.Message);
                }

            }

        }

        private void dtgCarModel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (dtgCarModel.SelectedItem != null)
                {
                    Skpatel cls;
                    cls = (Skpatel)dtgCarModel.SelectedItem;
                    LoadControls(cls);

                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        private void LoadControls(Skpatel skpatel)
        {

            try
            {
                txtModelName.Text = skpatel.ModelName;
                txtCarName.Text = skpatel.CarName;
                txtCarPrice.Text = skpatel.CarPrice.ToString();
                chkActive.IsChecked = (bool)(skpatel.Flag == 1 ? true : false);
                dtpManufactDate.Text = Convert.ToDateTime(skpatel.Manufactdate).ToShortDateString();
                ID = skpatel.ID;

            }
            catch (Exception ex)
            {

            }


        }


        public EventHandler<DELETECompletedEventArgs> srTestClient_DeleteCompleted { get; set; }
    }
}

5. General.cs – Class File

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Shaneesh
{

    public enum Pagestatus : int
    {
        AddMode = 1,
        EditMode = 2,
        ViewMode = 3,
        Blank = 4,
        Delete = 5,
    }

    public class General
    {
        public static void Save()
        {
            MessageBox.Show("Save has been Successfully.");
        }
        public static void Update()
        {
            MessageBox.Show("Update has been Successfully.");
        }

        public static void NoRecordFound()
        {
            MessageBox.Show("No Record Found");
        }

        public static void Message(string name)
        {
            MessageBox.Show(name);
        }

        public static void Delete()
        {
            MessageBox.Show("Record Deleted Successfully");
        }
    }
}


Crossdomain.xml File add in Web Project

xml version="1.0"?>
DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
 
cross-domain-policy>


6. ShaneeshDB.dbml – Add or Drag the Table and Store procedure in DBML File,

Table Name : PracticalTest
Sp Name : Practical


7. Add srTest.cs or srTest.svc Services File Code as below.


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;

namespace Shaneesh.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class srTest
    {

        [OperationContract]
        public bool INSERT(Skpatel skpatel)
        {
            try
            {
                ShaneeshDBDataContext db = new ShaneeshDBDataContext();
                //Nullable OutPut = null;
                var data = db.Practical(1,skpatel.ID, skpatel.ModelName,
                    skpatel.CarName, decimal.Parse(skpatel.CarPrice.ToString()),
                    skpatel.Manufactdate,Convert.ToInt16(skpatel.Flag));
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                throw;
            }
             
           
        }

        [OperationContract]
        public bool DELETE(Skpatel skpatel)
        {
            try
            {
                ShaneeshDBDataContext db = new ShaneeshDBDataContext();
                Nullable<int> Output = null;
                var data = db.Practical(3, skpatel.ID, skpatel.ModelName,
                    skpatel.CarName, decimal.Parse(skpatel.CarPrice.ToString()),
                    skpatel.Manufactdate, Convert.ToInt16(skpatel.Flag));
                db.SubmitChanges();
                // return true;
            }
            catch
            {

            }
            return true;
        }
        [OperationContract]
        public bool UPDATE(Skpatel skpatel)
        {

            try
            {
                ShaneeshDBDataContext db = new ShaneeshDBDataContext();
                Nullable <int> Output = null;
               
                var data = db.Practical(5, skpatel.ID, skpatel.ModelName,
                    skpatel.CarName, decimal.Parse(skpatel.CarPrice.ToString()),
                    skpatel.Manufactdate, Convert.ToInt16(skpatel.Flag));
                db.SubmitChanges();
                return true;
            }
            catch(Exception ex)
            {
                 throw ;
            }

       }
       

       [OperationContract]
       public List<Skpatel> Select(Skpatel skpatel)
        {
            try
            {
                ShaneeshDBDataContext db = new ShaneeshDBDataContext();
               // Nullable Output = null;
                var data = db.Practical(2, skpatel.ID, skpatel.ModelName,
                    skpatel.CarName, decimal.Parse(skpatel.CarPrice.ToString()),
                    skpatel.Manufactdate, Convert.ToInt16(skpatel.Flag));
                List<Skpatel> lstSkpatel = new List<Skpatel>();
                foreach (var row in data)
                {
                    lstSkpatel.Add(new Skpatel
                    {
                        ID = (int)row.ID,
                        ModelName = row.ModelName,
                        CarName = row.CarName,
                        CarPrice = Convert.ToDouble(row.CarPrice),
                        Manufactdate = row.ManufactureDate,
                        Flag = Convert.ToInt32(row.Status),
                    });

                }
                return lstSkpatel;

            }
            catch (Exception ex)
            {
                throw ;
            }
        }

       
        // Add more operations here and mark them with [OperationContract]
    }
   
    [DataContract ]
    public class Skpatel
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string ModelName { get; set; }
        [DataMember]
        public string CarName {get;set;}
        [DataMember]
        public double CarPrice{get;set;}
        [DataMember]
        public DateTime? Manufactdate{get;set;}
        [DataMember]
        public int Flag{get;set;}

    }

}

8. Output 



No comments:

Post a Comment