Friday, August 17, 2012

Get Records between two dates in MS SQL

Here query show how to select record between two dates in sql server.
select * from ContentMst
where c_date> = '2012-06-01' and c_date <= '2012-07-01'
order by c_date desc

How to insert record from one database to other database server

Here example show i am retrieving record from one server(DBServer2) and inserting in other server(DBServer1).
insert into Category(DBServer1)
select * from [DBServer2].[DatabaeName].[dbo].Category
Note: Both database server should be linq server otherwise it will give error.

Wednesday, July 4, 2012

How to create a hyperlink or any other control dynamically and add to this in panel control

 Here i am show how can you create hyperlink dynamically and add to it in panel control.  
 Here we can also create line break dynamically.  
   
 Take a asp.net panel in your .aspx page as given below:  
   
 <asp:Panel ID="Panel2" runat="server" CssClass="applycss">  
 </asp:Panel>  
   
 .cs code to create HyperLink dynamically and add to panel.  
        
 HyperLink hyprlink = new HyperLink();  
 hyprlink.Text = "Click here to subscribe.";  
 hyprlink.CssClass = "Ima12";  
 hyprlink.NavigateUrl = "http://yourdomain/SubApplication/?key=passparameter&rs=2";  
 Panel2.Controls.Add(hyprlink);  
 Panel2.Controls.Add(new LiteralControl("<br />"));  
   
 Regards  
 Santosh Singh  

Thursday, April 12, 2012

How to create or implement Remember me Login Page asp.net and c#


 Login page source code in asp.net and c#  
 Hi,as you have seen various example above,please see one other example for login page using  
 Here i have implement Remember me on Login Page using checkbox. now i am going to explain  
 how to use Remember Me checkbox and login page code using asp.net and c# net.When you checked Remember me  
 checkbox it will maintain username and password for website user using Cookies.  
 When user click login button that will stores the username and password in the cookie.  
 first determine if the remember me checkbox is checked or not, if it is checked then store the username and   
 password in the cookie for the 1 month and if not checked then set the expiration date to 1 day in else condition  
 to destroy the cookie.  
 protected void Page_Load(object sender, EventArgs e)  
 {  
      if (!Page.IsPostBack)  
      {  
           if (Request.Cookies["UserName"] != null)  
                txtUserName.Text = Request.Cookies["UserName"].Value;  
           if (Request.Cookies["Password"] != null)  
                txtPassword.Text = Request.Cookies["Password"].Value;  
           if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)  
                chkRember.Checked = true;   
      }  
 }  
 protected void btnLogin_Click(object sender, EventArgs e)  
 {  
       string stringconnection = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;  
       MySqlConnection connection = new MySqlConnection(stringconnection);  
      try  
      {   
           int flag = 0;  
           if (chkRember.Checked == true)  
           {  
                Response.Cookies["UserName"].Value = txtUserName.Text;  
                Response.Cookies["Password"].Value = txtPassword.Text;  
                Response.Cookies["UserName"].Expires = DateTime.Now.AddMonths(1);  
                Response.Cookies["Password"].Expires = DateTime.Now.AddMonths(1);  
           }  
           else  
           {  
                Response.Cookies["UserName"].Expires = DateTime.Now.AddMonths(-1);  
                Response.Cookies["Password"].Expires = DateTime.Now.AddMonths(-1);  
           }   
           MySqlCommand com = new MySqlCommand("select * from tbl_user_details", connection);  
           connection.Open();  
           if (connection.State == ConnectionState.Open)  
           {  
                MySqlDataReader objSqlDataReader;  
                objSqlDataReader = com.ExecuteReader();  
                while (objSqlDataReader.Read())  
                {  
                     if (objSqlDataReader[2].ToString().Equals(txtUserName.Text) && objSqlDataReader[5].ToString().Equals(txtPassword.Text))  
                     {  
                          flag = 1;  
                          Session["UserName"] = txtUserName.Text;  
                          Session["UserType"] = objSqlDataReader[8].ToString();  
                          Response.Redirect("ContactUs.aspx", false);  
                     }  
                     else  
                     {  
                          ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");  
                     }  
                }  
           }  
      }  
      catch (Exception ex)  
      {  
           lblMsg.Text = ex.ToString();  
      }  
      finally   
      {  
           connection.Close();  
      }  
 }  
 Regard  
 Santosh Singh  

Wednesday, March 7, 2012

How to improve asp.net Web application performance

 For application performance you need to some r & d on your query mean stored procedure  
 see their retrieval cost and find where it is taking too much time to retriev the data  
 and do some action on that table.  
 For eg.   
 1.You should be use index whereever required  
 2.Use joining if required otherwise remove unnesseary join.  
 3.Select only required field from table.  
 4.you can using caching  
 5.Create index for the table field which you are frequently using in where clause.  

