Total Pageviews

Friday, December 10, 2010

Send html page directly to the default printer without showing print dialog box

[if gte mso 9]> Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
<object classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0" id="WB" width="0">
object>

<script language="JavaScript">
DA = (document.all) ? 1 : 0
script>

<script language="VBScript">

'sub print()
'OLECMDID_PRINT = 6
'OLECMDEXECOPT_DONTPROMPTUSER '= 2
'OLECMDEXECOPT_PROMPTUSER '= 1
'on error resume next
'IE4 object has different command structure
'if DA then
'call 'WB.ExecWB(OLECMDID_PRINT, 'OLECMDEXECOPT_DONTPROMPTUSER,1)
'else
'call 'WB.IOleCommandTarget.Exec(OLECMDID_PRINT ',OLECMDEXECOPT_DONTPROMPTUSER,"","")
'end if

'end sub

'This will be interpreted during loading.
'It will write out the correct webbrowser object depending
'on the browser version. To be sure it works, make sure you
'include this script block in between the body tags.

if DA then
'this must be IE4 or greater
wbvers="8856F961-340A-11D0-A96B-00C04FD705A2"
else
'this must be IE3.x
wbvers="EAB22AC3-30C1-11CF-A7EB-0000C05BAE0B"
end if

document.write ""

script>

<style type="text/css">
#form1
{
height: 275px;
}
style>
head>
<%----%>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclientclick="window.print();"
Text="Button" />
<br />
<iframe src="Test.pdf" width="500px" height="500px">
this is test
iframe>
form>
body>
html&gt;

Thursday, October 7, 2010

Callback vs Postback

http://stackoverflow.com/questions/365100/difference-between-a-postback-and-a-callback

Thursday, September 23, 2010

Async File Upload control - Close file problem

Add this under section <system.web> section

<httpruntime maxrequestlength="51200" requestLengthDiskThreshold="4096" />



Tuesday, September 14, 2010

Disable a Button

override protected void OnInit(EventArgs e)
{
Button1.Attributes.Add("onclick", "javascript:" +Button1.ClientID + ".disabled=true;" + this.GetPostBackEventReference(Button1));
base.OnInit(e);
}


protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);


}

Wednesday, September 1, 2010

List SQL table column as rows

use TestDB

select COLUMN_NAME 'All_Columns' from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='tblTest'

Thursday, August 19, 2010

SQL Server - Ripping time part

-- Get current date (without time) as string:
SELECT CONVERT( CHAR(8), GetDate(), 112)

-- Get current date (without time) as date:
SELECT CAST( CONVERT( CHAR(8), GetDate(), 112) AS DATETIME)

Monday, August 16, 2010

ASP.NET Page Life Cycle Events

Page Life Cycle Events:


1. PreInit: This is the first real event you might handle for a page. You typically use this event only if you need to dynamically (from code) set values such as master page or theme. This event is also useful when you are working with dynamically created controls for a page. You want to create the controls inside this event.

2. Init: This event fires after each control has been initialized. You can use this event to change initialization values for controls.

3. InitComplete: Raised once all initializations of the page and its controls have been completed.

4. PreLoad: This event fires before view state has been loaded for the page and its controls and before PostBack processing. This event is useful when you need to write code after the page is initialized but before the view state has been wired back up to the controls

5. Load: The page is stable at this time; it has been initialized and its state has been reconstructed. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. The page’s load event is called first. Then, the load event for each child control is called in turn (and their child controls, if any). This is important to know if you are writing your own user or custom controls.

6. Control (PostBack) events: ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event, for example.

7. LoadComplete: At this point all controls are loaded. If you need to do additional processing at this time you can do so here.

8. PreRender: Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.

9. SaveStateComplete: Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. This is useful if you need to write processing that requires the view state to be set.

10. Render: This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser. This method is useful if you are writing your own custom control. You override this method to control output for the control.

11. UnLoad: This event is used for cleanup code. You use it to release any managed resources in this stage. Managed resources are resources that are handled by the runtime, such as instances of classes created by the .NET common language runtime.

Friday, August 13, 2010

Sunday, August 1, 2010

SQL Server - Sending XML string to SP

Creating XML format to send to Parameters as string to the SP

StringBuilder sbSites = new StringBuilder();
sbSites.Append("");

