Wednesday, 28 March 2018

code

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 1;
            string line;
            DataTable dt = new DataTable();
            DataColumn column1 = new DataColumn("Id", System.Type.GetType("System.Int32"));
            DataColumn column2 = new DataColumn("Record", System.Type.GetType("System.String"));

            dt.Columns.Add(column1);
            dt.Columns.Add(column2);

            // Read the file and display it line by line. 
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"E:/Study/Concepts/ConsoleApplication1/ConsoleApplication1/readfile.txt");
            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                DataRow dr = dt.NewRow();
                dr[0] = counter;
                dr[1] = line.ToString();
                dt.Rows.Add(dr);
                counter++;
            }

            file.Close();
            System.Console.WriteLine("There were {0} lines.", counter);
            // Suspend the screen. 
            System.Console.ReadLine();
        }
    }
}

Saturday, 10 March 2018

In mvc have scripts and want to script rendered in footer section

1) _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            @RenderSection("scriptSection", required: false)
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>


2)- Index.cshtml -

@{
    ViewBag.Title = "Home Page";
}

@section scriptSection{
    <script type="text/javascript">alert('hello index page');</script>
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>

3)- Contactus.cshtml

@{
    ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

@section scriptSection{
    <script type="text/javascript">alert('hello contactus page');</script>
}
<address>
    One Microsoft Way<br />
    Redmond, WA 98052-6399<br />
    <abbr title="Phone">P:</abbr>
    425.555.0100
</address>

<address>
    <strong>Support:</strong>   <a href="mailto:Support@example.com">Support@example.com</a><br />
    <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>

4) AboutUs.cshtml

in this page not create scriptSection

Once the running application, script which are witten under scriptSection on Index page will be fired.
Now click on About link script will not get executed because in AboutUs.cshtml we do not create scriptSection and if click on Contact link, script section will be executed.

Note: 
 @RenderSection("scriptSection", required: true)
 if set to required true then in every view like Index/About and ContactUs.cshtml pages we have to create scriptSection{} otherwise when click on About link then it will be throw error and for others link home and Contact it will be worked fine because on both views we have created script section{}.




What is unity of work


How to set response time when called from jquery to invoke server side action

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});
In ajax call do not have any default timeout for request processing and return the 
response. 
In above example, i have set timeout of 3 sec. If the server return response within 3 sec
then success function will be executed otherwise throws error of timeout and error fuction
will be executed.

Why Http is stateless and difference between Http and Https


How to maintain session between Jquery and server


Sql query

Current date is : 10 March 2018

I need 03 Feb 2018

Write sql query

What is using statement in c#

Ques:- Can i write own classes under using statement


The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

Yes, i can write own classes under using statement if the class implements IDisposable interface other wise it will gives error on compile time- 

//XYZ: type used in a using statement must be implicitly convertible to System.IDisposable

Here XYZ is class name

Exp:- 1

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CanWriteCustomClassInUsingStatement
{
    class XYZ
    {
        public void show()
        {
            Console.WriteLine("Testing..");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection con = new SqlConnection())
            {

            }
             
            //for SqlConnection  its perfectly works

            //throws error at compile time 
           / /XYZ: type used in a using statement must be implicitly convertible to System.IDisposable

            using (XYZ x= new XYZ())  
            {

            }
           
        }
    }

}

to remove error class XYZ should be implemented IDisposable interface and implements dispose method.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CanWriteCustomClassInUsingStatement
{
    class XYZ : IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void show()
        {
            Console.WriteLine("Testing..");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection con = new SqlConnection())
            {

            }
            // Now It works perfectly
            using (XYZ x= new XYZ())
            {

            }
        }
    }
}

It internally generates code similar to-

XYZ t = new XYZ ();

try {
    t.show(); 
}
finally {
   t.Dispose();
}

Difference between BasicHttp and WsHttpBinding in wcf


How to call StoredProcedure in web api


Friday, 9 March 2018

Mixed jquery examples

console.log({}+[]); //[object Object]
//================================
console.log({}+{}); //[object Object][object Object]
//================================
console.log(1+'1'); //11
//================================
console.log(1-'1'); //0
//================================
console.log([]+[]); //""
//================================
console.log([]-[]); //0
//================================
console.log([]*[]); //0
//================================
let arrray =[1,2,3,3,4,4,5]; //remove repeated elements

console.log([...new Set(arrray)]);  //[1,2,3,4,5]

//================================

let func = function(){
 
  {
   let l="let";
   var v ="var";
  }
 
  console.log(v); //var
  console.log(l); //error
}

