Tuesday, May 26, 2015

jQuery datepicker display format

  $('#txtPrebid').datepicker({
                    dateFormat: 'dd/mm/yy'
                });

Thursday, May 21, 2015

How to add a default “Select” option to this ASP.NET DropDownList control?

Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();

// Then add your first item
DropDownList1.Items.Insert(0, "Select");

Wednesday, May 20, 2015

ASP.NET Get data in json format from code behind

   $.ajax({
                url: baseUrl + "/Admin/GetEnrollment",
                type: "POST",
                contentType: "application/json; charset=UTF-8",
                dataType: "json",
                data: JSON.stringify(model),
                success: function (data) {
}});

[HttpPost]
        public System.Web.Mvc.JsonResult GetEnrollment(SchoolEnrollment model, HttpRequestMessage request)
        {
            IList<SchoolEnrollment> EnrollmentList = new List<SchoolEnrollment>();

            EnrollmentList = admin.GetEnrollment(model);

            var data = new { EnrollmentList };

            return new System.Web.Mvc.JsonResult()
            {
                Data = data,
                JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
            };
        }
  public IList<SchoolEnrollment> GetEnrollment(SchoolEnrollment model)
        {
            return dal.GetEnrollment(model);
        }

 public IList<SchoolEnrollment> GetEnrollment(SchoolEnrollment model)
        {
            IList<SchoolEnrollment> EnrollmentList = new List<SchoolEnrollment>();

            SqlParameter[] sqlParameters = {  SQLHelper.SqlParameter("@PageIndex",SqlDbType.Int, model == null ? 0 : model.PegInfo.PageIndex),
                                              SQLHelper.SqlParameter("@PageSize",SqlDbType.Int,  model == null ? 0 : model.PegInfo.PageSize),
                                             };

            try
            {
                using (SqlDataReader rdr = SQLHelper.ExecuteReader(SQLHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, "[usp]", sqlParameters))
                {
                    while (rdr.Read())
                    {
                        SchoolEnrollment vInfo = new SchoolEnrollment();
                        vInfo.ClassName = Functions.ToString(rdr["description"]);
                        vInfo.SchoolName = Functions.ToString(rdr["school_name"]);
                        vInfo.BoysCount = Functions.ToInt32(rdr["boys_count"]);
                        vInfo.GirlCount = Functions.ToInt32(rdr["girls_count"]);
                        vInfo.SchoolEnrollmentId = Functions.ToInt32(rdr["enrollment_id"]);

                        if (model != null)
                        {
                            if (model.PegInfo != null)
                            {
                                vInfo.PegInfo.PageIndex = model.PegInfo.PageIndex;
                                vInfo.PegInfo.PageSize = model.PegInfo.PageSize;
                                vInfo.PegInfo.TotalRecords = Functions.ToInt32(rdr["record_count"]);
                            }
                        }
                        EnrollmentList.Add(vInfo);
                    }



                    rdr.Close();
                    rdr.Dispose();
                }
                return EnrollmentList;
            }
            catch (Exception ex)
            {
                throw new BaseException(ex.Message, ex);
            }
            finally
            {

            }
        }

Tuesday, May 19, 2015

C# - serialize object to JSON format using JavaScriptSerializer

What is SERIALIZATION?

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

Friday, May 15, 2015

How to shutdown machine from ASP.NET


            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "shutdown";
            startInfo.Arguments = "/s /t 5";
            startInfo.UseShellExecute = true;
            startInfo.Verb = "runas";
            process.StartInfo = startInfo;
            process.Start();

