Thursday, April 10, 2008

Accessing server event using Ajax

Step:1

Install system.web.extension and ajax tools
Install ajax.dll in your system all add in reference of the project.

step:2
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>

step:3
Write javascript

<script language="javascript" type="text/javascript">
function Getconfirm()
{
var con=confirm("Are sure want to delete this");
var test;
if(con==false)
{
alert(Bala.Getvalue().value);
}
else
{
alert(Bala.Getvalue1().value);
}
}
</script>

step 4:
in c# page


public partial class Bala : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Bala));
//btnsubmit.Attributes.Add("onclick", "Getconfirm();");
}
[Ajax.AjaxMethod()]
public string Getvalue()
{
return "bala";

}
[Ajax.AjaxMethod()]
public string Getvalue1()
{
return "bala1";

}
}

Monday, April 7, 2008

Importan queries using Sqlserver

http://www.dotnetspider.com/kb/Article4097.aspx

Check if a date is a valid date in Sql Server 2005

Use the ISDATE() function

The ISDATE() function determines whether the variable or the expression contains a valid date. It returns 1(true) if the input expression is a valid date;

otherwise, it returns 0 (false).

For eg:

DECLARE @dt varchar(10)

SET @dt = '02/21/08'

SELECT ISDATE(@dt)-- Returns 1

DECLARE @dt varchar(10)

SET @dt = '13/21/08'

SELECT ISDATE(@dt)-- Returns 0 as 13 is not a valid month

Reset all control values in .NET Web pages.

private void ResetFields()
{

foreach (Control ctrl in this.Controls)

{if (ctrl is TextBox)

{

TextBox tb = (TextBox)ctrl;

if (tb != null)

{ tb.Text = string.Empty;

}

} else

if (ctrl is DropDownList)

{ DropDownList dd = (DropDownList)ctrl;

if (dd != null)

{

dd.SelectedIndex = 0;

}

}

}

How to Show Binary Files in the Browser using ASP.NET and VB.NET

This article explains how to show binary files as well as .doc .xls files in browser. We have seen in many sites that user can open .gif, .jpg, .doc and .xls files by clicking a link. The binary format file as well as .doc .xls is displayed in the browser
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.NET 2.0 Provies a wonderful solution by means of MultiView Control. The MultiView Control combined with the View Control can provide different UI on different scenarios as and when required.

<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);
}

Multiview control using

"goto" Using Dotnet framework 2.0

for (int k = 0; k < 2; k++)
{
Response.Write("Testing Goto");
goto Testing;
Testing:
Response.Write("Testing Goto in for loop");
}

output
Testing GotoTesting Goto in for loop

COALESCE using Sqlserver

I want get employeelist in one single string.
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.Threading.Thread Th = new System.Threading.Thread(delegate()
{
System.Console.Write("hi");
});
Th.Start();

Breaking out a loop in two ways

The two ways described below.
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

Nullable Data Type
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

In aspx Page

<script language="javascript" type="text/javascript">

function Getconfirm()
{
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-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.

Fundamental Concepts

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
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.

Programming Model

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

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

How to encrypt 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.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) Incremental search in Visual Studio.
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"