Posts

Showing posts from 2008

Refresh Button Issue

//Following Statement is used to avoid reexecution of Insert, Update, Delete Data to the Database when user press the Refresh button or F5 in browser. Response.Redirect(Request.Url.ToString(), false);

scaffolding

scaffolding is mechanism that enhance the functionality of the existing ASP.NET Framework by adding the ability to dynamically display pages based on the data model of the database. To see the Example Click Here

LINQ Basic

LINQ BASIC I am starting from this mail to show the technical skills to work with LINQ . The following is a very basic LINQ Query Expression Example: string[] strCities = { "Mumbai", "Delhi", "Surat", "Chennai", "Ahemdabad", "Jaipur" }; IEnumerable strResult = from city in strCities select city.ToUpper(); grdLinqBasic.DataSource = strResult; grdLinqBasic.DataBind(); In the above Example I am using the array of string and then using LINQ query expression against the array. I am also applying a string operation in the query itself, which help us to modify the result in the query itself. LINQ queries return results of type: IEnumerable Where is determined by the object type of the “select” clause of the query. In the above sample “city” is string. So the above example have the IEnumerable type is “string”. LINQ is STORNGLY-TYPED It means we can have compile-time c

To provide file download Facility in ASP.Net

Image
To provide file download facility to use in from the website the following code need to be done in the button click event protected void Button1_Click(object sender, EventArgs e) { string path = Server.MapPath("html-character-entities-cheat-sheet.pdf"); string name = System.IO.Path.GetFileName(path); Response.AppendHeader("content-disposition","attachment; filename=" + name); Response.ContentType = "Application/pdf"; Response.WriteFile(path); Response.End(); }

To Avoid Popup Blocker to open Pop up from website.

