miércoles, 24 de septiembre de 2014

Filling dropdownlist and filter gridview using Jquery & ASP.NET

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.7.1.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetCustomers",
                data: "{}",
                dataType: "json",
                async: true,
                cache: false,
                success: function (result) {
                    $.each(result.d, function (key, value) {
                        $("#combo").append($("<option></option>").val(value.id).html(value.name));
                    });
                },
                error: function (result) {
                    alert("Error");
                }
            });
        });
    </script>

    <script type="text/javascript">
        function changeIndex() {
            //clear grid rows
            $("[id*=gv] tr").not($("[id*=gv] tr:first-child")).remove();

            fillgrid($("#combo").val());        
        }
    </script>

    <script type="text/javascript">
        function fillgrid(val) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetComplaints",
                data: JSON.stringify({ id: val }),
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    for (var i = 0; i < data.d.length; i++) {
                        $("#gv").append(
                            "<tr><td>" +  data.d[i].complaintId +
                            "</td><td>" + data.d[i].complaintTypeId +
                            "</td><td>" + data.d[i].complaintSubtypeId +
                            "</td><td>" + data.d[i].closureDate +
                            "</td><td>" + data.d[i].expirationDate +
                            "</td><td>" + data.d[i].isActive +
                            "</td><td>" + data.d[i].createdBy +
                            "</td></tr>");
                    }
                },
                error: function (result) {
                    alert("Error");
                }
            });
        };
    </script>

    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="combo" runat="server" onchange="changeIndex();">
            <asp:ListItem Selected="True" Text="Seleccione..." Value="0"></asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
    </div>
        <asp:GridView ID="gv" runat="server"></asp:GridView>
    </form>
</body>
</html>


Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindColumnToGridview();
        }
    }

    public class customer
    {
        public int id { get; set; }
        public string name { get; set; }
    }

    [System.Web.Services.WebMethod]
    public static List<customer> GetCustomers()
    {
        customer cus = new customer();
        List<customer> cuslist = new List<customer>();

        System.Data.DataSet ds;

        using (SqlConnection con = new SqlConnection(
            "Data Source=FACTORY\\FACTORY;User Id=sa;Password=pa$$w0rd;DataBase=SAQ_DEV"))
        {
            using (SqlCommand cmd = new SqlCommand(
                "SELECT DISTINCT c.[CustomerId], c.[FullName] FROM [CMP_Complaint] cc " +
                "INNER JOIN [CUS_Customer] c ON c.CustomerId = cc.CustomerId", con))
            {
                con.Open();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {

                    ds = new DataSet();
                    da.Fill(ds);
                }
            }
        }
        try
        {
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            cuslist.Add(new customer()
                            {
                                id = Convert.ToInt32(dr["CustomerId"]),
                                name = dr["FullName"].ToString()
                            });
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return cuslist;
    }

    public class complaint
    {
        public int complaintId { get; set; }
        public int complaintTypeId { get; set; }
        public int complaintSubtypeId { get; set; }
        public string closureDate { get; set; }
        public string expirationDate { get; set; }
        public int isActive { get; set; }
        public string createdBy { get; set; }
    }

    private void BindColumnToGridview()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id queja");
        dt.Columns.Add("Id tipo de queja");
        dt.Columns.Add("Id subtipo de queja");
        dt.Columns.Add("Fecha de cierre");
        dt.Columns.Add("Fecha de expiracion");
        dt.Columns.Add("Activo");
        dt.Columns.Add("Creador");
        dt.Rows.Add();
        gv.DataSource = dt;
        gv.DataBind();
        gv.Rows[0].Visible = false;
    }

    [System.Web.Services.WebMethod]
    public static List<complaint> GetComplaints(int id)
    {
        complaint cmp = new complaint();
        List<complaint> cmplist = new List<complaint>();

        System.Data.DataSet ds;

        using (SqlConnection con = new SqlConnection(
            "Data Source=FACTORY\\FACTORY;User Id=sa;Password=pa$$w0rd;DataBase=SAQ_DEV"))
        {
            using (SqlCommand cmd = new SqlCommand(
                "SELECT [ComplaintId],[ComplaintTypeId],[ComplaintSubtypeId],[ClosureDate]," +
                "[ExpirationDate],[IsActive],[CreatedBy] FROM [CMP_Complaint] WHERE [CustomerId] = " + 
                id.ToString(), con))
            {
                con.Open();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    ds = new DataSet();
                    da.Fill(ds);
                }
            }
        }
        try
        {
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            try
                            {
                                cmplist.Add(new complaint()
                                {
                                    complaintId = Convert.ToInt32(dr["ComplaintId"]),
                                    complaintTypeId = Convert.ToInt32(dr["ComplaintTypeId"]),
                                    complaintSubtypeId = Convert.ToInt32(dr["ComplaintSubtypeId"]),
                                    closureDate = dr["ClosureDate"].ToString().Substring(0, 
                                                  dr["ClosureDate"].ToString().IndexOf(' ')),
                                    expirationDate = dr["ExpirationDate"].ToString().Substring(0, 
                                                     dr["ExpirationDate"].ToString().IndexOf(' ')),
                                    isActive = Convert.ToInt32(dr["IsActive"]),
                                    createdBy = dr["CreatedBy"].ToString()
                                });
                            }
                            catch { }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return cmplist;
    }
}