Tuesday, March 6, 2012

How to get label or textbox control from .aspx page in .ascx user control page

 How to access controls from .aspx in .ascx user control page  
 Here i am showing a simple example how can we access controls from aspx in .ascx page  
 First i have created a WebUserControl.ascx user control page which contain a button.  
 WebUserControl.ascx page  
 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>  
 <table>  
   <tr>  
     <td>  
       <asp:Button ID="btn_addUC" runat="server" Text="Add" OnClick="btn_addUC_Click" />  
     </td>  
   </tr>  
 </table>  
 Write below code in code behind   
 WebUserControl.ascx.cs page  
 protected void btn_addUC_Click(object sender, EventArgs e)  
 {  
      Button btnSender = (Button)sender;  
      Page parentPage = btnSender.Page;      
      TextBox txt = (TextBox)parentPage.FindControl("txtName");  
      Label lbl = (Label)parentPage.FindControl("lblNAme");  
      lbl.Text = txt.Text;  
 }  
 Take a another test_page.aspx page and register the above user control in it.as given below:  
 test_page.aspx page  
 <form id="form1" runat="server">  
      <div>  
           <uc1:WebUserControl runat="server" ID="WebUserControl" />  
      </div>  
      <div>  
           <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />  
           <asp:Label ID="lblNAme" runat="server" Text="Label"></asp:Label>  
      </div>  
 </form>  
      Run and test the application.  
 Regards  
 Santosh Singh  

Monday, February 27, 2012

How to detect MSISDN from browser headers

        How to detect MSISDN from browser headers  
        Things to note be remember that:  
        1.If the user has come to wap portal on WiFi then you will not receive msisdn.  
        2.User mobile operator has to support the passing of the msisdn in the HTTP      headers.  
                  
        Below is simple code to find msisdn from header.  
                  
        string[] strHeader = Request.Headers.AllKeys;  
       string strMSISDN="";  
       for (int i = 0; i < strHeader.Length; i++)  
       {  
         if (strHeader[i].Contains("msisdn") || strHeader[i].ToLower().StartsWith("msisdn", StringComparison.CurrentCultureIgnoreCase) ||strHeader[i].ToLower().EndsWith("msisdn", StringComparison.CurrentCultureIgnoreCase) ||strHeader[i].ToLower().StartsWith("mdn", StringComparison.CurrentCultureIgnoreCase) ||strHeader[i].ToLower().EndsWith("mdn", StringComparison.CurrentCultureIgnoreCase) ||)  
         {  
           strMSISDN = Request.Headers[strHeader[i]];  
   
           if (strMSISDN.Length >= 15)  
           {  
             for (int j = 0; j < strHeader.Length; j++)  
             {  
               if (strHeader[j].ToLower().StartsWith("mdn", StringComparison.CurrentCultureIgnoreCase) || strHeader[j].ToLower().EndsWith("mdn", StringComparison.CurrentCultureIgnoreCase))  
               {  
                 strMSISDN = Request.Headers[strHeader[j]];  
                 break;  
               }  
             }  
           }  
           else  
           {  
             break;  
           }  
         }  
       }  
   
 Thanks & Regards  
 Santosh  

Rain Water Harvesting

Wednesday, February 22, 2012

Create HTTP request and receive response using asp.net C#

 Create HTTP request and receive response using asp.net C#   
       1.Simple http request  
        Uri objurl = new Uri(url);  
       WebRequest objWebRequest = WebRequest.Create(objurl);  
       WebResponse objWebResponse = objWebRequest.GetResponse();  
       Stream objstream = objWebResponse.GetResponseStream();  
       StreamReader objStreamReader = new StreamReader(objstream);  
       string strHtml = objStreamReader.ReadToEnd();  
        2.HTTP Post request and response  
       HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://clinet-url.com/sub/Activate");        
       req.Method = "POST";  
       req.ContentType = "application/x-www-form-urlencoded";  
       req.Credentials = CredentialCache.DefaultNetworkCredentials;  
       req.ClientCertificates.Add(clint_certificate);  
       strNewReqValue = strFormValues + "&mssdn=" + msisdn + "&srv=" + Service + "&user=username";  
       req.ContentLength = strNewReqValue.Length;  
       StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);  
       stOut.Write(strNewReqValue);  
       stOut.Close();  
       StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());  
       Res = stIn.ReadToEnd();  
       Response = Res.ToString();  
       stIn.Close();  

Tuesday, February 21, 2012

