How to create timer using JavaScript? How to set time interval for next call in JavaScript? Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script>
        var inProcessCount =10;
        var myVar = setInterval(myTimer, 3000);
        function myTimer() {
            if (inProcessCount == 10) {
                alert("amit");
            }
            else {
                myStopFunction();
            }
        }

        function myStopFunction() {
            clearInterval(myVar);
        }
    </script>
</head>
<body>

</body>
</html>
Share:

How to count words in a string using JavaScript function? Example

<!DOCTYPE html>
<html>
<body>
    <input type="file" id="myFile" onchange="myFunction()">
    <script>
        function myFunction() {
            debugger
            var x = document.getElementById("myFile");
            var spiltFilename = x.files[0].name.split('.');
            var countFilenameChar = spiltFilename[0].length;
            if (countFilenameChar >= 2)
                alert("Filename should not exceed 200 characters");
        }
    </script>
</body>
</html>

Share:

How to find date differences between two date using JavaScript function? Example

<!DOCTYPE html>
<html>
   <body>
      <script>
         var dateFirst = new Date("11/26/2017");
         var dateSecond = new Date("11/28/2017");

         // time difference
         var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());

         // days difference
         var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

         // difference
         alert(diffDays);
      </script>
   </body>
</html>
Share:

How to set AM/PM in a textbox using JavaScript? Example

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/WebForms/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#test1").keypress(function (e) {
                debugger
                var regex = ["[0-2]",
                "[0-4]",
                ":",
                "[0-5]",
                "[0-9]",
                "(A|P)",
                "M"],
                string = $(this).val() + String.fromCharCode(e.which),
                b = true;
                for (var i = 0; i < string.length; i++) {
                    if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
                        b = false;
                    }
                }
                return b;
            });
        });
    </script>
</head>
<body>
    <form>
        <p>When?</p>
        <input type="text" id="test1" placeholder="hh:mm(AM|PM)" />
    </form>
</body>
</html>

Share:

How to consume Web Services in C#? Example.

Dictionary < string,
string > dictionary = new Dictionary < string,
string > ();
XElement data = new XElement("create-requests", new XElement("create-request", new XElement("servercode", "dev"), new XElement("projectcode", "your code project")));

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://www.google.co.in/");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(data.ToString());
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
 Stream responseStream = response.GetResponseStream();
 string responseStr = new StreamReader(responseStream).ReadToEnd();
}



Share:

What is Cross Page Posting in ASP. NET? Example

Cross Page Posting means you are posting form data from one page to another page. 

By default Asp.net web form page ,button and other controls that cause post back submits current page back to itself.

Example 

TextBox txtStartDate = (TextBox) PreviousPage.FindControl("txtStartDate ");  
Share:

What is COALESCE in SQL Server? Example

COALESCE 

The SQL Coalesce and IsNull functions are used to handle NULL values. 

During the expression evaluation process the NULL values are replaced with the user-defined value.
 
The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.

Example

Select Id,COALESCE (Fullname,Middlename,Lastname) as Name from Employee





Share:

What is Generics in C#? Example.

Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. 

In other words, generics allow you to write a class or method that can work with any data type. 

Example 

class Program
    {
        static void Main(string[] args)
        {
            int [] ar={10,20,30,50,80,60};
            string [] ar1 = { "kul","amit","soham"};
            Student.Show(ar);
            Student.Show(ar1);
            Console.ReadLine();
        }
    }
    static class Student
    {
        public static void Show<T>(T [] ar)
        {
            for (int i = 0; i < ar.Length;i++ )
            {
                Console.WriteLine(ar[i]);
            }
        }
    }
Share:

How to find second highest number in Array in C#? Example.

Example

class Program

{

static void Main(string[] args)

{

int[] ar = {
10,
20,
50,
70,
40,
60,
90,
80
};

Array.Sort(ar);

Array.Reverse(ar);

Console.WriteLine("Second highest number : {0}", ar[1]);

Console.ReadLine();

}

}
Share:

What is the difference between STUFF and REPLACE in SQL Server? Example.

STUFF: Using the stuff function we delete a substring of a certain length of a string and replace it with a new string. 

REPLACE: As the function name replace indicates, the replace function replaces all occurrences of a specific string value with another string.

Example

SELECT STUFF('kul shresth',1,3,'nagar')
SELECT REPLACE('kulshresth kumar','kumar','nagar')
Share:

