Wednesday, May 17, 2017

AngularJS Basics - Part 1

                                                                  AngularJS


What is AngularJS

  • ·         Framework by google
  • ·         It works on DOM element with attributes.
  • ·         Perfect for SPA (Single Page Application) 

Below highlighted attributes are component of AngularJS

 


Sample Code :
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="">
  
<p>Name : <input type="text" ng-model="name"></p>
  
<h1>Hello {{name}}</h1>
</div>

</body>
</html>

Thursday, December 8, 2016

SQL important Queries

Check sql server version in Sql Server


Ans-select @@version

check how many tables in Sql Server


Ans-select * from sys.tables

Show complete structure of table in Sql Server

Ans-EXEC sp_help TableName;

How to show all temp tables in sql server

Ans-select * from tempdb.sys.objects

List all indexes in Sql Server

SELECT T.Name, I.name FROM sys.indexes I INNER JOIN Sys.tables t ON t.object_id =
I.Object_ID WHERE index_id >= 1 -- skip heep

List all indexes with all details in Sql Server

select * from sys.indexes

Get first and last date of month in Sql Server

DECLARE @Month int
DECLARE @Year int

set @Month = 2
set @Year = 2005

select DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) /*First*/

select DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0))) /*Last*/

Display every Nth row in Sql Server


SELECT id FROM employees GROUP BY id  HAVING MOD(id, N) = 0;

Age in years in Sql Server


DECLARE @dob datetime
SET @dob='1992-01-09 00:00:00'

SELECT DATEDIFF(hour,@dob,GETDATE())/8766.0 AS AgeYearsDecimal
,CONVERT(int,ROUND(DATEDIFF(hour,@dob,GETDATE())/8766.0,0)) AS AgeYearsIntRound
,DATEDIFF(hour,@dob,GETDATE())/8766 AS AgeYearsIntTrunc

Date diffrence in Sql Server


DATEDIFF(datepart,startdate,enddate)

Update Table using Join in Sql Server


UPDATE employee e LEFT JOIN employee_salary s ON e.id=s.employee_id
SET s.salary='50000'
where e.first_name='Admin'
.

DELETE Table using Join in Sql Server


Delete employee_salary FROM employee_salary LEFT JOIN employee ON employee.id=employee_salary.employee_id
WHERE employee.first_name='Admin'

Select first 3 characters of FIRST_NAME from EMPLOYEE

 select substring(FIRST_NAME,0,3) from employee

Get position of 'L' in name 'Gulshan' from employee table


Select CHARINDEX('L',FIRST_NAME,0) from employee where first_name = 'Gulshan'

 Replacing 'L' with '$'

select REPLACE(FIRST_NAME,'L','$') from employee

Get FIRST_NAME ,Joining year,Joining Month and Joining Date from employee table


select SUBSTRING (convert(varchar,joining_date,103),7,4) , SUBSTRING (convert(varchar,joining_date,100),1,3) , SUBSTRING (convert(varchar,joining_date,100),5,2) from EMPLOYEE


Get employee details from employee table whose joining year is “2013”


Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,103),7,4) = '2013'

Get employee details from employee table whose joining month is “January”

Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,100),1,3) = 'Jan'

Get employee details from employee table who joined before January 1st 2013

Select * from EMPLOYEE where joining_date < '01/01/2013'

Get employee details from employee table who joined between January 1st and January 31st

Select * from EMPLOYEE where joining_date between '01/01/2013' and '01/31/2013'

Get Joining Date and Time from employee table

Select convert(varchar(19),joining_date,121) from EMPLOYEE

Get Joining Date,Time including milliseconds from employee table

select convert(varchar,joining_date,121) from EMPLOYEE

Get difference between JOINING_DATE and INCENTIVE_DATE from employee and incentives table

Select FIRST_NAME,INCENTIVE_DATE - JOINING_DATE from employee a inner join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

Get names of employees from employee table who has '%' in Last_Name.
Select FIRST_NAME from employee where Last_Name like '%[%]%'

Get Last Name from employee table after replacing special character with white space

Select REPLACE(LAST_NAME,'%',' ') from employee