func();
//================================
//to make var and let variable values not accessible outside of the function

let func = function(){
 
 {
    (function(){
       let l="let";
     var v ="var";
   })();
 }

  console.log(v);
  console.log(l);
}

func();
//================================
console.log(5<6<7); //true

console.log(5>6>7); //false
//================================
// true treat as 1
console.log(true < 7); //true
console.log(true > 7); //false
//================================
let X = function(){
  return
  { // after return there should not be any line break if any line break then return; will be treated as do       // not return any thing.
    message:'Hi'
  }
}

console.log(X());  //undefined
//================================
let X = function(){
  return{
    message:'Hi'
  }
}

console.log(X());  //return message:Hi with an object
//================================
let profile = {
  name: 'Ashish'
}


//Object.freeze(profile); //if we freeze the object then further can't modify the existing object
//property values and also can't add new property

profile.name="Ashish Kumar Verma";
profile.age=34;
console.log(profile.name); //disply -Ashish
console.log(profile.age);  // display -undefined

//================================
let profile = {
  name: 'Ashish'
}
//if we use seal() inplace of freeze() method with the current object then we can modifed only existing object property
// but can not add any new property with current object.
Object.seal(profile);
profile.name="Ashish Kumar Verma";
profile.age=34;
console.log(profile.name); //disply -Ashish Kumar Verma
console.log(profile.age);  // display -undefined
//================================
let profile = {
  name: 'Ashish'
}

Object.defineProperty(profile,'age',{
  value:4,
  writable:false // true then modify age value and if false then can not modify values of age
})

profile.name="Verma Kumar Ashish";
profile.age=10;

console.log(profile.name);
console.log(profile.age);


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

function a(){
  return "Hello,Function";
}

const sentance= a 'Hi';
const sentance= a('Hi');
console.log(sentance);//error
//================================
<div contentEditable="true">Ashish</div>
//================================
function y(){
  console.log(this.length);
}

var x={
  length:5,
  method:function(y){
    arguments[0]();
  }
};

x.method(y,1); //2
//================================
const x='constructor';

console.log(x);
console.log(x[x]);
console.log(String(01)); //"1"
console.log(x[x](01)); //"1"

Thursday, 8 March 2018

example of callback function

A callback is a plain javascript function passed to the some function as a argument or option.Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

Case -1

let x = function(){
   console.log('called from inside the function');
};

let y = function(callback){
   console.log('do something');
   callback();
};

y(x) //(index):54 do something
     // called from inside the function
   
  Case -2

   let calculate =function(num1, num2 , calltype){

   if(calltype === 'add'){
     return num1 + num2;
   }else if(calltype === 'multiply'){
     return num1 * num2;
   }
}
   
   
console.log(calculate(2,3, 'add')); //5

console.log(calculate(2,3, 'multiply')); //6

case-3

//better way to implement callback function

let add = function(num1, num2){
   return num1 + num2;
}

let multiply = function(num1, num2){
   return num1 * num2;
}

let dowork = function(num1, num2){
   console.log(`here are two numbers back ${num1} , ${num2}`);
}

let calculate = function(num1, num2, callback){
  return callback(num1, num2);
}
   
   
console.log(calculate(2,3, add)); //5

console.log(calculate(2,3, multiply)); //6

console.log(calculate(2,3, dowork)); //here are two numbers back 2 , 3

console.log(calculate(2,3, function(x,y){ return x-y})); //-1

case -4  //sorting array by call back function

var array =[
             {num:5, str:'apple'},
             {num:7, str:'cabbage'},
             {num:1, str:'ban'}
            ]
         
     array.sort(function(val1 , val2){
   
        //console.log(val1.str);
        //console.log(val2.str);
   
        if(val1.str < val2.str ){
         return -1;
        }else{
          return 1;
        }
     });
   
     console.log(array);
   
         






Example of Promises in javascript

Exp- 1

var promisesToCleanRoom = new Promise(function(resolve, reject){

//login for cleaning room

var IsRoomCleaned = false;

  if(IsRoomCleaned){
     resolve('clean');
  }
  else{
   reject('not clean');
  }
});

promisesToCleanRoom.then(function(fromResolve){
  console.log('Room is' + fromResolve);  //Room is clean
}).catch(function(fromReject){
 console.log('Room is ' +fromReject);   //Room is not clean
});

Exp- 2

let cleanRoom = function(){
    return new Promise(function(resolve, reject){
        resolve('Cleaned the room.')
    });
}