What is TPL in C#? Example.

Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces. 

The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications.
 
Example

class Program
    {
        static void Main(string[] args)
        {
            //Action delegate 
            Task task1 = new Task(new Action(HelloConsole));

            //anonymous function 
            Task task2 = new Task(delegate
            {
                HelloConsole();
            });

            //lambda expression 
            Task task3 = new Task(() => HelloConsole());

            task1.Start();
            task2.Start();
            task3.Start();

            Console.WriteLine("Main method complete. Press any key to finish.");
            Console.ReadKey(); 
        }
        static void HelloConsole()
        {
            Console.WriteLine("Hello Task");
        } 
    }
Share:

What is Channel Factory C#? Example.

Channel Factory enables you to create a communication channel to the service without a proxy. 

Channel Factory that creates and manages the various types of channels which are used by a client to send a message to various configured service endpoints.
   
Example 

class FactoryPatternCurrent
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("enter your vehicles");
                string str = Console.ReadLine();
                Factory obj = new Factory();
                obj.CreateObj(str).Name();
                Console.ReadKey();
            }

        }
    }
    class Factory
    {
        public Vehicles CreateObj(string type)
        {
            Vehicles obj = null;
            switch (type)
            {
                case "car":
                    obj = new Car();
                    break;
                case "bike":
                    obj = new Bike();
                    break;
                default:
                    obj = new Car();
                    break;
            }
            return obj;
        }
    }
    interface Vehicles
    {
        void Name();
    }

    class Car : Vehicles
    {
        public void Name()
        {
            Console.WriteLine("WagonR");
        }
    }
    class Bike : Vehicles
    {
        public void Name()
        {
            Console.WriteLine("Activa");
        }
    }
Share:

What is difference between Singleton and Static class in C#? Example.

Singleton:- allows a class for which there is just one, persistent instance across the lifetime of an application. 

Static class :-allows only static methods and and you cannot pass static class as parameter. 

Singleton :-can implement interfaces, inherit from other classes and allow inheritance.

A- Singleton objects are stored in Heap, but static objects are stored in stack

B-We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object.

C-Singleton classes follow the OOP (object oriented principles), static classes do not.

D-We can implement an interface with a Singleton class, but a class's static 
methods (Example:- a C# static class) cannot.


Important  :- Static Classes have only one object life, Hence we cannot create multiple objects of 
static classes but normal classes can be instantiated for creating many objects of the same class.

We use Static classes in scenarios in like creating a utilities class, implementing a singleton pattern.








Share:

What is use of Anonymous methods in C#? Example.

Anonymous methods provide a technique to pass a code block as a delegate parameter.

Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method.

It is inferred from the return statement inside the method body.

Example 

public delegate void Print(int value);

static void Main(string[] args)
{
    Print print = delegate(int val) 
    {
        Console.WriteLine("Inside Anonymous method. Value: {0}", val);
    };

    print(100);
}
Share:

How many types of backup in sql server? Example.

Where to Backup : Shared Drive , Storage Server,Cloud, Tapes, Dat Drives ,Logical

1: Normal Backup (Whole Backup) Full Backup once in week or month
2: Incremental Backup  (After Changes)
3: Differential Backup
4: Copy Backup (Full Backup)
5: Daily Backup (Creation or modification date of current date)

Files : Archive Bit (Off)
Change :  On after changes
Share:

How to delete duplicate rows using CTC in SQL? Example.

SELECT name ,COUNT(*) AS NumberOfTime FROM emp55 GROUP BY name HAVING COUNT(*)>1

WITH CTE AS 

 SELECT name,salary,ROW_NUMBER() OVER (PARTITION BY name ORDER BY salary) AS rn FROM Emp55

DELETE FROM CTE WHERE rn >1 
Share:

What is pivot in sql server? Example.

SELECT [Year], Kul,Amit,Raj FROM 
(SELECT Name, [Year] , Sales FROM Emp44 )Tab1 
PIVOT 

SUM(Sales) FOR Name IN (Kul,Amit,Raj)) AS Tab2 
ORDER BY [Tab2].[Year] 
Share:

How to get running total in sql server? Example.

create table #temp (id int identity,name varchar(50),department varchar(50),salary decimal,TotalRunningSalary decimal)
insert into #temp(name,department,salary) select e1.Name,e2.Department,e2.Salary from employee e1
inner join  EmployeeDetails e2 on e1.id=e2.did
select * from #temp

