Tuesday 20 January 2015

insert,update,delete and select using MVC5 and odata

ODATA CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using Test.Models;

namespace Test.Controllers
{
    /*
    To add a route for this controller, merge these statements into the Register method of the WebApiConfig class. Note that OData URLs are case sensitive.

    using System.Web.Http.OData.Builder;
    using Test.Models;
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<EMP1>("Emp");
    config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
    */
    public class EmpController : ODataController
    {
        private TestEntities db = new TestEntities();

        // GET odata/Emp
        [Queryable]
        public IQueryable<EMP1> GetEmp()
        {
            return db.EMP1;
        }

        // GET odata/Emp(5)
        [Queryable]
        public SingleResult<EMP1> GetEMP1([FromODataUri] int key)
        {
            return SingleResult.Create(db.EMP1.Where(emp1 => emp1.EID == key));
        }

        // PUT odata/Emp(5)
        public IHttpActionResult Put([FromODataUri] int key, EMP1 emp1)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (key != emp1.EID)
            {
                return BadRequest();
            }

            db.Entry(emp1).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EMP1Exists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(emp1);
        }

        // POST odata/Emp
        public IHttpActionResult Post(EMP1 emp1)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.EMP1.Add(emp1);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (EMP1Exists(emp1.EID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return Created(emp1);
        }

        // PATCH odata/Emp(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<EMP1> patch)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            EMP1 emp1 = db.EMP1.Find(key);
            if (emp1 == null)
            {
                return NotFound();
            }

            patch.Patch(emp1);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EMP1Exists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(emp1);
        }

        // DELETE odata/Emp(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            EMP1 emp1 = db.EMP1.Find(key);
            if (emp1 == null)
            {
                return NotFound();
            }

            db.EMP1.Remove(emp1);
            db.SaveChanges();

            return StatusCode(HttpStatusCode.NoContent);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool EMP1Exists(int key)
        {
            return db.EMP1.Count(e => e.EID == key) > 0;
        }
    }
}
WEBAPI CONFIC CODE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
using Test.Models;

namespace Test
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            //builder.EntitySet<EMP1>("Emp");
            //config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
            //config.MapHttpAttributeRoutes();
            builder.EntitySet<EMP1>("Emp");

            config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


INDEX PAGE CODE:

@{
    ViewBag.Title = "Index";
}
<table cellpadding="0" cellspacing="0" align="center" style="left:80px; top:20px; position:relative">
    <tr><td>EID</td><td>:</td><td><input type="text" id="tb1" /></td></tr>
    <tr><td>NAME</td><td>:</td><td><input type="text" id="tb2" /></td></tr>
    <tr>
        <td>&nbsp;</td>
   
        <td>&nbsp;</td>
     
        <td>
         
    <input type="button" id="btn" value="Save" style="width:80px" />&nbsp;<input type="button" id="btn1" value="Update" style="width:80px" />

        </td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>
            <table id="tb" border="1" cellpadding="0" cellspacing="0"></table>
        </td>
    </tr>
</table>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
    function x() {
        $.ajax({
            url: '/odata/Emp',
            contentType: "application/json; charset=utf-8",
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                $('#tb').empty().append("<tr><th>UPDATE</th><th>DELETE</th><th>EID</th><th>NAME</th></tr>");
                for (var i = 0; i < data.value.length; i++)
                    $('#tb').append("<tr><td><a href='#' onclick=z('" + data.value[i].EID + "')>Edit</a></td><td><a href='#' onclick=y('" + data.value[i].EID + "')>Delete</a></td><th>" + data.value[i].EID + "</th><th>" + data.value[i].NAME + "</th></tr>");
            }
        });
    }
    $(
        function () {
            x();
           
            $('#btn1').click(function () {
                $.ajax({
                    url: '/odata/Emp('+m+')',
                    contentType: "application/json; charset=utf-8",
                    type: 'PUT',
                    dataType: 'json',
                    data: "{EID:'" + $('#tb1').val() + "',NAME:'" + $('#tb2').val() + "'}",
                    success: function (data) {
                        alert('Data Updated.')
                        x();
                    }
                });

            });
            $('#btn').click(function () {
                $.ajax({
                    url: '/odata/Emp',
                    contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    dataType: 'json',
                    data: "{EID:'" + $('#tb1').val() + "',NAME:'" + $('#tb2').val() + "'}",
                    success: function (data)
                    {
                        alert('Data Saved.')
                        x();
                    }
                });
             
            });
        }
     
      );
    var m;
    function y(s)
    {
        if (confirm('Do you want to delete it ?'))
        {
            $.ajax({
                url: '/odata/Emp(' + s + ')',
                contentType: "application/json; charset=utf-8",
                type: 'DELETE',
                dataType: 'json',
                success: function () {
                    alert('Data Deleted.')
                    x();
                }
            });
        }
    }
    function z(s) {
        m = s;
        $.ajax({
            url: '/odata/Emp('+s+')',
            contentType: "application/json; charset=utf-8",
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                $('#tb1').val(data.EID);
                $('#tb2').val(data.NAME);
            }
        });
    }
