Tuesday, December 23, 2008

How Microsoft missed this!

Nobody can create a folder anywhere named as “con” , “PRN” , “LPT1” , “LPT2” , “LPT3” , “COM1” ,”aux” , “COM2” or “NUL”

This is something pretty cool...and unbelievable... At Microsoft the whole Team, including Bill Gates, couldn't answer why this happened! It is a standard device name in DOS. You cannot use these too

In addition, the following file names are pre-assigned to certain devices.

CON:

Console (screen display for output and keyboard for input)

PRN:

Printer. This is usually LPT1.

LPT1:

The first parallel printer/port. The printer device may be used only as an output device.

LPT2:

The second parallel printer/port (for output only).

LPT3:

The third parallel printer/port (for output only).

COM1: or AUX:

The first asynchronous communications adapter port.

COM2

The second asynchronous communications adapter port.

NUL:

A nonexistent device to avoid the generation of output from programs.

Try it out yourself...

Source: https://www.nilebits.com/blog/2009/01/how-microsoft-missed-this/

Wednesday, December 17, 2008

The Windows Installer Service is unavailable!

I got this error when I was trying to install any application, I didn't know if this error is a bug in Windows Vista Ultimate or a bug in Windows Installer.
However finally I got the solution after days of searching Google to get any solution for this error but I didn't find any.

What I have discovered so far is an application or registry entry I don't know, it starts the Windows installer process not the service and keeps it running so when you try to install it gives you this error:

"Another application may be running setup. Finish any installation in progress, or restart your computer and re-run the setup"

It feels that you are running another setup.

To be able to run your setup just ends the Windows Installer Process from the Task Manager.

Monday, November 3, 2008

What is SQL injection?

It is a way of hacking on a database driven Web site in which the hacker executes unauthorized SQL commands by taking advantage of insecure code on a system connected to the Internet,bypassing the firewall.

SQL injection hackers are used to steal information from a database from which the data would normally not be available and/or to gain access to an organization’s host computers through the computer that is hosting the database.

SQL injection attacks typically are easy to avoid by ensuring that a system has strong input validation.

Example:

This is your query when the user clicks on the Login button ->
Select [UserName], [Password] From Users Where UserID = 1; 
This the Hacker query "he types this query in the user name textbox"->
Select [UserName], [Password] From Users Where UserID = 1;
Drop Table Users;
So Never use a direct query from your Web Application to Database.

Instead use Stored Procedures and Implement Layers such as Data Access Layer and Business Logic Layer, this would protected you against the SQL Injection.

Source: https://www.nilebits.com/blog/2008/11/sql-injection/

Saturday, November 1, 2008

How to Export To Excel in ASP.NET

Export Gridview Control to Excel:
HtmlForm htmlForm = new HtmlForm();
string fileName = "attachment; filename=Reports.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", fileName);
Response.ContentType = "application/ms-excel";
StringWriter strw = new StringWriter();
HtmlTextWriter htxtw = new HtmlTextWriter(strw);
htmlForm.Controls.Add(GridViewReports);
this.Controls.Add(htmlForm);
GridViewReports.RenderControl(htxtw);
Response.Write(strw.ToString());
Response.End(); 
Export Data Table to Excel:
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
    context.Response.Write(column.ColumnName + ";");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
    for (int i = 0; i < table.Columns.Count; i++)
    {
        context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");
    }
    context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".csv");
context.Response.End();

Source: https://www.nilebits.com/blog/2008/10/export-excel-asp-dot-net-c-sharp/

Sunday, October 19, 2008

Force TextBox Values to Capital Letters whatever user types in ASP.NET

Create a css class with the following definition and apply the cssclass to the Textbox.
.MakeCapsStyle{text-transform: uppercase;}

Wednesday, October 15, 2008

How to Send email in ASP.NET using C# through Gmail Outgoing Mail Server

SmtpClient oSmtpClient = new SmtpClient();
oSmtpClient.Host = "smtp.gmail.com"; //The Outgoing mail server
oSmtpClient.Credentials = new NetworkCredential("Your Email", "Your password");
oSmtpClient.Port = 587;
oSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
oSmtpClient.EnableSsl = true;
MailMessage msg = new MailMessage("Email From", "Email To");
msg.Subject = "Subject goes here";
msg.Body = "Body goes here";
oSmtpClient.Send(msg);

Source: https://www.nilebits.com/blog/2008/09/send-email-using-c-sharp/

Wednesday, October 1, 2008

How to Avoid this error: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure...

INTRODUCTION

When you try to connect to an instance of Microsoft SQL Server 2005 from a remote computer, you may receive an error message. This problem may occur when you use any program to connect to SQL Server.

For example, you receive the following error message when you use the SQL Management Studio 2005 to connect to SQL Server:

Error: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

This problem may occur when SQL Server 2005 is not configured to accept remote connections. By default, SQL Server 2005 Express Edition and SQL Server 2005 Developer Edition do not allow remote connections.

To configure SQL Server 2005 to allow remote connections, complete all the following steps:

• Enable remote connections on the instance of SQL Server that you want to connect to from a remote computer.
• Turn on the SQL Server Browser service.
• Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

MORE INFORMATION

To enable remote connections on the instance of SQL Server 2005 and to turn on the SQL Server Browser service, use the SQL Server 2005 Surface Area Configuration tool.

The Surface Area Configuration tool is installed when you install SQL Server 2005.

