Thursday, July 31, 2008

Multiple Select Grid Row

To select row of grid on click of any cell

Put one datagrid and checkbox on the form, check checkbox to enable selection using control.

Add mouseup eventhandler

this.dgSelect.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgSelect_MouseUp);

Add the below method of mouseup event

private void dgSelect_MouseUp(object sender, MouseEventArgs e)
{
if(chkCtrl.Checked)
{
if(System.Windows.Forms.Control.ModifierKeys == Keys.Control)
{
select();
}
else
{
for(int j = 0; j < dgRow ; j++)
dgSelect.UnSelect(j);
selectedRow.Clear();
dgSelect.Select(dgSelect.CurrentCell.RowNumber);
selectedRow.Add(dgSelect.CurrentCell.RowNumber);
}
}
else
{
if(!(System.Windows.Forms.Control.ModifierKeys == Keys.Control))
{
select();
}
else
{
for (int i = 0; i < selectedRow.Count; i++)
{
dgSelect.Select(int.Parse(selectedRow[i].ToString()));
}
}
}
}

Add below methods to select

private void select()
{
int c = dgSelect.CurrentRowIndex;
if(selectedRow.Contains(c))
{
dgSelect.UnSelect(c);
selectedRow.Remove(c);
}
else
{
dgSelect.Select(c);
selectedRow.Add(c);
}
for (int i = 0; i < selectedRow.Count; i++)
{
dgSelect.Select(int.Parse(selectedRow[i].ToString()));
}
}

check checkbox to enable selection using control, uncheck it to select without control

Happy Coding :)

Monday, July 21, 2008

IIS Compression

There are three ways of doing IIS compression:

Static files only
Dynamic application only
Both static files and dynamic application

Why compression is required?

Compression is required for faster transport of data, as amount of data transfered will be less and to get faster user experience in case of low bandwidth. So we can say compression is required for speed and bandwidth.

How compression works?

When a request reaches to IIS, it checks whether the browser from which it got the request has compression-enabled or not.Then, it checks for kind of compression is enabled, i.e. static files or dynamic application.

IIS caches the compressed static files only, if it is already cached, IIS sends the compressed file to the requested browser. If IIS doesn't find the compressed version, it sends an uncompressed version of the requested file and in background it compresses the requested file for subsequent use.

In case of dynamic application(e.g aspx or asp), IIS doesn't cache it. It compresses the response as request reaches and sends response to the client.

Evaluating HTTP Compression

If application consists lots of dynamic content, we need to check few things to reach to decision whether to implement HTTP Compression.

If % Processor Time counter is higher than 70%, enabling HTTP compression is not recommended. If your server has multiple processors, you need to check the individual processors % Processor time.

Follow below link to know how to IIS compression

Using HTTP Compression

Happy Coding :)

Saturday, July 19, 2008

GET DNS IPs

To get DNS IPs we need to import System.Net Namespace. It contains Dns.GetHostByName method, IPHostEntry and IPAddress class.

Create two text boxes with txtDomainName and txtIPs ID respectively and create one button with btnGetIps ID.

Put below code in btnGetIps event

try
{
string strIPs = string.Empty;
IPHostEntry ipHE = Dns.GetHostByName(txtDomainName.Text);
IPAddress[] ipAdd = ipHE.AddressList;
foreach (IPAddress ip in ipAdd)
{
strIPs += ip + ",";
}
txtIPs.Text = strIPs;
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}

Enter domain name in txtDomainName text box and click btnGetIps.
All the IPs of the domain entered in txtDomainName textbox will appear in txtIPs textbox.

Happy Coding :)

Friday, July 18, 2008

SQL Split Function

CREATE FUNCTION Split
(
@Word VARCHAR(8000),
@Separator VARCHAR(255)
)
RETURNS @SplitKeyword TABLE (Keyword VARCHAR(8000))
AS
BEGIN
DECLARE @TempWord VARCHAR(255)
DECLARE @TempKeyword TABLE (Keyword VARCHAR(8000))

WHILE (CHARINDEX(@Separator, @Word, 1)>0)
BEGIN
SET @TempWord = SUBSTRING(@Word, 1 , CHARINDEX(@Separator, @Word, 1) - 1)
SET @Word = SUBSTRING(@Word, CHARINDEX(@Separator, @Word, 1) + 1, LEN(@Word))

INSERT INTO @TempKeyword VALUES(@TempWord)
END

INSERT INTO @TempKeyword VALUES(@Word)

INSERT @SplitKeyword
SELECT * FROM @TempKeyword
RETURN
END

SELECT * FROM Split('10/31','/')

