Thursday 27 September 2012

Angry Birds makers to launch a new game


Now it's the turn of pigs to take revenge on birds who attacked them with slingshots in Angry Birds.

Rovio Entertainment, the makers of popular mobile game - the Angry Birds, will launch another game today. The new game, named as Bad Piggies, will feature pigs who now will strike back at the birds who attacked them with slingshots in Angry Birds.
In Bad Piggies, instead of shooting with a slingshot, players build vehicles that help the characters get the birds' eggs.
Angry Birds makers to launch a new game today
The company said it is hoping the new game would breathe additional life into its brand.
"We see Bad Piggies as a long-term brand-building exercise. In three years from now, we want to see Angry Birds and Bad Piggies as strong vibrant brands out there," said Petri Jarvilehto, head of gaming at Rovio.
Rovio was founded in 2003 and became a global phenomenon after it launched Angry Birds for Apple's iPhone in late 2009. The Angry Birds helped Rovio's sales jump 10-fold to USD 100 million last year. However, later it launched the Amazing Alex, which could not match that success of Angry Birds.
Rovio is also expanding into merchandising, modeling its long-term strategy on Walt Disney by selling a range of stuffed and other toys, as well as branded playground equipment. Last year, some 30 per cent of turnover for Rovio came from items itself.

Tuesday 25 September 2012

How to add meta keywords and description from code behind page in asp.net


    protected void Page_Load(object sender, EventArgs e)
    {
            HtmlMeta tag = new HtmlMeta();
            tag.Name = "description";
            tag.Content = "My description for this page";
            Header.Controls.Add(tag);
    }

Monday 24 September 2012

Select records in asp.net using three tier architecture

Application Layer:

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
        <asp:ButtonField CommandName="Edit" Text="EDIT" />
        <asp:BoundField DataField="fname" HeaderText="First Name" />
        <asp:BoundField DataField="lname" HeaderText="Last Name" />
        </Columns>
       </asp:GridView>
  
    </div>
    </form>
</body>
</html>

BUSINESS ACCESS LAYER:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{

    DAL d1 = new DAL();
    DataSet ds = new DataSet();
    public BAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
   
    public DataSet select_BAL(string Str_Pro)
    {
       ds = d1.select_record("select_records");
       
        //DataSet ds = new DataSet();
        return ds;

    }


}

STORED PROCEDURE USED:

CREATE PROCEDURE select_records

AS
BEGIN

SELECT * FROM test_tab2

END


DATA ACCESS LAYER:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
    SqlConnection con = new SqlConnection();
    public DAL()
    {
        con = new SqlConnection("Data Source=EVEREST5026;Initial Catalog=sample;Integrated Security=True");
    }

    public DataSet select_record(string Str_Pro)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand(Str_Pro, con);
        cmd.CommandType = CommandType.StoredProcedure;

        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        da.Fill(ds);
        return ds;
       
    }
}

CODE BEHIND PAGE:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Show_Records : System.Web.UI.Page
{
    BAL b1 = new BAL();
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        fill_records();
    }

    private void fill_records()
    {
        ds = b1.select_BAL("select_records");

        GridView1.DataSource = ds;
        GridView1.DataBind();
        ds.Clear();

    }
}


Three tier architecture in asp.net example of inserting records

The 3-Tier architecture contains 3 layers
1.    Application Layer or Presentation Layer 
2.    Business Access Layer(BAL) or Business Logic Layer(BLL) 
3.    Data Access Layer(DAL)
 
Application Layer/ Presentation Layer:


 
 
 Business Access Layer(BAL) or Business Logic Layer(BLL) :
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
    string _fname, _lname;
    DAL d1 = new DAL();
      public BAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public string fname
    {
        get
        {
            return this._fname;
        }
        set
        {
            this._fname = value;
        }

    }
    public string lname
    {
        get
        {
            return this._lname;
        }
        set
        {
            this._lname = value;
        }

    }

    public void insert_BAL(string Str_Pro)
    {
        d1.insert_records(Str_Pro, this);
    }


}

STORED PROCEDURE USED:

CREATE PROCEDURE [dbo].[insert_record]

@fname varchar(50),
@lname varchar(50)

AS
BEGIN

INSERT INTO test_tab2 (fname,lname) values(@fname,@lname)