Enable remote connections for SQL Server 2005 Express or SQL Server 2005 Developer Edition:
You must enable remote connections for each instance of SQL Server 2005 that you want to connect to from a remote computer.


To do this, follow these steps:

1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
3. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply.

Note Click OK when you receive the following message:
Changes to Connection Settings will not take effect until you restart the Database Engine service.

4. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Service, click Stop, wait until the MSSQLSERVER service stops, and then click Start to restart the MSSQLSERVER service.

Enable the SQL Server Browser service:

If you are running SQL Server 2005 by using an instance name and you are not using a specific TCP/IP port number in your connection string, you must enable the SQL Server Browser service to allow for remote connections.

For example, SQL Server 2005 Express is installed with a default instance name of Computer Name\SQLEXPRESS. You are only required to enable the SQL Server Browser service one time, regardless of how many instances of SQL Server 2005 you are running.

To enable the SQL Server Browser service, follow these steps. Important These steps may increase your security risk.

These steps may also make your computer or your network more vulnerable to attack by malicious users or by malicious software such as viruses.

We recommend the process that this article describes to enable programs to operate as they are designed to, or to implement specific program capabilities.

Before you make these changes, we recommend that you evaluate the risks that are associated with implementing this process in your particular environment.

If you choose to implement this process, take any appropriate additional steps to help protect your system. We recommend that you use this process only if you really require this process.

1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
3. On the Surface Area Configuration for Services and Connections page, click SQL Server Browser, click Automatic for Startup type, and then click Apply.

Note When you click the Automatic option, the SQL Server Browser service starts automatically every time that you start Microsoft Windows.

4. Click Start, and then click OK.

Note When you run the SQL Server Browser service on a computer, the computer displays the instance names and the connection information for each instance of SQL Server that is running on the computer.

This risk can be reduced by not enabling the SQL Server Browser service and by connecting to the instance of SQL Server directly through an assigned TCP port. Connecting directly to an instance of SQL Server through a TCP port is beyond the scope of this article.

For more information about the SQL Server Browser server and connecting to an instance of SQL Server, see the following topics in SQL Server Books Online:

• SQL Server Browser Service
• Connecting to the SQL Server Database Engine
• Client Network Configuration

Create exceptions in Windows Firewall:

These steps apply to the version of Windows Firewall that is included in Windows XP Service Pack 2 (SP2) and in Windows Server 2003. If you are using a different firewall system, see your firewall documentation for more information.

If you are running a firewall on the computer that is running SQL Server 2005, external connections to SQL Server 2005 will be blocked unless SQL Server 2005 and the SQL Server Browser service can communicate through the firewall.

You must create an exception for each instance of SQL Server 2005 that you want to accept remote connections and an exception for the SQL Server Browser service.

SQL Server 2005 uses an instance ID as part of the path when you install its program files. To create an exception for each instance of SQL Server, you must identify the correct instance ID.

To obtain an instance ID, follow these steps:

1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager.
2. In SQL Server Configuration Manager, click the SQL Server Browser service in the right pane, right-click the instance name in the main window, and then click Properties.
3. On the SQL Server Browser Properties page, click the Advanced tab, locate the instance ID in the property list, and then click OK. To open Windows Firewall, click Start, click Run, type firewall.cpl, and then click OK.

Create an exception for SQL Server 2005 in Windows Firewall

To create an exception for SQL Server 2005 in Windows Firewall, follow these steps:

1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe executable program, click Open, and then click OK.

Note The path may be different depending on where SQL Server 2005 is installed. MSSQL.1 is a placeholder for the instance ID that you obtained in step 3 of the previous procedure.

4. Repeat steps 1 through 3 for each instance of SQL Server 2005 that needs an exception.

Create an exception for the SQL Server Browser service in Windows Firewall

To create an exception for the SQL Server Browser service in Windows Firewall, follow these steps:

1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe executable program, click Open, and then click OK.

Note The path may be different depending on where SQL Server 2005 is installed.

Source: https://www.nilebits.com/blog/2008/08/allow-remote-connections-to-sql-server/

Monday, September 29, 2008

What is the difference between 3 Tier & 3 Layer Applications?

The terms tier and layer are frequently used interchangeably, but actually there is a difference between them:

Tiers indicate a physical separation of components, which may mean different assemblies such as DLL, EXE etc on the same server or multiple servers; but layers refers to a logical separation of components, such as having distinct namespaces and classes for the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL).

Therefore, tier is about physical separation and units of deployment, and layers are about logical separation and units of design.

Source: https://www.nilebits.com/blog/2008/07/difference-between-three-tiers-three-layers-applications/

Thursday, September 25, 2008

How to Make a Captcha Image in C# .NET



What Captcha stand for?
Completely Automated Public Turing test to tell Computers and Humans Apart.
The Captcha technology help you to make sure your site is reasonably secure against automated attacks.