let removeGarbage = function(message){
    return new Promise(function(resolve, reject){
        resolve(message + 'Removed garbage.')
    });
}

let winIceCream = function(message){
    return new Promise(function(resolve, reject){
        resolve(message + 'You won icecream.')
    });
}

//to handle nested promises objects
//Case-1

cleanRoom().then(function(result){
    return removeGarbage(result);
}).then(function(result){
   return winIceCream(result);
}).then(function(result){
   console.log('finished!!'+ result );
});

//Case-2 if all of the function executes successfully then it executes call back function

Promise.all([cleanRoom(),removeGarbage(),winIceCream()]).then(function(){
  console.log('all finished!!');
})

//Case-3 any one of the function executes successfully then it executes call back function

Promise.race([cleanRoom(),removeGarbage(),winIceCream()]).then(function(){
  console.log('one of them is finished!!');
})



Explain call, apply and bind in OOJ


Examples:-

var obj={ num: 2};
var obj1={ num: 5};

var addNum = function(a,b,c){
   return this.num + a+ b +c;         
};


// by call() method associated of two objects
console.log(addNum.call(obj,1,2,3)); //8

// by apply() method
var arr = [1, 2, 3];
console.log(addNum.apply(obj,arr)); //8
console.log(addNum.apply(obj1,arr)); //11


// by bind() method

vr callbybind = addNum.bind(obj);
console.log(callbybind(3,4,5)); //14












aaa

explain closures in javascript

case 1-

var x = function(passed){
  var internal= 2;
  return passed + internal;
};

console.log(x(3));  //5


case-2
note:- removed passed which is passing as argument in x() function

var passed = 3; //lexical scope

var x = function(){
  var internal= 2;
  return passed + internal;
};

console.log(x());  //5

var passed = 4;

console.log(x());  //6


case -3

  var addNum = function(passed){

    var add = function(inner){
       
       return passed + inner;
    };
    
    return add;
};

var addThree = new addNum(3);
//console.dir(addThree); 

var addFour = new addNum(4);
//console.dir(addFour); 


console.log(addThree(1)); //4
console.log(addFour(2)); //6

case - 4
exp -

function expClosure(){
   var counter = 1;
 
   return{
      increment: function(){
        counter++;
      },
      Print: function(){
       console.log(counter);
     }
   }
}

var cl = expClosure();

cl.increment();

cl.Print(); //2

exp:-

var getName = function(firstName, lastName){
   var inititial="Hi, Mr";
 
   var makeFullName = function(){
      return inititial +" " + firstName + " " + lastName;
   }
 
   return makeFullName();
}

var name = getName('Ashish','Verma');
console.log(name);  // Hi, Mr Ashish Verma







Wednesday, 7 March 2018

JavaScript object created pattern

1) Factory pattern-

var personfactory = function(name, age, state){

   var temp = {};
   temp.name = name;
   temp.age = age;
   temp.state = state;
 
   temp.ShowDetails = function(){
     console.log(temp.name +" "+ temp.age +" "+ temp.state);
   }
 
   return temp;
};

var person1 = new personfactory('Ashish',34,'In');
var person2 = new personfactory('Soni',30,'Au');

person1.ShowDetails(); //Ashish 34 In

person2.ShowDetails(); Soni 30 Au

2)- Constructor pattern

var personConstructor = function(name, age){

    this.name = name;
    this.age = age;
 
    this.getDetails = function(){
      console.log(this.name + " " + this.age);
    }
};

var Male = new personConstructor('Ashish',34);
var Female = new personConstructor('geeta',30);

Male.getDetails();  //Ashish 34
Female.getDetails(); //geeta 30

3)- Prototype pattern

var person = function(){

};

  person.prototype.name ="no name";
  person.prototype.age = 0;
  person.prototype.state = "no state";
  person.prototype.showDetails = function(){
  console.log(this.name +" "+ this.age +" "+ this.state);
};

var male = new person();
male.name = "Ashish";
male.age = 34;
male.state = "UP";
male.showDetails(); // Ashish 34 UP

var female = new person();
female.name = "Sonam";
female.age = 30;
female.state = "MP";

female.showDetails();  // Sonam 30  MP

//case1 - female.name = "Sonam"; not commented this line
console.log('name' in female); //true
console.log(female.hasOwnProperty('name')); //true

//case2 - female.name = "Sonam"; is commented this line then it also gives true because it look up property in person object
console.log('name' in female); //true
console.log(female.hasOwnProperty('name')); //false