Tuesday, July 15, 2008

Understanding Session.Abandon

When the web application requires a log off based on session, clear the session state or call abandon(Session.Abandon) method.
Session.Abandon flushes the session state. The Abandon method sets flag which tells the session state needs to be abandoned.

The flag is evaluated at the end of the page request and action takes based on the status of the flag.
As soon as page processing is done, the session is removed.
When Session.Abandon is called, the session ID cookie is not removed for the browser.
Even after Session.Abandon call, any new request to the application uses the same Session ID with new session state instance.

If user opens another application within the same DNS domain, the user will not lose their session state after the Abandon method is called from the application.

To make session ID cookie null and to get rid of above problem, use the below code

Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

To assure that when user opens the log on page send null cookie to the client. The simple way to send a null cookie is using Response.Redirect.

Lets try one example :

create one aspx page and put below code in Page_Load

Response.Write(Session.SessionID + "
");
Session.Abandon();
Response.Write(Session.SessionID + "
");

you will get same SessionID before and after Session.Abandon

Lets create one more aspx with the below code

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && (Request.Cookies["TESTLOGIN"] == null || Request.Cookies["TESTLOGIN"].Value == ""))
{
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
AddCookie();
Response.Redirect(Request.Path);
}
Response.Write("Session.SessionID=" + Session.SessionID + "
");
Response.Write("Cookie ASP.NET_SessionId=" + Request.Cookies["ASP.NET_SessionId"].Value + "
");
}


private void AddCookie()
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "TestCookie", DateTime.Now, DateTime.Now.AddSeconds(5), false,"");
string encryptedText = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie("TESTLOGIN", encryptedText));
}

I have used a different cookie to find out whether I am redirected to the logon page.

Add watch and check Session.SessionId value. You will notice that session ID will change.

Happy Coding :)

Saturday, July 5, 2008

DropDownlist Tooltip for each item

Few days back one of my colleague wanted to show tool tip on each item, due to inappropriate rendering of contents of DropDownList. Below figure shows that DropDownlist Items are not coming completely due to small width of DropDownList and large data.



I searched on net but didn't find any appropriate solution for it.Then I thought to incorporate tooltip for each item. Here is the code to implement it.

string str = "Add Item in DDL ";
for (int i = 0; i < 11; i++)
{
DropDownList1.Items.Add(str + i.ToString());
DropDownList1.Items[i].Attributes.Add("title", str + i.ToString());
}

Title attributes add tooltip in each item in DropDownList.

Note : Title attribute doesn't work in IE 6.

Happy Coding :)

Friday, June 27, 2008

ASP.NET Deployment true

ASP.NET 2.0 comes with a new setting (< deployment retail = "true" />) in machine.config which disables debugging, tracing and error messages.

Tracing as well as asp.net error messages should not visible to the end user due to security reasons, so its always recommended to turn custom errors and tracing off in web.config.

Sometimes it is not possible to check all the web.config in an application individually and verify whether compilaion debug is true or false (< compilation debug=”true”/ >) in web.config, moreover its tedious process. To get rid of this pain, ASP.NET 2.0 has <deployment> section in machine.config file.

Turn this switch on

< system.web >
< deployment retail=”true”/ >
< /system.web >

it will disable the < compilation debug=”true”/> of web.config file.

In fact < deployment retail=”true”/ > overrides < compilation debug=”true”/ >.

Refer : http://msdn.microsoft.com/en-us/library/system.web.configuration.deploymentsection.retail(VS.80).aspx for more information

Thursday, June 26, 2008

Better way to maintain Rich Text Format in SQL

In my previous blog i discussed how can we maintain rich text format in SQL.

I got better and easier way to maintain rich text format in SQL.

Here is the code to save the rich text format in SQL (Create a table myRTF with column name Descriptionrtf):

