Sharing knowledge in Project, Program, Portfolio Innovation Management (PPIM) and various Technology.
Monday, April 7, 2008
How to Show Binary Files in the Browser using ASP.NET and VB.NET
1)Create an asp.net web project. Name the project as ShowBinary
2) Add a file of type (.gif,.jpg,.doc,.xls) to the project
3) Specify a Start page for the application4) Use following code snippet in the form load event handler
Private Sub Page_Load(sender as object, e as System.EventArgs)
Response.ContentType = “Application/pdf” ‘ Specify Content Type
Dim fpath as string = Mappath(“Mypdf.pdf”) ‘ Specify Physical Path of the file
Response.writefile(fpath)
End Sub
ASP.NET 2.0 MultiView Control
<asp:MultiView ID="MultiView1" runat="server" >
<asp:View ID="View1" runat="server">This is one section where you can have a set of controls / contents<asp:View>
<asp:View ID="View2" runat="server">This is another section where you can have a different set of controls / contents<asp:View>
</asp:MultiView>
Now, to show the different tabs based on different events, we just need to set the following code:-
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
}
"goto" Using Dotnet framework 2.0
{
Response.Write("Testing Goto");
goto Testing;
Testing:
Response.Write("Testing Goto in for loop");
}
output
Testing GotoTesting Goto in for loop
COALESCE using Sqlserver
now in new pl/sql version having the COALESCE function,
The magic of function is, it will automatically add "," seprator of employeelist.
///////////////////////////Before COALESCE ///
DECLARE @Emp_UniqueID int,
@EmployeeList varchar(100)
SET @EmployeeList = ''
DECLARE crs_Employees CURSOR
FOR SELECT Emp_UniqueID
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
OPEN crs_Employees
FETCH NEXT FROM crs_Employees INTO @Emp_UniqueID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @EmployeeList = @EmployeeList+CAST(@Emp_UniqueID AS varchar(5))+ ', '
FETCH NEXT FROM crs_Employees INTO @Emp_UniqueID
END
SET @EmployeeList = SUBSTRING(@EmployeeList,1,DATALENGTH(@EmployeeList)-2)
CLOSE crs_Employees
DEALLOCATE crs_Employees
SELECT @EmployeeLis
Output:
1, 2, 4
///////////////////////////After COALESCE/////////////
DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT @EmployeeList
Output:1,2,4
/////////////////////////////////////////////////////////////////////////////
Anonymous delegate using Dotnet framework 2.0
{
System.Console.Write("hi");
});
Th.Start();
Breaking out a loop in two ways
1) firstway is using "break" keyword
2) Second way is using variable declaration.
//First way
for (int i = 0; i < 5; i++)
{
Response.Write("bala");
break;
}
//Second Way
bool br = false;
for (int j = 0; j < 2&& br == false; j++)
{
Response.Write("testingbala");
br = true;
}
Nullable DataType in Dotnet Framework 2.0
If you dont have the value for nullable datatype, it will return automatically null as a value.
Example 1:
int? var1 = null;
int var2 = 5;
var1 = var2;
if (var1.HasValue == true) //Using HasValue properties will will findout "var1" variable having value or null.
{
Response.Write("bala");
}
else
{
Response.Write("bala1");
}
Output:
bala
Example 2:
float? a = 436;
float? b = null;
if (a.HasValue) Response.Write("testing");
if (b.HasValue) Response.Write("testi"); else Response.Write("test");
Output:
testingtest
Tuesday, March 25, 2008
Calling Javascript in Dotnet based on Button id
<script language="javascript" type="text/javascript">
{
var con=confirm("Are sure want to delete this");
var test;
if(con==false)
{
alert("test");
}
else
{
alert("test1");
}
}
</script>
<asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" />
In C# Page
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(btnsubmit, typeof(string), "bala", "Getconfirm();", true);
}
Note:btnsubmit is control id.
Monday, March 17, 2008
Windows Communication Foundation