Table column hide/show by checkbox

  function bindCasesTable(pageIndex) {
            var Pegination = {
                PageIndex: pageIndex,
                PageSize: 5,
            }

            var model = { PegInfo: Pegination }
            $.ajax({
                url: baseUrl + 'WS/GetCases',
                type: 'post',
                data: JSON.stringify(model),
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    console.log(data);
                    var strGrid = "<table id='grdCases' class='display' cellspacing='0' width='100%'> <thead> "
                                + "<tr>"
                                + "<th style='display:none;'>Case ID.</th>"
                                + "<th class='RefNo'>Ref. No.</th>"
                                + "<th class='Department'>Department</th>"
                                + "<th class='SubDivision'>Sub Division</th>"
                                + "<th class='WorkName'>Work Name</th>"
                                + "<th class='Activity'>Activity Type</th>"
                                + "<th class='WorkType'>Work Type</th>"
                                + "<th class='ExpectedCompletionDate'>Expected Completion Date</th>"
                                + "<th class='WorkStatus'>Work Status</th>"
                                + "<th class='WorkProgress'>Work Progress(%)</th>"
                                + "<th class='TotalBillPaid'>Total Bill Paid</th>"
                                + "</tr></thead><tbody>";

                    for (var i = 0; i < data.length; i++) {

                        var ExpextedDate = '';
                        if (data[i].ExpectedCompletionDateString == '') {
                            ExpextedDate = '';
                        }
                        else {
                            var tempaaDate = data[i].ExpectedCompletionDateString.split("/");
                            ExpextedDate = tempaaDate[1] + '/' + tempaaDate[0] + '/' + tempaaDate[2];
                        }



                        strGrid += ("<tr onclick=\"RedirectCaseInfoDashboard(" + data[i].CaseId + ")\">" +
                                    "<td style='display:none;'>" + data[i].UpdateStamp + "</td>" +
                                    "<td class='RefNo' style='text-align:center'>" + data[i].CaseRefNum + "</td>" +
                                    "<td class='Department' style='text-align:center'>" + data[i].DepartmentName + "</td>" +
                                    "<td class='SubDivision' style='text-align:left'>" + data[i].SubDivisionName + "</td>" +
                                    "<td class='WorkName' style='text-align:left'>" + data[i].WorkName + "</td>" +
                                    "<td class='Activity' style='text-align:left'>" + data[i].ActivityTypeName + "</td>" +
                                    "<td class='WorkType' style='text-align:left'>" + data[i].WorkTypeName + "</td>" +
                                    "<td class='ExpectedCompletionDate' style='text-align:center'>" + ExpextedDate + "</td>" +
                                    "<td class='WorkStatus' style='text-align:left'>" + data[i].WorkStatusName + "</td>" +
                                    "<td class='WorkProgress' style='text-align:center'>" + data[i].WorkProgress + "</td>" +
                                    "<td class='TotalBillPaid' style='text-align:right'>" + data[i].TotalBillPaid + "</td>" +
                                    "</tr>");
                    }
                    strGrid += "</tbody></table>";

                    var str = document.getElementById('dvAllCases');
                    str.innerHTML = strGrid;

                    $('#grdCases').dataTable({
                        //"scrollY": "400px",
                        "scrollCollapse": false,
                        "paging": false,
                        "info": "",
                        "order": [[0, "desc"]],
                        //"aoColumnDefs": [{ 'bSortable': false, 'aTargets': [0] }, { 'bSortable': false, 'aTargets': [8] }],
                        "columns": [
                            { "width": "2%" },
                            { "width": "8%" },
                            { "width": "5%" },
                            { "width": "9.5%" },
                            { "width": "9.5%" },
                            { "width": "10%" },
                            { "width": "9%" },
                            { "width": "17%" },
                            { "width": "9.4%" },
                            { "width": "12.1%" },
                            { "width": "10%" }

                        ]
                    });
                    if (data.length > 0) {
                        $(".Pager").ASPSnippets_Pager({
                            ActiveCssClass: "current",
                            PagerCssClass: "pager",
                            PageIndex: pageIndex,
                            PageSize: 5,
                            RecordCount: parseInt(data[0].PegInfo.TotalRecords)
                        });
                    }

                    $(".Pager .page").on('click', function () {
                        bindCasesTable(parseInt($(this).attr('page')));
                    });

                    $('#grdCases_filter').hide();
                },
                error: function (x, y, z) {
                    alert(x.err);
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }


 $(function () {
            var $chk = $("#grpChkBox input:checkbox");
            var $tbl = $("#grdCases");

            $chk.prop('checked', true);

            $chk.click(function () {
                var colToHide = $tbl.find("." + $(this).attr("name"));
                $(colToHide).toggle();
            });
        });    


<div id="grpChkBox">
            <input type="checkbox" name="RefNo" class="input" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Ref. No </span>
            <input type="checkbox" name="Department" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Department</span>
            <input type="checkbox" name="SubDivision" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Sub Division </span>
            <input type="checkbox" name="WorkName" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Work Name </span>
            <input type="checkbox" name="Activity" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Activity Type </span>
            <input type="checkbox" name="WorkType" />
            <span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Work Type </span>
            <input type="checkbox" name="ExpectedCompletionDate" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Expected Completion Date </span>
            <input type="checkbox" name="WorkStatus" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Work Status </span>
            <input type="checkbox" name="WorkProgress" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Work Progress </span>
            <input type="checkbox" name="TotalBillPaid" /><span style="font-family: Arial; font-size: small; padding-right: 3px; padding-left: 3px">Total Bill Paid </span>
        </div>

jquery check if checkbox checked or not

    $('#chkrefNo').change(function () {

                if ($(this).prop('checked') == true) {
                    alert('1');
                }
                else {
                    alert('2');
                }
            });

jQuery checkbox change and click event

<input type="checkbox" id="checkbox1" /> <br />
<input type="text" id="textbox1" />


$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function() {
        $('#textbox1').val(this.checked);
    });

    $('#checkbox1').click(function() {
        var self = this;
        setTimeout(function() {
           
            if (!self.checked) {
                var ans = confirm("Are you sure?");
                self.checked = ans;
                $('#textbox1').val(ans.toString());
            }
        }, 0);
    });
});