if (ddlManagingSite.SelectedValue != string.Empty)
{
sbSites.AppendFormat("", ddlManagingSite.SelectedValue);
}
else
{
foreach (ListItem item in ddlManagingSite.Items)
{
if (item.Text != "")
{
sbSites.AppendFormat("", item.Value);
}
}
}

sbSites.Append("
");



SP need to look like this

CREATE PROC [dbo].[uspGetVacancyNoticeBoardByStateAndSite]

@vcSiteCode varchar(MAX)=''

AS

DECLARE @iDocSites INT
EXEC sp_xml_preparedocument @iDocSites OUTPUT, @vcSiteCode

SELECT
[ID],
[LastDataUpdateDate],
[LastDataUpdateBy]
FROM [dbo].[tblVacancyNoticeBoard]
WHERE [SiteCode] IN (SELECT SiteCodeID FROM OPENXML (@iDocSites, '/AllSITES/SiteCode', 1) WITH (SiteCodeID VARCHAR(5)))


Tuesday, July 20, 2010

Concatanating SQL table column

Table as follows

JSKID Tickets
8765 Bobcat
1001 Bobcat
1001 Confined Spaces
1001 Road

Turn this table to following

JSKID Tickets
1001 Bobcat,Confined Spaces,Road
8765 Bobcat

Select tk1.[JSKID], stuff((SELECT ',' + [Tickets] FROM [tblTickets] tk where tk.[JSKID]= tk1.[JSKID] FOR XML PATH('')),1,2,'' ) AS Tickets from [tblTickets] tk1 group by tk1.[JSKID]

Saturday, July 10, 2010

Read All appsetting on web.config

This will read all appsetting collection on web.config or app.config

NameValueCollection mySettings = System.Configuration.ConfigurationSettings.AppSettings;
string connStr = mySettings["connectionString"];

Thursday, July 1, 2010

SQL Server- Script to rebuild all tables' indexes

USE DatabaseName --Enter the name of the database you want to reindex

DECLARE @TableName varchar(255)

DECLARE TableCursor CURSOR FOR

SELECT table_name

FROM information_schema.tables

WHERE table_type = 'base table'

OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @TableName

WHILE @@FETCH_STATUS = 0

BEGIN

DBCC DBREINDEX(@TableName,' ',90)

FETCH NEXT FROM TableCursor INTO @TableName
END

CLOSE TableCursor

DEALLOCATE TableCursor

Printing a Div in JAVAScript - Extended Version

This works in IE and Firefox, Mutiple Divs can be printed.

function PrintAllDivs(printDiv) {
if (typeof HTMLElement != "undefined" && !
HTMLElement.prototype.insertAdjacentElement) {
HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode) {
switch (where) {
case 'beforeBegin':
this.parentNode.insertBefore(parsedNode, this)
break;
case 'afterBegin':
this.insertBefore(parsedNode, this.firstChild);
break;
case 'beforeEnd':
this.appendChild(parsedNode);
break;
case 'afterEnd':
if (this.nextSibling)
this.parentNode.insertBefore(parsedNode, this.nextSibling);
else this.parentNode.appendChild(parsedNode);
break;
}
}

HTMLElement.prototype.insertAdjacentHTML = function(where, htmlStr) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var parsedHTML = r.createContextualFragment(htmlStr);
this.insertAdjacentElement(where, parsedHTML)
}


HTMLElement.prototype.insertAdjacentText = function(where, txtStr) {
var parsedText = document.createTextNode(txtStr)
this.insertAdjacentElement(where, parsedText)
}
}

var doc;
var contentDiv;
var content;

if (document.getElementById('printHiddenFrame') == null) {
document.body.insertAdjacentHTML("beforeEnd", "");
}
doc = printHiddenFrame.document;
doc.open();
doc.write("");
doc.write("");
doc.write("");
contentDiv = document.getElementById(printDiv);
if (contentDiv != null) {
doc.write(contentDiv.innerHTML);
}
ConvertToText(doc);
doc.write("");
setTimeout('document.getElementById(\'abc\')', 0);
doc.close();
return false;

}

function printHiddenPage() {

window.document.printHiddenFrame.focus();
window.document.printHiddenFrame.print();
}