declare @total int
set @total = 0
update #temp set TotalRunningSalary = @total, @total = @total + salary
select * from #temp
order by id
drop table #temp

Share:

How to find second highest salary in each department in sql server? Example.

select e1.Name,e2.Department,e2.Salary from employee e1
inner join  EmployeeDetails e2 on e1.id=e2.did

select Name,Department,Salary from (
select e1.Name,e2.Department,e2.Salary, dense_rank() over(PARTITION by e2.Department order by e2.Salary desc) as Rank from employee e1
inner join  EmployeeDetails e2 on e1.id=e2.did
) T
where T.Rank=2;
Share:

How to crack Wi-Fi password? Example.

If want to use. Comment please.

netsh wlan show profile name=YourWiFiName key=clear
Share:

Stylish Tooltip in Bootstrap

Example 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container">
        <br /><br /><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="right">Kulshresth Nagar</a><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="left" style="margin-left: 40px">Kulshresth Nagar</a><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="top">Kulshresth Nagar</a><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="bottom">Kulshresth Nagar</a>
    </div>
    <script>
        $(document).ready(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>
</body>
</html>
Share:

Bootstrap Modal Popup. Example.

Example 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container">
        <h1 class="text-center text-white bg-dark" >Kulshresth</h1>
        <button class="btn btn-success" data-target="#mymodal" data-toggle="modal">Sign Up</button>
        <div class="modal" id="mymodal">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="text-center text-primary">Sign Up</h3>
                        <button type="button" class="close" data-dismiss="modal">  &times;  </button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label><i class="fa fa-user fa-2x"></i> Username : </label>
                                <input type="text" name="username" class="form-control" />
                            </div>
                            <div class="form-group">
                                <label><i class="fa fa-lock fa-2x"></i> Password : </label>
                                <input type="password" name="password" class="form-control" />
                            </div>
                            <div class="form-group">
                                <label><i class="fa fa-envelope fa-2x"></i> Email : </label>
                                <input type="text" name="email" class="form-control" />
                            </div>


                        </form>
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button class="btn btn-danger " data-dismiss="modal">Submit</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Share:

What is Selector in JavaScript? Example.

Selectors are used to "find" (select) HTML elements based on their tag name, id, classes, types, attributes, values of attributes and much more. 

A list of all selectors can be found in our CSS Selector Reference.

Example 

Type Selector:-

p{
  color : red;
}

Class Selector:-

.head{
   color:green;
}

Id Selector:-

#Box{
   color: yellow;
}

Universal Selector:-

*{
   margin:0;
   padding:0;
}
Share:

When use Interface and Abstract class? Example.

An abstract class allows you to create functionality that subclasses can implement or override. 


An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.










Share:

Difference between == and .Equals method in C#. Example.

The Equals() method compares only content.

Example

