Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

To Check whether to see a string is empty

There are several ways to check a string to see if it’s empty. However, you should try to always use the following method. It’s faster, and uses less resources. This may seem like a minimal piece of code -

string strAmIEmpty = "";

if (strAmIEmpty.Length == 0)

{

// empty so do something

}


But if you were checking strings through out your application, it all adds up in the end.

If you have better solution, just tell me !

Check All Checkbox In GridView To Bulk Edit Or Update ASP.NET C# VB.NET

In this example i am going to describe how to implement CheckAll CheckBox in GridView to check all the rows in gridView.

For this i have put a checkBox in header Template of gridview which on checking will check all the rows in gridview using server side code.



Html Source of gridView

<asp:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="false"
CellPadding="2" ForeColor="#333333"
GridLines="Both"
DataKeyNames="ID"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll"
>
<
HeaderTemplate
>
<
asp:CheckBox ID="chkSelectAll" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelectAll_CheckedChanged"
/>
</
HeaderTemplate
>
<
ItemTemplate
>
<
asp:CheckBox ID="chkSelect" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate
>
</
asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate
>
<
asp:TextBox ID="txtName" runat="server"
Text='<%# Bind("Name") %>' ForeColor="Blue"
BorderStyle="none" BorderWidth="0px"
ReadOnly="true"
>
</
asp:TextBox
>
</
ItemTemplate
>
</
asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server"
Text='<%# Bind("Location") %>'
ForeColor="Blue" BorderStyle="none"
ReadOnly="true">
</asp:TextBox
>
</
ItemTemplate
>
</
asp:TemplateField
>
</
Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]"
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)"

UpdateCommand
="UPDATE [Details] SET [Name] = @Name,
[Location] = @Location WHERE [ID] = @ID"
>
<DeleteParameters
>
<
asp:Parameter Name="ID" />
</DeleteParameters
>

<
UpdateParameters
>
<
asp:Parameter Name="Name" />
<asp:Parameter Name="Location"
/>
<
asp:Parameter Name="ID"
/>
</
UpdateParameters
>
</
asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server"
OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server"
OnClick="btnDelete_Click"
Text="Delete" />
C# Code behind

protected void chkSelectAll_CheckedChanged
(object sender, EventArgs e)
{
CheckBox chkAll =
(CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
TextBox txtname = (TextBox)gvRow.FindControl("txtName");
TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
txtname.ReadOnly = false;
txtlocation.ReadOnly = false;
txtname.ForeColor = System.Drawing.Color.Black;
txtlocation.ForeColor = System.Drawing.Color.Black;
}
}
else
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
TextBox txtname = (TextBox)gvRow.FindControl("txtName");
TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
txtname.ReadOnly = true;
txtlocation.ReadOnly = true;
txtname.ForeColor = System.Drawing.Color.Blue;
txtlocation.ForeColor = System.Drawing.Color.Blue;
}
}
}
VB.NET code behind
Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"),CheckBox)
If chkAll.Checked = True Then
For Each gvRow As GridViewRow In GridView1.Rows
Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"),CheckBox)
chkSel.Checked = True
Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
txtname.[ReadOnly] = False
txtlocation.[ReadOnly] = False
txtname.ForeColor = System.Drawing.Color.Black
txtlocation.ForeColor = System.Drawing.Color.Black
Next
Else
For Each gvRow As GridViewRow In GridView1.Rows
Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
chkSel.Checked = False
Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
txtname.[ReadOnly] = True
txtlocation.[ReadOnly] = True
txtname.ForeColor = System.Drawing.Color.Blue
txtlocation.ForeColor = System.Drawing.Color.Blue
Next
End If
End Sub

If you have better solution, just tell me !

C# webbrowser control - Synchronization for Page navigation/loading

We will face lot of difficulties/errors if we are not handling page synchronization properly when using .NET webbrowser control for scrapping/crawling web pages.

(i-e) We need to write a code to start other activities only when page navigation is completely done.

We can use the below function "waitTillLoad()" for this synchronization purpose.