string conString = "DB Connection string";
SqlConnection con = new SqlConnection(conString);
SqlDataAdapter da = new SqlDataAdapter("Select Descriptionrtf From myRTF ", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;

char[] arr = richTextBox1.Rtf.ToCharArray();
string str = string.Empty;
for(int i = 0; i < arr.Length; i++)
str += arr[i].ToString();

da.Fill(ds,"MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();
myRow["Descriptionrtf"] = str;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");
con.Close();

Code to load date from SQL to rich text box :

string conString = "DB Connection string";
SqlConnection connection = new SqlConnection(conString );
SqlCommand command = new SqlCommand("Select Descriptionrtf From MyImages", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
try
{
richTextBox1.Rtf = reader.GetString(0) ;
}
catch(Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
reader.close();

Happy Coding :)

Tuesday, June 24, 2008

IIS : How Anonymous access works?

Let’s try to understand how anonymous access works in IIS

1. Create a simple asp page and put <%=DATE()%> in it save it as test.asp in the following location C:\Inetpub\wwwroot\TestAnonymous (Create TestAnonymous directory in C:\Inetpub\wwwroot).
2. Create a virtual directory with TestAnonymous and map it to
C:\Inetpub\wwwroot\TestAnonymous.
3. Create a user testuser using computer management.

4. Now open IIS and go to the directory security tab and click edit button in Anonymous Access frame and change user name to testuser(which we created using computer management) and give the same password that has been provided during creation of testuser, screen should look like below.

5. Make sure no other option is selected(like: Allow IIS to control password, Digest, Basic, Integrated).
6. Try to browse test.asp page, page should come on the browser.
7. Now change the password of testuser in IIS not in computer management i.e. provide wrong password in IIS.
8. Again make sure no other option is selected(like: Allow IIS to control password, Digest, Basic, Integrated).
9. Try to browse test.asp page, page should not come on the browser.
10. Now check Allow IIS to control password,Directory security tab should be like below image.



Above steps make us beleive that anonymous access user should be in sync with the user of the system.

Refer : http://support.microsoft.com/kb/216828 for more information to understand more about Allow IIS to control password.

Monday, June 16, 2008

Maintaining Rich Text Format in SQL

Recently i had to make User Interface with few rich text box controls. Rich text box control allows the user to input formatted text. But this formatted text is of no use if we don't persist the input format. I took few hours to get the solution. I thought why not to write a blog on it.

Create a Form and put the control like below screen shot





Formatting rich text box data :


private void Bold_Click(object sender, System.EventArgs e)
{
Font ft = new Font(richTextBox1.Font,FontStyle.Bold);
richTextBox1.SelectionFont = ft;
}

private void color_Click(object sender, System.EventArgs e)
{
richTextBox1.SelectionColor = Color.Red;
}



Saving rich text box data in SQL :

Create a table(MyImages)with one column(imgField) in SQL with DataType as image.

Create connection to SQL server to save rtf text in database. I preffered to temporarily save rtf in disk with SaveFile of rich text box control, then i created instance of FileStream object and put the data in byte array and saved the byte array in the database table(MyImages), then i deleted the temp(test.rtf) file.

private void savetoDB_Click(object sender, System.EventArgs e)
{

string connectionString = "";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
string filePath = @"..\..\RTFDoc\test" + DateTime.Now.Millisecond + ".rtf";
richTextBox1.SaveFile(filePath);
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
byte[] MyData= new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
da.Fill(ds,"MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");
con.Close();
File.Delete(filePath);
}


Reading data from SQL :

Create connection to SQL server to get formatted text from database. Then i read the data from database using SQLDataReader, i then created instance of ASCIIEncoding object to convert bytre array in a string object and using string object to fill rich text box control. Then i am closing the reader and connection instance.

private void loadfromDB_Click(object sender, System.EventArgs e)
{
string ConnectionString = "";
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand("Select * From MyImages", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Byte[] rtf = new Byte[Convert.ToInt32((reader.GetBytes(0, 0, null, 0, Int32.MaxValue)))];
long bytesReceived = reader.GetBytes(0, 0, rtf, 0, rtf.Length);
ASCIIEncoding encoding = new ASCIIEncoding();
richTextBox1.Rtf = encoding.GetString(rtf, 0, Convert.ToInt32(bytesReceived));
}
reader.Close();
connection.Close();
}

Happy Coding :)

Sunday, June 15, 2008

Updating NTEXT,TEXT

The SQL Server's ntext, text, and image data types can hold huge amount of data (up to 2 GB) in a single value.

SQL stores information of TEXT,NTEXT as a pointer in a row of the table.The pointer(textptr) points to the actual data storage page.

SQL server allows to store TEXT,NTEXT in a datarow itself rather than storing pointer in the row. To achieve this we need to enable text in row option using sp_tableoption

Below is the command :

EXEC sp_tableoption 'tablename', 'text in row', 'ON' //Enables the 'text in row' option for table 'tablename'

EXEC sp_tableoption 'tablename', 'text in row', '2000' //Enables the 'text in row' option for table 'tablename', and set the limit to 2000

If the size of NTEXT,TEXT OR Image is greater than specified text in a row ,textptr will be stored in the row.

Example of updating NTEXT :

As NTEXT stores information as a pointer in a row we need a txtptr to update NTEXT data

I have created one table (ntextTbl) with Remarks and Id column

DECLARE @ptrval VARBINARY(16),@Result VARCHAR(8000)

SET @Result = 'Testing NTEXT'

SELECT @ptrval = TEXTPTR(Remarks)FROM ntextTbl WHERE id = 1

UPDATETEXT ntextTbl.Remarks @ptrval NULL NULL @result //This will append 'Testing NText' in existing Remarks row

WRITETEXT ntexttbl.Remarks @ptrval 'Replace complete NTEXT' //This will replace existing remarks row with 'Replace Complete NTEXT'


Happy Coding :)

Sunday, June 8, 2008

pdf in modal dialog box

Few days back i was looking at tech forum in my organisation and i saw one query "how to open pdf in modal dialog box?". Initially i thought this is silly question but no question is silly :).
I tried to open pdf in modal dialog box but i couldn't succeed. I could open html or aspx page in modal dialog box but not pdf. This made me to reach conclusion that pdf doesn't like modal dialog box.
There is a work around of the above problem using which we can open pdf in modal dialog box.
Create a html page(try.html) and embed pdf in iframe like the below code.