using System;
namespace ComparisionExample {
   class Program { 
      static void Main(string[] args) { 
         string str = "hello"; 
         string str2 = str; 
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: True
Using equals() method: True

The Equality operator is used to compare the reference identity.

Example

using System;
namespace Demo {
   class Program { 
      static void Main(string[] args) { 
         object str = "hello";
         char[] values = {'h','e','l','l','o'};
         object str2 = new string(values);         
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: False
Using equals() method: True
Share:

What is Generics in C#? Example.

Question 1. What Is Generics?
Answer :
Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that allows us to write codes that works for any data types.
Question 2. What Is A Generic Class?
Answer :
A generic class is a special kind of class that can handle any types of data. We specify the data types during the object creations of that class. It is declared with the bracket <>. For example consider the following Comparer class, which has a method that compare two value and returns as Boolean output.
public class Comparer
{
    public bool Compare(Unknown t1, Unknown t2)
  {  
         if (t1.Equals(t2))
      {
            return true;
        }
        else
        {
            return false;
        }
    }
}
Comparer oComparerInt = new Comparer();
Console.WriteLine(oComparerInt.Compare(10, 10));
Comparer oComparerStr = new Comparer();
Console.WriteLine(oComparerStr.Compare("jdhsjhds", "10"));
Question 3. Why We Should Use Generics?
Answer :
Generic provides lot of advantages during programming. We should use generics for the following reasons:
It allows creating class, methods which are type-safe
It is faster. Because it reduce boxing/un-boxing
It increase the code performance
It helps to maximize code reuse, and type safety
Share:

What is Serialization in C#? Example.

Answer :
When we want to transport an object through network then we need to convert the object into a stream of bytes. Serialization is a process to convert a complex objects into stream of bytes for storage (database, file, cache, etc) or transfer. Its main purpose is to save the state of an object.
De-serialization is the reverse process of creating an object from a stream of bytes to their original form.
Question 2. What Are The Types Of Serialization?
Answer :
The types of Serializations are given bellow:
1  Binary Serialization
            In this process all the public, private, read only members are serialized and convert into stream of bytes. This is used when we want a complete conversion of our objects.
2  SOAP Serialization
           In this process only public members are converted into SOAP format. This is used in web services.
3  XML Serialization
            In this process only public members are converted into XML. This is a custom serialization. Required namespaces: System.Xml, System.Xml.Serialization.
Question 3. Why Serialization And Deserialization?
Answer :
For example consider, we have a very complex object and we need XML format to show it on HTML page. Then we can create a XML file in the disk, writes all the necessary data on the XML file, and use it for the HTML page. But this is not good approach for large number of users. Extra space is required; anyone can see the XML file which creates security issue. We can overcome it by using XML serialization.
Question 4. When To Use Serialization?
Answer :
Serialization is used in the following purposes:
To pass an object from on application to another
In SOAP based web services
To transfer data through cross platforms, cross devices
Share:

HTTP Error Code's

200 OK — This is most commonly used HTTP code to show that the operation performed is successful.
201 CREATED — This can be used when you use the POST method to create a new resource.
202 ACCEPTED — This can be used to acknowledge the request sent to the server.
400 BAD REQUEST — This can be used when client-side input validation fails.
401 UNAUTHORIZED / 403 FORBIDDEN— This can be used if the user or the system is not authorized to perform a certain operation.
404 NOT FOUND— This can be used if you are looking for a certain resource and it is not available in the system.
500 INTERNAL SERVER ERROR — This should never be thrown explicitly but might occur if the system fails.
502 BAD GATEWAY — This can be used if the server received an invalid response from the upstream server.
Share:

What is the difference between Rest and Soap in C#? Example.

SOAP
SOAP is a protocol.
SOAP stands for Simple Object Access Protocol.
SOAP can't use REST because it is a protocol.
SOAP uses services interfaces to expose the business logic.
SOAP defines standards to be strictly followed.
SOAP requires more bandwidth and resource than REST.
SOAP defines its own security.
SOAP permits XML data format only.
SOAP is less preferred than REST.
REST
REST is an architectural style.
REST stands for Representational State Transfer.
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.
REST uses URI to expose business logic.
REST does not define too much standards like SOAP.
REST requires less bandwidth and resource than SOAP.
RESTful web services inherits security measures from the underlying transport.
REST permits different data format such as Plain text, HTML, XML, JSON etc.
REST more preferred than SOAP.
Share:

What is the difference between Dictionary And Hashtable in C#? Example.

Dictionary
Dictionary is generic type Dictionary<TKey,TValue>
Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types for key and value.
There is no need of boxing/unboxing.
When you try to access non existing key dictionary, it gives runtime error.
Dictionary maintains an order of the stored values.
There is no need of boxing/unboxing, so it is faster than Hashtable.
Hashtable
Hashtable is non-generic type.
Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
Values need to have boxing/unboxing.
When you try to access non existing key Hashtable, it gives null values.
Hashtable never maintains an order of the stored values.
Hashtable needs boxing/unboxing, so it is slower than Dictionary.

Share:

What is Object and Collection initialization in C#? Example.

class Program
    {
        static void Main(string[] args)
        {
            List<Employee> emp = new List<Employee> {
                new Employee{Name="Kulshresth0",Address="Noida0"},
                new Employee{Name="Kulshresth1",Address="Noida1"},
                new Employee{Name="Kulshresth2",Address="Noida2"},
                new Employee{Name="Kulshresth3",Address="Noida3"},
            };
            foreach(Employee em in emp)
            {
                Console.WriteLine("Name : "+em.Name +" "+"Address : "+em.Address);
            }
            Console.ReadLine();
        }
    }-----------------------------

class  Employee
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }
Share:

Thursday, 21 November 2019

How to create timer using JavaScript? How to set time interval for next call in JavaScript? Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script>
        var inProcessCount =10;
        var myVar = setInterval(myTimer, 3000);
        function myTimer() {
            if (inProcessCount == 10) {
                alert("amit");
            }
            else {
                myStopFunction();
            }
        }

        function myStopFunction() {
            clearInterval(myVar);
        }
    </script>
</head>
<body>

</body>
</html>

How to count words in a string using JavaScript function? Example

<!DOCTYPE html>
<html>
<body>
    <input type="file" id="myFile" onchange="myFunction()">
    <script>
        function myFunction() {
            debugger
            var x = document.getElementById("myFile");
            var spiltFilename = x.files[0].name.split('.');
            var countFilenameChar = spiltFilename[0].length;
            if (countFilenameChar >= 2)
                alert("Filename should not exceed 200 characters");
        }
    </script>
</body>
</html>

Monday, 18 November 2019

How to find date differences between two date using JavaScript function? Example

<!DOCTYPE html>
<html>
   <body>
      <script>
         var dateFirst = new Date("11/26/2017");
         var dateSecond = new Date("11/28/2017");

         // time difference
         var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());

         // days difference
         var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

         // difference
         alert(diffDays);
      </script>
   </body>
</html>

Tuesday, 22 October 2019

How to set AM/PM in a textbox using JavaScript? Example

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/WebForms/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#test1").keypress(function (e) {
                debugger
                var regex = ["[0-2]",
                "[0-4]",
                ":",
                "[0-5]",
                "[0-9]",
                "(A|P)",
                "M"],
                string = $(this).val() + String.fromCharCode(e.which),
                b = true;
                for (var i = 0; i < string.length; i++) {
                    if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
                        b = false;
                    }
                }
                return b;
            });
        });
    </script>