It will wait till the browser readystate becomes "complete".

Since, initally the readystate will be "complete" there is a possibility of incorrectly exiting this function even before starting new page loading.

So to avoid this issue we have enhanced the function to wait for non-complete status before waiting for complete status.

(i-e) Page loading should occur only after stating the page navigation.

We need to mention timeout period (waittime), as the function may fall into infinite loop if we are calling it two times without initiating any further page navigation.

We can use the same function with little modifications in vb.net also.
It will be more useful and also I hope it will be more reliable as we are using it in many tools and applications for long time.

I can say that it is very essential if you are using webbrowser control for doing any page scrapping and web crawling.




private void waitTillLoad()
{
WebBrowserReadyState loadStatus;
//wait till beginning of loading next page
int waittime = 100000;
int counter = 0;
while (true)
{
loadStatus = webBrowser1.ReadyState;
Application.DoEvents();

if((counter > waittime)(loadStatus == WebBrowserReadyState.
           Uninitialized)  (loadStatus == WebBrowserReadyState.Loading)  
      (loadStatus == WebBrowserReadyState.Interactive))
{
break;
}
counter++;
}

//wait till the page get loaded.
counter = 0;
while (true)
{
loadStatus = webBrowser1.ReadyState;
Application.DoEvents();

if (loadStatus == WebBrowserReadyState.Complete)
{
break;
}
counter++;

}

}

If you have better solution, just tell me !

Finding broken links using Http WebRequest / Http WebResponse in C#

Status Code in the response will be used for finding whether the link is broken or not. But normally exception will be thrown if the link is broken. So the Timeout property of webrequest plays important role here.

(i-e) If we specify more timeout value, then total execution will take more time. If we specify less timout then there may a possiblity of declaring a valid link as a broken link. If anyone knows how to handle it appropriately, you can mention it in the comments.



private bool isBrokenLink(string url)
{

Boolean isBrokenLink = false;

try
{

WebRequest http = HttpWebRequest.Create(url);
http.Timeout = 5000;
HttpWebResponse httpresponse = (HttpWebResponse)http.GetResponse();

if (httpresponse.StatusCode == HttpStatusCode.OK)
{
isBrokenLink = false;
}
else
{
isBrokenLink = true;
}


}
catch (Exception ex)
{
isBrokenLink = true;

}
return isBrokenLink;

}

Making below two changes in the above code may increase the performance.

HttpWebRequest http = (HttpWebRequest) WebRequest.Create(url);
http.UserAgent = "Mozilla/9.0
              (compatible; MSIE 6.0; Windows 98)";
http.Method = "HEAD";

Actually the HEAD method will allow verifying the link without downloading entire content. So the performance will be increased. Particularly, it will improve the performance significantly when verifying the missing images.

If you have better solution, just tell me !

Creating Captcha using PHP and Handling Captcha using C# web browser control


These days captcha is used widely in most of the websites for preventing automated entry of details in their websites.

For those who are hearing the word Captch first time - You might have seen an image with blurred alpha numeric content with different font style and font size and with different orientation. It is used in the forms of websites to prevent automated entry of details using software programs such as bots and crawlers. So only the human can read those contents and we need to enter that content in the text box provided near this image. This system is called as Captcha.

If you want to avoid dependency of this third-party service you can create your own captcha images dynamically using GDLibrary of PHP. Simple Google search will give you the code. Please find below the sample one.