WCF is nothing but a Distributed system. Combination of Object Oriented Architechtre and Service Oriented Architecture.
NET 3.0 comes with three main technologies in core: Windows Presentation Foundation, Windows Workflow Foundation and Windows Communication Foundation.
Windows Communication Foundation (WCF), codenamed Indigo in Microsoft, is the last generation of service oriented technologies for development. It provides all the latest means to help developers build service oriented applications. The result of service oriented design is a distributed system which runs between services and clients. Windows Communication Foundation is Microsoft infrastructure for Service Oriented architecture
Advantages
Windows Communication Foundation has some important enhancements in comparison with preceding technologies·
. It merges all older separate technologies in one place and allows you to do things easier.
· It has rich communication capabilities.
· It comes with many powerful and ready to use enterprise features.
· It can be integrated with other technologies and has great interoperability.
Windows Communication Foundation consists of three main concepts.
· Services: Programs that respond to clients. They can send or receive messages.
· Clients: Programs that ask for a service. They can send or receive messages.
· Intermediaries: Programs that sit between services and clients (Figure 2). They can work as a firewall or can rout messages. In all cases neither services nor clients need to be aware of intermediaries.
Architecture of Windows Communication Foundation consists of five layers. These layers from top to down are:
· Application: In this level application is located.
· Contracts: In the second layer service, data and message contracts as well as bindings and policies are present. In this level services describe themselves to clients.
· Runtime: Behaviors are located in this layer. Runtime layer loads all services.
· Messaging: Different types of channels as well as encoders are here. This layer enables communications for services.
· Hosting: This layer is where host services in different manners, but there are two common ways to host a service. You can host a service in Internet Information Services (IIS) which is easier than the second approach and starts and stops your services automatically. The second approach is to create executable files (.EXE) for services and start and stop them manually by writing more codes.
Windows Communication Foundation has simple and easy to write/understand codes. It has many APIs, but beside this only a small amount of these API's is common.
There are three programming approaches in Windows Communication Foundation:
· Imperative: You use programming codes in different languages to accomplish a task.
· Configuration Based: You use configuration files to do things.
· Declarative: You use attributes to declare something.
On the other hand, you can use typed services and untyped services. In typed services you pass normal objects and data types and/or get normal objects and data types, but in untyped services you pass and get messages to work directly with messages at a lower level..
Installation
Installation of Windows Communication Foundation and its development tool is easy and consists of these steps:
· Download and install .NET Framework 3.0 RTM. I also strongly recommend you to download and install WinFX SDK as well. After this step you have all necessary API's to run Windows Communication Foundation.
· Download and install Visual Studio 2005xtensions for .NET Framework 3.0 WCF and WPF). After installing this package, you will have new project templates in your Visual Studio to start developing for Windows Communication Foundation
Sunday, March 16, 2008
verbatim literal
Another useful feature of C# strings is the verbatim literal
which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".
Cracking .NET Assemblies
This is nice articale for cracking the .net assemblies
http://www.grimes.demon.co.uk/workshops/fusionWSCrackThree.htm#Cracking_Whidbey_Assemblies
Monday, February 25, 2008
Encrypt and Decrypt configuration files using Code
Using System.web.configuration;
Protected void button_click(object sender,eventargs e)
{
string webconfigpath="~";
configuration config=webconfigurationmanager.openwebconfiguration(webconfigpath);
configurationsection configsection=config.Getsection("connectionstrings");
configsection.sectionInformation.protectsection("Dataprotectionconfigurationprovider");
config.save();
}
How to decrypt connection string in asp.net stored in web.config.
Using System.web.configuration;
Protected void button_click(object sender,eventargs e)
{
string webconfigpath="~";
configuration config=webconfigurationmanager.openwebconfiguration(webconfigpath);
configurationsection configsection=config.Getsection("connectionstrings");
configsection.sectionInformation.Unprotectsection();
config.save();
}
Encryption connectionstring .NET Framework 2.0 using Tool
Configuration File Encryption
In the .NET Framework 2.0, developers will be able to encrypt sensitive parts of the web.config file (if containing password or keys, for instance) using the aspnet_regiis utility. The decryption is done transparently.
The DPAPI protected configuration provider supports machine-level and user-level stores for key storage. The choice of store depends largely on whether or not the application shares state with other applications and whether or not sensitive data must be kept private for each application.
If the application is deployed in the Web farm scenario, developers should use RSAProtectedConfigurationProvider to leverage the ease with which RSA keys can be exported on multiple systems. It uses RSA public key cryptography to provide data confidentiality.
The following example encrypts the connection string section using the tool aspnet_regiis:
try out this...
aspnet_regiis.exe -pef "connectionStrings" C:\VirtualDirectory\Path
URL Mapping in asp.net 2.0
URL Mapping is a mechanism by which you can change the displayed url in address bar.
Example
Step1: Add Mapping URL in web.config file.<system.web>
<urlMappings enabled="true">
<add url="~/Department.aspx" mappedUrl=" oldforms/frmDept.aspx"/>
<add url="~/Employee.aspx" mappedUrl=" oldforms/frmEmployee.aspx"/>
<add url="~/Product.aspx" mappedUrl="& gt;
</urlMappings></system.web>
Step2: Change the URL in .aspx file
<a href="Department.aspx">Department</a><br />
<a href="Product.aspx">Product</a><br />
<a href="Employee.aspx">Employee</a>
Thursday, February 21, 2008
Tips & Tricks for Dotnet
1. Press Ctrl+I.
2. Start typing the text you are searching for. Note: you'll see the cursor jump to the first match, highlighting the current search string.
3. Press Ctrl+I again to jump to the next occurrence of the search string.
4. To stop search, press Esc. Advanced tip: Press Ctrl+Shift+I to search backwards.
2) Make Window Fit any Resolution
Create function definition
<script language="Javascript">
function resolution()
{
UserWidth = window.screen.availWidth
UserHeight = window.screen.availheight
window.resizeTo(UserWidth, UserHeight)
window.moveTo(0,0)
}
</script>
</head>
2) Call the function on load event of body.
<body OnLoad=”resolution();”>
3) Adding a Print Button with Javascript
Add this line to the Page_Load event
btnPrint.Attributes("onClick") ="javascript:window.print();"
*Add a button to the page called 'btnPrint' Technically, that's it, but, let's say you want to do something a little fancier, using DotNet.
Then, add a subroutine (let's call it 'DoPrint'):
Sub doPrint(Source as Object, E as EventArgs)
lblResults.visible="True"
lblResults.text="Page has successfully been sent to the printer!"
End Sub
Then, add a direction to this sub, in the button's tag: onServerclick="doPrint"
4) *To print certain areas of a page
Create a style sheet for printing purpose, normally by removing/hiding background colors, images.... After that include it with media="print",
so that this style sheet will be applied while printing.
<LINK media="print" href="styles/printStyle.css" type="text/css" rel="stylesheet">
5) Fade Effect on Page Exit
<meta http-equiv="Page-Exit" content="progid:DXImageTransform.Microsoft.Fade(duration=.9)">
6)Disabling a Button Until Processing is Complete
Here's the scenario - let's say you have an Insert subroutine,
called 'doInsert'.
You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times. For this,
use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this:
<INPUT id="Button1" onclick="document.form1.Button1.disabled=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert">
Then, in the very last line of the 'doInsert' subroutine, add this line: Button1.enabled="True"
Javascript Debugger Enabling
function someFunct()
{
Javascript:debugger;alert(window.name)
alert("Mahesh");
}
Tuesday, February 19, 2008
What's new in C# 3.0
Local variables can be declared as type var, whose actual type of the variable is determined by the compiler based on the data schema (see Listing 1). It's mainly used to store anonymous types in LINQ.
// This is an integer
var nId = 1234567;
//This is a string
var strFullname = "John Charles Olamendy Turruellas";
Sunday, February 17, 2008
XML
Well, that's quite a question, xml is a platform and language independent, which means it doent matter that computer may be using(Solaris, unix, linux), XML is potential fit for exchange format. The following are just few example.
1)Reducing Server load.
2)Web site Content.
3)RPC(Remote procedure call).
4)E-Commerce.
2) Illegal PCDATA Character
They are some reserverd character that you cant include in your PCDATA(Parsed Character Data) because they are used in xml syntax. The below characters are reserved word in xml.
1) &
2) <
3) >
4) '
5) ""
They are two ways you can get around this,
1) Escaping characters.
2)Enclosing tag with CDATA Sections.
1)Escaping Characters.
& -- amp;
<--lt;
2)Enclosing tag with CDATA Sections.
if you have lot of "<" and ">" that you need to cdata.
<test><![cdata[<is<7&7>7]]></test>
Output
<is<7&7>7
Stylee Sheet Using XML
Coming soon....
Wednesday, February 13, 2008
How to use DbProviderFactory and DbConnection
Refer this
http://www.developer.com/net/net/print.php/11087_3530396_2
Example
DbProviderFactory Factory = DbProviderFactories.GetFactory("DDTek.Oracle");DbConnection Conn1 = Factory.CreateConnection();
Conn1.ConnectionString ="Host=Accounting;Port=1521;User ID=scott;Password=tiger; " + "Service Name=ORCL;Min Pool Size=50";
Conn1.Open();// Pool A is created and filled with connections to the //
minimum pool size
DbConnection Conn2 = Factory.CreateConnection();
Conn2.ConnectionString = "Host=Accounting;Port=1521;User ID=Jack;Password=quake; " + "Service Name=ORCL;Min Pool Size=100";
Conn2.Open();// Pool B is created because the connections strings differDbConnection Conn3 = Factory.CreateConnection();
Conn3.ConnectionString = "Host=Accounting;Port=1521;User ID=scott;Password=tiger; " + "Service Name=ORCL;Min Pool Size=50";Conn3.Open();//
Conn3 is assigned an existing connection that was created in // Pool A when the pool was created for Conn1
Friday, February 8, 2008
Statemanagement Using C#.Net
State Management is a process of maintaining the state of the control or variable after page postback from server or between pages. In Asp.Net we are having many ways to maintain the state management. Basically it is dividied into server side and client side state management. Depends on the resource that we have to plan. They are as follows....
1. Session state
2. Hidden Variables
3. Query String
4. Cookies
5. ViewState
6. Caching
Out of which session state and caching are server side state management. others are client side state management.
1. Session StateSession State is responsible for maintaining the state of a variable between pages and page postback. There are two types of session state. They are
a. Application state
b. Session state
An object that is instant in application state will be available to the entire application. The lifetime of that instance will be available as long as application exists. Synatax for it is
Application.lock();
Application["Name"] = "Senthil";
Application.unlock();
string strName = Application["Name"].ToString();
and an instance created in session state will be available for that session (i.e browser).
Session["RoleID"] = "ADMIN";
string strRole = Session["RoleID"].ToString();
Session state can stored in three places
a. InProc - same system
b. StateServer - storing values in other server. Use " net start aspnet_state" for configuring the state server.
c. SQLServer - In database - use "aspnet_regsql" for configuring the sql server.
This can be set in web.config
<configuration> <system.web> <sessionstate mode="InProc" stateserver="129.23.33.53" sqlserver="" cookieless="true" /> </system.web></configuration>
To get more info about state management, set the trace to on
<configuration> <system.web> <trace enable="true" pageoutput="true" />
</system.web>
If pageoutput is set to false, then we find the contents in trace.axd file which is available in the root folder.
2. Hidden variables
Hidden controls are for storing few informations and retrieving it when page gets submits. We cannot get one hidden value in another page. The syntax for hidden variables are as follows.
<input type="hidden" name="hid" value="">
<%=Request.Form("hid")%>
3. QueryString
Easiest way to transfer data between pages is the querystring. But we cannot transfer a bulk of data through it. Basically querystring has two keywords ? and &.
Example
document.frm.action="login.aspx?Name=" & strName & "?Role=ADMIN"
<%= Request.QueryString["Name"] %>
4. Cookies
Cookies are client side and it is used to store few values in the client machine. We cannot create cookies in server side. Many browsers restrict using cookies in the websites. The class that supports cookies in dotnet are HttpCookies.
5. ViewState
ViewState are used to maintain the state of the control. It can be set page wise or control wise. To set it by page wise
<% @ Page EnableviewState="True" %>
For setting viewstate control wise set the viewstate property to true.
The value of the control would be retained once the pages get postback.
6. Caching
Caching too places a part in state management. Its similar to session state but the only difference is we have to set the duration for it.
Caching can be done by page levels or application levels.
Syntax for page level caching[CODE]
<% outputcache duration="10" valuebyParam="none" />[CODE]
Thursday, February 7, 2008
Working with XML and DataSets
1) Getxml Method
The getxml method lets you to convert the dataset to xml.
Example
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("id");
DataColumn dc2 = new DataColumn("firstname");
DataColumn dc3 = new DataColumn("lastname");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
for (int i = 0; i < 3; i++)
{
DataRow dr=dt.NewRow();
dr[0] = i.ToString();
dr[1] = "sdf";
dr[2] = "test";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
string getxmldata = ds.GetXml();
How to access XPathNavigator using XML DOM
access the node or set of nodes in an xml document. xpath treats xml document as a tree
structure.
xpath implementation recognize the several node types in the xml document, such as root, node, element, attribute, comment, white space, significant whitespace, namespace,
Xpath class defined in the system.xml.path, Xpath navigator can access any of the datasource , such as Dataset, database, xml document.
The below code describe , how to acces the xpathnavigator class.
XPathDocument Doc = new XPathDocument("emp.xml");
XPathNavigator navigator = Doc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/employees/employee");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Name);
Console.WriteLine(iterator.Current.Value);
}
Inserting some values in XML DOM
The DOM class lets you read, write , manipulate the xmldocument.
The below examlple for reading and writing xml in file using xmldocument objects.
string getvalueexisting = string.Empty;
string getvaluetag = string.Empty;
string s = string.Empty;
string firstname = txtfirstname.Text;
string lastname = txtlastname.Text;
string address = txtaddress.Text;
string path = Server.MapPath("XMLDATA");
XmlDocument copyexisting = new XmlDocument();
copyexisting.Load(path + "\\test.xml");
XmlTextReader XTR = new XmlTextReader(path + "\\test.xml");
while (XTR.Read())
{
if (XTR.Name != "student")
{
if (XTR.NodeType == XmlNodeType.Element)
{
getvalueexisting += "<" + XTR.Name + ">";
}
if (XTR.NodeType == XmlNodeType.Text)
{
getvalueexisting += XTR.Value;
}
if (XTR.NodeType == XmlNodeType.EndElement)
{
getvalueexisting += "</" + XTR.Name + ">";
}
}
}
XTR.Close();
s = "<student>" + getvalueexisting + "<abc><firstname>" + firstname + "</firstname><lastname>" + lastname + "</lastname><address>" + address + "</address></abc></student>";
xmldoc.LoadXml(s);
xmldoc.Save(path + "\\test.xml");
Displaying images in URL
Create a image which you want to display on the url.
Go to favicon.comThere you have a browse option.Select the image from your local machine
using the browse optionClick submitIt will create a small icon and it will display on the page.
Right click and save as "favicon.ico"
Give the exact file name as favicon.ico.Normally it opens in paint.
Now paste that image in your website root directory and on your masterpagewithin <head></head> tags copy and paste the below given link tag:
<link rel="shortcut icon" href="favicon.ico" />
Thats it! You can view it on the url!
Wednesday, February 6, 2008
Using Keyword advantage in framework 2.0
using (SqlConnection myconn = new SqlConnection(connstring))
{
using (SqlCommand mycomm = new SqlCommand("select * from employee", myconn))
{
mycomm.CommandType = CommandType.StoredProcedure;
myconn.Open(); /////Here u opened the connection but no close
SqlDataReader myread;
myread = mycomm.ExecuteReader();
dt.Load(myread);
}
}
Note
This above code work only in C#
Accesing Parent Window through Childwindow using Javascript
alert(window.opener.document.getElementById("HidString").value)
///////////////////////End Accessing Id///////////////////////////
///////////////////////Accessing Function///////////////////////////
child.aspx
window.opener.LoadEmp(obj)
parent.aspx
function LoadEmp(ob)
{
alert(ob);
}
///////////////////////End Accessing Function///////////////////////////
///////////////////////Refershing Parent Page from Child page////////////
Response.Write("<script language='javascript'>
window.opener.location.href=opener.location.href;</script>");
Using Javascript creating control without postback
////Note dont delete the id of table (i am using that in javascript)////////
<table cellspacing="0" cellpadding="0" width="100%" border="0" id="Tellafriend1">
<tr>
<td colspan="3" align="right"><input type="button" value="Addmore" onclick="fnAddRow()" /> <input type="button" value="DeleteRow" onclick="fnDelRow()" /></td>
</tr>
<tr>
<td colSpan="3"><br /></TD>
</tr>
<tr>
<td>
Friend Name</td>
<td>
Email Id</td>
<td>
Delete</td>
</tr>
<tr>
<td>
<input type="text" id="txtfriendname1" name="txtfriendname1" /></td>
<td>
<input type="text" id="txtfriendemail1" name="txtfriendemail1" /></td>
<td>
<input type="checkbox" disabled="true" id="chkdelete" name="chkdelete" />
</td>
</tr>
</table>
/////////////////////////////////Javascript///////////////////////////
///////////////////This is for adding row/////////////////////////////
var rowcount=1;
var checkcount=1;
function fnAddRow()
{
rowcount++;
// var check=validate(); //this is for my page validation
if(check!=false)
{
var objTbl = document.getElementById("Tellafriend1");
var objTbody = objTbl.getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
//txtfriendname///
var friendnameval=document.createElement("td");
var friendnameDel = document.createElement("INPUT")
friendnameDel.setAttribute("type","text");
friendnameDel.setAttribute("name","txtfriendname"+rowcount);
friendnameDel.setAttribute("id","txtfriendname"+rowcount);
friendnameval.appendChild(friendnameDel)
row.appendChild(friendnameval);
//txtfriendname///
//txtfriendemail///
var friendemailval=document.createElement("td");
var friendemailDel = document.createElement("INPUT")
friendemailDel.setAttribute("type","text");
friendemailDel.setAttribute("name","txtfriendemail"+rowcount);
friendemailDel.setAttribute("id","txtfriendemail"+rowcount);
friendemailval.appendChild(friendemailDel)
row.appendChild(friendemailval);
//txtfriendemail///
//checkbox///
var checkval=document.createElement("td");
var ChkDel = document.createElement("INPUT")
ChkDel.setAttribute("type","checkbox");
ChkDel.setAttribute("name","chkDelete"+rowcount);
ChkDel.setAttribute("id","chkDelete"+rowcount);
checkval.appendChild(ChkDel)
row.appendChild(checkval);
//End check box checkbox///
objTbody.appendChild(row);
}
else
{
return false;
}
}
///////////////////End adding row/////////////////////////////
Note:For deleting i am using checkbox...................
///////////////Deleting Row//////////////////////////////////
function fnDelRow()
{
var ChkOption = ""
for(var i=2;i<=rowcount;i++)
{
var ChkCtrl = document.getElementById("chkDelete"+i)
if(ChkCtrl == '[object]')
{
if(ChkCtrl.checked)
{
ChkOption = "1"
delRow(ChkCtrl)
checkcount++;
}
}
}
if(ChkOption == "" && rowcount!=1)
{
alert("Select any one option to delete")
return false;
}
}
function delRow(button)
{
var row = button.parentNode.parentNode;
var tbody = document.getElementById('Tellafriend1').getElementsByTagName('tbody')[0];
tbody.removeChild(row);
}
/////////////////////////////End Deleting row////////////////////////////////
Reading and removing Listbox using Javascript
var listEmp=document.getElementById("PMEmpname");
for(j=0;j<listEmp.options.length;j++)
{
listEmp.options[j].value //Value field
listEmp.options[j].text //Text Field
}
///////////Deleting///////////////////////////////////
for(j=0;j<listEmp.options.length;j++)
{
listEmp.remove(j);
}
Friday, January 18, 2008
SqlCacheDependency using ASP.NET 2.0 and SQL Server 2005
SqlCacheDependency using Asp.net 2.0 and sqlserver 2005 is a beautiful thing :) Although getting SqlCacheDependency to work with SQL Server 2000 have to add some additional step.
Now we will go with Asp.net 2.0 with sqlserver 2005
Enable Service Broker
Before SqlCacheDependency will work with SQL Server 2005, you first have to enable Service Broker, which is reponsible for the notification services that let the web cache know a change has been made to the underlying database and that the item in the cache must be removed.
ALTER DATABASE Store SET ENABLE_BROKER;
GO
--SqlCacheDependency.Start() in Global.asax
In ASP.NET, you need to run SqlCacheDependency.Start(connectionString) in the Global.asax:
Example:
void Application_Start(object sender, EventArgs e)
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
SqlDependency.Start(connectionString);
}
SqlCacheDependency in ASP.NET 2.0 Example
Now you can just create your SqlCacheDependency as normal in your ASP.NET 2.0 page. Here is a simple example:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable categories = (DataTable)Cache.Get("Categories");
if (categories == null)
{
categories = GetCategories();
Label1.Text = System.DateTime.Now.ToString();
}
GridView1.DataSource = categories.DefaultView;
GridView1.DataBind();
}
private DataTable GetCategories()
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
DataTable categories = new DataTable();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID,Code,Title
FROM dbo.Categories", connection);
SqlCacheDependency dependency =
new SqlCacheDependency(command);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
categories = dataset.Tables[0];
Cache.Insert("Categories", categories, dependency);
}
return categories;
}
}
Wednesday, January 16, 2008
Scrapping using C#.Net
using System.io;
WebRequest request = WebRequest.Create("http://localhost:4733/strings.aspx");
WebResponse response = request.GetResponse();
Stream s=response.GetResponseStream();
StreamReader sr = new StreamReader(s);
string line = sr.ReadLine();
while ((line=sr.ReadLine()) !=null)
{
Response.Write(line);
}
Datatable Load option in Dotnet Framework 2.0
Definition
Using datatable.load you can load the sqldatareader value directly
Example
DataTable dt = new DataTable();
string connectionstring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection myconn = new SqlConnection(connectionstring);
SqlCommand mycomm = new SqlCommand("select * from FA_contactdetails", myconn);
myconn.Open();
SqlDataReader sqldataread = mycomm.ExecuteReader();
dt.Load(sqldataread);////
myconn.Close();
dggrid.DataSource = dt;
dggrid.DataBind();
Thursday, January 10, 2008
.NET BEST PRACTICES
# Use Master Pages for common content across pages.
# Use the “@” prefix for string literals instead of using escaped strings.
# Avoid Empty Catch-blocks# In the .NET framework 2.0: use the New AppendDataBoundItems property in ListControls.
# Close DataReaders and Connections as soon as possible.
# All important graphics should have tool tip and alternate text.
# Use Typed Datasets wherever possible and required.
# Use Validators / Validator Groups for validation.
# Include exception handling in the Application_Error event of global.asax file for unhandled exceptions – implement a Global.asax error handler.
# Choose the most appropriate data type. It is advisable to stop using the “image” data type in SQL Server for any fresh development. Microsoft is planning to phase it out in future versions of SQL Server. You should use the “varbinary(max)” data type instead.
.NET Security Tips
# Keep “Persist Security Info” as false in the connection string.
# Remove the authentication cookie in Session_End event or application specific logout event.
# Security decisions should not rely only on client-side validations – they should be verified on the server side too!
# Hashed password format should be specified in provider configuration.
# The website should be partitioned into public access areas and restricted areas that require authentication access. Navigation between these areas should not flow sensitive credentials information.
# Protect your website against Cross-Site Scripting or XSS attacks
# Dynamic queries that accept user input should be used only if stored procedures cannot be used. Even these queries should use parameters.
# Ensure that utilizing the “View source” option does not divulge any sensitive information.
# Set mode attribute in customErrors to On to prevent displaying detailed error messages to the caller.
# Ensure that utilizing the “View source” option does not divulge any sensitive information.
Performance Boosting .NET coding tips
# Instantiate Objects only if really needed { will NOT use up memory unnecessarily }
# Prefer using String.Empty instead of "" for string initialisation
# Prefer using StringBuilder for dynamic creation of Strings.
# Avoid String datatype while using Switch Case programming-construct
# Use Server.Transfer() instead of Response.Redirect() method.
# Avoid use of Page.DataBind() method
# Define the four most frequently used local variables as the first four variables.
# Even inside vb.net OR c# code, Avoid using the “select * from table” syntax.
# Use proper column case in queries.dr[“ProductName”] vs dr[“PRODUCTNAME”]
# Use Page.IsPostBack to minimize redundant processing in page load.
# Avoid server round trips (by using client scripts, validator controls, html controls, caching techniques (for pages, user controls and objects)).
# Disable view state on a control-level / page-level if you do not need it.DataGrid with ViewState disabled is 66% faster than DataGrid with ViewState enabled.
# Minimize the number of objects you store in view state.
# Use a DataReader for fast and efficient data binding.
# Prefer to Use try/finally on disposable resources.
# Minimize calls to DataBinder.Eval
Moving Listitem from left Listbox to right Listbox
{
ArrayList arrfirst = new ArrayList();
foreach (ListItem lstfirstitem in lstfirst.Items)
{
if (lstfirstitem.Selected == true)
{
arrfirst.Add(lstfirstitem);
}
}
for (int i = 0; i < arrfirst.Count; i++)
{
ListItem tst = (ListItem)arrfirst[i];
if (lstsecond.Items.Contains(tst) == false)
{ lstsecond.Items.Add(tst);
lstfirst.Items.Remove(tst);
}
}
}
protected void btnmoveleft_Click(object sender, EventArgs e)
{
lstfirst.SelectionMode = ListSelectionMode.Multiple;
lstfirst.Attributes.Add("SelectionMode", "Multiple");
ArrayList arrsecond= new ArrayList();
foreach (ListItem lstseconditem in lstsecond.Items)
{ if (lstseconditem.Selected == true)
{ arrsecond.Add(lstseconditem); }
} for (int i = 0; i < arrsecond.Count; i++)
{ ListItem tst = (ListItem)arrsecond[i];
if (lstfirst.Items.Contains(tst) == false)
{ lstfirst.Items.Add(tst);
lstsecond.Items.Remove(tst);
}
}
lstfirst.SelectedItem.Selected = false;
lstfirst.SelectionMode = ListSelectionMode.Single;
}
Maxlength checking in Textarea Using Javascript
{
var maxval=1000;
var maxtxtlength=window.document.myform.Description.value.length;
if(parseInt(maxtxtlength)>parseInt(maxval))
{
alert("This Description field accept only 1000 characters");
window.document.myform.Description.innerText=window.document.myform.Description.value.substring(0,1000);
return false;
}
}
Sunday, January 6, 2008
Friday, January 4, 2008
What is the purpose of AppendDataBoundItems for dropdown
AppendDataBoundItems
Definition:
Using this you can append dynamically.
Examplestring[] sdss ={ "test", "test1" };
this.myDropDown.AppendDataBoundItems = true;
this.myDropDown.Items.Add(new ListItem("Bitte wählen...", ""));
this.myDropDown.DataSource = sdss;
this.myDropDown.DataBind();
output
Bitte wählen
test
test1
IDictionary
ht.Add(1, "bala");
ht.Add(2, "bala1");
IDictionary idic = (IDictionary)ht;
foreach (DictionaryEntry de in idic)
{
Response.Write(de.Key);
Response.Write(de.Value);
Response.Write("
");
}
out put
2bala1
1bala
IDictionaryEnumerator
ht.Add(1, "bala");
ht.Add(2, "bala1");
IDictionaryEnumerator ss = ht.GetEnumerator();
while (ss.MoveNext())
{
Response.Write(ss.Key);
Response.Write(" "+ss.Value);
Response.Write("
");
}
output:
2 bala1
1 bala
Inbuilt Interface Using Dotnet
Definition:
Using this interface you can read the array,string, Performance is good.
Example:1
string[] sdss ={ "test", "test1" };
IEnumerator enumerator = sdss.GetEnumerator();
while (enumerator.MoveNext())
{
Response.Write(enumerator.Current.ToString() +"
");
}
output
test
test1
Example:2
string s="dd";
IEnumerator enumerator = s.GetEnumerator();
while (enumerator.MoveNext())
{
Response.Write(enumerator.Current.ToString() +"
");
}
output
d
d
Thursday, January 3, 2008
Retrieving Selected Text Using Javascript
function copy()
{
var selectedText = document.selection;
if (selectedText.type == 'Text')
{
var newRange = selectedText.createRange();
form1.txtTest.focus();alert(newRange.text)}else{alert('Please Select The Text');
}}
Wednesday, January 2, 2008
Tuesday, January 1, 2008
Interop Services
>>handling unmanaged code we have to use Interop services.
The Microsoft .NET Framework promotes interaction with COM components,
COM+ services, external type libraries, and many operating system services. Data types, method signatures, and error-handling mechanisms vary between managed and unmanaged object models. To simplify interoperation between .NET Framework components and unmanaged code and to ease the migration path, the common language runtime conceals from both clients and servers the differences in these object models.
Code executing under the control of the runtime is called managed code. Conversely, code that runs outside the runtime is called unmanaged code.
Example of Unmanaged code
COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code.
Monday, December 17, 2007
Thursday, December 13, 2007
Sending Email using "System.Net.Mail"
void Page_Load()
{
//SmtpClient client = new SmtpClient();
//client.Host = "localhost";
//client.Port = 25;
//client.Send("steve@somewhere", "bob@somewhere.com", "Let's eat lunch!", "Lunch at the Steak House?");
}
Sunday, December 9, 2007
Generating excel sheet for all the tables the Data Set contains using Excel XML.
{
/// Create and Excel File using Excel Xml
///
/// Complete File Path
/// Data Set
/// Work Sheet Name
/// No of records to show per sheet.
public static void CreateExcelXML(string FileName, DataSet Ds, string SheetName, int RecordsPerSheet)
{
StringWriter S = new StringWriter();
XmlTextWriter X = new XmlTextWriter(S);
StreamWriter Writer = new StreamWriter(FileName, false);
try
{
SheetName = (SheetName.Trim().Length == 0) ? "WorkSheet" : SheetName;
RecordsPerSheet = (RecordsPerSheet <= 0) ? 650000 : RecordsPerSheet;
X.Formatting = Formatting.Indented;
X.Indentation = 4;
X.WriteProcessingInstruction("xml", "version=\"1.0\"");
X.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");
X.WriteStartElement("Workbook", string.Empty);
X.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:spreadsheet");
X.WriteAttributeString("xmlns:o", "urn:schemas-microsoft-com:office:office");
X.WriteAttributeString("xmlns:x", "urn:schemas-microsoft-com:office:excel");
X.WriteAttributeString("xmlns:ss", "urn:schemas-microsoft-com:office:spreadsheet");
X.WriteAttributeString("xmlns:html", "http://www.w3.org/TR/REC-html40");
X.WriteStartElement("DocumentProperties", string.Empty);
X.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:office");
X.WriteElementString("Author", "Farhan Khan");
X.WriteElementString("LastAuthor", string.Empty);
X.WriteElementString("Created", string.Empty);
X.WriteElementString("Company", string.Empty);
X.WriteElementString("Version", "1.0");
X.WriteEndElement();
X.WriteStartElement("ExcelWorkBook", string.Empty);
X.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:office");
X.WriteEndElement();
X.WriteStartElement("Styles", string.Empty);
X.WriteStartElement("Style", string.Empty);
X.WriteAttributeString("ss:ID", "Default");
X.WriteAttributeString("ss:Name", "Normal");
X.WriteStartElement("Alignment", string.Empty);
X.WriteAttributeString("ss:Vertical", "Bottom");
X.WriteEndElement();
X.WriteElementString("Borders", string.Empty);
X.WriteElementString("Font", string.Empty);
X.WriteElementString("Interior", string.Empty);
X.WriteElementString("NumberFormat", string.Empty);
X.WriteElementString("Protection", string.Empty);
X.WriteEndElement();
X.WriteEndElement();
for (int i = 0; i < Ds.Tables.Count; i++)
{
int k = 0;
for (int j = 0; j < Ds.Tables[i].Rows.Count; j++)
{
string Name = string.Empty;
if (j == 0)
{
Name = SheetName + " " + Convert.ToString(i + 1) + "." + k.ToString();
WriteWorkSheetStart(X, Ds, i, Name);
k++;
}
else if ((j % RecordsPerSheet) == 0)
{
Name = SheetName + " " + Convert.ToString(i + 1) + "." + k.ToString();
WriteWorkSheetEnd(X);
WriteWorkSheetStart(X, Ds, i, Name);
k++;
}
// Writing Data Rows
X.WriteStartElement("Row");
for (int x = 0; x < Ds.Tables[i].Columns.Count; x++)
{
X.WriteStartElement("Cell");
X.WriteStartElement("Data");
X.WriteAttributeString("ss:Type", "String");
X.WriteValue(Ds.Tables[i].Rows[j][x].ToString());
X.WriteEndElement();
X.WriteEndElement();
}
X.WriteEndElement();
}
WriteWorkSheetEnd(X);
}
X.WriteEndElement(); // End Workbook Element
X.Flush();
Writer.Write(S.ToString());
}
finally
{
Writer.Close();
S.Close();
X.Close();
S.Dispose();
Writer.Dispose();
}
}
private static void WriteWorkSheetStart(XmlTextWriter X, DataSet Ds, int i, string SheetName)
{
X.WriteStartElement("Worksheet", string.Empty);
X.WriteAttributeString("ss:Name", SheetName);
X.WriteStartElement("Table", string.Empty);
X.WriteAttributeString("ss:ExpandedColumnCount", Ds.Tables[i].Columns.Count.ToString());
X.WriteAttributeString("ss:ExpandedRowCount", Convert.ToString(Ds.Tables[i].Rows.Count + 1));
X.WriteAttributeString("x:FullColumns", "1");
X.WriteAttributeString("x:FullRows", "1");
X.WriteStartElement("Row");
for (int j = 0; j < Ds.Tables[i].Columns.Count; j++)
{
X.WriteStartElement("Cell");
X.WriteStartElement("Data");
X.WriteAttributeString("ss:Type", "String");
X.WriteValue(Ds.Tables[i].Columns[j].ColumnName);
X.WriteEndElement();
X.WriteEndElement();
}
X.WriteEndElement();
}
private static void WriteWorkSheetEnd(XmlTextWriter X)
{
X.WriteEndElement();
X.WriteStartElement("WorksheetOptions", string.Empty);
X.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:excel");
X.WriteStartElement("Panes", string.Empty);
X.WriteStartElement("Pane", string.Empty);
X.WriteElementString("ActiveRow", "2");
X.WriteElementString("ActiveCol", "1");
X.WriteEndElement();
X.WriteEndElement();
X.WriteElementString("ProtectObjects", "False");
X.WriteElementString("ProtectScenarios", "False");
X.WriteEndElement();
X.WriteEndElement();
}
}
Friday, November 2, 2007
Tips for spliting string using C#
Spliting string using C#.netstring bala = "slfjslf/dfd";
bala.Split(new string[] { "slf" }, StringSplitOptions.None);
Thursday, October 18, 2007
Null-Coalescing Operator ( ?? )
If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“।
This can now be abbreviated as follows using the Null-Coalescing Operator:
string fileName = tempFileName ?? "Untitled";
The logic is the same। If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.
The Null-Coalescing Operator comes up a lot with nullable types, particular when converting from a nullable type to its value type:
int? count = null;
int amount = count ?? default(int);
Since count is null, amount will now be the default value of an integer type ( zero )।
These Conditional and Null-Coalescing Operators aren't the most self-describing operators :),
but I do love programming in C#!
C# 2.0 Anonymous Methods
C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.
Here is a simple example of using an anonymous method to find all the even integers from 1...10:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, delegate(int integer)
{
return (integer%2 == 0);
}
);
The Anonymous Method is:
delegate(int integer)
{
return (integer%2 == 0);
}
which is called for each integer in the array and returns either true or false depending on if the integer is even।
If you don't use an anonymous method, you will need to create a separate method as such:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, IsEven);
private bool IsEven(int integer)
{
return (integer%2 == 0);
}
When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.
Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):
List
{
return city.State.Name.Equals(States.SelectedValue);
}
);
You can also use anonymous methods as such:
button1.Click +=
delegate
{
MessageBox.Show("Hello");
};
which for such a simple operation doesn't “deserve“ a separate method to handle the event.
Other uses of anonymous methods would be for asynchronous callback methods, etc.
Anonymous methods don't have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.
Wednesday, October 17, 2007
Using a Thread Pool in C# for Multiple Currency Conversion
System.Collections.Generic.List
System.Threading.ManualResetEvent
System.Threading.Thread
System.Threading.ThreadPool
System.Threading.WaitHandle
System.Threading.ThreadStart
Introduction
A thread pool is a collection of threads that can be used to perform a number of tasks in the background. This relieves the primary thread free to perform other tasks asynchronously. Thread pools are often employed in server kind of applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without locking up the primary thread or delaying the processing of subsequent requests in the queue. Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the overhead of creating a new thread for each task. Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available. It is easier to use the thread pool provided by the .NET Framework through the ThreadPool class as against creating a custom thread pool of our own.
Real World Example: Multi currency converter
Here is an example of multi currency conversion is simulated; which does processing of currency conversion. An exchange unit is modeled by a class called ExchangeUnit which carries the information of input & output currency and amount to be converted. Multiple objects of ExchangeUnit are created with different currency information and are fed into a ThreadPool for doing the multiple conversions. The ExchangeUnit class provides a method called ThreadPoolCallback that performs the conversion. An object representing each exchange required is created, and the ThreadPoolCallback method is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method.
There is another class called MulticurrencyExchanger which maintains an internal list of latest conversion rates among the currencies. This list is periodically updated by a different thread which arrives at the percentage change in exchange rates based on a random number principle. In real world application latest exchange rates would be fed typically fed by a web service.
Here is the code for different classes:
using System;using System.Collections;using System.Collections.Generic;using System.Threading;using ClassLibrary;class Program{ static void Main(string[] args) { //Invoke the MulticurrencyExchanger Init() method on a separate thread MulticurrencyExchanger exchanger = new MulticurrencyExchanger(); Thread thread = new Thread(new ThreadStart(exchanger.Init)); thread.Start(); ExchangeUnit[] exchanges = new ExchangeUnit[3]; // One event is used for each ExchangeUnit object ManualResetEvent[] signalEvents = new ManualResetEvent[3]; for (int i = 0; i < 3; i++) { signalEvents[i] = new ManualResetEvent(false); } exchanges[0] = new ExchangeUnit(100.00, "USD", "RS", signalEvents[0]); exchanges[1] = new ExchangeUnit(100.00, "EURO", "RS", signalEvents[1]); exchanges[2] = new ExchangeUnit(100.00, "GBP", "RS", signalEvents[2]); // Calculate exchanges for 10 times so that fluctuating exchange rates reflect for (int j = 0; j < 10; j++) { // Launch threads for an ExchangeUnit using ThreadPool for (int i = 0; i < 3; i++) { ThreadPool.QueueUserWorkItem(exchanges[i].ThreadPoolCallback, exchanges[i]); } // Wait for all threads in pool WaitHandle.WaitAll(signalEvents); // Display the results for (int i = 0; i < 3; i++) { Console.WriteLine("{0} {1}={2} {3}", exchanges[i].CurrencyIn, exchanges[i].Amount, exchanges[i].CurrencyOut, exchanges[i].ExAmount); } // Sleep for 1 sec before going to next iteration Thread.Sleep(1000); } // Stop the thread for the MulticurrencyExchanger object thread.Abort(); Console.ReadLine(); }}
Connection Pooling in ASP.NET
If all connections in the pool are busy and the maximum pool size has not been reached, then new connection is created and added to the pool. When the pool reaches its maximum size all new connection requests are being queued up until a connection in the pool becomes available or the connection attempt times out.
These are four parameters that control most of the connection pooling behavior
Max Pool Size - the maximum size of your connection pool. Default is 100
Min Pool Size - initial number of connections which will be added to the pool upon its creation. Default is zero
Connect Timeout - controls the wait period in seconds when a new connection is requested, if this timeout expires, an exception will be thrown. Default is 15 seconds.
Pooling - controls if your connection pooling on or off. Default as you may've guessed is true. Read on to see when you may use Pooling=false setting.
eg.
connstring="server=myserver;database;abcdefg;Min pool size=5;Max pool size=100;connection timeout=15;pooling=yes"
Most of the Connection problems are because of Connection Leaks
SqlConnection conn=new SqlConnection(constring);
conn.Open();
//do some thing
conn.Close();
while executing the functionality if Exception occurences, then for sure connection wont be closed , to close connection explicitly .. the simple way is ..
SqlConnection conn=new SqlConnection(constring);
try{
conn.Open();
//do some thing
}
finally()
{
conn.Close();
Alternate method for renaming a Database in Sql server 2005
To rename database it is very common to use for SQL Server 2000 user :
EXEC sp_renameDB 'oldDB','newDB'
sp_renameDB syntax will be deprecated in the future version of SQL Server. It is supported in SQL Server 2005 for backwards compatibility only. It is recommended to use ALTER DATABASE MODIFY NAME instead. New syntax of ALTER DATABASE MODIFY NAME is simple as well.
--Create Test Database
CREATE DATABASE Test
GO
--Rename the Database Test to NewTest
ALTER DATABASE Test MODIFY NAME = NewTest
GO
--Cleanup NewTest Database
--Do not run following command if you want to use the database.
--It is dropped here for sample database clean up.
DROP DATABASE NewTest
GO
Heap table in sqlserver
What is a table called, if it does not have neither Cluster nor Non-cluster Index? What is it
used for?
Unindexed table or Heap. Microsoft Press Books and Book On Line (BOL) refers it as Heap.
A heap is a table that does not have a clustered index and, therefore, the pages are not linked by
pointers. The IAM pages are the only structures that link the pages in a table together.
Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table
and than do bulk of inserts and to restore those indexes after that.
NULLIF function in Sql server
Syntax:
NULLIF ( expression , expression )
Paragraph Heading N
Returns a null value if the two specified expressions are equal. NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression. NULLIF is equivalent to a searched CASE function in which the two expressions are equal and the resulting expression is NULL.
Following is good example of NULLIF
USE AdventureWorks;
GO
SELECT ProductID, MakeFlag, FinishedGoodsFlag,
NULLIF(MakeFlag,FinishedGoodsFlag)AS 'Null if Equal'
FROM Production.Product
WHERE ProductID < 10;
GO
SELECT ProductID, MakeFlag, FinishedGoodsFlag,'Null if Equal' =
CASE
WHEN MakeFlag = FinishedGoodsFlag THEN NULL
ELSE MakeFlag
END
FROM Production.Product
WHERE ProductID < 10;
GO
Explanation of ISNULL
Syntax:
ISNULL ( check_expression , replacement_value )
Replaces NULL with the specified replacement value. The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different.
Following is good example of ISNULL from BOL:
USE AdventureWorks;
GO
SELECT AVG(ISNULL(Weight, 50))
FROM Production.Product;
GO
Observation:
Interesting observation is NULLIF returns null if it comparison is successful, where as ISNULL returns not null if its comparison is successful. In one way they are opposite to each other.
If you execute this in SQL Server 2005's standard AdventureWorks database, what happens?
select
Identity(smallint, 100,1) as ReportID
, c.AccountNumber
, h.SalesOrderID
, h.OrderDate
, h.TotalDue
into Sales.CustomerReport
from Sales.Customer c
inner join Sales.SalesOrderHeader h
on c.CustomerID = h.CustomerID
where h.SalesPersonID = 279
Correct Answer: This runs and creates a new table.
The IDENTITY function can be used to populate a new table based on a SELECT statement. In this case the 429 rows matching the query will be inserted into a new table (Sales.CustomerReport) with the first column being ReportID and populated with the values 100 through 528.
Tips for Developer
Here's the scenario - let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times.
For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this:
<INPUT id="Button1" onclick="document.form1.Button1.disabled=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert"&rt;
Then, in the very last line of the 'doInsert' subroutine, add this line:
Button1.enabled="True"
There are three ways to add Javascript attributes to a particular ASP.Net Server control:
1. button1.Attributes.Add("OnClick", "document.form1.txtName.focus();")
2. button1.Attributes("OnClick")="document.form1.txtName.focus();"
3. button1.clientclick="function name"";
onbeforeunload Javascript
Probably end user pressed the X button by mistake and he/she might loose his/her current state
There is onbeforeunload event for the JavaScript that fires when you are navigating away from the current page.
Here is the Code for that.
script type="text/javascript"
function close()
{
event.returnValue = "This will navigate to next page.";
}
script
body onbeforeunload="close()"
a href="microsoft.com" Click Here to navigate to Microsoft a
body
html
Note:
The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
Friday, October 12, 2007
Wednesday, October 10, 2007
Differences between WSS and MOSS
Differences between WSS and MOSS
When thinking of WSS and MOSS, the important thing to understand is that WSS is the foundation and MOSS is an optional add-on. In fact, you cannot install MOSS by itself. If you try to do this, you will be requested to install WSS first. So, the question is: What differs between WSS and MOSS? If you have never seen SharePoint before, some of these answers might be hard to understand. Give it a try anyhow. The following chapters further flesh out the following points.
Windows SharePoint Services 3.0WSS 3.0 has the following characteristics:
# It is a web-based application.
# It stores all information in an MS SQL database.
# It displays information using web parts.
# It has good document-management features.
# It has a number of list types that you can use for storing all kinds of information.
# It allows you to build workflow solutions that start when a document is changed.
# It is perfect for simple, but effective, intranet solutions.
# It is ideal for collaboration on project data, meetings, social events, and the like.
# It has its own index and search engine.
# Its lists and libraries can operate as RSS Feeds.
# It comes with site temples for creating Wiki and Blog sites.
# It is a free add-on to MS Windows 2003 Server (any edition).
In other words, WSS is the perfect place to collect information for your projects, your customers, and your meetings। You can move all documents from your file system into WSS and by doing so get access to the powerful document-management features it offers. It is also a very good solution when you need local intranets for teams or departments. And all this is free when you run Windows 2003 Server!
But there are things that WSS does not offer। The following are just a few examples:
# There is no support for indexing and searching information outside the WSS.
# It has no advanced intranet features, such as targeted information and content management.
# It has no advanced document management features, such as document policies.
# It has no record management of legal and other important documents.
# It cannot display InfoPath forms in a web browser.
# It cannot display MS Excel spreadsheets as web parts.
# It comes with less than 10 web parts.
# It cannot read and write to and from external databases.
This is where MOSS comes in.
MS Office SharePoint Server 2007MOSS 2007 uses the same types of sites as WSS 3।0 but adds a lot of functionality to WSS 3.0, making it possible to do the following:
# Use global search functionality to find any type of information regardless of type and location.
# Target information to one or more user groups.
# Import user data from Active Directory.
# Use advanced content management for public Internet sites or portal sites.
# Use the RSS web part to list information fetched from RSS feeds.
# Display and use InfoPath forms with a web client, using the Forms Service.
# Display MS Excel spreadsheets and charts in a web part, using Excel Services.
# Search, display and edit content in external databases, such as SAP, using Business Data Catalog.
# Give each SharePoint user a personal web site, for both private and public use।
These characteristics make MOSS a very good solution for building public Internet sites or global intranets that are smart enough to show the right information to the right people. MOSS is also a good solution when you want to build a site for displaying business data, such as MS Excel spreadsheets, forms, and key performance indicators (KPIs)
Security
when the application uses windows authentication। Asp।Net checks the project's web।config authorization list to see which network users are allowed to access the application. The asterstick(*) and question mark(?) characters have some special meaning in the autorization.
* Charatcter indicates all users
? character indicates unauthenticated users.
Example:
Introduction to Sharepoint
SharePoint helps you gather information together.
Advantages:
It is actually hard to describe what SharePoint is in just a few words, but let's give it a try. Using this application, you can build a web-based environment that includes the following, and more:
1) A public Internet site
2) An intranet portal for the organization and each department
3) An extranet portal for your customers and partners
4) A team site for your sales department
5) A project site for the development team
6) A document management system that is compliant with Sarbanes-Oxley (SOX) and ISO-9000
7) A personal site for each user where they can store personal data and create links to their team sites
8) A digital dashboard for storing business intelligence data such as key performance indicators
9) A place to search and locate any type of information, regardless of where it is stored
10) A record management system for storing legal information in a secure way.
The list goes on and on. Since SharePoint is such a flexible and powerful application, it is almost only your own imagination that limits what you can do with it. It is also very fun to work with, since it is so easy to build an impressive solution with it. Microsoft has most certainly created a killer application - again! shows a typical SharePoint 2007 site, just to give you an idea about how it looks.
The important things you should remember:
@ STS(sharepoint team services) is the old name for WSS and is still used in SharePoint 2007 in some places, such as the administrative tool tsadm.exe and the folder sts storing the site definition for WSS sites.
@ MOSS has replaced SPS(sharepoint portal services).
@ MOSS comes in Standard and Enterprise editions and has optional servers.
@ MS SQL Server is used by MOSS(Microsoft office sharepoint services) and WSS(windows sharepoint services) 3.0.
Note:
The features and functionality of both WSS 3.0 and MOSS 2007, which are also known as SharePoint Products and Technology (SPPT) 2007.
Tuesday, October 9, 2007
Output Parameters using C#
if you want to return more than one value from method, You have to use out put parameters.
Example:
Public void site(out string site)
{
Site="bala";
}
public void showord()
{
string site;
site(out site);
Response.write("The site of the day is "+site);
}
Out put:
The site of the day is bala
Monday, October 8, 2007
How to get the textbox value at the client side
{
if (document.getElementById('<%=textbox2.ClientID%>').value == "")
{
alert("Please enter a value");
return;
}
}
How to create an array of Web Controls
TextBox[] textboxes = new TextBox[5];
for (int i=0; i<5; i++)
{
textboxes[i] = new TextBox();
textboxes[i].ID = "TextBox" + i;
textboxes[i].AutoPostBack = true;
PlaceHolder1.Controls.Add(textboxes[i]);
}
Clear Textbox
foreach (Control ctl in Page.Controls[1].Controls )
{
TextBox tb = ctl as TextBox;
if (tb!=null)
{
tb.Text = "" ;
}
}
Config files
In web.config with in appsetting you have to write the connection string..