</head>
<body>
    <form>
        <p>When?</p>
        <input type="text" id="test1" placeholder="hh:mm(AM|PM)" />
    </form>
</body>
</html>

Friday, 18 October 2019

How to consume Web Services in C#? Example.

Dictionary < string,
string > dictionary = new Dictionary < string,
string > ();
XElement data = new XElement("create-requests", new XElement("create-request", new XElement("servercode", "dev"), new XElement("projectcode", "your code project")));

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://www.google.co.in/");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(data.ToString());
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
 Stream responseStream = response.GetResponseStream();
 string responseStr = new StreamReader(responseStream).ReadToEnd();
}



Tuesday, 10 September 2019

What is Cross Page Posting in ASP. NET? Example

Cross Page Posting means you are posting form data from one page to another page. 

By default Asp.net web form page ,button and other controls that cause post back submits current page back to itself.

Example 

TextBox txtStartDate = (TextBox) PreviousPage.FindControl("txtStartDate ");  

What is COALESCE in SQL Server? Example

COALESCE 

The SQL Coalesce and IsNull functions are used to handle NULL values. 

During the expression evaluation process the NULL values are replaced with the user-defined value.
 
The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.

Example

Select Id,COALESCE (Fullname,Middlename,Lastname) as Name from Employee





Saturday, 7 September 2019

What is Generics in C#? Example.

Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. 

In other words, generics allow you to write a class or method that can work with any data type. 

Example 

class Program
    {
        static void Main(string[] args)
        {
            int [] ar={10,20,30,50,80,60};
            string [] ar1 = { "kul","amit","soham"};
            Student.Show(ar);
            Student.Show(ar1);
            Console.ReadLine();
        }
    }
    static class Student
    {
        public static void Show<T>(T [] ar)
        {
            for (int i = 0; i < ar.Length;i++ )
            {
                Console.WriteLine(ar[i]);
            }
        }
    }

Thursday, 5 September 2019

How to find second highest number in Array in C#? Example.

Example

class Program

{

static void Main(string[] args)

{

int[] ar = {
10,
20,
50,
70,
40,
60,
90,
80
};

Array.Sort(ar);

Array.Reverse(ar);

Console.WriteLine("Second highest number : {0}", ar[1]);

Console.ReadLine();

}

}

What is the difference between STUFF and REPLACE in SQL Server? Example.

STUFF: Using the stuff function we delete a substring of a certain length of a string and replace it with a new string. 

REPLACE: As the function name replace indicates, the replace function replaces all occurrences of a specific string value with another string.

Example

SELECT STUFF('kul shresth',1,3,'nagar')
SELECT REPLACE('kulshresth kumar','kumar','nagar')

Wednesday, 4 September 2019

What is TPL in C#? Example.

Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces. 