< iframe id="iframetest" src="http://localhost:1446/openPdf/csharp_ebook.pdf" height="100%" width="100%"> Test Iframe </iframe>

open the html page using javascript
function popWin(){
window.showModalDialog("http://localhost/openPdf/try.html",'','dialogHeight:650px;dialogWidth:1000px')
}
This will open the pdf in modal dialog box.

Happy Coding :)

Friday, May 30, 2008

Fun with javascript

I was working with javascript and found myself in weird situation. I banged my head several minutes to resolve the issue which would have resolved in a second.
Try to follow below steps:

Create one html page and call this javascript


function fnCall(){
for(x = 0; x < 10; x++){
fnCall1();
alert(x);
}
}

function fnCall1(){
for(x = 0; x < 10; x++){
//your code
}

}

If you go through below snippet of code you must be wondering why alert is coming only once, when it is expected to come 10 times

function fnCall(){
for(x = 0; x < 10; x++){
fnCall1();
alert(x);
}
}

function fnCall1(){
for(x = 0; x < 10; x++){
//your code
}

Above behavior is normal because x is global. If the variable doesn’t have var javascript treats it as a global variable.
Since the x doesn’t have var the variable is global. When fnCall1 is called, loop increments that value of x to 10 making fnCall to run only once.

To resolve the issue, put var in front of x

for(var x = 0; x < 10; x++)

Sunday, May 18, 2008

Add digital signature in pdf using c#

Few days back, one of our client wanted to add digital signature in pdf using window application. Windows application which will run after scheduled time need to add the the signature. Windows application was written in c#.

To achieve above goal, Adobe Acrobat professional and Adobe SDK is required.

Before writing c# code we need to following configuration setting

copy sdkAddSignature.js from Adobe\Acrobat 8 SDK\Version2\JavaScriptSupport\samples\outsidepdf\addsignature to adobeprofession javascript folder

copy DrTest.pft from Adobe\Acrobat 8 SDK\Version2\JavaScriptSupport\samples\outsidepdf\addsignature to C:\ (anywhere you like to)

Add reference of Interop.Acrobat.dll from Acrobat SDK

we can modify the location of signature on pdf or even hide it modifying the AddSignatureField function in sdkAddSignature.js.

Here is the final c# code which will add signature on pdf

Type AcrobatCAcroAppType;
AcrobatCAcroAppType = Type.GetTypeFromProgID("AcroExch.app");
Acrobat.CAcroApp gapp = (Acrobat.CAcroApp)Activator.CreateInstance(AcrobatCAcroAppType);

Type AcrobatPDDocType;
AcrobatPDDocType = Type.GetTypeFromProgID("AcroExch.PDDoc");
Acrobat.CAcroPDDoc gpddoc = (Acrobat.CAcroPDDoc)Activator.CreateInstance(AcrobatPDDocType);

object jso ;

if(gpddoc.Open("c:\\s.pdf"))
{
jso = gpddoc.GetJSObject();
object[] param = new object[1];
param[0] = "testpassword";
object con = jso.GetType().InvokeMember("SetUserPassword",
BindingFlags.InvokeMethod , null, jso, param);

param[0] = "C:\\DrTest.pfx";

con = jso.GetType().InvokeMember("SetUserDigitalIDPath",
BindingFlags.InvokeMethod , null, jso, param);

param[0] = jso;

con = jso.GetType().InvokeMember("AddSignature",
BindingFlags.InvokeMethod , null, jso, param);

Happy Coding

:)

Site Meter