Tuesday, January 17, 2017

Kendo Datasource

module Example.Datasource {
 
    let ds = new kendo.data.DataSource();
    $(() => {
 
        $('#grid').kendoGrid();
 
        $('#btnFillValues').bind('click', fillValues);
        $('#btnViewData').bind('click', showData);
        $('#btnAddTupple').bind('click', addTupple);
        $('#btnRemoveByIndex').bind('click', removeByIndex);
        $('#txtFileterText').bind('keyup', search);
        $('#btnViewFirstIndex').bind('click', getItemByIndex);
        $('#btnInsert').bind('click', insert);
        $('#btnAddToGrid').bind('click', addToGrid);
        $('#btnDeleteFilterdRows').bind('click', searchAndRemove);
        $('#btnSearchAndUpdate').bind('click', searchAndUpdate);
    });
 
    function fillValues() {
 
        var data = [
            { name: "Jane Doe", age: 30 },
            { name: "Chamith Saranga", age: 33 }
        ];
        ds.data(data);
    }
 
    function showData() {
        var view = ds.view();
        $.each(view, (i, d) => {
            console.log(d.name);
        });
        $('#grid').data('kendoGrid').setDataSource(new kendo.data.DataSource({ data: view }));
    }
    function addTupple() {
        ds.add({ name: 'sajeeka', age: 20 });
    }
 
    function removeByIndex() {
        ds.remove(ds.at(0));
    }
 
    function getItemByIndex() {
        var dataItem: any = ds.at(0);
        alert(dataItem.name);
    }
    function removeMultiple() {
        var val = $('#txtFileterText').val();
        //ds.remove(ds.filter({ field: "name", operator: "startswith", value: val }));
    }
 
    //Inserts a data item in the data source at the specified index.
    function insert() {
        ds.insert(1, { name: "Kasun Chathuranga", age: 20 });
        showData();
    }
 
    function search() {
        var val = $('#txtFileterText').val();
        console.log(val);
        ds.filter({ field: "name", operator: "startswith", value: val });
        showData();
    }
 
    function addToGrid() {
 
        ds.insert(0, { name: $('#txtName').val(), age: Number($('#txtAge').val()) });
        showData();
    }
 
    function searchAndRemove() {
 
        $.each(ds.data(), (i, d) => {
            if (d.name === $('#txtFileterText').val()){
                ds.remove(ds.at(i));
            }
        });
        showData();
    }
 
    function searchAndUpdate() {
        $.each(ds.data(), (i, d) => {
            if (d.name === $('#txtFileterText').val()) {
                d.age = 55;
            }
        });
        showData();
    }
}

////////////////////////////
///HTML
///////////////////////////

<!DOCTYPE html>
<html>
<head>
    <title></title>
 <meta charset="utf-8" />
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.rtl.min.css" />
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.silver.min.css" />
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.mobile.all.min.css" />
 
    <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.2.607/js/kendo.all.min.js"></script>
</head>
<body>
    <input type="button" name="name" value="Fill values" id="btnFillValues" />
    <br />
    <input type="button" name="name" value="Add Tupple" id="btnAddTupple" />
    <br />
    <input type="button" name="name" value="view values" id="btnViewData" />
    <br />
    <input type="button" name="name" value="remove by index" id="btnRemoveByIndex" />
    <br />
    <input type="button" name="name" value="view First Index" id="btnViewFirstIndex" />
    <br />
    <input type="button" name="name" value="Insert" id="btnInsert" />
    <br />
    <input type="button" name="name" value="Remove Filted rows" id="btnDeleteFilterdRows" />
    <br />
    <input type="button" name="name" value="Search And Update" id="btnSearchAndUpdate" />
    <hr />
    <h1>Grid View</h1>
    Name : <input type="text" name="name" value="" id="txtName" /> 
    Age : <input type="number" name="name" value="" id="txtAge"/>
    <input type="button" name="name" value="Add"  id="btnAddToGrid"/>
    <br /><br />
    <input type="text" name="name" value="" id="txtFileterText" placeholder="type something to fileter"/>
    <div id="grid"></div>
</body>
 
<script src="../assets/ts/datasource.js"></script>
</html>



Saturday, January 7, 2017

Routing web api

Routing is how Web API matches a URI to an action

Web API used convention-based routing

https://github.com/api2/github/iamchamith/BestPractices/blob/master/Test.ts


[RoutePrefix("api2")]
   public class RoutingExampleController : ApiController
   { 
       [Route("github/{user}/{repo}/blob/master/{file}")]
       public string GetFile(string user,string repo,string file) {
 
           return $"{user}-> {repo}->{file}";
       }
   }

github is must


Route Constraints

[Route("user/{id:int}")]
       public string GetUser(int id)
       {
 
           return "Chamith " + id;
       }


ConstraintDescriptionExample
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
{x:length(1,20)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(10,50)}
regexMatches a regular expression.{x:regex(^\d{3}-\d{3}-\d{4}$)}

Optional URI Parameters and Default Values

Default parameter
public class BooksController : ApiController
{
    [Route("api/books/locale/{lcid:int?}")]
    public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
}
Url parameter
public class BooksController : ApiController
{
    [Route("api/books/locale/{lcid:int=1033}")]
    public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
}
Init routing in application startup 
inside Globle.asax

protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }


Using router table


public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
          // Web API routes
           config.MapHttpAttributeRoutes();
 
           config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
     }
}







DI


Unity


// ui
   public class DIController : ApiController
   {
 
       /*
        -> techniq that helps to inject dependant objects to the class.
        -> why di
           -> reduce tide cupling. and be a losely cuple archi.
           -> core of decuppling in two layers are interface.
        */
 
       private ICustomer cus;
       public DIController(ICustomer _cus) {
           cus = _cus;
       }
       [HttpGet]
       public string Add()
       {
           cus.Add();
           return "added";
       }
   }
 
   // bl
 
   public interface ICustomer {
 
       void Add();
   }
 
   public class Customer:ICustomer
   {
       public string CustomerName { getset; }
 
       private IDal obj;
       public Customer(IDal iobj)
       {
           obj = iobj;
       }
       public void Add()
       {
           obj.Add();
 
       }
   }
 
   // dal
 
   public interface IDal
   {
       void Add();
   }
 
   public class SqlDal : IDal
   {
 
       public void Add()
       {
 
           Console.WriteLine("recode inserted to sql server");
       }
   }
 
   public class OracleDal : IDal
   {
 
       public void Add()
       {
 
           Console.WriteLine("recode inserted to oracle server");
       }
 
   }

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
 
            // Web API routes
            config.MapHttpAttributeRoutes();
 
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
 
            var container = new UnityContainer();
            container.RegisterType<IDalSqlDal>(new HierarchicalLifetimeManager());
            container.RegisterType<IDalOracleDal>(new HierarchicalLifetimeManager());
            container.RegisterType<ICustomerCustomer>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);
        }
    }

///////////////////////////////////////////////////

namespace DependancyInjections.App_Start
{
    public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;
 
        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;
        }
 
        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }
 
        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }
 
        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new UnityResolver(child);
        }
 
        public void Dispose()
        {
            container.Dispose();
        }
    }
 
}


Sql server row level policy