The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications.
 
Example

class Program
    {
        static void Main(string[] args)
        {
            //Action delegate 
            Task task1 = new Task(new Action(HelloConsole));

            //anonymous function 
            Task task2 = new Task(delegate
            {
                HelloConsole();
            });

            //lambda expression 
            Task task3 = new Task(() => HelloConsole());

            task1.Start();
            task2.Start();
            task3.Start();

            Console.WriteLine("Main method complete. Press any key to finish.");
            Console.ReadKey(); 
        }
        static void HelloConsole()
        {
            Console.WriteLine("Hello Task");
        } 
    }

What is Channel Factory C#? Example.

Channel Factory enables you to create a communication channel to the service without a proxy. 

Channel Factory that creates and manages the various types of channels which are used by a client to send a message to various configured service endpoints.
   
Example 

class FactoryPatternCurrent
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("enter your vehicles");
                string str = Console.ReadLine();
                Factory obj = new Factory();
                obj.CreateObj(str).Name();
                Console.ReadKey();
            }

        }
    }
    class Factory
    {
        public Vehicles CreateObj(string type)
        {
            Vehicles obj = null;
            switch (type)
            {
                case "car":
                    obj = new Car();
                    break;
                case "bike":
                    obj = new Bike();
                    break;
                default:
                    obj = new Car();
                    break;
            }
            return obj;
        }
    }
    interface Vehicles
    {
        void Name();
    }

    class Car : Vehicles
    {
        public void Name()
        {
            Console.WriteLine("WagonR");
        }
    }
    class Bike : Vehicles
    {
        public void Name()
        {
            Console.WriteLine("Activa");
        }
    }

What is difference between Singleton and Static class in C#? Example.

Singleton:- allows a class for which there is just one, persistent instance across the lifetime of an application. 

Static class :-allows only static methods and and you cannot pass static class as parameter. 

Singleton :-can implement interfaces, inherit from other classes and allow inheritance.

A- Singleton objects are stored in Heap, but static objects are stored in stack

B-We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object.

C-Singleton classes follow the OOP (object oriented principles), static classes do not.

D-We can implement an interface with a Singleton class, but a class's static 
methods (Example:- a C# static class) cannot.


Important  :- Static Classes have only one object life, Hence we cannot create multiple objects of 
static classes but normal classes can be instantiated for creating many objects of the same class.

We use Static classes in scenarios in like creating a utilities class, implementing a singleton pattern.








Tuesday, 3 September 2019

What is use of Anonymous methods in C#? Example.

Anonymous methods provide a technique to pass a code block as a delegate parameter.

Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method.

It is inferred from the return statement inside the method body.

Example 

public delegate void Print(int value);

static void Main(string[] args)
{
    Print print = delegate(int val) 
    {
        Console.WriteLine("Inside Anonymous method. Value: {0}", val);
    };

    print(100);
}

Saturday, 31 August 2019

How many types of backup in sql server? Example.

Where to Backup : Shared Drive , Storage Server,Cloud, Tapes, Dat Drives ,Logical

1: Normal Backup (Whole Backup) Full Backup once in week or month
2: Incremental Backup  (After Changes)
3: Differential Backup
4: Copy Backup (Full Backup)
5: Daily Backup (Creation or modification date of current date)

Files : Archive Bit (Off)
Change :  On after changes

How to delete duplicate rows using CTC in SQL? Example.

SELECT name ,COUNT(*) AS NumberOfTime FROM emp55 GROUP BY name HAVING COUNT(*)>1

WITH CTE AS 

 SELECT name,salary,ROW_NUMBER() OVER (PARTITION BY name ORDER BY salary) AS rn FROM Emp55

DELETE FROM CTE WHERE rn >1 

What is pivot in sql server? Example.

SELECT [Year], Kul,Amit,Raj FROM 
(SELECT Name, [Year] , Sales FROM Emp44 )Tab1 
PIVOT 

SUM(Sales) FOR Name IN (Kul,Amit,Raj)) AS Tab2 
ORDER BY [Tab2].[Year] 

How to get running total in sql server? Example.

create table #temp (id int identity,name varchar(50),department varchar(50),salary decimal,TotalRunningSalary decimal)
insert into #temp(name,department,salary) select e1.Name,e2.Department,e2.Salary from employee e1
inner join  EmployeeDetails e2 on e1.id=e2.did
select * from #temp

