Saturday 11 April 2015

Web API : Consume Multiple resultset return from stored proc in code first approch

Hi friends,
after a big big break I come back again.
I come up with some new topics.
Some of days back I am working on Web Api. using code first approch because client dont want to give me database.
So I just have signature of stored proc and return structure.
Everything is working fine.
I am building Web Api for Mobile applications with Ionic framework.
Everything is simple upto this. the main 'yow' thing comes when client give me multiple result sets return from his stored proc.
I have never done this before in code first accespting multiple result sets.
I have started looking to it and yeesss I got it..
So the solution is We can achive this by using command reader and IObjectContextAdapter

The whole concept is first of all we need to create classes
Each class for each resultset.

for testing pourpose I have used AdventureWorks 2012 Database. Created a small stored proc which returns me Department detail and its employee list.
As per above request my classes will because

 public class Employee
    {
     
        public DateTime BirthDate { get; set; }
        public string JobTitle { get; set; }
    }
    [ComplexType]
    public class DepartmentEmpBase
    {
    
        public string Name { get; set; }
        public string GroupName { get; set; }
        public List<Employee> EmployeeList { get; set; }
    }
   
   
   
    Next I have to create Context object inherited by Dbcontext And we need to add complex object in Context object while model building
   
   
     public class DepartmentContext : NovaContext
    {
     
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.ComplexType<DepartmentEmpBase>();
          
        }

    }
    Next and final task is to call stored proc and read one by one dataset
   
     DepartmentEmpBase bs = new DepartmentEmpBase();
            using (var db = new DepartmentContext())
            {
               
                // Create a SQL command to execute the sproc
                var cmd = db.Database.Connection.CreateCommand();
                cmd.CommandText = Sql;

                try
                {

                  
                    db.Database.Connection.Open();
                    var reader = cmd.ExecuteReader();

                  
                    var depts = ((IObjectContextAdapter)db)
                        .ObjectContext
                        .Translate<DepartmentEmpBase>(reader);
                    bs = depts.FirstOrDefault();
                  

                   
                    reader.NextResult();
                    var emp = ((IObjectContextAdapter)db)
                        .ObjectContext
                        .Translate<Employee>(reader);


                
                    bs.EmployeeList = emp.ToList();
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    db.Database.Connection.Close();
                }
            }

Thats It!!

Friday 3 May 2013

Disable controls in GridView

Hi all,

after so long time this is my new beginning...!

Lets start..

you can disable controls of your GridView  by simply make control Disabled=true;
you can do this by other way...

suppose your gridview name is gvtest. On its 'onrowdatabound event you need to call below funtion.



 protected void gvtest_RowDataBound(object sender, GridViewRowEventArgs e)
        {
         
       
             if (e.Row.RowType == DataControlRowType.DataRow)
             {

           
               
                     e.Row.Cells[2].Attributes.Add("disabled", "disabled");
                     e.Row.Cells[3].Attributes.Add("disabled", "disabled");
     
                 }
           
               
               
            }
           

       

Wednesday 28 December 2011

Display Records From Database using jQuery

Hey Hi,

In this post you will see how to display records using jQuery. As JQuery is light weight so we can call any method from our .vb/.cs page using  $.ajax() method . There are other ways to do this like $.get() method
Here I will show you with $.ajax call.
For the new users I will explain what is the use of doing this. Suppose you want to show data on image (hover effect) or suppose you need to display error messages or suppose you need to display anything but "Without Page refresh" you can do it with jQuery.

So lets start now,
Let us consider I have a listing screen each row represents data about employee. I need to display details about that employee when I click the image button placed before name.
In my aspx page I placed a html table
   

<table align="center">
    <tr>
    <td><img src="CallSend.jpg"  height="20" width="20" id="imgDetail" style="cursor:hand;" onclick="getCars(event,0)"/><div id="output" class="pop-up" visible="false">
 
    </div></td>
    <td width="5px"></td>
    <td>Detail</td>
    </tr>
    <tr>
    <td colspan="2" height="5px"></td>
    </tr>
    <tr>
    <td><img src="CallSend.jpg"  height="20" width="20" id="imgDetail2" style="cursor:hand;" onclick="getCars(event,1)"/> </td>
    <td width="5px"></td>
    <td>Detail</td>
    </tr>
    </table>


Now, when I click on 'imgDetail' button I will see details.

Here you can see getDetails() function with parameters. This function contains jQuery coding to fetch data
Here is the code



<script type="text/javascript" src="jquery/jquery-1.3.2.min.js"></script>

    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
  function getCars(e,callid) {
      $.ajax({
          type: "POST",
          url: "getData.aspx?callid=" + callid,
          data: "{}",
          contentType: "application/json",
          dataType: "json",
          success: function(response) {
              var posx = e.pageX;
              var posy = e.pageY;
              var cars = response.d;
              var data = eval(response);

              $('#output').show()
              $('#output').css('top', e.pageY)
              $('#output').css('left', e.pageX)
              $('#output').empty();
              $('#output').append('<table>')
         
              $.each(data, function(index, data) {             
                  $('#output').append('<tr><td>ID :' + data._Id + '</td><td>&nbsp;</td><td> Name:' + data._name + '</td><td>&nbsp;</td><td> Address:' + data._address + '</td></tr>');
                  $('#output').append('<tr><td colspan=5 width=' + '2px' + '></td></tr>');

              });
           
              $('#output').append('</table>');
          },
          failure: function(msg) {
              $('#output').text(msg);
          }
      });
  }