class CaptchaImages {

var $font = 'monofont.ttf';

function generateCode($characters) {
/* list all possible characters, similar looking characters and
                                          vowels have been removed */
$possible = '23456789bcdfghjkmnpqrstvwxyz';
$code = '';
$i = 0;
while ($i < $characters) { $code .= substr($possible, mt_rand(0,
                                             len($possible)-1), 1);    
      $i++;   
}   return $code;  
}   function CaptchaImages($width='120',$height='40',$characters='6') 
{
$code = $this->generateCode($characters);
/* font size will be 75% of the image height */
$font_size = $height * 0.75;
$image = @imagecreate($width, $height) or die('Cannot initialize new
                                                    GD image stream');
/* set the colours */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$noise_color = imagecolorallocate($image, 100, 120, 180);
/* generate random dots in background */
for( $i=0; $i<($width*$height)/3; $i++ ) {
  imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 
      1, 1, $noise_color);
}
/* generate random lines in background */
for( $i=0; $i<($width*$height)/150; $i++ ){imageline($image, mt_rand
                                        (0,$width), mt_rand(0,$height), 
 mt_rand(0,$width), mt_rand(0,$height), $noise_color);
}
/* create textbox and add text */
$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die
                     (               'Error in imagettfbbox function');
$x = ($width - $textbox[4])/2;
$y = ($height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color,
      $this->font , $code) or die('Error in imagettftext function');
/* output captcha image to browser */
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
$_SESSION['security_code'] = $code;
}
}
$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters']
                                 > 1 ? $_GET['characters'] : '6';

$captcha = new CaptchaImages($width,$height,$characters);

Till now we have seen how to implement Captcha to avoid automated form filling using bots.

Sometimes we may need to navigate the websites using bots created using webbrowser control. As the bots can not read the captcha content, it is not possible to navigate the sites without interruption. In this case, we can create a code atleast for allowing the user to manually enter the captcha text while the bot continues the execution.


public partial class ModalesMsgBox : Form
{
public string captchaWord;
public string captchaurl;
public bool isEntered;
public ModalesMsgBox(string strcaptchaurl,string strMsg)
{
captchaurl = strcaptchaurl;
isEntered = false;
InitializeComponent();
lblMsg.Text = strMsg;

}

private void btnsubmit_Click(object sender, EventArgs e)
{
captchaWord = txtCaptcha.Text;
isEntered = true;
this.Close();
}



private void ModalesMsgBox_Load(object sender, EventArgs e)
{

try
{

webBrowser1.Navigate(captchaurl);

}
catch(Exception ex)
{

}

}

Find below the sample code for using the above class in the typical webbrowser control navigation code.


 string strMsgrd = "Please enter captcha letters and click 
'Enter' in this Dialog box.\n Don't type 'Enter'  and don't click 'Submit' button in the browser control";
string strCaptchImgrd = webBrowser1.Document.GetElementById
                                              ("capimage").GetAttribute("src");
ModalesMsgBox msgrd = new ModalesMsgBox(strCaptchImgrd, strMsgrd);
wait(70000);
msgrd.Show();
wait(500000);
while (!msgrd.isEntered)
{
Application.DoEvents();
}
string strCaptchard = msgrd.captchaWord.ToString();
webBrowser1.Document.GetElementById("captcha").Focus();
wait(70000);
webBrowser1.Document.GetElementById("captcha").InnerText = strCaptchard;
wait(700000);
HtmlElementCollection SubmitButton = webBrowser1.Document.
                                                  GetElementsByTagName("button");
SubmitButton[0].InvokeMember("click");

If you have better solution, just tell me !

Deleting Session Cookie in Webbrowser control.

We know that many websites are using cookies for storing some user data in browser to improve user experience.

C#.net is having webbrowser control for creating applications useful for automatically navigating/crawling websites.

It will be required to delete these cookies in webbrowser control when using it for different set of user logins.

Below C# function will be useful for deleting the cookie for IE (Internet Explorer) browser. As webbrowser control will share the cookie with IE, this code can be used for deleting webbrowser control cookie.

I heard that cookie will be stored somewhere temporarily also, and this function won't delete it. But I am not sure about. If anyone know more details about this temporary cookie you can share it here.



private void deletecookie()
{
string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));

foreach(string currentFile in theCookies)
{

try
{

System.IO.File.Delete(currentFile);

}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}

}

}

If you have better solution, just tell me !

User validation across pages using session after login in ASP.NET using C sharp

In this example i m showing how to validate a user across different pages whether user is logged in or not using session variables in Global.asax through Session_Start event and Application_OnPostRequestHandlerExecute event which checks for the login validation which occurs when ant asp.net event handler finish execution