function ConvertToText(doc) {
var f = doc.getElementsByTagName('textarea');

for (var i = 0; i < f.length; i++) {
var txt = doc.getElementById(f[i].id + 'Print');

f[i].style.display = 'none';
f[i].style.visibility = 'hidden';

if (txt != null) {
f[i].value == "" ? txt.innerHTML = " " : txt.innerHTML = f[i].value.replace(/\n\r/g, "

");
}
}
}

Sunday, June 20, 2010

Preventing Paste function from Jquery

http://www.4guysfromrolla.com/articles/060910-1.aspx

Thursday, June 17, 2010

Printing a Div in JAVAScript

There several version of implementing. With iframe and without it.

With Iframe

function CallPrint() {

var content = document.getElementById('ctl00_DefaultContent_divShippingRate');
var pri = document.getElementById('ifmcontentstoprint').contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();
}

Add this iframe to html with iframe tags

iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"

Call by button client click

OnClientClick="CallPrint();"

Without Iframe

function CallPrint()
{

var printContent = document.getElementById('ctl00_DefaultContent_divShippingRate');
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'left=0,top=5000,width=7000,height=0');

printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();

printWindow.close();

}

Just call from onClientclick()

Wednesday, June 16, 2010

Opening Windows by JAVAScript

When you show a modal dialog the window remains on top of other windows until the user explicitly closes it.

window.showModalDialog("Test.html","dialogWidth:400px; dialogHeight:225px; status:no; center:yes");

When you show a modeless dialog the window remains on top of other windows, but you can still access the other windows.

window.showModelessDialog("Test.html","dialogWidth:400px; dialogHeight:225px; status:no; center:yes");

Monday, June 14, 2010

Article on Page Events

http://codeasp.net/articles/asp.net/71/asp-net-page-life-cycle

Implementation of ASP.Net Post back on the Client side

Implementation of ASP.Net Post back on the Client side:

Post back is implemented with the use javascript in the client side. The HTML page generated for each .aspx page will have the action property of the form tag set to the same page. This makes the page to be posted on to itself. If we check the entry on the HTML file, it will look something like this.

form name="_ctl1" method="post" action="pagename.aspx?getparameter1=134" language="javascript" onsubmit="if (!ValidatorOnSubmit()) return false;" id="_ctl1"

Also, all the validation code that is written (Required Field Validation, Regular Expression validation etc.,) will all be processed at the client side using the .js(javascript) file present in the webserver_wwwroot/aspnet_client folder.

With this new ASP .Net model, even if the user wants to post the data to a different .aspx page, the web server will check for the runat='server' tag in the form tag and post the web form to the same .aspx page. A simple declaration as in the following code snippet will be enough to create such a web form.

form id="form1" runat="server"

form

Thursday, June 3, 2010

Popup in Javascript

Image button Event
onclientclick="javascript:PopUp('CharityDesignationReport.aspx')"

Following will fire after validating the page


function PopUp(ref)
{

if (Page_ClientValidate()) {


var strFeatures = "toolbar=no,status=no,menubar=no,location=no"
strFeatures = strFeatures + ",scrollbars=no,resizable=no,height=600,width=630"

newWin = window.open(ref, "TellObj", strFeatures);
newWin.opener = top;

}

}



Monday, May 17, 2010

Quick ASP,NET Guide

Check this out
http://www.aspdotnetfaq.com/

ASP.NET basic page life cycle

Followings are the page cycle events on chronological order.

1. PreInit
2. Init
3. InitComplete
4. PreLoad
5. Load
6. LoadComplete
7. PreRender
8. PreRenderComplete
9. SaveStateComplete
10. Unload

Capturing Key stroke and Do the post back

With the invention of Web 2.0 customers are becoming more and more demanding when it comes to interactive Web UI.With application being moved from Desktops to web, end users demand that the web application provide them the same look and feel as they had in their legacy desktop applications.Well this includes Key combinations provided by the desktop applications to do some quick tasks like “save”, “Edit” etc to name a few.Providing this feature in Web application is a bit tricky but using JavaScript this can be done.

Well the first step in the process is to capture the Key press event that has happened when the user has pressed some key while he is using you web page.

The way to do this is something like this.

The KeyID will provide you with a number that indicates which key was pressed. You can build a logic based on the value of KeyID. You can also use the key combinations and like “cntrl+S” etc.

The below code is written and tested to do post back for various keys press events.

First add this JavaScript to your page.

This script does a post back and passes the name of the key pressed as the value of the “Request["__EVENTARGUMENT"]” key in the Request object.
For making the “__doPostBack” to work we will have to do some register the postback event reference during page load. The code below explains how it is done
protected void Page_Load(object sender, EventArgs e)