How to use stored Procedure with output parameters with ASP.NET,c#

 How to retrieve store procedure output parameter value?I have given a simple code example.  
 I have created a store procedure with output parameter. After that I get it from code behind page of  
 asp.net and stored it a variable.    
 private void GetInfo()  
   {  
     DALUtility objDALUtility = null;  
     SqlConnection con = null;  
     SqlCommand cmd = null;  
     SqlDataAdapter da = null;  
     try  
     {  
       objDALUtility = new DBUtility(ConfigurationManager.AppSettings["myconString"]);  
       con = objDALUtility.GetDBConnection();  
       con.Open();  
       cmd = new SqlCommand();  
       cmd.Connection = con;  
       cmd.CommandType = CommandType.StoredProcedure;  
       cmd.CommandTimeout = 500;  
       cmd.CommandText = "usp_MyInfo";  
       cmd.Parameters.AddWithValue("@Id", strId);  
       cmd.Parameters.AddWithValue("@empName", Convert.ToString(Session["Name"]));        
       cmd.Parameters.Add("@TotalCount", SqlDbType.Int).Direction = ParameterDirection.Output;  
       da = new SqlDataAdapter(cmd);  
       DataSet objDS = new DataSet("MyInfo");  
       da.Fill(objDS);  
       con.Close();  
       int Total = Convert.ToInt32(cmd.Parameters["@TotalCount"].Value);  
     }  
   }  
 Stored Procedure  
 CREATE Proc [dbo].[usp_MyInfo]  
  @Id int,            
  @Name varchar(50) = null,      
  @Total int = 0 OUTPUT  
 AS          
 SET @Total = (Select COUNT(Distinct tbl_Logs.ContentId) From tbl_Logs with(nolock)         
  Inner Join tbl_Logs_details with(nolock) on tbl_Logs_details.ContentId = tbl_Logs.ContentId  
  Where id = @id and tbl_Logs_details.ContentId = 2   
 Select @Total as Count   

Tuesday, December 6, 2011

Export DataSet to XML File

create xml file from a dataset
This code snippet show how to export DataSet to xml file.Here we have taken data from database and fill dataset.We have taken a aspx page and a button there,after clicking the button a xml file will be created at specified location.

 public void CreateXml()  
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("usp_GetAddressDetails",con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
StreamWriter objStreamWriter = new StreamWriter("E:\\Santosh\\Practices\\ASP\\XMLFiles\\EmpAddress.xml", false);
ds.WriteXml(objStreamWriter);
objStreamWriter.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateXml();
}


Regards
Santosh Singh

Monday, December 5, 2011

Insert XML data into SQL Server 2008

 protected void Button1_Click(object sender, EventArgs e)   
  {   
       string EmpCode = null;   
       string City = null;   
       string State = null;   
       string Country = null;   
       string str = null;   
       SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Test;Integrated Security=True");   
       XmlDocument document = new XmlDocument();   
       document.Load("E:\\Santosh\\EmpAddress.xml");   
       XmlNodeList xmlNodeList = document.SelectNodes("EmpAddress/Address");   
       foreach (XmlNode node in xmlNodeList)   
       {   
            EmpCode = node["EmpCode"].InnerText;   
            City = node["City"].InnerText;   
            State = node["State"].InnerText;   
            Country = node["Country"].InnerText;   
            str = "INSERT INTO AddressDetail (EmpCode,City,State,Country) values ('" + EmpCode + "', '" + City + "','" + State + "','" + Country + "')";   
            SqlCommand cmd = new SqlCommand();   
            cmd = new SqlCommand(str, con);   
            cmd.CommandType = CommandType.Text;   
            con.Open();   
            cmd.ExecuteNonQuery();   
            con.Close();   
       }   
  }    

Sunday, March 27, 2011

Create PDF from DataTable in Asp.net

In this article ,i am explaining you how to create pdf file from datatable.i am passing a datatable in this function and code to convert this in pdf file.

I am using iTextSharp you can download it from internet. it is free.
you need to create a simple asp.net page and get data from database.Then pass it to ExportToPDF method.We can set PDF page margins, change page orientation (portrait, landscape), customize headers and footers add page numbers and more.Do some R & D with iTextSharp.


 public void ExportToPdf(DataTable myDataTable)  
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
pdfDoc.Add(p);
string clientLogo = System.Web.HttpContext.Current.Session["CompanyName"].ToString();
clientLogo = clientLogo.Replace(" ", "");
string clogo = clientLogo + ".jpg";
string imageFilePath = System.Web.HttpContext.Current.Server.MapPath("../ClientLogo/" + clogo + "");
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(80f, 60f);
//Give space before image
jpg.SpacingBefore = 0f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.HEADER;
pdfDoc.Add(jpg);
Font font8 = FontFactory.GetFont("ARIAL", 7);
DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (DocumentException de)
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}