Get department,no of employees in a department,total salary with respect to a department from employee table order by total salary descending

Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by DEPARTMENT order by Total_Salary descending

 Select Last Name from employee table which contain only numbers

Select * from EMPLOYEE where lower(LAST_NAME) = upper(LAST_NAME)

Insert into employee table Last Name with ''' (Single Quote - Special Character, Use single quote before special character )

Insert into employee (LAST_NAME) values ('Test''')

Select Nth Highest salary from employee table

select min(SALARY) from (select top N * from employee) a
select min(SALARY) from (select top 2 * from employee) a

Select max incentive with respect to employee from employee and incentives table using sub query

select DEPARTMENT,(select ISNULL(max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID = EMPLOYEE_ID) Max_incentive from EMPLOYEE

Select first_name, incentive amount from employee and incentives table for all employees who got incentives using left join

Select FIRST_NAME, isnull(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID


 Select first_name, incentive amount from employee and incentives table for all employees even if they didn't get incentives and set incentive amount as 0 for those employees who didn't get incentives.

Select FIRST_NAME, ISNULL(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID



Wednesday, July 10, 2013

How to call code behind method from jquery

ASPX PAGE
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="myjavascript.js" type="text/javascript"></script>
    <script type = "text/javascript">
        function DisplayMessageCall() {

            var pageUrl = '<%=ResolveUrl("~/WebService/HelloWorld.asmx")%>'

            $('#<%=lblOutput.ClientID%>').html('Please wait...');

            $.ajax({
                type: "POST",
                url:  "Default4.aspx/DisplayMessage",
                data: "{'NameInfo':'" + $('#<%=txtName.ClientID%>').val()
                    + "','Location':'" + $('#<%=txtLocation.ClientID%>').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccessCall,
                error: OnErrorCall
            });

        }

        function OnSuccessCall(response) {
            $('#<%=lblOutput.ClientID%>').html(response.d);
        }

        function OnErrorCall(response) {
            alert(response.status + " " + response.statusText);
        }
</script>


</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>&nbsp;Call Webmethod using JQuery AJax (With Multiple Input)</h2>
Enter your Name: <asp:TextBox ID="txtName" runat="server" Text=""></asp:TextBox><br />
Enter Location: <asp:TextBox ID="txtLocation" runat="server" Text=""></asp:TextBox><br />
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me"
            OnClientClick="DisplayMessageCall();return false;" onclick="btnGetMsg_Click" /><br />
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

    </div>
    </form>
</body>
</html>



CODE BEHIND PAGE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class Default4 : System.Web.UI.Page
{
    [WebMethod]
        public static string DisplayMessage(string NameInfo, string Location)
        {
            //Creating Delay
            System.Threading.Thread.Sleep(1000);
            return "Welcome " + NameInfo + ", Your location is " + Location;
        }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnGetMsg_Click(object sender, EventArgs e)
    {

    }

}

How to use toggle in Jquery

ASPX PAGE

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="myjavascript.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {

        alert("I am ready!");
            $("div.test").add("p.quote").html("a little test").toggle(3000);
      });

   
</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div class="test">
  <p class="quote"> this is division...</p>
    </div>
    </form>
</body>
</html>

How to bind gridview with Jquery

ASPX Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default9.aspx.cs" Inherits="Default9" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="myjavascript.js" type="text/javascript"></script>
    <script type="text/javascript">
       
        $(function () {
            $("div.test").toggle(15000)
            $.ajax({

            type: "POST",
            url: "Default9.aspx/GetCustomers",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    });

    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var customers = xml.find("Table");
        var row = $("[id*=gvCustomers] tr:last-child").clone(true);
        $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
        $.each(customers, function () {
            var customer = $(this);
            $("td", row).eq(0).html($(this).find("RBDID").text());
            $("td", row).eq(1).html($(this).find("BATCHID").text());
            $("td", row).eq(2).html($(this).find("REQUESTID").text());
            $("[id*=gvCustomers]").append(row);
            row = $("[id*=gvCustomers] tr:last-child").clone(true);
        });
    }
</script>


</head>
<body>
    <form id="form1" runat="server">
    <div class="test">
    <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" Font-Names="Arial"
    Font-Size="10pt" RowStyle-BackColor="#A1DCF2" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor = "White">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="RBDID" HeaderText="CustomerID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="BATCHID" HeaderText="CustomerID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="REQUESTID" HeaderText="City" />
    </Columns>
</asp:GridView>

<asp:Button runat="server" ID="b1" Text="click me" />
    </div>
    </form>
</body>
</html>


Code Behind Page

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System;

public partial class Default9 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindDummyRow();
        }
    }

    private void BindDummyRow()
    {
        DataTable dummy = new DataTable();
        dummy.Columns.Add("RBDID");
        dummy.Columns.Add("BATCHID");
        dummy.Columns.Add("REQUESTID");
        dummy.Rows.Add();
        gvCustomers.DataSource = dummy;
        gvCustomers.DataBind();
    }



    [WebMethod]
    public static string GetCustomers()
    {
        string query = "select top 10 RBDID,BATCHID,REQUESTID From dbo.RG_ResponseBatchData";
        SqlCommand cmd = new SqlCommand(query);
        return GetData(cmd).GetXml();
    }
    private static DataSet GetData(SqlCommand cmd)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds;

                }
            }
        }
    }

}


