Skip to main content


Showing posts from September, 2012

ASP.Net: Validate the accepted file type of a file upload using RegularExpressionValidator

While working with file upload control, it is common requirement that user should upload only flie type that suits requirement. For example there is option of uploading resume in your application, resume is normally word or Pdf document, now suppose there is no validation of required file types and user uploaded image file or excel file instead of document, so here come loophole in your application.

We can validate required file type either using JavaScript or we can use RegularExpression Validator to validate file.

Here I am writing example for RegularExpressionValidator:  <asp:FileUploadID="fileUpload"runat="server"/>
<asp:RegularExpressionValidatorID="regFileType"runat="server" ControlToValidate=" fileUpload"Text="*Only accepted file formats are pdf, doc and docx"ValidationExpression="^.+(.pdf|.PDF|.doc|.DOC|.docx|.DOCX)$"ValidationGroup="vg"ForeColor="Red"> </asp:RegularExpressionVa…

Populate selected items of CheckBoxList/ListBox from comma separated string in C#

In my last postI have described how you can get a comma separated string of selected value of a CheckBoxList or Listbox. In this example I am writing a method which will take string of values (comma separated) and CheckBoxList/ListBox as parameter and populate provided control.
In few examples I have found that user have iterated over two loops to populate selected items, but here I am iterating over only Control’s item and then make use of LINQ over splitted string instead of iterating over it. So here comes power of LINQ over normal iterating code and this is more efficient way of doing this as we needn’t to run loop inside another loop and just one line of LINQ code served our purpose.
Note: Please includeSystem.Text andSystem.Web.UI.WebControls and System.Linq namespaces for this sample code.
So here we go:
//for Listbox:pass ListBox control. privatevoid PopulateSelectedItems(string selectedItems, CheckBoxList control) { if (!string.IsNullOrWhiteSpace(selectedItems))     { string[] i…

C#: Get all selected items of CheckBoxList or ListBox in comma separated string

If you want to store selected value of a CheckBoxList or Listbox in comma separated string, then you are on right place. Sometime it is requirement that we want a comma separated string of selected value of CheckBoxList or Listbox control (I.e. to save your Control’s selected value in one String field of DB). So here I am writing one small function which will take CheckBoxList or ListBox as parameter and return comma separated string of selected items.
Note: Please include System.Text and System.Web.UI.WebControls namespaces for this sample code.
//for Listbox:provide ListBox control.
publicstring GetSelectedItems(CheckBoxList control) { var items = newStringBuilder(); foreach (ListItem item in control.Items)     { if (item.Selected)             items.Append(string.Format("{0},", item.Value));     } //Remove last comma before returning back. return items.ToString().TrimEnd(','); }

Use this function as: var selectedValues = GetSelectedItems(control); //control is name…

C#: Extension method with Regular expression to check or validate if a string is a valid GUID

So here I am writing another extension method for String to validate if sting value is a valid Guid or not with the help of regular expression.
using System; using System.Text.RegularExpressions; publicstaticclassStringExtensions { publicstaticbool IsValidGuid(thisString inputValue)     { Regex isGuid = newRegex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled); bool isValid = false; if (!String.IsNullOrWhiteSpace(inputValue))         {             isValid = isGuid.IsMatch(inputValue);         } return isValid;     } }
And here is how you can use this:
String testString = "6FE4851B-27A9-4D18-A51D-36B262023F39"; if (testString.IsValidGuid()) {     Response.Write("String is a valid GUID"); } else {     Response.Write("String is not a valid GUID"); }

JavaScript confirm box to ask if user want to delete or perform any specific action.

There are sometime requirement that user should get a confirmation before performing an action, i.e. for example when click on Delete link, you want a confirmation from user whether he/she is really want to delete or they accidently clicked on delete link. So here I'm showing how you can show confirmation box.
<scripttype="text/javascript"> function confirmDelete(delUrl) { if (confirm("Are you sure you want to delete this record?")) { returntrue;         } returnfalse;     } </script>
And call this function as: <ahref="javascript:return confirmDelete();">Delete</a>
Another way We can write JavaScript confirm code inline as well:
<aonclick="javascript:return confirm('Are you sure you want to delete this record?');">Delete</a>

Encode and decode a String in C# with HtmlEncode and HtmlDecode methods

While working some time we need to encode or decode our string that contains HTML. Here is the example of encoding and decoding the html string:
using System; using System.Web; using System.Diagnostics; usingSystem.Web.UI;
publicpartialclassDefault : Page {         protectedvoid Page_Load(object sender, EventArgs e)         { String originalValue = "<h1>This is Test Header</h1>"; String encodedValue = HttpUtility.HtmlEncode(originalValue); String decodedValue = HttpUtility.HtmlDecode(encodedValue); Debug.WriteLine(originalValue); Debug.WriteLine(encodedValue); Debug.WriteLine(decodedValue);         } }
The output will be: <h1>This is Test Header</h1> &lt;h1&gt;This is Test Header&lt;/h1&gt; <h1>This is Test Header</h1>
If you are using .NET 4.0+ you can also use WebUtility.HtmlEncode  and  WebUtility.HtmlDecode which is available in the System.Net namespace.

Walk through to Entity Framework and Edmx file with working sample

One of my friends wanted to learn entity framework and requested me for a running sample of entity framework file.
Here I am writing an entity framework sample application to demonstrate the whole idea of entity and we can check how powerful it is while we walk through the sample. Before starting with application part, I have already one DB “Test_DB” which I will use in this sample application.
You can check I have three tables in the DB to check the relationship between tables let’s see the DB diagram for this DB.

Here you can check “tb_Section” and “tb_Class” are referenced in table “tb_Student”. (One thing you should make sure that table should be properly referenced if you wanted to make full and powerful use of Entity Framework).
So our DB is ready now let’s starting with our application. Open Visual Studio and add Blank Solution and name it as “TestApplication”. After that add new ASP.Net Application project to this solution and name it as “TA.Portal”. Visual Studio created the…

Const vs. readonly vs. static readonly comparison in C# .NET

Const in C# lets you define constant values.  In C#, you can declare a const of any type as long as the value assigned can be fully evaluated at compile time.  A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the  const keyword and must be initialized as they are declared. For example:

publicclass TestClass { publicconstdouble DaysInWeek = 7; publicconst string FullNameFormat = “Mr.” + “{0} {1}”; } Constant are Static by default, Constants are accessed as if they were static fields, and we can’t usestatic keyword withconst. Constant cannot be changed in the application anywhere else in the code as this will cause a compiler error.Constants must be a value type (byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration.String and a reference to null are the two types of reference values that can be determined at compile time.  So, any other reference type can be declared…