{

Page.ClientScript.GetPostBackEventReference(this, "");
string eventArgs = Request["__EVENTARGUMENT"];if(!string.IsNullOrEmpty(eventArgs))

{
switch (eventArgs)

{
case "F7":

DoF7();

break;
case "F8":

DoF8();
break;case "F9":

DoF8();

break;
case "F10":

DoF8();
break;

}

}

}

Based on the value received in the Request["__EVENTARGUMENT"] we can take appropriate action during postback.

Load Balancing

In one of our project the site usage of site was very heavy and we need to migrate it to load balancing server. I have never configured the sites in the load balancing server but it was quite interspersing experience Here are the some points which we need to take care while we move asp.net sites into the load balancing environments. So first we will see what is load balancing.

Following is a load balancing definition from the Google.

In computer networking, load balancing is a technique to distribute workload evenly across two or more computers, network links, CPUs, hard drives, or other resources, in order to get optimal resource utilization, maximize throughput, minimize response time, and avoid overload.

Following are the points which you need to take care when you are deploying your asp.net sites into load balancing server environments.

Machine Key Should be same for both servers: View state and session both are depends on the machine key. If you machine key is not same then you will have problems related to session and view state you may loose your session and view state in between request during post backs. If machine key will not be same then its possible that you can get strange result in Ajax requests. There is a machine key section in web.config where you can specify machine key.

  1. <machineKey validationKey='C44B8B7C521CB5BC7E602BAE6118AA44CD690C7304817129DA27C17E800132A
  2. 1BD946C6D9AD12F0A5B342840C7D130564195428160B7466146938CA9E3A62686' decryptionKey='0E9DF2DA7F210B84087690FF0BF25C905182AD81E16A5FA9' validation='SHA1'/>
Session Configuration: Any web application is not possible without having session as web pages are stateless so you can configure session in load balancing also. There are two configuration which can be used in load balancing environments. One is state service and another is Storing session in SQL Server.

Following is a good link to learn how you can configure sessions state in asp.net application.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0d9dc063-dc1a-46be-8e84-f05dbb402221.mspx?mfr=true

And here is a good link to configure session on SQL Server.

http://support.microsoft.com/kb/317604

You can configure session state mode in your web.config like following.

  1. <sessionState mode="SQLServer" StateConnectionString="tcpip=127.0.0.1:42424"

  2. SqlConnectionString = "data source=SERVERNAME; user id=sa; password=sa"

  3. cookieless="false" timeout="20" />
enableViewStateMac="false": This is a alternative approach to machine key. This will tell asp.net engine that whether it should check Machine authentication check or not and if you made it false then it will not check for machine authentication. You can define that in your web.config pages section like following.
  1. <system.web>
  2. <pages enableViewStateMac="false" />
  3. system.web>
Caspol Utility: You can use caspol utility to share some resources on between load balancing servers. Like we have file base cache dependency in our application so we have created a central location(A shared folder for cache files) for the both the server and used Caspol utility to give full trust share on that folder for load balancing servers. Following are some of the good links to which will teach how you can use CasPol utility to for asp.net application

http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx

http://forums.asp.net/p/1119925/1881331.aspx#1881331

http://www.eggheadcafe.com/software/aspnet/30227544/caspol-addfulltrust.aspx

File Replication:File Replication is also an important features of load balancing you should have replication enabled on the folders of web application so if you upload anything on one server it should replicated to other sites. Following is good link to understand file replication.

http://www.tgrmn.com/web/kb/item28.htm

Sticky Sessions:
In some scenario Sticky session is very useful. In one page our application we have used extensive Ajax and we need that for each request and partial post back it should stay on one server till request completes.To achieve that we can used sticky session. Following are some good links to know about sticky sessions.

http://dev.fyicenter.com/Interview-Questions/JavaScript/What_does_the_term_sticky_session_mean_in_a_web_.html

http://blogs.msdn.com/drnick/archive/2007/07/13/sticky-sessions.aspx

Hope this will help you on deploying your asp.net on load balancing sites. Following are some good links for understanding load balancing in more details

http://technet.microsoft.com/en-us/library/bb742455.aspx
http://support.microsoft.com/kb/323437
http://technet.microsoft.com/en-us/library/cc754833%28WS.10%29.aspx.
http://edge.technet.com/Media/Network-Load-Balancing-NLB-in-Windows-Server-2008/

Wednesday, May 12, 2010

What is Boxing & Unboxing in C#?