</script>

   
   


Here in simple function getDetails() we are calling aspx page getData.aspx page in ajax call
The getData.aspx.vb contains following


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim id = Convert.ToInt32(Request.QueryString("callid"))
        Response.Write(getList(id))
        Response.End()

    End Sub
    Public Function getList(ByVal id As Integer) As String
        Dim str As String
        Dim obj As data = New data()
        If id = 1 Then
            str = obj.createList(id)
        Else
            str = obj.createList()
        End If

        Return str
    End Function

The createList function is placed in data.vb file, the file is like this


Imports Microsoft.VisualBasic
Imports System.Web.Script.Serialization


Public Class data
    Private components As System.ComponentModel.IContainer
    Private _Id As Integer
    Private _name As String
    Private _address As String
    'NOTE: The following procedure is required by the Component Designer
    'It can be modified using the Component Designer.
    'Do not modify it using the code editor.
    Private Sub InitializeComponent()
        components = New System.ComponentModel.Container
    End Sub
    Public Sub New()
        MyBase.New()
        InitializeComponent()
    End Sub
    Public Property Id() As Integer
        Get
            Return _Id
        End Get
        Set(ByVal Value As Integer)
            _Id = Value
        End Set
    End Property
    Public Property name() As String
        Get
            Return _name
        End Get
        Set(ByVal Value As String)
            _name = Value
        End Set
    End Property
    Public Property address() As String
        Get
            Return _address
        End Get
        Set(ByVal Value As String)
            _address = Value
        End Set
    End Property

    Public Sub Add(ByVal Id As Integer, ByVal name As String, ByVal address As String)
        _Id = Id
        _name = name
        _address = address
    End Sub
    Public Function createList() As String
        Dim datalist(3) As data
        Dim str As String
        Dim js As JavaScriptSerializer
        js = New JavaScriptSerializer()
        datalist(0) = New data()
        datalist(1) = New data()
        datalist(2) = New data()
        datalist(3) = New data()
        datalist(0).Add(1, "ABC", "Mumbai")
        datalist(1).Add(1, "PQR", "Mumbai")
        datalist(2).Add(1, "XYZ", "Mumbai")
        datalist(3).Add(1, "DEF", "Mumbai")
        str = js.Serialize(datalist)
        Return str

    End Function

    Public Function createList(ByVal id As Integer) As String
        Dim datalist(3) As data
        Dim str As String
        Dim js As JavaScriptSerializer
        js = New JavaScriptSerializer()
        datalist(0) = New data()
        datalist(1) = New data()
        datalist(2) = New data()
        datalist(3) = New data()
        datalist(0).Add(1, "RK", "Mumbai")
        datalist(1).Add(2, "RK", "Mumbai")
        datalist(2).Add(3, "RD", "Mumbai")
        datalist(3).Add(4, "RD", "Mumbai")
        str = js.Serialize(datalist)
        Return str
    End Function
End Class

Here I will explain you what happens actually ,
The user will click on image button then getDetails() function gets executed. In that we are calling page getData.aspx page through ajax call.
In that page we are creating list and serialized it with javascript Serializer . The data will be look like

[{"_Id":1,"_name":"RK","_address":"Mumbai"},{"_Id":2,"_name":"RK","_address":"Mumbai"},{"_Id":3,"_name":"RD","_address":"Mumbai"},{"_Id":4,"_name":"RD","_address":"Mumbai"}]

we will got this in 'response' after successful execution. Then we will show it in div

This is simple .











Monday 26 December 2011

Google Crome And IE difference

Hi,

Good Afternoon!!
There are so so many differences between Chrome and IE. many of us believed on IE and many on Chrome.
Today I am browsing many pages and 2 Chrome windows are open with many tabs.
I want to copy one url and want to view in second window as this was an answer of another solution which is opened in first window. I just drag this tab (from second window) to tabs of first window and it gets placed in first one.
I tried the same thing in IE. but I couldn't  :(
try it and find out some more difference..

 

Tuesday 20 December 2011

Show/Hide div using jQuery

Jquery is very useful plugin while developing websites. Its well known now. I know , you all are thinking that why
I am posting such simple solution again? this is so simple. Right na,
I am thinking same as you before doing this and checking it on all browsers.
Lets do this,

I have a div by name 'divTest' with some controls which I want to be access in my code page .cs/.vb
for that I need to apply attribute as 'runat=server' , like this


<div id="divTest" runat="server">
-
-
</div>

now jQuery code to hide/ show this div
lets add some more stuff. I want to display div on checkbox checked event

then the jQuery function will be -




 function HideDiv() {
            var ckh = $('#chkTest').attr('checked');
            var row = $('#divTest');     

            if (ckh == true) {
                row.hide();
         
            }
            if (ckh == false) {
                row.show();
            }
            return true;
        }

and finally the checkbox to hide/show div


<asp:CheckBox ID="chkTest" runat="server" onclick="HideDiv();"/>


This is fine.but now the problem comes when we hide this div from my code (.cs/.vb)

I will put simple code


divTest.visible=false

but this is wrong. If you click on checkbox then this will not display your div.
so the solution is

I have to set style of this div like


to hide -  divTest.Style.Add("display", "none") or
to show -  divTest.Style.Add("display", "block")

thats it!!

Happy Programming!!

Hello World!!

Hi ,

I am one of you. A learner, developer..
This blog is space for me to keep my programming ideas, fundas at one place.
Hope this will helps you.....



Happy Programming!!