Tuesday, May 3, 2016

SQL


get table and SP dependencies



EXEC sp_depends   N'[dbo].[RecItemDates]'

[dbo].[RecItemDates] -- > table name

loop sql table rows


DECLARE @LoopCounter INT = 210, @MaxEmployeeId INT = 401,
        @EmployeeName int = 0;

WHILE(@LoopCounter <= @MaxEmployeeId)
BEGIN
   SELECT @EmployeeName =  [EventDateFacilityTimeslotID]
   FROM RecEventDateFacilityTimeslot WHERE  [EventDateFacilityTimeslotID] = @LoopCounter

   update RecEventDateFacilityTimeslot set [EventScheduleGroupID] =  @EmployeeName
    WHERE  [EventDateFacilityTimeslotID] = @EmployeeName

   PRINT @EmployeeName
   SET @LoopCounter  = @LoopCounter  + 1      
END


second example


declare @table table(
  facilityID int 
)

insert into @table 
select facilityid from  RecFacility 



declare @count int = 0;
select @count = count(*)  from RecFacility
print @count ; 
declare @id int = 0;
While (@count > 0)  
Begin
     Select Top 1 @Id = facilityid From @table  

print @id;

select DefaultBumpInMinutes,DefaultBumpOutMinutes from RecFacility where FacilityID = @id

update RecFacility set DefaultBumpInMinutes = (SELECT  ROUND(((90 -15) * RAND() + 15), 0)) , DefaultBumpOutMinutes = (SELECT  ROUND(((90 -15) * RAND() + 15), 0)) where FacilityID = @id;
 
set @count = @count-1;

delete from @table where facilityid = @id;


End

-------------


select statement with if EXISTS condition 

 IF EXISTS (SELECT * FROM Products WHERE id = ?)
BEGIN

END


========================

database normalization


create database efficiently .

---------------------------------------------


SQL functions 


CREATE FUNCTION dbo.AddFunc(@First int,@Second int)  
RETURNS int   
AS   
-- Returns the stock level for the product.  
BEGIN  
  
    RETURN @First+@Second;  
END;  
GO  


SELECT dbo.AddFunc(10,20); // 30




IS NULL RETURN DEFAULT VALUE 


select EventId,AttachmentName,IsNull(fileName_, 'Unknown Name') as FileName_ from RecEventsAttachments



Alter table add colom inside if condition




IF NOT EXISTS(SELECT * FROM sys.columns  WHERE Name = 'IsSystemGenarated' AND OBJECT_ID = 
OBJECT_ID('SubAccounts'))
                    BEGIN
                         alter table SubAccounts
                        add   IsSystemGenarated bit
                        END;


Create table if not




IF NOT EXISTS ( Select * From sysObjects Where Name ='RecEventTicketTemplate')
                              BEGIN
                              create table RecEventTicketTemplate
                              (
                                  Id int identity(1, 1) primary key,
                                  TemplateName varchar(100),
                                  TemplateContent nvarchar(max),
                                  IsEnable bit,
                                  InsertedTime datetime,
                                  InsertedUser varchar(100)
                              );
                        END




IF check value is exsist 



IF NOT EXISTS (SELECT * FROM RecEventTicketingPlaceHolders WHERE PlaceHolderName = 'A' and PlaceHolderDescription = 'B')
    BEGIN
     print 'yes'
    END
  ELSE
    BEGIN
      PRINT 'NO'
    END






Sunday, May 1, 2016

EF