//case3 - blabla is not having any property with this name either in female or person object
console.log('blabla' in female); //false

note: if comment  //female.name = "Sonam";
then female.showDetails();  will print-  no name 30  MP

4) dynamic prototype pattern

var dynamicPerson = function(name, age, state){
    this.name = name;
    this.age = age;
    this.state = state;
   
    if(typeof this.showDetails !== 'function'){
       dynamicPerson.prototype.showDetails = function(){
         console.log(this.name +" "+ this.age +" "+ this.state);
       };
    }
};

var male = new dynamicPerson('Ashish',34,'Up');
male.showDetails();  //Ashish 34 Up


Tuesday, 6 March 2018

A class can have static constructor and public constructor,If yes then how it will be called

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConstructorCallingStaticAndPublicConstructor
{
    class Program
    {
        static Program()
        {
            Console.WriteLine("static constructor called");
        }

        public Program()
        {
            Console.WriteLine("public constructor called");
        }
        static void Main(string[] args)
        {
            Program p = new Program();

            Console.ReadLine();
        }
    }
}


output:-

static constructor called
public constructor called

Flow of execution:-
Once class is loaded into memory by CLR then static constructor will be called automatically at only once.
now control of execution moves to main method and execute Program p=new Program();
at this point public constructor will be called.

Note: if comment Program p=new Program() line
then only one static contructor will be called when code will be run. 

How to call abstract class constructor. Prove it because can not create instance of abstract class so how it will called.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractClassInterfaceCalled
{
    abstract class Demo
    {
        static Demo()
        {
            Console.WriteLine("static constructor Demo");
        }
        public Demo()
        {
            Console.WriteLine("public constructor Demo");
        }

        public void Show()
        {
            Console.WriteLine("Abstract class Show method");
        }
    }
    class Program : Demo
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Show();
            Console.ReadLine();
        }
    }
}

output:-

static constructor Demo
public constructor Demo
Abstract class Show method

Can inherit class after interface inheritance in c#

Exp like :-   class Program : IA, IB, XYZ

Error -  Base class 'XYZ' must come before any interfaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImplementMultipleInheritanceWithClass
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ImplementMultipleInheritanceWithClass
    {
        public interface IA
        {
            void show();
        }
        public interface IB
        {
            void show();
        }

        public class XYZ
        {
            public void Display()
            {
                Console.WriteLine("Display method");
            }
        }
        class Program : IA, IB, XYZ    //Error -  Base class 'XYZ' must come before any interfaces
        {
            static void Main(string[] args)
            {
                IA ai = new Program();
                ai.show();

                IB bi = new Program();
                bi.show();

                Console.ReadLine();
            }

            void IA.show()
            {
                Console.WriteLine("IA interface method show.");
            }
            void IB.show()
            {
                Console.WriteLine("IB interface method show.");
            }
        }
    }
}

So, how to resolve this error-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImplementMultipleInheritanceWithClass
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ImplementMultipleInheritanceWithClass
    {
        public interface IA
        {
            void show();
        }
        public interface IB
        {
            void show();
        }

        public class XYZ
        {
            public void Display()
            {
                Console.WriteLine("Display method");
            }
        }
        class Program : XYZ, IA, IB  // corrected at this point
        {
            static void Main(string[] args)
            {
                IA ai = new Program();
                ai.show();

                IB bi = new Program();
                bi.show();

                Console.ReadLine();
            }

            void IA.show()
            {
                Console.WriteLine("IA interface method show.");
            }
            void IB.show()
            {
                Console.WriteLine("IB interface method show.");
            }
        }
    }
}

output:-

IA interface method show.
IB interface method show.

How to implement multiple interfaces with same name in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImplementMultipleInterfaceWithSameName
{
    public interface IA
    {
        void show();
    }
    public interface IB
    {
        void show();
    }
    class Program : IA,IB
    {
        static void Main(string[] args)
        {
            IA ai = new Program();
            ai.show();

            IB bi = new Program();
            bi.show();

            Console.ReadLine();
        }

        void IA.show()
        {
            Console.WriteLine("IA interface method show.");
        }
        void IB.show()
        {
            Console.WriteLine("IB interface method show.");
        }
    }
}

output:

IA interface method show.
IB interface method show.

Write a program to print *