END
 
 
 Data Access Layer(DAL):

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
    SqlConnection con = new SqlConnection();
    public DAL()
    {
        con = new SqlConnection("Data Source=EVEREST5026;Initial Catalog=sample;Integrated Security=True");
    }

    public void insert_records(string Str_Pro, BAL b1)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand(Str_Pro, con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter param1, param2;

        param1 = new SqlParameter("@fname", SqlDbType.VarChar);
        param1.Value = b1.fname;
       // param1.Direction = ParameterDirection.Input;
        cmd.Parameters.Add(param1);

        param2 = new SqlParameter("@lname", SqlDbType.VarChar);
        param2.Value = b1.lname;
       // param2.Direction = ParameterDirection.Input;
        cmd.Parameters.Add(param2);

        cmd.ExecuteNonQuery();
        con.Close();

    }

}


CODE BEHIND PAGE:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class index : System.Web.UI.Page
{
    BAL b1 = new BAL();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        b1.fname = TextBox1.Text;
        b1.lname = TextBox2.Text;
        b1.insert_BAL("insert_record");
    }
}

 

Saturday 15 September 2012

How to show value upto two decimal places even if the value is integer

In case of Code behind Page:


  double d = Convert.ToDouble(TextBox1.Text);
  Label1.Text = d.ToString("0.00");


In case of Eval in .aspx Page:

Text='<%# Convert.ToDouble(Eval("QTY")).ToString("0.00") %>'>

Friday 14 September 2012

301 Redirection in Web.config


<configuration>
    <location path="bing.htm">
      <system.webServer>
        <httpRedirect enabled="true" destination="http://bing.com" httpResponseStatus="Permanent" />
      </system.webServer>
    </location>
    <location path="google.htm">
      <system.webServer>
        <httpRedirect enabled="true" destination="http://google.com" httpResponseStatus="Permanent" />
      </system.webServer>
    </location>
    <location path="yahoo.htm">
      <system.webServer>
        <httpRedirect enabled="true" destination="http://yahoo.com" httpResponseStatus="Permanent" />
      </system.webServer>
    </location>
  </configuration>

What is difference between Applicatiion State and Session State

A session is usually for a user and only lasts from when they login to when they logout (or get timed out). Application State has a much longer lifetime, is shared between all users, and is only cleared when the process is restarted.

Sunday 9 September 2012

Create table having auto increamented column in Sql Server

Create table reg_tab
(
id int not null identity(1,1),
fname varchar(50),
addr varchar(100),
email varchar(50),
contact numeric(12,0),
CONSTRAINT reg_tab_pk PRIMARY KEY(id)
)


Saturday 8 September 2012

Insert Into Table Stored Procedure

CREATE PROCEDURE insert_pro
    -- Add the parameters for the stored procedure here
 @order_no int,
 @customer varchar(50),
 @amount numeric(10,2),
 @order_date datetime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO orders (order_no,customer,amount,order_date) VALUES(@order_no,@customer,@amount,@order_date)
END



I would like to find the customer, who has Highest order count in SQL Table

I would like to find the customer, who has Highest order count.



SOLUTION:

;with t as
(
select customer,count(customer) as cnt_cust from orders   group by customer
)
select top 1 * from t


RESULT:


Powered by: Codersspace webtech solutions Codersspace webtech solutions

Friday 7 September 2012

when the last time each distinct report was run and who ran it last in SQL Server

I'm trying to fetch some info out of a table. To simplify, let's say the table (report_history) has 4 columns:
user_name, report_job_id, report_name, report_run_date.
Each time a report is run in SQL, a record is written to this table noting the above info. What I am trying to do is pull from this table when the last time each distinct report was run and who ran it last.


OR, Other way to do this:

select user_name,report_run_date from report_history where report_run_date=(select max(report_run_date) from report_history)

Using this above query the result will be same , only the difference between these two queries is that the above query will give errors in case of same records in "report_run_date" column which will overcome by second below written query.


Powered by: Codersspace webtech solutions Codersspace webtech solutions

Thursday 6 September 2012

Create table having Primary Key in Sql Server



Powered by: Codersspace webtech solutions Codersspace webtech solutions

Min Function in Sql Server

The MIN function returns the minimum value of an expression.
The syntax for the MIN function is:
SELECT MIN(expression )
FROM tables
WHERE predicates;

Simple Example:

For example, you might wish to know the minimum salary of all employees.
SELECT MIN(salary) as "Lowest salary"
FROM employees;
In this example, we've aliased the min(salary) field as "Lowest salary". As a result, "Lowest salary" will display as the field name when the result set is returned.

Example using GROUP BY:

In some cases, you will be required to use a GROUP BY clause with the MIN function.
For example, you could also use the MIN function to return the name of each department and the minimum salary in the department.
SELECT department, MIN(salary) as "Lowest salary"
FROM employees
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the MIN function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