</script>


CURD operation using odata , mvc5 and jtable



Odata code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using Test.Models;

namespace Test.Controllers
{
    /*
    To add a route for this controller, merge these statements into the Register method of the WebApiConfig class. Note that OData URLs are case sensitive.

    using System.Web.Http.OData.Builder;
    using Test.Models;
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<EMP1>("Emp");
    config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
    */
    public class EmpController : ODataController
    {
        private TestEntities db = new TestEntities();

        // GET odata/Emp
        [Queryable]
        public IQueryable<EMP1> GetEmp()
        {
            return db.EMP1;
        }

        // GET odata/Emp(5)
        [Queryable]
        public SingleResult<EMP1> GetEMP1([FromODataUri] int key)
        {
            return SingleResult.Create(db.EMP1.Where(emp1 => emp1.EID == key));
        }

        // PUT odata/Emp(5)
        public IHttpActionResult Put([FromODataUri] int key, EMP1 emp1)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (key != emp1.EID)
            {
                return BadRequest();
            }

            db.Entry(emp1).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EMP1Exists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(emp1);
        }

        // POST odata/Emp
        public IHttpActionResult Post(EMP1 emp1)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.EMP1.Add(emp1);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (EMP1Exists(emp1.EID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return Created(emp1);
        }

        // PATCH odata/Emp(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<EMP1> patch)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            EMP1 emp1 = db.EMP1.Find(key);
            if (emp1 == null)
            {
                return NotFound();
            }

            patch.Patch(emp1);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EMP1Exists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(emp1);
        }

        // DELETE odata/Emp(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            EMP1 emp1 = db.EMP1.Find(key);
            if (emp1 == null)
            {
                return NotFound();
            }

            db.EMP1.Remove(emp1);
            db.SaveChanges();

            return StatusCode(HttpStatusCode.NoContent);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool EMP1Exists(int key)
        {
            return db.EMP1.Count(e => e.EID == key) > 0;
        }
    }

}


WEBAPI confic code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
using Test.Models;

namespace Test
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<EMP1>("Emp");
            config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Wiew Code:



@{

    Layout = null;
}

<body>
   
    <div style="width:100%">
        <div id="EmpContainer"></div>
    </div>
</body>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/jtable/themes/lightcolor/gray/jtable.css" rel="stylesheet" />
<link href="~/jtable/themes/metro/lightgray/jtable.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.js"></script>
<script src="~/jtable/jquery.jtable.min.js"></script>