Sunday, July 7, 2013

Access server side function using JQuery.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Website1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script lang="javascript" src="JQuery.js" type="text/javascript"></script>
    <script lang="javascript">
            function chk()
            {
            $.ajax (
            {
                type: "POST",
                url: "WebForm1.aspx/show",  // show is the name of function 
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType:"json",
                async: true,
                cache: false,
                success: function (msg) 
                {
                    $('#div1').text(msg.d); 
                },
                error: function (x, e)
                {
                alert("The call to the server side failed. " + x.responseText);
                }
            });
                return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="div1" style="width:500px; height:40px; background-color:aqua">

            This is hidable.

        </div>

    <div>
        <asp:TextBox ID="Text"  CssClass="abc" Text="" runat="server"></asp:TextBox>
        <asp:Button ID="btnShow" OnClientClick="return chk();" runat="server" OnClick="btnShow_Click" Text="Javascript" />
    </div>
    </form>
</body>
</html>

Thursday, June 27, 2013

Complex Queries in SQL- Part1

  1. To fetch ALTERNATE records from a table. (EVEN NUMBERED)select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);
  2. To select ALTERNATE records from a table. (ODD NUMBERED)select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);
  3. Find the 3rd MAX salary in the emp table.select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal <= e2.sal);
  4. Find the 3rd MIN salary in the emp table.select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where e1.sal >= e2.sal);
  5. Select FIRST n records from a table.select * from emp where rownum <= &n;
  6. Select LAST n records from a tableselect * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);
  7. List dept no., Dept name for all the departments in which there are no employees in the department.select * from dept where deptno not in (select deptno from emp); 
    alternate solution:  select * from dept a where not exists (select * from emp b where a.deptno = b.deptno);
    altertnate solution:  select empno,ename,b.deptno,dname from emp a, dept b where a.deptno(+) = b.deptno and empno is null;
  8. How to get 3 Max salaries ?select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal <= b.sal) order by a.sal desc;
  9. How to get 3 Min salaries ?select distinct sal from emp a  where 3 >= (select count(distinct sal) from emp b  where a.sal >= b.sal);
  10. How to get nth max salaries ?
    select distinct hiredate from emp a where &n =  (select count(distinct sal) from emp b where a.sal >= b.sal);
  11. Select DISTINCT RECORDS from emp table.select * from emp a where  rowid = (select max(rowid) from emp b where  a.empno=b.empno);
  12. How to delete duplicate rows in a table?delete from emp a where rowid != (select max(rowid) from emp b where  a.empno=b.empno);
  13. Count of number of employees in  department  wise.select count(EMPNO), b.deptno, dname from emp a, dept b  where a.deptno(+)=b.deptno  group by b.deptno,dname;
  14.  Suppose there is annual salary information provided by emp table. How to fetch monthly salary of each and every employee?
select ename,sal/12 as monthlysal from emp;
  1. Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;
  1. Select all record from emp table where deptno=30 and sal>1500.
select * from emp where deptno=30 and sal>1500;
  1. Select  all record  from emp where job not in SALESMAN  or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');
  1. Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.