How to get Nth Max or Min value in SQL


Sum Function in Sql Server

The SUM function returns the summed value of an expression.
The syntax for the SUM function is:
SELECT SUM(expression )
FROM tables
WHERE predicates;
expression can be a numeric field or formula.

Simple Example:

For example, you might wish to know how the combined total salary of all employees whose salary is above $25,000 / year.
SELECT SUM(salary) as "Total Salary"
FROM employees
WHERE salary > 25000;
In this example, we've aliased the sum(salary) field as "Total Salary". As a result, "Total Salary" will display as the field name when the result set is returned.

Example using DISTINCT:

You can use the DISTINCT clause within the SUM function. For example, the SQL statement below returns the combined total salary of unique salary values where the salary is above $25,000 / year.
SELECT SUM(DISTINCT salary) as "Total Salary"
FROM employees
WHERE salary > 25000;
If there were two salaries of $30,000/year, only one of these values would be used in the SUM function.

Example using a Formula:

The expression contained within the SUM function does not need to be a single field. You could also use a formula. For example, you might want the net income for a business. Net Income is calculated as total income less total expenses.
SELECT SUM(income - expenses) as "Net Income"
FROM gl_transactions;

You might also want to perform a mathematical operation within a SUM function. For example, you might determine total commission as 10% of total sales.
SELECT SUM(sales * 0.10) as "Commission"
FROM order_details;

Example using GROUP BY:

In some cases, you will be required to use a GROUP BY clause with the SUM function.
For example, you could also use the SUM function to return the name of the department and the total sales (in the associated department).
SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the SUM function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Wednesday 5 September 2012

Count Function in Sql Server

The COUNT function returns the number of rows in a query.
The syntax for the COUNT function is:
SELECT COUNT(expression)
FROM tables
WHERE predicates;

Note:

The COUNT function will only count those records in which the field in the brackets is NOT NULL.
For example, if you have the following table called suppliers:
Supplier_ID Supplier_Name State
1 IBM CA
2 Microsoft
3 NVIDIA
The result for this query will return 3.
Select COUNT(Supplier_ID) from suppliers;
While the result for the next query will only return 1, since there is only one row in the suppliers table where the State field is NOT NULL.
Select COUNT(State) from suppliers;

Simple Example:

For example, you might wish to know how many employees have a salary that is above $25,000 / year.
SELECT COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000;
In this example, we've aliased the count(*) field as "Number of employees". As a result, "Number of employees" will display as the field name when the result set is returned.

Example using DISTINCT:

You can use the DISTINCT clause within the COUNT function.
For example, the SQL statement below returns the number of unique departments where at least one employee makes over $25,000 / year.
SELECT COUNT(DISTINCT department) as "Unique departments"
FROM employees
WHERE salary > 25000;
Again, the count(DISTINCT department) field is aliased as "Unique departments". This is the field name that will display in the result set.

Example using GROUP BY:

In some cases, you will be required to use a GROUP BY clause with the COUNT function.
For example, you could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year.
SELECT department, COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the COUNT function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

TIP: Performance Tuning

Since the COUNT function will return the same results regardless of what NOT NULL field(s) you include as the COUNT function parameters (ie: within the brackets), you can change the syntax of the COUNT function to COUNT(1) to get better performance as the database engine will not have to fetch back the data fields.
For example, based on the example above, the following syntax would result in better performance:
SELECT department, COUNT(1) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;
Now, the COUNT function does not need to retrieve all fields from the employees table as it had to when you used the COUNT(*) syntax. It will merely retrieve the numeric value of 1 for each record that meets your criteria.

Practice Exercise #1:
Based on the employees table populated with the following data, count the number of employees whose salary is over $55,000 per year.
CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);



INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1001, 'John Smith', 62000);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1002, 'Jane Anderson', 57500);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1003, 'Brad Everest', 71000);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1004, 'Jack Horvath', 42000);
Solution:
Although inefficient in terms of performance, the following SQL statement would return the number of employees whose salary is over $55,000 per year.
SELECT COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 55000;
It would return the following result set:
Number of employees
3
A more efficient implementation of the same solution would be the following SQL statement:
SELECT COUNT(1) as "Number of employees"
FROM employees
WHERE salary > 55000;
Now, the COUNT function does not need to retrieve all of the fields from the table (ie: employee_number, employee_name, and salary), but rather whenever the condition is met, it will retrieve the numeric value of 1. Thus, increasing the performance of the SQL statement.