declare @total int
set @total = 0
update #temp set TotalRunningSalary = @total, @total = @total + salary
select * from #temp
order by id
drop table #temp

How to find second highest salary in each department in sql server? Example.

select e1.Name,e2.Department,e2.Salary from employee e1
inner join  EmployeeDetails e2 on e1.id=e2.did

select Name,Department,Salary from (
select e1.Name,e2.Department,e2.Salary, dense_rank() over(PARTITION by e2.Department order by e2.Salary desc) as Rank from employee e1
inner join  EmployeeDetails e2 on e1.id=e2.did
) T
where T.Rank=2;

Friday, 12 July 2019

Thursday, 11 July 2019

Stylish Tooltip in Bootstrap

Example 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container">
        <br /><br /><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="right">Kulshresth Nagar</a><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="left" style="margin-left: 40px">Kulshresth Nagar</a><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="top">Kulshresth Nagar</a><br /><br />
        <a href="#" title="Software Developer" data-toggle="tooltip" data-placement="bottom">Kulshresth Nagar</a>
    </div>
    <script>
        $(document).ready(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>
</body>
</html>

Bootstrap Modal Popup. Example.

Example 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container">
        <h1 class="text-center text-white bg-dark" >Kulshresth</h1>
        <button class="btn btn-success" data-target="#mymodal" data-toggle="modal">Sign Up</button>
        <div class="modal" id="mymodal">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="text-center text-primary">Sign Up</h3>
                        <button type="button" class="close" data-dismiss="modal">  &times;  </button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label><i class="fa fa-user fa-2x"></i> Username : </label>
                                <input type="text" name="username" class="form-control" />
                            </div>
                            <div class="form-group">
                                <label><i class="fa fa-lock fa-2x"></i> Password : </label>
                                <input type="password" name="password" class="form-control" />
                            </div>
                            <div class="form-group">
                                <label><i class="fa fa-envelope fa-2x"></i> Email : </label>
                                <input type="text" name="email" class="form-control" />
                            </div>


                        </form>
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button class="btn btn-danger " data-dismiss="modal">Submit</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Thursday, 4 July 2019

What is Selector in JavaScript? Example.

Selectors are used to "find" (select) HTML elements based on their tag name, id, classes, types, attributes, values of attributes and much more. 

A list of all selectors can be found in our CSS Selector Reference.

Example 

Type Selector:-

p{
  color : red;
}

Class Selector:-

.head{
   color:green;
}

Id Selector:-

#Box{
   color: yellow;
}

Universal Selector:-

*{
   margin:0;
   padding:0;
}

Tuesday, 2 July 2019

When use Interface and Abstract class? Example.

An abstract class allows you to create functionality that subclasses can implement or override. 


An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.










Difference between == and .Equals method in C#. Example.

The Equals() method compares only content.

Example