Output:-

               *
               * *
               * * *
               * * * *
               * * * * *
                               --- till n length

Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            int length = Convert.ToInt32(Console.ReadLine());
            Console.Write(Environment.NewLine);

            for (int i = 0; i < length; i++)
            {
                string printValues = string.Empty;
                for (int j = 1; j <= i + 1; j++)
                {
                    string printStar= "*";

                    printValues = printValues + " " + printStar;

                    if (i + 1 == j)
                    {
                        Console.WriteLine(printValues);
                    }
                }
            }
            Console.ReadLine();
        }
    }
}


Write a program in c#

Output:-
                1
                1,2
                1,2,3
                1,2,3,4
                1,2,3,4,5

enter user input to print program n length

If i put 5 then program run the length of 5 time.

Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            int length=  Convert.ToInt32(Console.ReadLine()); //enter user input
            Console.Write(Environment.NewLine); //new line

            for (int i = 0; i < length; i++)
            {
                string printValues = string.Empty;
                for (int j = 1; j <= i+1; j++)
                {
                    printValues = printValues + j +",";

                    if(i+1 == j)
                    {
                        if (printValues.Contains(","))
                        {
                            printValues = printValues.Remove(printValues.Length - 1, 1);
                        }
                        Console.WriteLine(printValues);
                    }
                }
            }
            Console.ReadLine();
        }
    }
}



Sunday, 4 March 2018

Create trigger for deleting records from table should inserted into another table in sql server

CREATE TABLE CUSTOMERS_HIST(
ID   INT     NOT NULL,
NAME VARCHAR (50)     NOT NULL
);


CREATE TRIGGER TRG_CUSTOMERS_DEL 
ON Customer
FOR DELETE
AS
     INSERT INTO CUSTOMERS_HIST (ID, NAME)
     SELECT Id, Username
     FROM DELETED


select * from Customer



delete from Customer where id=4



 select * from CUSTOMERS_HIST



Saturday, 3 March 2018

What will be output

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestFunction
{
    class Program
    {
        public static int ShowDetails(var a, dynamic b)
        {
            return (a + b);
        }
        static void Main(string[] args)
        {
            ShowDetails("Ashish", 100);
        }
    }
}

Note:- It will gives compile time error because we can not pass var as a parameter.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestFunction
{
    class Program
    {
        public static int ShowDetails(Object a, dynamic b)
        {
            return (a + b); //need to typecast
        }
        static void Main(string[] args)
        {
             ShowDetails("Ashish", 100); //throw error
             ShowDetails(1, 100); //throw error
        }
    }
}

Difference between let and var in javascript

<script>
    //differnce between let and var in javascript

        function checkVarScope() {
            for (var i = 0; i < 5; i++) {

            }
            console.log(i);
        }

        function checkLetScope() {
            for (let i = 0; i < 5; i++) {
                console.log(i);
            }
            //console.log(i); //throw error i is not defined
        }

        $(document).ready(function () {
           //Initialisation
            let a=100;
            //let a=200; //do not reinitialize again
            var b = 50;
            var b = 60; //reinitialize again and again
            var b = 70;
            //console.log(b);

            //scope-
            checkVarScope(); //in var value is available to the function scope till function(){}.
            checkLetScope(); //in let value is available to the block scope means till for(){}.

            //hoisting
            (function () {
                a = 10;
                console.log(a); //10
                var a;
            })();

            (function () {
                b = 11; //throw error let do not give hoisting feature in javascript
                console.log(b);
                let b;
            })();
        });
</script>

Javascript fundamentals