Create first Simple basic EF - Code first Application

  1. Create console application with EF nuget
  2. create simple class as following
 public class Person
    {
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

 public class Context: DbContext
    {
         // EF is not created database
        public Context(): base(@"Data Source=.;Initial Catalog=EF")
        {
        }
        public DbSet<Person> People { get; set; }
    }

  
 static void Main(string[] args)
    {
      // if not created EF database create it
      using (var context = new Context())
       {
                context.Database.CreateIfNotExists();
       }
  }


now created new database call EF with in sql server . (it is fun and vary easy)

 
primary key was id, and it will be identity colom

Save Tuple in Database


       using (var context = new Context())
            {
                context.People.Add(new Person
                {
                    FirstName = "chamith",
                    LastName = "Sarang",
                    PersonId = 1
                });
                context.SaveChanges();
            }

Select To db

using (var context = new Context())
            {
                var x =  context.People;

                foreach (var item in x.ToList())
                {
                  Console.WriteLine("first name {0} \t last name {1} \t Person id {2} \t",
                    item.FirstName, item.LastName, item.PersonId
                  );
                }
                Console.WriteLine(x.ToString());
            }

console result
first name chamith       last name Sarang        Person id 1
first name chamith       last name Sarang        Person id 2
SELECT
    [Extent1].[PersonId] AS [PersonId],
    [Extent1].[FirstName] AS [FirstName],
    [Extent1].[LastName] AS [LastName]
    FROM [dbo].[People] AS [Extent1]
created


Updating recode

           // update recode
            using (var context = new Context())
            {
                var x = context.People.SingleOrDefault(p => p.PersonId == 2);
                x.FirstName = "sajeeka";
                x.LastName = "nanayakkara";
                context.SaveChanges();
            }

.NET && sql server data type mapping




Domain Headers


check constraint entity framework

EF does not currently support Check constraints.
use following code on code first migration

public override void Up()
{
    // Auto generated code here
    // ...

    // YOUR CUSTOM SQL GOES HERE
    Sql("ALTER TABLE foo ADD CONSTRAINT CK_Some_Check CHECK (SomeDate > '20121110 00:00:00.000'");**
}


Uniq key constrant

[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string Emial{get;set;}

or update uniqkey by migration script .


Call sp from Entity framework 

it is just like dapper
this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);

Entity Framework code first with Data Annotations

 [NotMapped]
Data tyle
 [Column("Name", TypeName="ntext")]
ComplexType
Validation 
[MaxLength(50),MinLength(2)]
[MaxLength(20)] ==  [StringLength(50)]
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Range(typeof(DateTime), "1/1/1966", "1/1/2020")]
[Range(1, 100),DataType(DataType.Currency)]
Time Span (Ask from peter)
  1. use for row versioning.
  2. can use over concurrencyCheck annotation.
  3. none-nullable.
  4. can be have one timeSpan propoerty in db
 [Timestamp]
 public Byte[] TimeStamp { get; set; }
Alias
[Table("StudentMaster")]

[Table("StudentMaster", Schema="Admin")]

[Column("Name")]
public string StudentName { get; set; }
[Column("Name", TypeName="varchar")]
Index

default indexing 
[Index]
public int Rating { get; set; }

Naming Indexing 
 [Index("PostRatingIndex")]
    public int Rating { get; set; }
Multiple Colomn Indexing
  [Index("IX_BlogIdAndRating", 2)]
   public int Rating { get; set; }
[Index("IX_BlogIdAndRating", 1)]
 public int BlogId { get; set; }
Primary Key
[Key]
public int StudentId
Composite Key 
[Key] //composite key
[Colomn(Order = 1)]
public int StudentId{get;set;}
[Key]
[Colomn(Order = 2)]
public int SubjectId{get;set;}
ConcurrencyCheck
 [ConcurrencyCheck, MaxLength(10, ErrorMessage="BloggerName must be 10 characters or less"),MinLength(5)]
 public string BloggerName { get; set; }
if some one read 
BloggerName . mean while some one update to BloggerName.In That case him 
get an exception call 
ConcurrencyCheck. (THAT AVOID CONCURRENCY READ AND UPDATE)


Handle transaction on Entity framework 

we dont want to handle transaction to ef explisitly. cntx.SaveChange(); will handle transactions also

example:
public void DeleteUser(int userId){

 using(var cnt = Context){
   
   try{
    DeleteUserRoles(cnt,userId);
    DeleteUserIdentity(cnt,userId);
   cnt.saveChange();
  }catch{ throw;}

}
}
public void DeleteUserRoles(DbContext cnt,int userId){

  try{
   var user = cnd.UserRoles.Where(p=>p.Id == userId).FirstOrDefault();
   cnt.UserRoles.Remove(user);
  }catch{ throw;}

}
public void DeleteUserIdentity(DbContext cnt,int userId){

try{
  var user = cnd.UserIdentity.Where(p=>p.Id == userId).FirstOrDefault();
 cnt.UserIdentity.Remove(user);
}catch{throw;}
}

Or someting like following 

using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction( ))
    {
        try
        {
            Student std1 = new Student() { StudentName = "newstudent" };
            context.Students.Add(std1);
            context.Database.ExecuteSqlCommand(
                @"UPDATE Student SET StudentName = 'Edited Student Name'" +
                    " WHERE StudentID =1"
                );
            context.Students.Remove(std1);

            //saves all above operations within one transaction
            context.SaveChanges();

            //commit transaction
            dbTran.Commit();
        }
        catch (Exception ex)
        {
            //Rollback transaction if exception occurs
            dbTran.Rollback();
        }

    }

Entity framework with async 




Migration commands

-> enable-migrations
-> add migration nameOfMigration
-> update-database
-> update-database -verbose
   update database with showing executed quary

Create Stored Procedure DbMigration

Sql(@"Alter PROCEDURE SomeSP
               AS
                BEGIN
                   select Getdate() as DateTime;
             END
           GO");





Wednesday, April 27, 2016

Web Api

Web Api Session


//create new class and add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web.SessionState;

namespace AAA.Controllers
{
    public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState
    {
        public SessionableControllerHandler(RouteData routeData)
            : base(routeData)
        { }
    }
    public class SessionStateRouteHandler : IRouteHandler
    {
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            return new SessionableControllerHandler(requestContext.RouteData);
        }
    }
}

-----------
Change default web api router as following


using AAA.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Routing;

namespace AAA
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

-----------------------------------
create and access session as following


  // GET api/<controller>
        public IEnumerable<string> Get()
        {
            if ((HttpContext.Current.Session["SomeData"] as string) == null)
            {
                HttpContext.Current.Session["SomeData"] = "Hello from session";
            }
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return (HttpContext.Current.Session["SomeData"] as string);
        }


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


Web Api Documentation

01) create new web api project with template .
   it will include helpPage as following

\


02) Then enable documentation


  1.   set documentation path in project (project->proporties->build-->output--> xml documantation file ).
  2. set path to App_Data
  3. change    HelpPageConfig and set following to same path.
    config.SetDocumentationProvider(new XmlDocumentationProvider
    (HttpContext.Current.Server.MapPath("~/App_Data/DependancyInjections.xml")));


     now documentation xml file is save on the App_Data folder

/// <summary>
        /// Add Customer
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Add()
        {
            cus.Add();
            return "added";
        }




/////

Authorize filter life cycle.




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

web api return type

web api has 4 return types


  1. void
  2. IHttpActionRersult
  3. HttpResponseMessage
  4. another type

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

Error and Exception handling in web api


public class ExceptionsController : ApiController
    {
 
        public async Task<IHttpActionResult> GetItem(int id)
        {
 
            throw new HttpResponseException(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.Forbidden,
                ReasonPhrase = "item not found",
                Content = new StringContent(string.Format("No product with ID = {0}", id)),
 
            });
        }
        public async Task<HttpResponseMessage> GetProduct(int id)
        {
            if (id == 1)
            {
                var message = string.Format("Product with id = {0} not found", id);
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, new { name = "pencile", id = 2 });
            }
        }
    }

Error Handling in web api 

  • HttpResponseException
    public async Task<IHttpActionResult> GetItem(int id)
           {
     
               throw new HttpResponseException(new HttpResponseMessage
               {
                   StatusCode = HttpStatusCode.Forbidden,
                   ReasonPhrase = "item not found",
                   Content = new StringContent(string.Format("No product with ID = {0}", id)),
     
               });
           }
  • Exception Filters
  • Registering Exception Filters
  • HttpError.
    public async Task<HttpResponseMessage> GetProduct(int id)
          {
              if (id == 1)
              {
                  var message = string.Format("Product with id = {0} not found", id);
                  return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
              }
              else
              {
                  return Request.CreateResponse(HttpStatusCode.OK, new { name = "pencile", id = 2 });
              }
          }
////////////////////////////////

Tracing



public HttpResponseMessage GetTrace() {
 
            ITraceWriter x = Configuration.Services.GetTraceWriter();
            x.Trace(Request, "Category", TraceLevel.Error, $"this is test");
 
            return null;
        }


public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
        config.EnableSystemDiagnosticsTracing();
        traceWriter.IsVerbose = true;

       }
}

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