select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');
  1. Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';
  1. Select all records where ename may be any no of  character but it should end with ‘R’.
select * from emp where ename like'%R';
  1. Count  MGR and their salary in emp table.
select count(MGR),count(sal) from emp;
  1. In emp table add comm+sal as total sal  .
select ename,(sal+nvl(comm,0)) as totalsal from emp;
  1. Select  any salary <3000 from emp table. 
select * from emp  where sal> any(select sal from emp where sal<3000);
  1. Select  all salary <3000 from emp table. 
select * from emp  where sal> all(select sal from emp where sal<3000);
  1. Select all the employee  group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;
  1. How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
  1. How to retrive record where sal between 1000 to 2000?
    Select * from emp where sal>=1000 And  sal<2000
  2. Select all records where dept no of both emp and dept table matches.
    select * from emp where exists(select * from dept where emp.deptno=dept.deptno)
  3. If there are two tables emp1 and emp2, and both have common record. How can I fetch all the recods but common records only once?
    (Select * from emp) Union (Select * from emp1)
  4. How to fetch only common records from two tables emp and emp1?
    (Select * from emp) Intersect (Select * from emp1)
  5.  How can I retrive all records of emp1 those should not present in emp2?
    (Select * from emp) Minus (Select * from emp1)
  6. Count the totalsa  deptno wise where more than 2 employees exist.
    SELECT  deptno, sum(sal) As totalsal
    FROM emp
    GROUP BY deptno
    HAVING COUNT(empno) > 2


Message Contract in Wcf

Consume Class:




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Enter a Key");
                string _AuthorId = Console.ReadLine();
                ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();
                ServiceReference1.Author a = sc.GetAuthorInfo(_AuthorId);
                if (a != null)
                {
                    Console.WriteLine(a.ArticleId);
                    Console.WriteLine(a.FirstName);
                    Console.WriteLine(a.LastName);

                }
                else
                {
                    Console.WriteLine("Key is not valid");
                }
                    Console.ReadLine();
            }
            catch (FaultException<string> e1)
            {
                Console.WriteLine(e1.Message);
                Console.WriteLine(e1.Reason);
                Console.WriteLine(e1.Detail);
            }
        }
    }
}



Service.Cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
    private const string _AuthorId = "Gulshan";
    SqlConnection con;

    SqlDataAdapter dap;
    DataSet ds;
    public bool CreateConnection(AuthorRequest Req)
    {
        con = new SqlConnection();
        con.ConnectionString = "Data Source=xxxx;Initial Catalog=Master;User Id=xxxxx;Password=xxxxxx;";

        dap = new SqlDataAdapter("SELECT EMP_ID FROM Employee_Test1 where EMP_ID='"+Req._AuthorId+"'", con);
        ds = new DataSet();
        dap.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string x = "Data Exists";
            return true;

        }
        else
        {
            return false;
        }
       


    }


    public AuthorResponse GetAuthorInfo(AuthorRequest Req)
    {
        bool b=CreateConnection(Req);
        if (b == true)
        {

            //if (Req._AuthorId != _AuthorId)
            //{
            //    string _Error = "Invalid Author Id";
            //    throw new FaultException<string>(_Error);
            //}
            AuthorResponse au = new AuthorResponse();
            au.Obj = new Author();
            au.Obj.FirstName = "Gulshan Kumar";
            au.Obj.LastName = "Arora";
            au.Obj.ArticleId = "11001";
            return au;

        }
        else
        {
            AuthorResponse au = new AuthorResponse();
            au.Obj = null;
            return au;

        }
     
    }
}


Interface:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
    [OperationContract]
    [FaultContract(typeof(string))]
    AuthorResponse GetAuthorInfo(AuthorRequest Req);


}
[MessageContract]
public class AuthorRequest
{
    [MessageHeader(Name = "AuthorId")]
    public string _AuthorId;


}
[MessageContract]
public class AuthorResponse
{
    [MessageBodyMember]
   public Author Obj;

}

[DataContract]
public class Author
{
    [DataMember]
    public string FirstName;

    [DataMember]
    public string LastName;

    [DataMember]
    public string ArticleId;
}


AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...