Thanks & Regards
Santosh Singh

Wednesday, December 29, 2010

Multiple file upload in asp.net

This code show how to upload multiple file and save to database using asp.net and c#.
 HttpFileCollection hFileCollection = HttpContext.Current.Request.Files;  
for (int i = 0; i <= hFileCollection.Count; i++)
{
HttpPostedFile hPostedFile = hFileCollection[i];
if (hPostedFile.ContentLength > 0)
{
Stream fs = hFileCollection[i].InputStream;
int ImgLength = hFileCollection[i].ContentLength;
string contenttype = hFileCollection[i].ContentType;
string filePath = Path.GetFullPath(hFileCollection[i].FileName);
string filename = Path.GetFileName(filePath);
string extension = Path.GetExtension(hFileCollection[i].FileName).ToLower();
byte[] BinaryData = new byte[ImgLength];
int n = fs.Read(BinaryData, 0, ImgLength);
int DrawingID = objbztDrawingMasterBLL.CreateDrawingMaster(objbztDrawingMasterCls);
objbztDrawingMasterCls.DfileName = filename;
objbztDrawingMasterCls.FileConetentType = contenttype;
objbztDrawingMasterCls.FileData = BinaryData;
if (extension == ".doc" || extension == ".docx" || extension == ".xls" || extension == ".xlsx" || extension == ".jpg" || extension == ".png" || extension == ".gif" || extension == ".pdf")
{
string cmdstr = "INSERT INTO tblDtFiles(DID,DFileName,FileConetentType,FileData) VALUES(" + DID + "," + Convert.ToString(filename) + "," + Convert.ToString(contenttype) + "," + BinaryData + ")";
SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, cmdstr);
}
else
{
msg.Text = "Uploaded file should be doc/xls/jpg/png/gif/pdf...!";
}
}
}


Thanks & Regards
Santosh Singh

Thursday, October 21, 2010

Rounded off total income

Rounded off total income
       Int32 roundedAmt;  
Int32 torounded = Convert.ToInt32(lblTotalIncome.Text);
int lastdigit = torounded % 10;
if (lastdigit >= 5)
{
roundedAmt = torounded - lastdigit + 10;
}
else
{
roundedAmt = torounded - lastdigit;
}
lblRoundedOf.Text = Convert.ToString(roundedAmt);


Thanks & Regards
Santosh

Monday, October 11, 2010

Enable and disable textbox when checked the checkbox

Here code show how enable and disble textbox when user checked the textbox.
code disble the row which contain the textbox.you can also take only checkbox
to enable and disble not neccessary to disble row.

function showHide()
{

var chkSignature = document.getElementById('ctl00_ContentPlaceHolder1_tabContainer_pnl_chkSign');
var trsign = document.getElementById('ctl00_ContentPlaceHolder1_tabContainer_pnl_trsign');
if(chkSignature.checked)
{
if(trsign != null)
{
trsign.style.display = '';
}
}
else
{
if(trsign != null)
{
trsign.style.display = 'none';
}
}
}

<tr>
<td style="height: 22px; width: 180px;">
</td>
<td align="left" colspan="3" style="height: 22px; text-align: left">
<asp:CheckBox ID="chkSignature" runat="server" Text="Show Signature" onclick="showHide()"/>
</td>
</tr>
<tr id="trsign" runat="server" style="display:none">
<td style="height: 22px; width: 180px;">
</td>
<td align="left" colspan="3" style="height: 22px; text-align: left">
<asp:TextBox ID="txtSignature" runat="server" Width="350px" TextMode="MultiLine" ></asp:TextBox>
</td>
</tr>

Thanks & Regards
Santosh

Thanks & Regards
Santosh

Sunday, October 10, 2010

Bind DropDownList using SqlDataReader

This code pulling out data from a database into a data reader is as follows.
 protected void Page_Load(object sender, EventArgs e)  
{
if (!Page.IsPostBack)
{
bindDDL();
}
}
Public void bindDDL()
{
SqlConnection con =new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString.ToString();)
SqlCommand cmd=new SqlCommand();
cmd.connection=con;
con.open();
cmd.commandText="SELECT Citiid,CitiName FROM tableCity";
SqlDataReader dr;
dr=cmd.ExecuteReader();
ddlname.DataSource =dr;
ddlname.DataTextField = "CitiName";
ddlname.DataValueField = "Citiid";
ddlname.DataBind();
dr.close();
con.close();
}