Here is my login page , i've used hard coded values to login.

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Login.aspx.cs" Inherits="_Default" %>


<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:left" >
<table width="40%" style="text-align: center">
<tr><td style="width: 20%">
<asp:Label ID="lblUserName"
runat="server" Text="Enter UserName:">
</asp:Label></td>
<td style="width: 20%">
<asp:TextBox ID="txtUserName"
runat="server">
</asp:TextBox></td>
</tr>
<tr>
<td style="width: 20%">
<asp:Label ID="lblPassword" runat="server"
Text="Enter Password:">
</asp:Label></td>
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password">
</asp:TextBox></td>
</tr><tr><td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server"
Text="Sign in" OnClick="btnLogin_Click" />
</td></tr>
</table>
<asp:Label ID="Label1" runat="server"
Text="Label">
</asp:Label><br />
</div>

</form>
</body>
</html>


After checking the username and password i m creating a new Session variable and setting the flag kindaa value in it , which is "Yes" in this example, this session value will be checked when ever user go to other pages and if it's null than user in not logged in.


protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "amit" && txtPassword.Text == "amit")
{
Session["Authenticate"] = "Yes";
Response.Redirect("Default2.aspx");
}
else
Label1.Text = " login failed";
}

In Global.asax, in Session_Start event i m assigning null value to the session variable created at the time of Login and than calling the method to check the login, same is in Application_OnPostRequestHandlerExecute event as well.

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["Authenticate"] = "";
CheckLogin();

}
void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}

void CheckLogin()
{
string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (SessionData == "" && TestUrl != "Login.aspx")
{
Response.Redirect("~/Login.aspx");
}
}
If you have better solution, just tell me !

ASP.NET Add AutoNumber Column in GridView or DataList

Send Email using Gmail ASP.NET C# VB.NET

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;
Now write this code in click event of button
C# code
protected void Button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add("jainamit.agra@gmail.com");
mail.To.Add("amit_jain_online@yahoo.com");
mail.From = new MailAddress("jainamit.agra@gmail.com");
mail.Subject = "Email using Gmail";
string Body = "Hi, this mail is to test sending mail"+
"using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);
}
VB.NET code 
Imports System.Net.Mail
Protected Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
Dim mail As MailMessage = New MailMessage()
mail.To.Add("jainamit.agra@gmail.com")
mail.To.Add("amit_jain_online@yahoo.com")
mail.From = New MailAddress("jainamit.agra@gmail.com")
mail.Subject = "Email using Gmail"
String Body = "Hi, this mail is to test sending mail"+
"using Gmail in ASP.NET"
mail.Body = Body
mail.IsBodyHtml = True
Dim smtp As SmtpClient = New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.Credentials = New System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword")
smtp.EnableSsl = True
smtp.Send(mail)
End Sub

Change YourUserName@gmail.com to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

Than you need to check your Gmail username and password.

Hope this helps

JavaScript, C#, and ExtSharp

Colin Ramsay thinks that JavaScript and C# can be scarily similar as he shows an ExtJS example:


JAVASCRIPT:
  1. var win = new Ext.Window({
  2. title: 'Order Viewer', layout: 'border',
  3. width: 500, height: 500,
  4. modal: true, resizable: false, closable: false, draggable: false,
  5. items: [ frm, lst ]
  6. });
  7. win.on('render', function() {
  8. load(5);
  9. });
  10. win.show();


C#:

  1. var win = new Ext.Window{
  2. Title = "OrderViewer", Layout = Layout.Border,
  3. Width = 100, Height = 200,
  4. Modal = true, Resizable = false, Closable = false, Draggable = false,
  5. Items = new [] { frm, lst }
  6. };
  7. win.Render += delegate {
  8. load(5);
  9. };
  10. win.show();

This works well for ExtJS since it is written in a style that leads itself to this similarity. Colin also points out ExtSharp, a project that lets you write your Ext application in C#:

If you have better solution, just tell me !