<script type="text/javascript">
    $(function () {
        $('#EmpContainer').jtable({
            title: 'Employee Information',
            paging: true,
            pageSize: 5,
            sorting: true,
            multiSorting: true,
            defaultSorting: 'EID asc',
            actions: {

                listAction: getListData,
                deleteAction: deleteItem,
                createAction: createItem,
                updateAction: updateItem
            },
            fields: {
              
                EID: {
                    title: 'EID',
                    width: '30%',
                    key: true,
                    create: true,
                    edit: false,
                    list: true
                },
                NAME: {
                    title: 'Name',
                    width: '50%'
                }

            }
        });
        $('#EmpContainer').jtable('load');

        function getListData(postData, jtParams) {
            var ret;
            var query = "/odata/Emp" //root uri
            + "?$select=EID,NAME" //reduce the payload to what we need
            + "&$inlinecount=allpages"
            + "&$skip=" + jtParams.jtStartIndex
            + "&$top=" + jtParams.jtPageSize
             + "&$orderby=" + jtParams.jtSorting.replace(' DESC', ' desc').replace(' ASC', ' asc')
            // + "&$format=json" //give me json... will be used in newer OData
            //+ "&$callback=callback"; //this is my callback for future
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: query,
                    type: 'GET',
                    dataType: 'json',
                    data: postData,
                    success: function (data) {
                        ret = {
                            'Result': "OK",
                            'Records': data.value,
                            'TotalRecordCount': data['odata.count']
                        };
                        $dfd.resolve(ret);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });

        }
        function createItem(postData) {
            var ret;
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '/odata/Emp',
                    type: 'POST',
                    dataType: 'json',
                    data: postData,
                    success: function (data) {
                        ret = {
                            'Result': "OK",
                            'Record': data
                        };
                        $dfd.resolve(ret);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        }

        function updateItem(item) {
            var ret;
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '/odata/Emp(' + getParameterByName(item, 'EID') + ')',
                    type: 'PUT',
                    dataType: 'json',
                    data: item,
                    success: function (data) {
                        ret = {
                            'Result': "OK",
                            'Record': data
                        };
                        $dfd.resolve(ret);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        }

        function getParameterByName(str, name) {
            var sURLVariables = str.split('&');
            for (var i = 0; i < sURLVariables.length; i++) {
                var sParameterName = sURLVariables[i].split('=');
                if (sParameterName[0] == name) {
                    return sParameterName[1];
                }
            }
        }

        function deleteItem(item) {
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '/odata/Emp(' + item.EID + ')',
                    type: 'DELETE',
                    dataType: 'json',
                    data: item,
                    success: function (data) {
                        $dfd.resolve({ 'Result': "OK" });
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        }
    });
</script>



Friday 16 January 2015

how to change the background color of a row in SSRS

write the code in BackgroundColor of  the row of the tablix
=iif(RowNumber(Nothing) Mod 2,"White","#f2f2f2")

Thursday 15 January 2015

multiple checkbox select

 $.ajax({
            type: 'POST',
            url: url,
            cache: false,
            data: { 'reportType': type, 'frequency': frequency },
            dataType: 'json',
            success: function (data) {
                //$('#clients option').remove();
                $('#clients').html('<input id="chkAll" name="chkAll" type="checkbox" onchange="CheckUncheckAll(this)" ><span>All</span><br />');
                $.each(data, function (index, val) {

                    var chk = '<input id="clientList_' + index + '" name="clientList_' + index + '" type="checkbox" value="' + val.Text + '">';
                    var hdn = '<input name="clientList_' + index + '" type="hidden" value="false">';
                    var text = '<label for="clientList_' + index + '">' + val.Text + '</label><br />';
                    $('#clients').append(chk);
                    $('#clients').append(hdn);
                    $('#clients').append(text);
                    $("input[name=frequency]:radio").prop("disabled", false);
                    //                        //$('#clientoptions').append($('<option/>', { value: val.value }).html(val.Text));
                    //                        var optionTag = $('<option></option>');
                    //                        $(optionTag).val(val.Value).text(val.Text);
                    //                        $('#clients').append(optionTag);
                });
                getClientReasonCodes();
                getTantaCommReasonCodes();
            },
            error: function (xhr, msg, err) {
                alert(err);
            }

        });

------------------------------------------
function CheckUncheckAll(chk) {
    $(chk).closest('div').find('input[type=checkbox]').prop('checked', $(chk).prop('checked'));
}

Monday 5 January 2015

Querying Using OData on Web API

Introduction
In this article I am going to explain how to query a Web API.

The Open Data Protocol (OData) is a web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years. OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional web sites.


OData is consistent with the way the web works - it makes a deep commitment to URIs for resource identification and commits to an HTTP-based, uniform interface for interacting with those resources (just like the web). This commitment to core web principles allows OData to enable a new level of data integration and interoperability across a broad range of clients, servers, services, and tools. more

In this article I am using the same application as in the http://www.c-sharpcorner.com/UploadFile/amit12345/mvc-4-web-api-net-4-5/ article.

Let's see how OData is working on Web API.

Now here is our URL http://localhost:40683/api/customer. It's a MVC 4 Web API application. You can download it from the above specified article. You need to change only one thing in the CustomerController class. In the sample Get method the return type is IEnumerable<CustomerModel> so you have to change it to use IQueryable<CustomerModel>.

See the following code.

public IQueryable<CustomerModel> Get()

{
IQueryable<CustomerModel> list = null;
list = (from c in context.Customers
select new CustomerModel { Id = c.Id, Name = c.Name, Salary = (long)c.Salary }).AsQueryable<CustomerModel>();

return list;
}

You can see in the following image that there is data being shown for a Customer in the form of a list; now we fire a query on the list.

ODatawebApi.png


















Let's see what the OData Uri Conventions are.

Query Options
$top
$filter
We can filter data by using this $filter query - http://localhost:40683/api/customer?$filter=Name%20eq%20'Amit'
$skip
If we use $skip only we will get following error. The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.
We can $skip with $orderby query only. - http://localhost:40683/api/customer?$skip=2&$orderby=Name
$orderby
$format)
We can define output format like JSON, XML etc http://localhost:40683/api/customer?$format=xml
$select
You can specify the fields