Enable cors (Cross origin resource sharing)


  1. instrall cors nuget
  2. add following code to webApiConfig--> register method

public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
        config.EnableCors();
         config.EnableCors(New EnableCrosAtribute("*",""));

       }
}


/////////////////////////
INTERVIEW QUESTIONS


  1. what is web api.
    it is service run at iis, handle client http requests.






Thursday, March 17, 2016

Load Partial Content Async

http://improve-mvc-perf-with-async-views.azurewebsites.net/async

View/Index
<script src="~/Scripts/site.js"></script>
<p>
    Below are three sections. Initially they are all computed during the request. We are moving
    the slow ones to their own actions with partial views and loading them via JavaScript asynchronously.
</p>

<div class="news">
    <h3>News (slow)</h3>
    <div class="partialContents" data-url="/AsyncPageLoading/One">
        <img src="http://www.xiconeditor.com/image/icons/loading.gif" /> Loading ...
    </div>
</div>

<div class="popular">
    <h3>Most Popular (slow)</h3>
    <div class="partialContents" data-url="/AsyncPageLoading/two">
        <img src="http://www.xiconeditor.com/image/icons/loading.gif" /> Loading ...
    </div>
</div>
--------------------------------------------

Controller

  // GET: AsyncPageLoading
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult One()
        {
            Thread.Sleep(5000);
            return PartialView();
        }

        public ActionResult Two()
        {
            return PartialView();
        }
------------------
partial view

<h2>One</h2>
Hi
In our previous program we have used Microsoft date picker and we created our own user control and there we made the feature where user can select the date from the picker or user can type the date into the date picker and on the even leave we will format the date according to the format we need. if user enter an invalid date on the leave even we will show a error (validator) to show that the date entered is invalid.

Now in our new module we have used the Telerik date picker and can we do the similar where we allow the user type the date, when you check the attached video in our old date picker as soon as the user click in to the date piker control the date format ("/") get removed and only the numbers left so user can delete and retype.

Since user used to this feature and we want to do the same with the Telerik date picker can you please give me a small sample working code that I can achieve similar feature.

--------------------------
Javascript

/// <reference path="../Scripts/jquery-1.8.2-vsdoc.js" />

var site = site || {};
site.baseUrl = site.baseUrl || "";

$(document).ready(function (e) {

// locate each partial section.
// if it has a URL set, load the contents into the area.

$(".partialContents").each(function(index, item) {
var url = site.baseUrl + $(item).data("url");
if (url && url.length > 0 ) {
$(item).load(url);
}
});

// DEMO ONLY - JUST IGNORE
// Just to make the loading time obvious....
$("a.nav").click(function() {
$("body").html("");
});

});






Monday, March 14, 2016

Convert Json string to C# object



MapPolicySnapshop snap = JsonConvert.DeserializeObject<MapPolicySnapshot>(responseString);
using Newtonsoft.Json;
String To Object
public T StringToObject<T>(string json){
 return JsonConvert.DeserializeObject<T>(responseString);
}

obj
public string ObjectToString(T obj){
   return JsonConvert.DeserializeObject<T>(obj);
}

Tuesday, March 8, 2016

Get elements inside elementes jquary

 <div id="sortable-horizontal" style="width:100%">
            <img src="https://s-media-cache-ak0.pinimg.com/736x/88/70/72/8870729d814f13885f8dc25d9c90111e.jpg"  id="1"/>
            <img src="http://www.dailyfreepsd.com/wp-content/uploads/2013/06/Face-Expression-of-surprise-and-scare-120x120.png" id="2"/>
            <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRxW0ma1d149zo2koacBtH7YUkGQMbVid6QsdhzKjxfwGg2XjQl" id="3"/>
            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Face-kiss.svg/120px-Face-kiss.svg.png"id="4" />
            <img src="http://images.clipshrine.com/getimg/PngThumb-Sad-Face-3301.png" id="5"/>
        </div>

 function GetOrder() {
                    var liIds = $('#sortable-horizontal img').map(function (i, n) {
                        return $(n).attr('id');
                    }).get().join(',');

                    console.log(liIds);
                }

if class
                    var liIds = $('#sortable-horizontal .className').map(function (i, n) {
                        return $(n).attr('id');
                    }).get().join(',');

                    console.log(liIds);
                }

Sql server row level policy