The Following code will used to open popup window and the popup blocker will not block it. Code Of The Parent Page of Popup <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPopupBlocker.aspx.cs" Inherits="TestPopupBlocker" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" &gt ; <html xmlns=" http://www.w3.org/1999/xhtml " > <head runat="server"> <title>Untitled Page</title> <script language ="javascript"> function getAjaxXml() { var xml; if(document.all) { //IE xml = new ActiveXObject("Microsoft.XMLHTTP"); } else { //FF,Opera,NN

Chanakya's Quotes - Worth reading a million times…

Chanakya's Quotes - Worth reading a million times… *************************************************** 'A person should not be too honest. Straight trees are cut first and Honest people are victimised first.' *************************************************** 'Even if a snake is not poisonous, it should pretend to be venomous.' *************************************************** 'The biggest guru-mantra is: Never share your secrets with anybody. ! It will destroy you.' *************************************************** 'There is some self-interest behind every friendship. There is no Friendship without self-interests. This is a bitter truth.' *************************************************** 'Before you start some work, always ask yourself three questions - Why am I doing it, What the results might be and Will I be successful. Only when you think deeply and find satisfactory answers to these questions, go ahead.' ****************

Anger & Love

ANGER & LOVE While Dad was polishing his new car, his four-year old son picked up a stone & scratched lines on the side of the car. In his anger, Dad took the child's hand & hit it many times, not realizing he was using a wrench. At the hospital, his child said, "Dad, when will my fingers grow back?" Dad was so hurt, he went back to the car and kicked it a lot of times. Sitting aside, he looked at the scratches. Child wrote, "I LOVE YOU DAD". ANGER & LOVE have no limits..... we never realize when we hurt someone..... its easy hurting..... n its easy forgiving but its very hard to forget..... specially for the one who's hurt..... Whenever you are angry remember this story...

Error Logging using ASP.NET 2.0

Error Logging using ASP.NET 2.0 This article has been republished with a few minor changes. Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application. In this article, we will adopt a simple mechanism to log errors and exceptions in our website. We will be using a mechanism where the user will be redirected to a separate page whenever an error is encountered in the application. Simultaneously, the error will get logged in a text file on the server. The error file will be created on a daily basis, whenever the error is encountered. Having said that, let us now see some code. Step 1: Start by creating an Error folder where all errors will be logged. Right click the website > New Folder. Rename the folder to “Error”. Also add a web.config file, if one does not already exist in your site. Right click the website > Add New Item > Web.config. Step

Using Session State with SQL Server

SQL Server Session State in ASP.NET 2.0 The Following Command is used to install Sql Server Session state for ASP.NET 2.0 c:\Program Files\Microsoft Visual Studio 8\VC>aspnet_regsql.exe -C "Data Source=PC8\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True" -ssadd -sstype c Start adding session state. .......... Finished. To use this custom session state database in your web application, please specify it in the configuration file by using the 'allowCustomSqlDatabase' and 'sqlConnectionString' attributes in the \ section. c:\Program Files\Microsoft Visual Studio 8\VC> The Following statement is needed to add in WEb.config File < system.web > < sessionstate allowcustomsqldatabase="true" timeout="20" mode="SQLServer" cookieless="false" sqlconnectionstring="Data Source=PC8\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True" > < /sessionstate > < /SYSTEM.W

SQL Query With Parameter

To Query on Sql Server With Parameter- The Best Way string sqlCon = ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString; SqlConnection con = new SqlConnection(sqlCon); SqlCommand com = new SqlCommand("select * from Test1 where ID=@ID", con); com.Parameters.Add("@ID", SqlDbType.Int).Value = 6; SqlDataAdapter adp = new SqlDataAdapter(com); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind();

Why the Elephants Don't Run?

Why the Elephants Don't Run? A number of years ago, I had the rather unique experience of being backstagein Madison Square Garden, in New York, during the Ringling Brothers Barnum &Bailey Circus. To say the least, it was a fascinating experience. I was ableto walk around looking at the lions, tigers, giraffes and all the othercircus animals. As I was passing the elephants, I suddenly stopped, confusedby the fact that these huge creatures were being held by only a small ropetied to their front leg. No chains, no cages. It was obvious that theelephants could, at any time, break away from their bonds but for somereason, they did not. I saw a trainer near by and asked why these beautiful,magnificent animals just stood there and made no attempt to get away."Well," he said, "when they are very young and much smaller we use the samesize rope to tie them and, at that age, it's enough to hold them. As theygrow up, they are conditioned to believe they cannot break away

GridView Manual Sorting

/// /// The GridView_OnSorting event which is fired when the header of the column to sort is clicked. /// /// /// protected void gvItems_Sorting(object sender, GridViewSortEventArgs e) { try { DataTable dt = GetAllItems(); DataView dv = new DataView(dt); if (GridViewSortDirection == SortDirection.Ascending) { GridViewSortDirection = SortDirection.Descending; dv.Sort = e.SortExpression + " DESC"; } else { GridViewSortDirection = SortDirection.Ascending; dv.Sort = e.SortExpression + " ASC"; } gvItems.DataSource = dv; gvItems.DataBind(); } catch (Exception ex) { } } /// /// The GridV

To Read, Write, append and Edit To XML File

Write To The XML File: filename = Server.MapPath("test.xml"); string strId = "1"; string strFourmName = "NewlyDiagnose"; string strTopic = "how r u"; string strUserName = "jaimin"; string strPostBy = "modi"; string strDate = "11/11/2007"; XmlTextWriter xtw = new XmlTextWriter(filename, null); xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement(strFourmName); xtw.WriteStartElement("item"); xtw.WriteAttributeString("Id", strId); xtw.WriteElementString("Topic", strTopic); xtw.WriteElementString("UserName", strUserName); xtw.WriteElementString("PostBy", strPostBy); xtw.WriteElementString("Date", strDate); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndDocument(); xtw.Flush(); xtw.Close(); // for append file......... XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("test.xml")); XmlElement s = doc

To Read and Write to Excel file

Image
string strFilePath = FileUpload1.PostedFile.FileName; string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ strFilePath+";Extended Properties=Excel 8.0;"; //write into excel file OleDbConnection oldbcon=new OleDbConnection(connectionString); OleDbCommand oldc = new OleDbCommand("Insert into [Age$](Name,Age) values('Nirav',23)", oldbcon); oldbcon.Open(); int i=oldc.ExecuteNonQuery(); oldbcon.Close(); //Read from Excel file DataSet cities = new DataSet(); OleDbDataAdapter oledbAd = new OleDbDataAdapter("Select * from [Age$]", connectionString); oledbAd.Fill(cities); GridView1.DataSource = cities; GridView1.DataBind(); //The Excel File

Good To Know

Here are somethings you may not know...... 1. Coca-Cola was originally green. ---------------------------------------------------------------------- 2. The most common name in the world is Mohammed. ---------------------------------------------------------------------- 3. The name of all the continents ends with the same letter that they start with. ---------------------------------------------------------------------- 4. The strongest muscle in the body is the tongue. ---------------------------------------------------------------------- 5. There are two credit cards for every person in the United States . ---------------------------------------------------------------------- 6. TYPEWRITER is the longest word that can be made using the letters only on one row of the keyboard. ---------------------------------------------------------------------- 7. Women blink nearly twice as much as men! --------------------------------------------------------------------- 8. Y

Even if u answer **five** questions its great...Feel proud...

Even if u answer **five** questions its great...Feel proud... 1. What programming language is GOOGLE developed in? 2. What is the expansion of YAHOO? 3. What is the expansion of ADIDAS? 4. Expansion of Star as in Star TV Network? 5. What is expansion of "ICICI?" 6. What does "baker's dozen" signify? 7. The 1984-85 season. 2nd ODI between India and Pakistan at Sialkot - India 210/3 withVengsarkar 94*. Match abandoned. Why? 8. Who is the only man to have written the National Anthems for two different countries? 9. From what four word ex-pression does the word `goodbye` derive? 10. How was Agnes Gonxha Bojaxhiu better known? 11. Name the only other country to have got independence on Aug 15th? 12. Why was James Bond Associated with the Number 007? 13. Who faced the first ball in the first ever One day match? 14. Which cricketer played for South Africa before it was banned from internationalcricket and later represented Zimbabwe ? 15. The faces of which four Preside

Default Page Load Event Calling Every time any page navigate of the site

Problem: Default Page Load Event Calling Every time any page navigate of the site. Solution: IT happens only if you have any "img" tag with 'scr=" " ' in this case the iis will redirect the response to the default page of the site and then again it will go to your calling page. but increase the extra load of excuting default page's page_load event.

Teacher Student Jokes

Teacher:"What is your name?". Student:"Mera naam Suraj Prakash hai." Teacher:"When I ask a question in English, answer it in english." Student:"My name is Sunlight. ------------ --------- --------- --------- --------- --------- --------- ---------- Teacher: What happened in 1869? Student:Gandhi ji was born. Teacher :What happened in 1873? Student:Gandhiji was four years old. ------------ --------- --------- --------- --------- --------- --------- ---------- Question:What is the fullform of maths. Answer: Mentally affected teachers harassing students ------------ --------- --------- --------- --------- --------- --------- -------------- Teacher : Now children , if I saw a man beating a donkey and stopped him then what virtue would I be showing ? Student : BROTHERLY LOVE ------------ --------- --------- --------- --------- --------- --------- -------------- Teacher :Because of Gandhiji's hard work what do we get on 15th August. Student:A holiday ---
SQL Stored Procedure to Send Email using OLE You Just need to change SMTP Server address CREATE PROCEDURE [dbo].[WSA_sp_SendEmail]@From varchar(100),@To varchar(1000),@Subject varchar(250),@Body varchar(max),@CC varchar(1000) = nullASBEGINDeclare @iMsg intDeclare @hr intDeclare @source varchar(255)Declare @description varchar(500)Declare @output varchar(1000)EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUTPrint @FromEXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', '10.0.0.100'EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null--Print @ToEXEC @hr = sp_OASetProperty @iMsg, 'To', @ToEXEC @hr = sp_OASetProperty @iMsg, 'From', @Fromif (@Cc <> '')EXEC @hr = sp_OASetProperty @iMsg, &

To Read and Write to Text file from ASP.NET

To Write C# code If the file does not exist you will get an error. You can check to see if the file exists using this code: if (System.IO.File.Exists(Server.MapPath("test.txt"))) To write the contents of a TextBox control to a text file using the System.IO.StreamWriter class use the following code: System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(Server.MapPath("test.txt")); StreamWriter1.WriteLine(TextBox1.Text); StreamWriter1.Close(); Inserting "\r\n" will create a line break in the text file. Adding line breaks from code can be done using this code: StreamWriter1.WriteLine("Some text on line1.\r\nSome text on line2."); To Read c# code System.IO.StreamReader StreamReader1 = new System.IO.StreamReader(Server.MapPath("test.txt")); TextBox2.Text = StreamReader1.ReadToEnd(); StreamReader1.Close();

To Insert Data into Excel using Office object libray

C# file code 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; using Microsoft.Office.Interop.Excel; using System.Reflection; using Microsoft.Office.Core; using System.Drawing; using SAMSBusinessLayer; using SAMSDataAccessLayer; using System.IO; using System.Diagnostics; public partial class Admin_Report_SamsReport : basePageSessionExpire { #region Private_Variable Microsoft.Office.Interop.Excel.Application excelapp; Microsoft.Office.Interop.Excel.Workbook wb; int iSelectedMonth = 0; int iSelectedYear = 0; ExecuteSummaryDataFilter objExecuteSummaryDataFilter; ExecuteSummaryData objExecuteSummaryData; int iRowNo_for_Executive_Summary_Sheet = 1; int iRowNo_for_Slide_Views_Sheet = 1; int iRowNo_for_Fulfillment_Report_Sheet = 1; string Table_Logins_By_Month_StartRange = "&q