Database tables and example data view



Final result



lunes, 22 de septiembre de 2014

Boxing & Unboxing in C#


The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

Boxing Conversion

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Boxing is implicit

// Boxing copies the value of i into object o.
object o = i;

int i = 123;
object o = (object)i;  // explicit boxing



Unboxing Conversion 

Unboxing extracts the value type from the object.

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of: Checking the object instance to make sure that it is a boxed value of the given value type. Copying the value from the instance into the value-type variable.

Unboxing is explicit.

int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing


source: msdn.microsoft.com

viernes, 19 de septiembre de 2014

Twenty C# questions explained

#​1 When do you use structs vs classes?

  • structs are value types that can contain data and functions
  • structs are value types and do not require heap allocation. 
  • structs directly store their data in the struct, classes store a reference to a dynamically allocated object. 
  • structs are useful for small data structures 
  • structs can affect performance
  • Constructors are invoked with the new operator, but that does not allocate memory on the heap
  • A struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
  • With classes, multiple variables may have a reference to the same object
  • It is possible for operations on one variable to affect the object referenced by the other variable.
  • With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. 
  • structs do not support user-specified inheritance, and they implicitly inherit from type object




call to functions




#​How Does One Parse XML Files?

  • Reference System.Xml
  • Use XmlReader to parse the text string
  • You will need to have an idea of the XML elements and attributes for this example
  • Use the XmlReader methods to read the XML data





#​What is the difference between String and string ?

  • No difference but code conventions state that upper case String should be used for class methods.




#​How do I get the application’s path in a C# console app?

  • Use reflection to get the executing assembly path
  • Pass that the IO.Path.GetDirectoryName



#​How do you call a base constructor in C#?

  • Method 1 - Traditional
public InheritTest(string newName) : base(newName) {     }  
  • Method 2 - New
public InheritTest(string name) : base(ModifyBase(name)) {     }  
private static string ModifyBase(string newName) {  return newName.ToUpper();  }









#​How would you count the occurrences of a string within a string?

  • Single character search
- foreach
  • String search
- RegEx

#​How to Check if a Number is a Power of 2?

  • Use binary & operator
  • Converts values to binary
  • Performs logical AND operation on values

1000 - 8
0111 - 7
0000 – 0

1001 – 9
1000 – 8
1000 - 8


#​What is the difference between break and continue in a loop?


  • Break leaves immediately
  • Continue allows loop to continue
  • Place the word loop after each keyword to make sense of it

break loop
continue loop

#​What is the difference between abstract and virtual functions?

  • Abstract methods have no implementation and MUST be overridden
  • Virtual methods MAY have an implementation but are not required to and then CAN be overridden.
  • You cannot call base.method() for abstract but you can for virtual methods



#​10 What is the difference between ref and out keywords?

  • ref causes an argument to be passed by reference not by value.  It provides a reference to the source value and changes made in the method will be made to the source object

- Arguments passed as ref must be initialized before they are passed.

  • out also causes an argument to be passed by reference.  Changes made to the parameter are also changed in the source.

- Arguments passed using out do not have to be initialized first.
- The called method must assign a value prior to the method return statement


#​11 Explain how to encrypt/decrypt a string in .NET?

  • Generate secret key
  • Encrypt string
  • Decrypt string using same key and encryption provider




#​12 How do I get the index of the current iteration of a foreach loop?

  • Maintain a counter and increment it manually
  • Some collection types provide IndexOf()


#​13 How do I get my own IP address in C#?

  • Check private internal IP address
- Use Dns.GetHostEntry, IPAddress, and AddressList
  • Check public external IP address
- Make external calls


#​14 How do I calculate someone's age in C#?

  • Use the DateTime class
  • Get the current date
  • Subtract the birth year from the current year
  • Allow for actual birth month

#​15 How do I get string value of an enum?


  • Use Enum.GetName()
  • Use ToString()


#​16 How do I  make a textbox that only accepts numbers?


  • Use NumericUpDown
  • Handle the KeyPress Event
  • Handle the Text_Changed Event


#​17 How do I  round a decimal value to two places for output?


  • Use string format specifiers
  • ("#.##")
  • ("{0:0.00}", value)
  • ("n2")
  • ("{0:c}", value)


#​18 How do I remove duplicates from an array?


  • Use LINQ
  • Use a List


#​19 How do I sort a dictionary by value?


  • Use LINQ
  • Sorts into a new object


#​20 How do I return multiple values from a function in C#?


  • Using out parameters
  • Using arrays or structs
  • Consider finding min and max values in an array


source: Microsoft MVA