Practice Exercise #2:
Based on the suppliers table populated with the following data, count the number of distinct cities in the suppliers table:
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);



INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5001, 'Microsoft', 'New York');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5002, 'IBM', 'Chicago');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5003, 'Red Hat', 'Detroit');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5004, 'NVIDIA', 'New York');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5005, 'NVIDIA', 'LA');
Solution:
The following SQL statement would return the number of distinct cities in the suppliers table:
SELECT COUNT(DISTINCT city) as "Distinct Cities"
FROM suppliers;
It would return the following result set:
Distinct Cities
4

Practice Exercise #3:
Based on the customers table populated with the following data, count the number of distinct cities for each customer_name in the customers table:
CREATE TABLE customers
( customer_id number(10) not null,
customer_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);



INSERT INTO customers (customer_id, customer_name, city)
VALUES (7001, 'Microsoft', 'New York');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7002, 'IBM', 'Chicago');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7003, 'Red Hat', 'Detroit');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7004, 'Red Hat', 'New York');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7005, 'Red Hat', 'San Francisco');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7006, 'NVIDIA', 'New York');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7007, 'NVIDIA', 'LA');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7008, 'NVIDIA', 'LA');
Solution:
The following SQL statement would return the number of distinct cities for each customer_name in the customers table:
SELECT customer_name, COUNT(DISTINCT city) as "Distinct Cities"
FROM customers
GROUP BY customer_name;
It would return the following result set:
CUSTOMER_NAME Distinct Cities
IBM 1
Microsoft 1
NVIDIA 2
Red Hat 3

Insert multiple records using single query in Sql server


Distinct Clause in Sql Server

The DISTINCT clause allows you to remove duplicates from the result set. The DISTINCT clause can only be used with select statements.
The syntax for the DISTINCT clause is:
SELECT DISTINCT columns
FROM tables
WHERE predicates;

Example #1:

Let's take a look at a very simple example.
SELECT DISTINCT city
FROM suppliers;
This SQL statement would return all unique cities from the suppliers table.

Example #2:

The DISTINCT clause can be used with more than one field.
For example:
SELECT DISTINCT city, state
FROM suppliers;
This select statement would return each unique city and state combination. In this case, the distinct applies to each field listed after the DISTINCT keyword.

Select Statement in Sql server

The SELECT statement allows you to retrieve records from one or more tables in your database.
The syntax for the SELECT statement is:
SELECT columns
FROM tables
WHERE predicates;

Example #1:

Let's take a look at how to select all fields from a table.
SELECT *
FROM suppliers
WHERE city = 'Newark';
In our example, we've used * to signify that we wish to view all fields from the suppliers table where the supplier resides in Newark.

Example #2:

You can also choose to select individual fields as opposed to all fields in the table.
For example:
SELECT name, city, state
FROM suppliers
WHERE supplier_id > 1000;
This select statement would return all name, city, and state values from the suppliers table where the supplier_id value is greater than 1000.

Example #3:

You can also use the select statement to retrieve fields from multiple tables.
SELECT orders.order_id, suppliers.name
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;
The result set would display the order_id and supplier name fields where the supplier_id value existed in both the suppliers and orders table.

Datatypes in Sql Server

Data Type Syntax Explanation (if applicable)
integer integer
smallint smallint
numeric numeric(p,s) Where p is a precision value; s is a scale value. For example, numeric(6,2) is a number that has 4 digits before the decimal and 2 digits after the decimal.
decimal decimal(p,s) Where p is a precision value; s is a scale value.
real real Single-precision floating point number
double precision double precision Double-precision floating point number
float float(p) Where p is a precision value.
character char(x) Where x is the number of characters to store. This data type is space padded to fill the number of characters specified.
character varying varchar2(x) Where x is the number of characters to store. This data type does NOT space pad.
bit bit(x) Where x is the number of bits to store.
bit varying bit varying(x) Where x is the number of bits to store. The length can vary up to x.
date date Stores year, month, and day values.
time time Stores the hour, minute, and second values.
timestamp timestamp Stores year, month, day, hour, minute, and second values.
time with time zone time with time zone Exactly the same as time, but also stores an offset from UTC of the time specified.
timestamp with time zone timestamp with time zone Exactly the same as timestamp, but also stores an offset from UTC of the time specified.
year-month interval
Contains a year value, a month value, or both.
day-time interval
Contains a day value, an hour value, a minute value, and/or a second value.

                                                            
 
Design by Abhinav Ranjan Sinha