Boxing means converting Value type to a Reference type.

Ex :

int i=100;

object obj=(object) i;

Unboxing means converting Reference type to a Value type.

Ex:

object obj=100;

int i=(int)obj;

Usage of SQL SELECT statements

Followings are some examples of using SELECT statement. My table name tblTest. Followings are columns. (TestID, TestName, TestDate, TestCity )


1) Select * from tblTest (Returns all columns/Rows)

2) Select * from tblTest Where TestID=2 (Returns the row/s which TestID has value 2)

3) Select * from tblTest where TestID Between 10 and 20 (Return all rows between 10 and 20, this result includes 10 and 20)

4) Select * from tblTest Where TestCity in ('New York','Washington','California') (Returns all rows which city is NewYork, Washington, california)

5) Select * from tblTest Where TestName Like 'A%' (Return all rows where the name starts letter A)

6) Select * from tblTest Where TestName Like '%A' (Return all rows where the name ends letter A)

7) Select * from tblTest Where TestName Like '[ABC]%' (Return all rows of name start with A / B / C)

8) Select * from tblTest Where TestName Like '[^ABC]%' (Return all rows of name not start with A and B and C)

9) Select (TestName+space(1)+TestCity) as Address from tblTest (Returns single column address, name and city added together with a space)

10) Select * from tblTest Where TestName IS NULL (Return all rows which TestNane has null values)

11) Select * from tblTest Where TestName IS NOT NULL (Return all rows which TestNane has not null values)

12) Select * from tblTest Order By TestID Desc (Sort the result set descending order, Asc or not using any sort Ascending order)

13) Select 'Visual Studio' as IDE, '2010' as Version (Creating memory resident result set with two columns[IDE and Version])

14) Select Distinct TestID from tblTest (Returns unique rows based on TestID)

15) Select Top 10 * from tblTest (Return 10 customers randomly)

16) Select getdate() (Shows the current date)

17) Select db_name() (shows the database name which you are working on)

18) Select @@Servername (Shows name of the server)

19) Select serverproperty ('Edition') (You can pass following ServerName, Edition, EngineEdition, ProductLevel to get current information about the server)

20) Select user_name() (Get current user)

21) Select * into #test from tblTest (Create temporary table #test and insert all records from tblTest)

22) Select Max(TestID) from tblTest (Returns Maximum TestID from tblTest)

23) Select * from tblTest Compute Max(TestID) (Returns two result sets - getting all rows and maximum value of TestID)

24) Select FirstName, LastName, Salary, DOB,

Case Gender
When 'M' Then 'Male'
When 'F' Then 'Female'
End
From Employees

(This Change Gender fields as if M then prints Male and if F then prints Female)

VS Shortcuts

Followings are some useful shortcuts for coders:

Copy a single line - CTRL+C [Move the insertion point at the begin or end and press space bar, then press the shortcut key combination]

Cut a single line - CTRL+X [Move the insertion point at the begin or end and press space bar, then press the shortcut key combination]

Comment a line - CTRL+K, CTRL+C [Keep the insertion point any where on line and press ]

UnComment a line - CTRL+K, CTRL+U [Keep the insertion point any where on line and press ]

Put/Remove a break point - F9

Remove all break points as once - CTRL+SHFT+F9

Expand/Collapse a region- CTRL+M, CTRL+M

Intellisense - Ctrl+Space [Press CTRL again make the drop down transparent]

Build Solution - Ctrl+Shft+B

Expand All regions - Ctrl+M+P

Collapse All regions - Ctrl+M+O

New Break Point - Ctrl+B

Thursday, April 8, 2010

Encrypting and Decrypting ConnectinString

Web.Config







The easiest way to encrypt the section is to use the aspnet_regiis command-line tool.
This tool is located in the following folder:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\

Executing the following command encrypts the section of a Web.Config file
located in a folder with the path c:\Websites\MyWebsite:

aspnet_regiis -pef connectionStrings "c:\Websites\MyWebsite"

The -pef option (Protect Encrypt Filepath) encrypts a particular configuration section located at a particular path.

You can decrypt a section with the -pdf option like this:
aspnet_regiis -pdf connectionStrings "c:\Websites\MyWebsite"

Saturday, February 27, 2010

Best Ebook webs site

http://happi2share.blogspot.com/search/label/Dotnet

Friday, February 26, 2010

ASP.Net Session

http://www.codeproject.com/KB/aspnet/ExploringSession.aspx