using System;
namespace ComparisionExample {
   class Program { 
      static void Main(string[] args) { 
         string str = "hello"; 
         string str2 = str; 
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: True
Using equals() method: True

The Equality operator is used to compare the reference identity.

Example

using System;
namespace Demo {
   class Program { 
      static void Main(string[] args) { 
         object str = "hello";
         char[] values = {'h','e','l','l','o'};
         object str2 = new string(values);         
         Console.WriteLine("Using Equality operator: {0}", str == str2);
         Console.WriteLine("Using equals() method: {0}", str.Equals(str2));
         Console.ReadKey();
      }  
   }
}

Output

Using Equality operator: False
Using equals() method: True

What is Generics in C#? Example.

Question 1. What Is Generics?
Answer :
Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that allows us to write codes that works for any data types.
Question 2. What Is A Generic Class?
Answer :
A generic class is a special kind of class that can handle any types of data. We specify the data types during the object creations of that class. It is declared with the bracket <>. For example consider the following Comparer class, which has a method that compare two value and returns as Boolean output.
public class Comparer
{
    public bool Compare(Unknown t1, Unknown t2)
  {  
         if (t1.Equals(t2))
      {
            return true;
        }
        else
        {
            return false;
        }
    }
}
Comparer oComparerInt = new Comparer();
Console.WriteLine(oComparerInt.Compare(10, 10));
Comparer oComparerStr = new Comparer();
Console.WriteLine(oComparerStr.Compare("jdhsjhds", "10"));
Question 3. Why We Should Use Generics?
Answer :
Generic provides lot of advantages during programming. We should use generics for the following reasons:
It allows creating class, methods which are type-safe
It is faster. Because it reduce boxing/un-boxing
It increase the code performance
It helps to maximize code reuse, and type safety

What is Serialization in C#? Example.

Answer :
When we want to transport an object through network then we need to convert the object into a stream of bytes. Serialization is a process to convert a complex objects into stream of bytes for storage (database, file, cache, etc) or transfer. Its main purpose is to save the state of an object.
De-serialization is the reverse process of creating an object from a stream of bytes to their original form.
Question 2. What Are The Types Of Serialization?
Answer :
The types of Serializations are given bellow:
1  Binary Serialization
            In this process all the public, private, read only members are serialized and convert into stream of bytes. This is used when we want a complete conversion of our objects.
2  SOAP Serialization
           In this process only public members are converted into SOAP format. This is used in web services.
3  XML Serialization
            In this process only public members are converted into XML. This is a custom serialization. Required namespaces: System.Xml, System.Xml.Serialization.
Question 3. Why Serialization And Deserialization?
Answer :
For example consider, we have a very complex object and we need XML format to show it on HTML page. Then we can create a XML file in the disk, writes all the necessary data on the XML file, and use it for the HTML page. But this is not good approach for large number of users. Extra space is required; anyone can see the XML file which creates security issue. We can overcome it by using XML serialization.
Question 4. When To Use Serialization?
Answer :
Serialization is used in the following purposes:
To pass an object from on application to another
In SOAP based web services
To transfer data through cross platforms, cross devices

HTTP Error Code's

200 OK — This is most commonly used HTTP code to show that the operation performed is successful.
201 CREATED — This can be used when you use the POST method to create a new resource.
202 ACCEPTED — This can be used to acknowledge the request sent to the server.
400 BAD REQUEST — This can be used when client-side input validation fails.
401 UNAUTHORIZED / 403 FORBIDDEN— This can be used if the user or the system is not authorized to perform a certain operation.
404 NOT FOUND— This can be used if you are looking for a certain resource and it is not available in the system.
500 INTERNAL SERVER ERROR — This should never be thrown explicitly but might occur if the system fails.
502 BAD GATEWAY — This can be used if the server received an invalid response from the upstream server.

What is the difference between Rest and Soap in C#? Example.

SOAP
SOAP is a protocol.
SOAP stands for Simple Object Access Protocol.
SOAP can't use REST because it is a protocol.
SOAP uses services interfaces to expose the business logic.
SOAP defines standards to be strictly followed.
SOAP requires more bandwidth and resource than REST.
SOAP defines its own security.
SOAP permits XML data format only.
SOAP is less preferred than REST.
REST
REST is an architectural style.
REST stands for Representational State Transfer.
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.
REST uses URI to expose business logic.
REST does not define too much standards like SOAP.
REST requires less bandwidth and resource than SOAP.
RESTful web services inherits security measures from the underlying transport.
REST permits different data format such as Plain text, HTML, XML, JSON etc.
REST more preferred than SOAP.

What is the difference between Dictionary And Hashtable in C#? Example.

Dictionary
Dictionary is generic type Dictionary<TKey,TValue>
Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types for key and value.
There is no need of boxing/unboxing.
When you try to access non existing key dictionary, it gives runtime error.
Dictionary maintains an order of the stored values.
There is no need of boxing/unboxing, so it is faster than Hashtable.
Hashtable
Hashtable is non-generic type.
Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
Values need to have boxing/unboxing.
When you try to access non existing key Hashtable, it gives null values.
Hashtable never maintains an order of the stored values.
Hashtable needs boxing/unboxing, so it is slower than Dictionary.

Saturday, 29 June 2019

What is Object and Collection initialization in C#? Example.

class Program
    {
        static void Main(string[] args)
        {
            List<Employee> emp = new List<Employee> {
                new Employee{Name="Kulshresth0",Address="Noida0"},
                new Employee{Name="Kulshresth1",Address="Noida1"},
                new Employee{Name="Kulshresth2",Address="Noida2"},
                new Employee{Name="Kulshresth3",Address="Noida3"},
            };
            foreach(Employee em in emp)
            {
                Console.WriteLine("Name : "+em.Name +" "+"Address : "+em.Address);
            }
            Console.ReadLine();
        }
    }-----------------------------

class  Employee
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }

Popular

Blog Archive

Total Pageviews

Archive