Write the following code in a class named Captcha :
public class Captcha
{
    //make the captcha image for text
    public Bitmap MakeCaptchaImage(string txt, int width, int hight, string fontFamilyName)
    {
        //make the bitmap and the associated Graphics object
        Bitmap bm = new Bitmap(width, hight);
        Graphics gr = Graphics.FromImage(bm);
        gr.SmoothingMode = SmoothingMode.HighQuality;
        RectangleF recF = new RectangleF(0, 0, width, hight);
        Brush br;
        br = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
        gr.FillRectangle(br, recF);
        SizeF text_size;
        Font the_font;
        float font_size = hight + 1;
        do
        {
            font_size -= 1;
            the_font = new Font(fontFamilyName, font_size, FontStyle.Bold, GraphicsUnit.Pixel);
            text_size = gr.MeasureString(txt, the_font);
        }
        while ((text_size.Width > width) || (text_size.Height > hight));
        // Center the text.
        StringFormat string_format = new StringFormat();
        string_format.Alignment = StringAlignment.Center;
        string_format.LineAlignment = StringAlignment.Center;

        // Convert the text into a path.
        GraphicsPath graphics_path = new GraphicsPath();
        graphics_path.AddString(txt, the_font.FontFamily, 1, the_font.Size, recF, string_format);

        //Make random warping parameters.
        Random rnd = new Random();
        PointF[] pts = { new PointF((float)rnd.Next(width) / 4, (float)rnd.Next(hight) / 4), new PointF(width - (float)rnd.Next(width) / 4, (float)rnd.Next(hight) / 4), new PointF((float)rnd.Next(width) / 4, hight - (float)rnd.Next(hight) / 4), new PointF(width - (float)rnd.Next(width) / 4, hight - (float)rnd.Next(hight) / 4) };
        Matrix mat = new Matrix();
        graphics_path.Warp(pts, recF, mat, WarpMode.Perspective, 0);

        // Draw the text.
        br = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
        gr.FillPath(br, graphics_path);

        // Mess things up a bit.
        int max_dimension = System.Math.Max(width, hight);
        for (int i = 0; i <= (int)width * hight / 30; i++)
        {
            int X = rnd.Next(width);
            int Y = rnd.Next(hight);
            int W = (int)rnd.Next(max_dimension) / 50;
            int H = (int)rnd.Next(max_dimension) / 50;
            gr.FillEllipse(br, X, Y, W, H);
        }
        for (int i = 1; i <= 5; i++)
        {
            int x1 = rnd.Next(width);
            int y1 = rnd.Next(hight);
            int x2 = rnd.Next(width);
            int y2 = rnd.Next(hight);
            gr.DrawLine(Pens.DarkGray, x1, y1, x2, y2);
        }
        for (int i = 1; i <= 5; i++)
        {
            int x1 = rnd.Next(width);
            int y1 = rnd.Next(hight);
            int x2 = rnd.Next(width);
            int y2 = rnd.Next(hight);
            gr.DrawLine(Pens.LightGray, x1, y1, x2, y2);
        }
        graphics_path.Dispose();
        br.Dispose();
        the_font.Dispose();
        gr.Dispose();
        return bm;
    }
}
Write the following code in the page load event:
Captcha oCaptcha = new Captcha();
Random rnd = new Random();
string[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
int i;
StringBuilder sb = new StringBuilder(4);
for (i = 0; i <= 4; i++)
{
    sb.Append(s[rnd.Next(1, s.Length)]);
}
Bitmap bm = oCaptcha.MakeCaptchaImage(sb.ToString(), 200, 100, "Arial");
string url = Server.MapPath("~/Images/Captcha.bmp");
bm.Save(url);
Image1.ImageUrl = "~/Images/Captcha.bmp";

Source: https://www.nilebits.com/blog/2008/06/captcha-image-c-sharp-dot-net/

Tuesday, September 9, 2008

The difference between Server.Transfer and Response.Redirect in ASP .NET

Server.Transfer processes the page from one page directly to the next page without making a round-trip back to the client's browser. This way is faster, with a little less overhead on the server.
However, it does not update the clients url history list or current url.

Response.Redirect, as expected, is used to redirect the user's browser to another page or site. It does perform a trip back to the client where the client's browser is actually redirected to the new page.
The browser history list is updated to reflect the new address.

Source: https://www.nilebits.com/blog/2008/05/difference-between-server-transfer-response-redirect-asp-dot-net/

Sunday, September 7, 2008

Javascript is not working with AJAX

If you are using AJAX, and control (inside an UpdatePanel) causes a postback that would normally run Javascript, and you find the Javascript is not running, add a Postback Trigger to the UpdatePanel using the ID of the control that causes the postback.

And this would solve the issue.

Source: https://www.nilebits.com/blog/2008/04/javascript-not-working-with-updatepanel/

Friday, September 5, 2008

How To Make Previous Calendar Dates Not Selectable in ASP.NET

In order to make all dates before the current date, not able to be selected, in the onDayRender event for your Calendar:
if (e.Day.Date < DateTime.Today)
{
    e.Day.IsSelectable = false;
}
To make it more obvious to the end user, also add:
e.Cell.BackColor = Drawing.Color.GhostWhite;
e.Cell.ForeColor = Drawing.Color.Gainsboro;

Source: https://www.nilebits.com/blog/2008/03/make-previous-calendar-dates-not-selectable-asp-dot-net/

Wednesday, September 3, 2008

How can you speed up your ASP .NET application in the Production Environment?

After you finish your ASP .NET Application "Developing and Testing", and before you upload the application to a production server, don't forget to change the value of debug="true" to false in the compilation section in the Web.Config file.

This would increase the performance of your application.

Source: https://www.nilebits.com/blog/2008/02/speed-up-asp-dot-net-applications-production-environment/

Monday, September 1, 2008

How to Get the referring page on Page_Load event in ASP .NET

When a page loads, in order to get the name of the page that sent you there, all you need to use is:
Request.UrlReferrer.ToString();
You can create a global variable to hold it:
string sReferrer = "";
Then, in the Page_Load event, assign it:
if (!Page.IsPostback)
{
    sReferrer = Request.UrlReferrer.ToString();
}
Or, you can put it in ViewState at that time:
if (!Page.IsPostback)
{
    ViewState("Referrer") = Request.UrlReferrer.ToString();
}
From there, on out, within that page, you can use either the variable, or ViewState, within that page as a link, or whatever you need it for.

Source: https://www.nilebits.com/blog/2008/01/get-referring-page-page-load-event-asp-dot-net/

Saturday, August 23, 2008

Interviews Tips and Advices

Some stuff you should do in the Interviews:

1 - Arrive on time or early but not too early.
2 - Dress formally, this would give you a self-confident.
3 - Be polite to everyone in the office.
4 - Act confident, but not overconfident.
5 - Give the appearance of energy as you walk.
6 - Don't forget to Smile.
7 - Shake hands firmly and stand until offered a chair.
8 - Look to the interviewer in the eye while speaking.
9 - If the interviewer ask you to fill an application do it and finish it all.
10 - Listen carefully, this would help you finding the best answers.
11 - Take your time and think carefully before answering any question.
12 - Make sure that your good points come across to the interviewer in a factual, sincere manner.
13 - Always conduct yourself as if you are determined to get the job you are discussing.
14 - Stress your achievements.
15 - Finaly don't forget to thank the interviewer for interviewing you.

Some stuff you should not do in the Interviews:

1 - Don’t be late or overdressed.For women wear only light perfume, make up, and jewelry.
2 - Don't forget to bring a copy of your resume!
3 - Don't smoke or chew gum, even if the interviewer does and offers you either.
4 - Don't answer with a simple "yes" or "no".
5 - Don’t over-answer questions or talk too much either.
6 - Don't lie. Answer questions truthfully, frankly, and briefly.
7 - Don't make derogatory remarks about your present or former employers and co-workers.
8 - Don’t mention other companies that turned you down.
9 - Don't inquire about salary, vacations, etc. during the first interview unless you are sure the employer is interested in hiring you.
10 - Don’t take anyone with you to the interview.
11 - Don’t apologize for lack of experience or training; stress your strong points instead.
12 - Don’t put anything on the interviewer's desk.
13 - Don’t try to be very funny.
14 - Don’t hang around after the interview.
15 - Don’t make elaborate promises.

Thursday, August 21, 2008

How to Add static item to the top of DropDownList ASP.NET Web Control after biniding it

Sometimes you need to add a static item to the top of DropDownList ASP.NET Web Control, Such as "----" or "Select" or any other text.

If you add it in the design time you would see it but when you run the web site this item would be removed and replaced with the items that comes from the Data Source that you are using for binding.

In order to keep the static item, set the "AppendDataBoundItems" property of the DropDownList to "True".

Source: https://www.nilebits.com/blog/2007/10/add-static-item-to-dropdownlist-web-control-after-data-bind-in-asp-dot-net/

Tuesday, August 19, 2008

How to Ignore JavaScript errors

Sometimes when you are working on a page and want to publish it and you have some JavaScript errors, but you don't have time to debug it, you can put the following code in order to ignore the JavaScript errors:
<head>
<script language="javascript">
    function stoperror() {
        return true;
    }
    window.onerror = stoperror();
</script>
</head>

Sunday, August 17, 2008

How to Solve this error "The GridView 'MyGridview' fired event PageIndexChanging which wasn't handled."

You can see this error when you are populating a Gridview with code, and you enabled the Paging Property of the Gridview without implementing the PageIndexChanging Event.

So when you click the next Page in the Gridview you will see this error:

"The GridView 'MyGridview' fired event PageIndexChanging which wasn't handled."

To avoid this issue simply write this code in the PageIndexChanging Event:
MyGridview.PageIndex = e.NewPageIndex;
MyGridview.DataBind();

Friday, August 15, 2008

How to Use Response Object in a Class

If you try to use
Response.Write(MyString);
Method for example in a class you will receive an error telling you that the Response Object is not available in this context.

In order to use the Response Object in a class without having this error, instead of writing
Response.Write(MyString);
write this
HttpContext.Current.Response.Write(MyString);
Or you can use any method of the Response Object.

And don't forget to write Using System.Web in the top of the class.

Wednesday, August 13, 2008

How to Replace a text in SQL Server Table Column

If you have a Table which has a Column of type char or varchar or even text, and you want to change a portion of text in it for example a path.
In this case you need to change the same text with new one in every records.

Here is the SQL Statement that do this:
UPDATE [TableName] SET [ColumnName] = Replace([ColumnName],'OldText','NewText');

Source: https://www.nilebits.com/blog/2007/09/replace-text-in-a-column-in-sql-server/

Monday, August 11, 2008

How to Change the file size in FileUpload control

I tried to upload file using FileUpload Control in ASP.NET but I had a problem which is the maximum file size is 4 MB, and I was uploading a file larger than the maximum size.
So to solve this problem, in the HTTPRuntime section in the Web.config file set the maxRequestLength in KB:
<system.web>
  <httpRuntime maxRequestLength="1500000" />
</system.web>

Source: https://www.nilebits.com/blog/2007/07/string-functions-startswith-and-endswith-are-case-sensitive-in-dot-net/

Saturday, August 9, 2008

Confirmation Messagebox when deleting an item from the GridView ASP.NET Control

Many Users click the delete button within the GridView with no attention then the result the item will be deleted from the GridView, so we can add confirmation messagebox to appear to tell the user "Are you sure you want to delete this item?".

First of all we have to attach the javascript code for each delete button within the GridView, we can do that in the itemdatabound method of the GridView:
HttpContext.Current.Response.Write(MyString);
LinkButton deleteButton = e.Item.Cells[0].Controls[0];
deleteButton.Attributes.Add("onclick","javascript:return confirm('Are you sure you want to delete this item?')");
where the first cell in the GridView is a linkbutton.
So when the user clicks the delete button then a confirmation message appears so if the user clicks No then nothing happens else postback will happen then it should be a server event such as a onDeleteCommand that fires when the user clicks the delete button as
private void dgPendingCompleteForms_Delete(Object sender, DataGridCommandEventArgs e)
{
    //Put your code here when the user presses the yes button on the confirmation meessagebox
}

Source: https://www.nilebits.com/blog/2007/11/confirmation-message-deleting-item-gridview-control-asp-dot-net/

Thursday, August 7, 2008

The string function "EndsWith" is case-sensitive

Did you know that "EndsWith" String function is case-sensitive even in VB.NET?

You need to make sure you are looking for the correct string, since 'abc' with case-sensitivity is different than 'ABC'.

So, if your function is looking for 'abc', you must make sure that you make adjustments to the string, in order to catch things like this.

To do this, you would need to change:
myString.EndsWith("abc");
to
myString.ToLower.EndsWith("abc");

Source: https://www.nilebits.com/blog/2007/07/string-functions-startswith-and-endswith-are-case-sensitive-in-dot-net/

Tuesday, August 5, 2008

Password Recovery Web Control cannot send email Via SSL Mail Servers

I was using lately the Login Controls in a Website I am working on it, and I discovered a bug or you can call it limitation in Password Recovery Web Control. I used to use the Membership provider and Login Controls, but I didn't face this problem before since I was send the email via Non SSL Enabled SMTP server.

Now I was trying to send email using Password Recovery Control via Gmail, I got this error:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. 32sm15616652wfa.13 Password Recovery control read most of the settings from web.config file.

Internally it uses System.Net.Mail to send out email, which does not support reading EnableSSL setting from web.config. This bring us into a situation where Password Recovery control cannot send emails to SSL enabled smtp servers.

This because there is no settings in the Web.Config file for System.Net.Mail (.NET 2.0) that maps to EnableSSL Property of System.Net.Mail.SmtpClient.

Here is the solution for this problem:

1- We will consume the SendingMail Event.
2- This provide us access to the Email Message being sent and also give us option to cancel the sending operation.
3- We Will make a copy of this email message, and create a new instance of System.Net.Mail.SmtpClient
4- This time we have complete access to its properties and we can turn On/Off the EnableSSL setting
5- Lets set EnableSSL to true and send the email message to desired SMTP server.

The below code snippet can do the job:
protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
{
    System.Net.Mail.SmtpClient smtpSender = new System.Net.Mail.SmtpClient("smtp.google.com", 587);
    smtpSender.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtpSender.Credentials = new System.Net.NetworkCredential("username@gmail.com", "password");
    smtpSender.EnableSsl = true;
    smtpSender.Send(e.Message);
    e.Cancel = true;
}

Source: https://www.nilebits.com/blog/2007/01/password-recovery-web-control-can-not-send-email-via-ssl-mail-servers-in-asp-dot-net/

Sunday, August 3, 2008

Change the back color of a Gridview row when you click the Edit button or link

If you have an editable Gridview and you need to change the backcolor of the row you are editing, just write these tow lines of code in the Gridview's RowEditing Event.
MyGridview.SelectedIndex = e.NewEditIndex;
MyGridviewID.SelectedRow.BackColor = Drawing.Color.Red;

Friday, August 1, 2008

Some Stuff You Should Know About Windows XP - Part2

To see part 1 Click Here

6 - Non-expired password for all users

If you want to make the password never expire for all the users type this in DOS Prompt
net accounts /maxpwage:unlimited 7-Cancellation folder "Shared Documents"
If you want to remove the Shared Documents Folder that show for all the users with the LAN do the following:

a-Go to Start -> Run -> regedit -> Enter
This would open the Registry editor for you.
b- Go to HKEY _CURRENT_USER -> Software -> Microsoft -> Windows -> CurrentVersion ->Policies -> Explorer
c-Create new Value and choose DWORD type for this value.
d-Name this Value NoSharedDocuments and give it 1 as Value.

7 - Change the Programmes that run in the sartup

Go to Satart -> Run -> msconfig then press enter. This would open the System Configuration Utility for you.

Go to Startup Tab and choose which programmes do you like to start when windows start and which programmes not.

8 - Administrative Tools Programes

For unknown reason there are some programes should be in the Administrative Tools Folder in Control Panel but it just not there.

In order to use it type this in Run:

Computer Management - compmgmt.msc Disk Managment - diskmgmt.msc Device Manager - devmgmt.msc Disk Defrag - dfrg.msc Event Viewer - eventvwr.msc Shared Folders - fsmgmt.msc Group Policies - gpedit.msc Local Users and Groups - lusrmgr.msc Performance Monitor - perfmon.msc Resultant Set of Policies - rsop.msc Local Security Settings - secpol.msc Services - services.msc Component Services - comexp.msc

9 - How to add NetBEUI Protocle

Some poeple belive that NetBEUI Protocl don't work with Windows XP. The fact is this protocl don't come dirctly with Windows Xp in order to use it do the following:

a-Go to VALUEADD -> MSFT -> NET -> NETBEUI in the Windows XP Installation CD
b-Copy NBF.SYS file to WINDOWS -> SYSTEM32 -> DRIVERS
c-Copy NETNBF.INF file to WINDOWS -> INF
d-From the LAN properties you can now use NetBEUI Protocol like any other one.

To see part 1 Click Here

Wednesday, July 9, 2008

Some Stuff You Should Know About Windows XP - Part1

In this article we will discover some secrets about Windows XP. I believe most of you know some of these stuff or even all of it but I think it's very useful to know it anyway. If you have any new stuff just send it to me and I will add it in a new post.

1 - Rename Folders or/and Files in one step

a-Select all the Folders and Files that you want to rename them.
b-Press right click on the first Folder or file and choose Rename then rename it with any name for example "MyDoc".
c-Now Windows XP will rename the rest of the Folders and files automatically.
d-The name of the Folders and Files will be like this (MyDoc1,MyDoc2,...)

2 - Bigger size for Thumbnails

When you set the View of any folder to Thumbnails, the names of the files appear underneath it. You can show the files without their names underneath it, just press the Shift key and hold while you open the folder which contains the Thumbnails files.

3 - Get rid of "Thumbs.db" files

When you open a Folder with Thumbnails View Windows XP create a file named Thumbs.db, which contains some information about the folder, in order to accelerate the performance next time you open the Folder.

If you want to make Windows XP to stop creating these files do the following:

a-Open My Computer.
b-From Tools choose Folder Options.
c-Choose View Tab.
d-Advanced Settings -> Files and Folders -> Do Not Cache Thumbnails.
check it and press OK, this would prevent Windows XP from creating the Thumbs.db files again.

4 - Choose the Details of the Details

When you choose to show a Folder with Details View, you can specify which details to show and which to hide. To do so go to View and click on Choose Details.

5 - More Windows Components

For unknown reason Windows XP hides some of the Windows Components, in the Add/Remove Program.
To show all the Windows Components go to Windows Folder then open Inf Folder.

Look for sysoc.inf file open it and delete the word Hide from it save it then go to Control Panel open Add/Remove Programs then click on Add/Remove Windows Components.

Now you can see there are some new components you can see.
--------------------------------------------------------------------------------

Please visit my Blog frequently to see Part 2.

Monday, July 7, 2008

Five rules of variable naming

1. Make your variable names long and descriptive

Visual Studio has IntelliSense, Eclipse has its own code completion, and I'm sure whatever IDE you're using can finish your variable names off for you, too. Using long names prevents the ambiguity of short or cryptic names.

2. Put units in your variable names

If you are writing an engineering application you are going to be using variables with units. Embed the unit name in the variable, for example, distanceInMM.

3. If you are using Camel Case, don't capitalize commonly hyphened, or combined words

Let me explain.Callback is normally spelt as one word. So, pretty please, don't call your variable callBack.

4. Never, ever use the variable name temp

The only perfectly valid exception to this rule, is when you're writing a swap function.

5. int i is perfectly valid in a small loop

I've met programmers who would crucify me for saying this, but when your loop is half a dozen lines of code long or less, int i is perfectly valid as a loop counter. It's so widely used, it's almost expected.

Quoted.

Saturday, July 5, 2008

JavaScript Code In Address Bar!

Go to Google.com choose Images and type Flowers, press search images button then copy and past this code in your browser Address Bar then press enter and Enjoy!

javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.getElementsByTagName("img"); DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px"; DIS.top=(Math.cos(R*y1+i*y2+y3)*y4+y5)+"px"}R++}setInterval('A()',5); void(0);

Note:
You can do this with any page has photos in it.

Thursday, July 3, 2008

Kill Database Connections

In some cases you want to delete or detach database in order to move it to another place.
But you can't do it if there are connections open with this database so you can use this procedure to kill all the connections with the database.
CREATE PROCEDURE [dbo].[killDataBaseConnections] @DatabaseName VARCHAR(50), @WithMessage BIT=1 
AS 
BEGIN
SET NOCOUNT ON
    DECLARE @spidstr VARCHAR(8000)
    DECLARE @ConnectionKilled SMALLINT 
    SET @ConnectionKilled=0 
    SET @spidstr = '' 
    
    IF DB_ID(@DatabaseName) < 4 
    BEGIN 
        PRINT 'No can do...'
        RETURN
    END 
    
    SELECT @spidstr = COALESCE(@spidstr,',' ) + 'KILL ' + CONVERT(VARCHAR, spid) + '; ' 
    FROM [master]..sysprocesses
    WHERE dbid = DB_ID(@DatabaseName) IF LEN(@spidstr) > 0
     
    BEGIN 
        EXEC(@spidstr) SELECT @ConnectionKilled = COUNT(1) FROM [master]..sysprocesses
        WHERE DBID = DB_ID(@DatabaseName)
    END
    
    IF @WithMessage = 1 
    
    PRINT CONVERT(VARCHAR(10), @ConnectionKilled) + ' Connection(s) killed for DB ' + @DatabaseName
END
Note: Don't do this if the database on a production server.

Source: https://www.nilebits.com/blog/2007/05/kill-database-connections-in-sql-server/

Tuesday, July 1, 2008

Fourteen ways to be a Creative Programmer

1. Learn a new language

Programmers are constantly learning new languages, either for fun or necessity. Don’t limit yourself to what just what you know and are comfortable with. Branch out and learn a new skill.

2. Start from the ground up

If you’re going to write software, you can’t just start halfway through the project. You have to start at square one. Sometimes this is the best way to find a creative solution for a problem is to go back to the beginning and work forward.

3. Question everything

Questioning everything means taking every assumption and making sure it’s correct. All programming starts with making the most basic assumptions, and then building on those basic assumptions. If something is wrong with the code at the base, then the software isn’t going to work well at all.
Sometimes creativity is limited by assumptions. New solutions arrive when we tear down assumptions and start with fresh perspectives.

4. Do it for fun

If you know any programmers, they’re constantly building something. Even when they’re done for the day on work-related projects, they’ll spend hours of time working on fun projects for themselves. Their work is also their hobby.

Continually mulling over new ideas and solutions is something that shouldn’t be a chore. It should be something that you find yourself doing constantly, like a reflex. And it should excite you.

5. Never stop testing ideas

Programmers are constantly benchmarking code to make sure that it’s as efficient as possible. Even the smallest change can bring a program or Web site to it’s knees, so constant testing and improvement is important to any bit of software.

Ideas should be tested rigorously and refined on a consistent basis. Your ideas will change over time, it just depends how much. Constantly evaluating them and just plain thinking them through is a great way to “benchmark” your idea.

6. Find a passion

If you’ve ever spent more than two minutes talking with a programmer about his work, you’ll find out very quickly that programmers have a passion for what they do. They eat, sleep and breathe programming.
Do you have a passion for your ideas and projects?

7. Master your tools

Programmers constantly improve their knowledge and usage of their tools. A great coder keeps tabs on software and is constantly finding ways to improve his usage of them. You’ll seldom find a programmer who doesn’t tweak his toolbox regularly.

No matter what your skill set, you’re limited to your skill with the tools you use to create. The more of an expert you are with your tools, the more you’ll be able to create.

8. Start making abstract associations

What if you used computers as telephones?
What would happen if you used a web site as a Word processor?
Would people care about what other people are doing right now?
The people behind projects like Skype, Google Docs and Twitter all have one thing in common: They fused seemingly abstract concepts together. Taking what-ifs and testing them is a great way to start thinking of things in a different, more creative light.

9. Think of structure as a tool, not a limitation

People associate creativity with taking a giant, blank canvas and letting our ideas flow without any sort of limiting structures. However, there’s a huge problem with this type of thinking: It’s a great big creativity myth.
See, limitations are everywhere.

We can’t avoid them, we can only hope to work with them. A programmer embraces the limitations of his programming language or tools and works around them. These limitations help him as they make a foundation to work from. Sometimes discovering a new workaround will lead to an even bigger idea. Necessity is the mother of invention.

10. Don’t rule anything out until you try it

Your kindergarten teacher was right: There is no such thing as a stupid question. If you’re adhering to #3 and dismissing all assumptions, you can’t be certain it’s not going to work until you’ve tested it. How do you know it won’t work unless you try it? You might be surprised. Even if the proposed solution doesn’t work, it may help you find a solution.

Sometimes it’s just best to start with a prototype and try it out. If your prototype doesn’t work, then trash it. If it does, you’ll have stumbled upon something that just might work.

11. Always look for a simpler and more elegant solution

A good programmer is one that understands that finding the simplest solution is always going to be better. Complicated solutions lead to… complications. A practical approach to programming always works best in the long run.

Our ideas sometimes become too complicated. We get caught up in the novelty of the idea that we ignore how practical it really is. The simplest way to solve a problem is often the best way to solve a problem.

12. Don’t be afraid to build off the code of others

The beauty of the Internet is that the solution your looking for has probably already been done by someone else. When building a new site I almost always use pre-existing open source code. Why recreate the wheel?
Putting a great idea into motion doesn’t mean you have to start from scratch to create it. Use existing ideas and turn them in to something better.

Sometimes a great idea is only modifying something that’s already been done. Gmail is a great example. They “reinvented” email by adding useful features to traditional email.

13. Don’t be afraid to collaborate

Some of the best coding — or any creative projects for that matter — are done not just by one coder but by many excellent people inspired to work toward the same goal. Assemble a great team, use the most brilliant ideas no matter who they come from, and let everyone contribute.

14. From the very basic, create the beautiful.

Programmers often use some very basic code over and over, and while those small bits of programming language aren’t necessarily beautiful in and of themselves, they can come together to create a final product that is amazing. No matter what creative project you’re working on, pay attention to the details, but most especially pay attention to the effect those details have on the overall picture.

Quoted.

Monday, May 19, 2008

How to Generate Barcode in ASP.NET

I will show you how to generate bar code images using .NET Built-in classes.
You will not need a Third Party tool or external DLL library.
As we all know that Barcodes depends on Fonts, there are plenty of them used for Barcodes.
The most famous font for Barcode is "Code 39" and anyone can download it for free.
After you download the font and install it to Windows Fonts, use the following method to generate Barcode images:
public void GenerateBarcodes(string productCode, string productName, string productPrice)
{
    Font stringFornt = new Font("Arial", 15, FontStyle.Bold, GraphicsUnit.Point);
    Font barcodeFont = new Font("Free 3 of 9", 40, FontStyle.Regular, GraphicsUnit.Point);
    Bitmap barcodeImage = new Bitmap(140, 110);
    Graphics graph = Graphics.FromImage(barcodeImage);

    graph = Graphics.FromImage(barcodeImage);
    graph.Clear(Color.White);
    graph.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
    graph.DrawString(productName, stringFornt, new SolidBrush(Color.Black), 10, 0);
    graph.DrawString(productCode, barcodeFont, new SolidBrush(Color.Black), 0, 30);
    graph.DrawString(productCode, stringFornt, new SolidBrush(Color.Black), 10, 70);
    graph.DrawString("#CODE#" + productPrice, stringFornt, new SolidBrush(Color.Black), 10, 90);
    graph.Flush();

    barcodeImage.Save(Server.MapPath("~/BarcodeImages/barcode.jpg"), ImageFormat.Jpeg);

    barcodeImage.Dispose();
    graph.Dispose();
    barcodeFont.Dispose();
}

Source: https://www.nilebits.com/blog/2007/06/generate-barcode-using-csharp/

Tuesday, April 15, 2008

How to Clear GridView Quickly

If you need to completely clear a GridView quickly, write the following code:
protected void ClearGrid(GridView gv)
{
    gv.DataSource = null;
    gv.DataSourceID = null;
    gv.DataBind();
}

Saturday, March 1, 2008

How to Disable Configuration Inheritance in ASP.NET Child Applications

Configuration inheritance is a very good feature of ASP.NET. It allows you to set configuration settings in the Web.Config file of a parent application and have it automatically be applied to all of its child applications.

But sometimes you do not want the child applications to inherit the Configuration from its parent application. In order to solve this issue you use the following code:
<location inheritinchildapplications="false" path=".">
  <system.web>
    <!--System.web Configurations goes here -->
  </system.web>   
</location>
The above code would prevent the child application from inherit the configuration from the parent application.
Source: https://www.nilebits.com/blog/2007/04/disable-configuration-inheritance-in-asp-dot-net/

Sunday, February 3, 2008

How to Convert String to Image in C#

I had worked on a project that required a conversion from string the user would enter to an image, this can be used as easy Captcha too. Here is a method of how to Convert String to Image:
public static void DrawText(Color foreColor, Color backColor, string fontName, int fontSize, string txt, int height, int width, string imagePath)
{
    Bitmap img = new Bitmap(height, width);
    Graphics Gimg = Graphics.FromImage(img);
    Font imgFont = new Font(fontName, fontSize);
    PointF imgPoint = new PointF(5, 5);
    SolidBrush bForeColor = new SolidBrush(foreColor);
    SolidBrush bBackColor = new SolidBrush(backColor);

    Gimg.FillRectangle(bBackColor, 0, 0, width, height);
    Gimg.DrawString(txt, imgFont, bForeColor, imgPoint);
    img.Save(imagePath, ImageFormat.Jpeg);
}

Source: https://www.nilebits.com/blog/2007/02/write-text-to-an-image-using-csharp/

Friday, February 1, 2008

How to Get XPath to an XML Node

There are a lot of XSL templates out there that get a human readable path to a node. But none that cover the case when there are more than one node of the same element at the same level.

In order to solve this problem you can use the following code:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes">
    <xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:tagibute name="position">
          <xsl:call-template name="xpath.position">
            <xsl:apply-templates select="@*|node()"></xsl:apply-templates>
          </xsl:call-template>
        </xsl:tagibute>
      </xsl:copy>
    </xsl:template>

    <xsl:template name="xpath.position">
     <xsl:param name="node" select="."></xsl:param>
     <xsl:param name="path" select="''"></xsl:param>
     <xsl:variable name="next.path">
      <xsl:text>*[position()=</xsl:text>
      <xsl:value-of select="$node/count(preceding-sibling::*)+1">
       <xsl:text>]</xsl:text>
       <xsl:if test="$path != ''">/</xsl:if>
       <xsl:value-of select="$path"></xsl:value-of>
      </xsl:value-of>
     </xsl:variable>

   <xsl:choose>
    <xsl:when test="$node/parent::*">
      <xsl:call-template name="xpath.position">
        <xsl:with-param name="node" select="$node/parent::*"></xsl:with-param>
          <xsl:with-param name="path" select="$next.path"></xsl:with-param>
      </xsl:call-template>
    </xsl:when>
 
    <xsl:otherwise>
      <xsl:text>/</xsl:text>
        <xsl:value-of select="$next.path"></xsl:value-of>
      </xsl:otherwise>
    </xsl:choose>
   </xsl:template>
  </xsl:output>
</xsl:stylesheet>

Source: https://www.nilebits.com/blog/2007/03/get-xpath-of-an-xml-node/

Tuesday, January 1, 2008

Welcome to my Blog

Hello everyone,

I hope you find my blog interesting and useful for you. I will be adding a very good articles about everything related to Software Industry, New Technologies, Source Code, Fresh Ideas, Solutions to the Common Problems, and More...

You are welcome to send me any questions to amr.saafan@hotmail.com

Don't forget to leave comments for every article, your feedback is very important to me.
Please visit my Blog Frequently to be able to see new articles.