Thanks & Regards
Santosh

Saturday, October 9, 2010

Get duplicated record from sql server table

Here query describes how to find duplicate record from a table in sql server

SELECT User_ID FROM tbl_Member
GROUP BY User_ID
HAVING count( * ) > 1

Thanks & Regards
Santosh Singh

Friday, October 1, 2010

Refresh the aspx page automatically

This small code refresh the aspx page automatically.
Set the time according to your requirment in content="time in sec".

<head runat="server">
<title>Untitled Page</title>
<meta http-equiv="refresh" content="20" />
</head>

Thursday, September 30, 2010

select data from one database and insert into another table

insert into tblMonthMst
select * from EMPMain.[dbo].[tblMonthMst]

Wednesday, September 29, 2010

Sql Server query Optimization

Optimization in Practice

Example 1:
I want to retrieve the name and salary of the employees of the R&D department.


Original:
Query : Select * From Employees
In Program : Add a filter on Dept or use command : if Dept = R&D--

Corrected :
Select Name, Salary From Employees Where Dept = R&D--

In the corrected version, the DB filters data because it filters faster than the program.
Also, you only need the Name and Salary, so only ask for that.
The data that travels on the network will be much smaller, and therefore your performances will improve.

Example 2 (Sorting):

Original:
Select Name, Salary
From Employees
Where Dept = 'R&D'
Order By Salary

Do you need that Order By Clause? Often, people use Order By in development to make sure returned data are ok; remove it if you don't need it.
If you need to sort the data, do it in the query, not in the program.

Example 3:
Original:
For i = 1 to 2000
Call Query : Select salary From Employees Where EmpID = Parameter(i)

Corrected:
Select salary From Employees Where EmpID >= 1 and EmpID <= 2000

The original Query involves a lot of network bandwidth and will make your whole system slow.
You should do as much as possible in the Query or Stored Procedure. Going back and forth is plain stupid.
Although this example seems simple, there are more complex examples on that theme.
Sometimes, the processing is so great that you think it's better to do it in the code but it's probably not.
Sometimes, your Stored Procedure will be better off creating a temporary table, inserting data in it and returning it than going back and forth 10,000 times.
You might have a slower query that saves time on a greater number of records or that saves bandwidth.

Example 4 (Weak Joins):
You have two tables Orders and Customers. Customers can have many orders.

Original:
Select O.ItemPrice, C.Name
From Orders O, Customers C

Corrected:
Select O.ItemPrice, C.Name
From Orders O, Customers C
Where O.CustomerID = C.CustomerID

In that case, the join was not there at all or was not there on all keys. That would return so many records that your query might take hours.
It's a common mistake for beginners.

Corrected 2:
Depending on the DB you use, you will need to specify the Join type you want in different ways.
In SQL Server, the query would need to be corrected to:

Select O.ItemPrice, C.Name
From Orders O INNER JOIN Customers C ON O.CustomerID = C.CustomerID

Choose the good join type (INNER, OUTER, LEFT, ...).
Note that in SQL Server, Microsoft suggests you use the joins like in the Corrected 2 instead of the joins in the Where Clause because it will be more optimized.

Example 5 (Weak Filters):
This is a more complicated example, but it illustrates filtering at its best.
We have two tables -- Products (ProductID, DescID, Price) and Description(DescID, LanguageID, Text). There are 100,000 Products and unfortunately we need them all.
There are 100 languages (LangID = 1 = English). We only want the English descriptions for the products.

We are expecting 100 000 Products (ProductName, Price).

First try:
Select D.Text As ProductName, P.Price
From Products P INNER JOIN Description D On P.DescID = D.DescID
Where D.LangID = 1

That works but it will be really slow because your DB needs to match 100,000 records with 10,000,000 records and then filter that Where LangID = 1.
The solution is to filter On LangID = 1 before joining the tables.

Corrected:
Select D.Text As ProductName, P.Price
From (Select DescID, Text From Description Where D.LangID = 1) D
INNER JOIN Products P On D.DescID = P.DescID

Now, that will be much faster. You should also make that query a Stored Procedure to make it faster.

Example 6 (Views):
Create View v_Employees AS
Select * From Employees

Select * From v_Employees

This is just like running Select * From Employees twice.
You should not use the view in that case.

If you were to always use the data for employees of R&D and would not like to give the rights to everyone on that table because of salaries being confidential,
you could use a view like that:

Create View v_R&DEmployees AS
Select Name, Salary From Employees Where Dept = 1
(Dept 1 is R&D).

You would then give the rights to View v_R&DEmployees to some people and would restrict the rights to Employees table to the DBA only.

That would be a possibly good use of views.