Thursday, May 14, 2015

Tooltip example - Password strenght,characters in password

<html>
<head>
 <style>
 #foo {
position: absolute;
display: none;
background: White;
border: 1px solid #CCCCCC;
margin-left:3px;
margin-left:4px;
}
          </style>
 <script src="jquery-1.10.2.min.js"></script>

</head>
<body>
  <img class="helpIcoPassword" src="../App_Themes/RxWiki/images/help_icon.png"
            style="padding-right: 5px; cursor: help;" data-tooltip="#foo" /></span>

<div id="foo">
              <span style="color:red;font-size:12px">&nbsp;&nbsp; Password needs to meet the following requirements: <br />
                  &nbsp;&nbsp 1 . 8-20 characters. &nbsp;&nbsp <br />
                   &nbsp;&nbsp 2 . Should have at least 1 uppercase and 1 lowercase characters (A-Z, a-z).  &nbsp;&nbsp
                  <br />
                  &nbsp;&nbsp 3 . Should have at least 1 numeric characters (0-9). &nbsp;&nbsp
                  <br />
                   &nbsp;&nbsp 4 . Should have at least 1 special character (=.*[@#$%/!^&+|?<>,~`;:{}-]). &nbsp;&nbsp</span>
           </div>
    <script>

        $(".helpIcoPassword").hover(function (e) {
            $($(this).data("tooltip")).css({
                left: e.pageX + 1,
                top: e.pageY + 1
            }).stop().show(100);
        }, function () {
            $($(this).data("tooltip")).hide();
        });
    </script>

</body>
</html>

Trigger Example

To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters:
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
   sal_diff number;
BEGIN
   sal_diff := :NEW.salary  - :OLD.salary;
   dbms_output.put_line('Old salary: ' || :OLD.salary);
   dbms_output.put_line('New salary: ' || :NEW.salary);
   dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.

Creating Triggers

The syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name 
{BEFORE | AFTER | INSTEAD OF } 
{INSERT [OR] | UPDATE [OR] | DELETE} 
[OF col_name] 
ON table_name 
[REFERENCING OLD AS o NEW AS n] 
[FOR EACH ROW] 
WHEN (condition)  
DECLARE
   Declaration-statements
BEGIN 
   Executable-statements
EXCEPTION
   Exception-handling-statements
END;
Where,
  • CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with the trigger_name.
  • {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF clause is used for creating trigger on a view.
  • {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
  • [OF col_name]: This specifies the column name that would be updated.
  • [ON table_name]: This specifies the name of the table associated with the trigger.
  • [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML statements, like INSERT, UPDATE, and DELETE.
  • [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.
  • WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid only for row level triggers.

Benefits of Triggers

Triggers can be written for the following purposes:
  • Generating some derived column values automatically
  • Enforcing referential integrity
  • Event logging and storing information on table access
  • Auditing
  • Synchronous replication of tables
  • Imposing security authorizations
  • Preventing invalid transactions

PL/SQL - Triggers

Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events:
  • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
  • A database definition (DDL) statement (CREATE, ALTER, or DROP).
  • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is associated.

To whom choose between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

WCF Rest

  1. To use WCF as WCF REST Service  you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

Difference Between Temporary Table and Table Variable in Sql Server

Difference Between Temporary Table and Table Variable – Summary

Both Temporary Tables (a.k.a # Tables) and Table Variables (a.k.a @ Tables) in Sql Server provide a mechanism for Temporary holding/storage of the result-set for further processing.
Below table lists out some of the major difference between Temporary Table and Table Variable. Each of these differences are explained in-detail with extensive list of examples in the next articles in this series which are listed above.
1. SYNTAX
Below is the sample example of Creating a Temporary Table, Inserting records into it, retrieving the rows from it and then finally dropping the created Temporary Table.
-- Create Temporary Table
CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
--Insert Two records
INSERT INTO #Customer
VALUES(1,'Basavaraj')
INSERT INTO #Customer
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM #Customer
--DROP Temporary Table
DROP TABLE #Customer
GO

Below is the sample example of Declaring a Table Variable, Inserting records into it and retrieving the rows from it.
-- Create Table Variable
DECLARE @Customer TABLE
(
 Id INT,
 Name VARCHAR(50)  
)
--Insert Two records
INSERT INTO @Customer
VALUES(1,'Basavaraj')
INSERT INTO @Customer
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM @Customer
GO
RESULT:
2. MODIFYING STRUCTURE
Temporary Table structure can be changed after it’s creation it implies we can use DDL statements ALTER, CREATE, DROP.
Below script creates a Temporary Table #Customer, adds Address column to it and finally the Temporary Table is dropped.
--Create Temporary Table
CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
GO
--Add Address Column
ALTER TABLE #Customer
ADD Address VARCHAR(400)
GO
--DROP Temporary Table
DROP TABLE #Customer
GO
Table Variables doesn’t support DDL statements like ALTER, CREATE, DROP etc, implies we can’t modify the structure of Table variable nor we can drop it explicitly.
3. STORAGE LOCATION
One of the most common MYTH about Temporary Table & Table Variable is that: Temporary Tables are created in TempDB and Table Variables are created In-Memory. Fact is that both are created in TempDB, below Demos prove this reality.
4. TRANSACTIONS
Temporary Tables honor the explicit transactions defined by the user.Table variables doesn’t participate in the explicit transactions defined by the user.
5. USER DEFINED FUNCTION
Temporary Tables are not allowed in User Defined Functions.Table Variables can be used in User Defined Functions.
6. INDEXES
Temporary table supports adding Indexes explicitly after Temporary Table creation and it can also have the implicit Indexes which are the result of Primary and Unique Key constraint.Table Variables doesn’t allow the explicit addition of Indexes after it’s declaration, the only means is the implicit indexes which are created as a result of the Primary Key or Unique Key constraint defined during Table Variable declaration.
7. SCOPE
There are two types of Temporary Tables, one Local Temporary Tables whose name starts with single # sign and other one is Global Temporary Tables whose name starts with two # signs.Scope of the Local Temporary Table is the session in which it is created and they are dropped automatically once the session ends and we can also drop them explicitly. If a Temporary Table is created within a batch, then it can be accessed within the next batch of the same session. Whereas if a Local Temporary Table is created within a stored procedure then it can be accessed in it’s child stored procedures, but it can’t be accessed outside the stored procedure.Scope of Global Temporary Table is not only to the session which created, but they will visible to all other sessions. They can be dropped explicitly or they will get dropped automatically when the session which created it terminates and none of the other sessions are using it.Scope of the Table variable is the Batch or Stored Procedure in which it is declared. And they can’t be dropped explicitly, they are dropped automatically when batch execution completes or the Stored Procedure execution completes.