<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<div>
    <h1>Copy array</h1>
 
    <script>
        $(document).ready(function () {

            var array = [1, 2, 3, 4, 5];
            var array1 = [6, 7, 8];

            var arra2 = [1, 2, 3, 3, 4, 5]; var arra4 = [3, 3];
            var arra3 = [3, 3, 5];
           
            //remove all occurances of 3 from arra2
            //output will be [1,2,4,5]

            function unique(arra2) {
                var result = [];
                $.each(arra2, function (i, e) {
                    if ($.inArray(e, arra4) == -1) result.push(e);
                });
                return result;
            }
            console.log(unique(arra2));
            //------------------------------------------------------------------//
            //remove arra3 elements from arra2
            //output like [1,2,4]

            var newFileredArray = [];
            arra2.filter(function (e, i) { //e= element i= index
                if ($.inArray(e, arra3) == -1) {
                  newFileredArray.push(e);
                }
                return newFileredArray;
            });

            console.log(newFileredArray);

   //------------------------------------------------------------------//

            //remove 3 from array
            var index = array.indexOf(3);
            array.splice(index,1);
            console.log(array);

   //------------------------------------------------------------------//
            //copy array by slice
            var newArray = array.slice(0); //copy array by using slice, starting from 0
            console.log(newArray);

   //------------------------------------------------------------------//
            //if i want to take [1,2,3] from original array
            //can we take by using slice() method
            var newArray1 = array.slice(0,3); //copy array by using slice, starting from 0
            console.log(newArray1);
   //------------------------------------------------------------------//
            //copy array by using ...
            var newArray1 = [...array]
            console.log(newArray1);
   //------------------------------------------------------------------//
            //creating new object of same array. If change new object 0 index value to 10. It does not effect to original
            //array 0 index value
            var array1 = Object.assign({}, array);
            array1[0] = 10;
            console.log(array1[0]);
            console.log(array[0]);
            console.log(array1);
   //------------------------------------------------------------------//
            //combined result of one or more array
            var combineArray = [...array, ...array1]
            console.log(combineArray);
   //------------------------------------------------------------------//
            //object creation in javascript
            var Person = { Id: 1, Name: 'Ashish', Address: 'Chandigarh' };
            console.log(Person.Id + " " + Person.Name);
   //------------------------------------------------------------------//
            //another way of creating object in javascript
            var obj = new Object();
            obj.Id = 101;
            obj.Name = "Aakash";
            console.log(obj.Id + " " + obj.Name);
   //------------------------------------------------------------------//
            //deep copy is point to same reference copy of an object. If any property values is changed into new variable then original object
            //properties values are also changed.
            var deepCopy = Person;
            deepCopy.Name = "Kumar Verma";
            console.log(deepCopy.Id + " " + deepCopy.Name);
            console.log(Person.Id + " " + Person.Name);
   //------------------------------------------------------------------//
            //shallow copy is created by using Object.Create() method. It will create new object with same property name and
            //values but if changed any property values of newly created object then it does not effect on Original object
            //properties values
         
            var shallowCopy = Object.create(Person);
            shallowCopy.Name = "Kumar Verma";
            console.log(shallowCopy.Id + " " + shallowCopy.Name);
            console.log(Person.Id + " " + Person.Name);

   //------------------------------------------------------------------//
            //Object.assign is used to combine both object values into new object
            var persons = { Id: 101, Name: 'Radha' };
            var person1 = { Name: 'Ashish Kumar Verma' };
            var newObj = Object.assign({}, persons, person1);
            console.log(newObj.Id + " " + newObj.Name);
        });
    </script>
</div>

Friday, 2 March 2018

Difference between char,nchar,varchar and nvarchar in sql server

Char Data Type - It can store alphanumeric characters(special characters also). But size of char datatype is fixed. Each character takes 1 bytes in memory. If storing 'Ashish1@!' whose length is 9 but it occupied memory of 20 bytes,rest of 11 bytes is waistage of memory.Maximum size of char is 8000 characters.It store non-unicode values.Char datatype is suitable when we know exact size of data to stored in database. Exp- Gender char(1) for M/F


declare @ch char(20)

set @ch ='Ashish1@!'

select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength




nchar DataType - It can store alphanumeric characters(special characters also). But size of nchar datatype is fixed. Each character takes 2 bytes in memory. If storing 'Ashish1@!' whose length is 9 but it occupied memory of 40 bytes. Maximum size of nchar is 4000 characters.It store unicode & non unicode values.nchar datatype is suitable when we know exact size of data to stored in database.

declare @ch nchar(20)

set @ch ='Ashish1@!'


select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength






Varchar DataType - It can store alphanumeric characters(special characters also). But size of Varchar datatype is not fixed. Each character takes 1 bytes in memory. If storing 'Ashish1@!' whose length is 9 so it occupied memory of 9 bytes only, rest of 11 bytes of memory is free.Maximum size of Varchar is 8000 characters.It store non-unicode values.Varchar datatype is suitable when we do not know exact size of data to stored in database.

declare @ch Varchar(20)

set @ch ='Ashish1@!'


select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength





nVarchar DataType - It can store alphanumeric characters(special characters also). But size of nVarchar datatype is not fixed. Each character takes 2 bytes in memory. If storing 'Ashish1@!' whose length is 9 so it occupied memory of 9*2 = 18 bytes only, rest of 22 bytes of memory is free.Maximum size of nVarchar is 4000 characters.It store unicode & non unicode values.nVarchar datatype is suitable when we do not know exact size of data to stored in database.

declare @ch nVarchar(20)

set @ch ='Ashish1@!'


select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength