Checking if any text field empty is relatively easy because we can use RequiredFieldValidator control as I mentioned in this post. However, the same control (RequiredFieldValidator) cannot be used for  a list box. You need to work a little more to validate item count in a list box.

Background

We have two list box in our page (I use a Telerik control, RadListBox). We want to check if the list on the right side (listCountryDestination) empty or not after clicking “Submit” button.

<telerik:RadListBox RenderMode="Lightweight" runat="server" ID="listCountrySource" Height="200px" Width="225px" AllowTransfer="true" TransferToID="listCountryDestination" ButtonSettings-AreaWidth="30px" SelectionMode="Multiple">
<ButtonSettings TransferButtons="All"></ButtonSettings>
<Items>
<telerik:RadListBoxItem Text="Argentina"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Australia"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Brazil"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Canada"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Chile"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="China"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Egypt"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="England"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="France"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Germany"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="India"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Indonesia"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Kenya"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="Mexico"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="New Zealand"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="South Africa"></telerik:RadListBoxItem>
<telerik:RadListBoxItem Text="USA"></telerik:RadListBoxItem>
</Items>
</telerik:RadListBox>
<telerik:RadListBox RenderMode="Lightweight" runat="server" ID="listCountryDestination" Height="200px" Width="195px">
</telerik:RadListBox>

Solution

You can use a CustomValidator and a JavaScript function to validate your list box. Add this CustomValidator below your list box:

<asp:CustomValidator ID="CustomValidator1" runat="server" Display="Dynamic" ClientValidationFunction="ValidationCriteria" ErrorMessage="Select at least 1 country"></asp:CustomValidator>

Add the code block below into your page (preferably after </html> tag).

<script type="text/javascript">
    function ValidationCriteria(source, args) {
        var listbox = $find('listCountryDestination');
        var check = 0;
        var items = listbox.get_items();
        var cnt = items.get_count();
        if (cnt)
            args.IsValid = true;
        else
            args.IsValid = false;
    }
</script>

Your page will show a warning if the list box is empty as seen in the screenshot below.

untitled

Everybody knows and follows general work ethics such as being present at work, doing tasks assigned to you, attending meetings, etc. Apart from these typical office routines, there are some behaviors that are not discussed but should be avoided if you don’t want to distract colleagues.
Unspoken work ethics…

Don’t bite an apple at work

1

It’s not a joke! Every bite you take from your apple may be a very noisy distraction for your office mates. Keep it quiet. Eat as many apples as you want AT HOME. The same applies for peaches, pears, etc. If you really have to eat fruits, go for bananas or grapes, which can be eaten quietly. If you love apples so much that you can’t survive without them at work, try using a knife.

Lunch is more delicious at outside of the office

2

Get some fresh air during lunchtime .  It will dramatically increase your productivity. Many people bring lunch from home, which is a great habit for saving money and spending less time for lunch. However, you don’t have to eat it at your desk. Check if your company has spaces that are allocated for eating and relaxing. If it doesn’t, search within a few blocks from your work to find a food court or a park. Eating at the desk may be very annoying for your office mates, especially if you like smelly foods or if you keep your mouth open while eating.

Keep your distance from chewing gum

3

I know that it’s tempting. You may need it to fight with stress or to keep your teeth clean when you don’t have a chance to brush. It’s understandable, but make sure to take it out after a reasonable time. If you’re chewing for half of the day, your office mates may notice the systematic noise from your desk and it may distract them.

Your love can wait until five o’clock

4

We want to keep in touch with our loved ones, which is a beautiful thing. Call him/her whenever you get a chance but don’t forget that you are paid to work, not to have personal calls. If you have personal calls for hours at work, it may cause your office mates to question your workload and integrity. I had a colleague a while ago — he was a quiet guy while he was single, but once he got engaged, he started spending half of the day on the phone through his Bluetooth headset. It’s distracting.

Don’t sleep (and if you do, don’t snore)

6

Yes, I had colleagues sleeping at work regularly. It’s normal for people to fall asleep when they are very tired but if someone falls asleep every day, it raises a red flag about that person’s work ethics.

Limit using slang

7

Writing “rite” instead of “right” won’t save hours from your schedule. Instead, it will make your emails and IMs difficult to read. Besides, it’s not professional. It is useful and understandable to use some acronyms such as “FYI” and “COB”. However, there is no good reason to write “u” instead of “you” or “k” instead of “okay”.

Meeting is for meeting

8

Meetings are not for eating. Try not to bring any food to a meeting room. You may have a very tight schedule and you may not have time for your lunch, but please note that it’s not other participants’ concern. It is disrespectful to eat while your colleagues are talking or when they are expecting you to talk.

Know your desk’s borders

9

You can be super messy and unorganized in your desk space — it’s your work area. However, make sure that your stuff doesn’t fly or move to your colleagues’ desk. This includes your chair and bag.

Reply to the questions in emails

10

If someone sends an email with questions, make sure to reply to them. Leaving an email unanswered is neither kind nor ethical. You are getting paid to read and reply to your work emails, not to ignore them.

Please stop labeling your apps as “Available on Apple Store and Google Play”. Your apps should work on all platforms. Please spend some time to brush up your skills and move up to the next level, which is “develop once, run everywhere”.

1_k-eFZo9lOGweclzzWTRJKg

App should work on all platforms, not just on iPhone and Android!

You don’t have excuses anymore. All you need is HTML5/CSS3/JS, as you know. Besides, there are several mobile development platforms to make development easier for you. Give it a try. I know you are very busy with your full-time job and family. You may need to sacrifice your evenings and weekends for the learning curve, but believe me, it is worth it.

You probably think cross-platform apps won’t have all the capabilities that native apps do. Don’t worry about it. If your app is not firing a rocket to space, you will be okay.

You may be thinking that you already cover 95% of the mobile users by developing for iOS and Android only. Please note that the 5% you ignore is about 100 million users. They will thank you if you don’t ignore them. If you do, think about the advertisement revenue you will make from them. There is less competition and more demand in that 5%.

I’ve been using Microsoft’s and BlackBerry’s mobile operating systems for over 10 years. This means you have been ignoring me for over a decade. You probably don’t have any idea of how annoying it is to see those applications that you want to use only work on iOS and Android. It’s sometimes a banking application, sometimes a game, sometimes a dating trend. Most of the time, I don’t have any alternative to use, like the case of Snapchat and Angry Birds. Sometimes I have limited alternatives, such as 6tin for Tinder and 6tag for Instagram. Sometimes I try to use a mobile browser to get the job done, like I do with Bank of America and Chase. However, they are not full-featured on the browser. For example, you can’t deposit checks by taking photos of them on the mobile browser, while you can do it in the mobile application.

I had been using Lumia 1020 (Windows Phone 8.1) until last week. My carrier told me that I have a free upgrade to change my device. Guess what? I bought a Lumia 950 (Windows Phone 10)! I’m pretty happy with it. User-friendly interfaces, fast screen animations and page switches, amazing shots even in dark scenes, and fully synchronized OneDrive photos and documents are some of the cool things I like about this phone. I said that I’m “pretty” happy, not completely, because of the apps I don’t have…

I’m not working for Microsoft, nor am I getting paid for this post. I’m just telling how it is to use a smartphone that doesn’t run on Android or iOS.

PLEASE HELP people by making your application available on all platforms.

Ned

OneDrive or other cloud solutions sync your Camera Roll. That’s great but how about other folders such as WhatsApp photos or Saved Pictures? Connecting the USB cable and using Photos application to import photos may help but it wasn’t the case for me because of the partially broken USB port on my phone.

After spending sometime searching for an app, I found this one, File Manager, to transfer the folders I select to a cloud solution such as Box, Google Drive or DropBox (Please note that I’m not affiliated with the creator of this app). Trial version will probably do the job.

Folders are being transferred to Box.

Folders are being transferred to Box.

Thanks to built-in features of .NET Framework, it’s easier than ever to protect your applications against XSS attacks. I’m explaining simple steps to avoid this vulnerability.

What is XSS (Cross Site Scripting)?

From Wikipedia:

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users.

A simple example of an XSS attack is that entering “// ” into an input field. Depending on the script that will be executed, It may harm your application and data in several ways.

Solution

You should follow at least these 3 steps to protect your ASP.NET application against XSS attacks:

  1. Use ASP.NET Request Validation
    It’s in place starting from .NET Framework 4.5. Do not disable it unless you want your users to enter HTML codes (such as , ) on purpose.
  2. Use HtmlEncode method
    If you are not using ASP.NET TextBox control which automatically encodes data, you should explicitly use HtmlEncode. There are different ways to leverage this functionality:

    HttpUtility.HtmlEncode(Request.Form["name"])
    Server.HtmlEncode(Request.Form["name"])
    AntiXss.HtmlAttributeEncode(TextBox1.Text)
  3. Implement client-side and server-side input validation
    Push your users to enter valid data by using client-side and server-side validation techniques.

References:

Here is an easy way to check user inputs in ASP.NET: RegularExpressionValidator control. You can compare the input with the regular expression you provide and show users corresponding validation errors.

Validation Rules

In this example, my validation rules are below.

Field Allowed Characters Min Length Max Length
Name a-z, A-Z, period (.), apostrophe (‘) 2 50
Job Title a-z, A-Z, period (.), apostrophe (‘), ampersand (&), parenthesis (()), slashes (/\) 2 50
Organization a-z, A-Z, period (.), apostrophe (‘), ampersand (&), parenthesis (()), slashes (/\) 2 50
Department a-z, A-Z, period (.), apostrophe (‘), ampersand (&), parenthesis (()), slashes (/\) 2 50
Fax Number 0-9, period (.), space ( ), parenthesis (()), plus (+), hyphen (-), forward slash (/) 2 20
Email Address a-z, A-Z, 0-9, at-sign (@), period (.), hyphen (-), underscore (_) 8 50
Phone Number 0-9, period (.), space ( ), parenthesis (()), plus (+), hyphen (-), forward slash (/) 2 20
Organization’s website a-z, A-Z, 0-9, “http://”, “https://”, period (.), hyphen (-), underscore (_) 4 50

Validation Controls

ASP.NET code for input controls and validation controls are below. Please note that I used RequiredFieldValidator as well as RegularExpressionValidator.

<asp:ValidationSummary ID="smryUpdate" EnableClientScript="true" ShowSummary="true" ValidationGroup="smryUpdate" HeaderText="Please correct the following errors:" DisplayMode="BulletList" runat="server" >

<asp:TextBox runat="server" ID="txtName" MaxLength="100" Width="150px"></asp:TextBox>

<asp:RequiredFieldValidator ID="rqdName" SetFocusOnError="true" ValidationGroup="smryUpdate" Text="*" ErrorMessage="Name is required" ControlToValidate="txtName" runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorName" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^[a-zA-Z''-'\s.&amp;/\\()]{2,50}$" ControlToValidate="txtName" ErrorMessage="Invalid Name Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtJobTitle" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdTitle" ValidationGroup="smryUpdate" Text="*" ErrorMessage="Job Title is required" ControlToValidate="txtJobTitle" runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorJobTitle" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^[a-zA-Z''-'\s.&amp;/\\()]{2,50}$" ControlToValidate="txtJobTitle" ErrorMessage="Invalid Job Title Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtOrganization" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdOrganization" ValidationGroup="smryUpdate" Text="*" ErrorMessage="Organization is required" ControlToValidate="txtOrganization" runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorOrg" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^[a-zA-Z''-'\s.&amp;/\\()]{2,50}$" ControlToValidate="txtOrganization" ErrorMessage="Invalid Organization Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtDepartment" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdDepartment" ValidationGroup="smryUpdate" Text="*" ErrorMessage="Department is required" ControlToValidate="txtDepartment" runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorDept" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^[a-zA-Z''-'\s.&amp;/\\()]{2,50}$" ControlToValidate="txtDepartment" ErrorMessage="Invalid Department Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtFaxNo" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorFax" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^[0-9.()\-+/]{2,20}$" ControlToValidate="txtFaxNo" ErrorMessage="Invalid Fax Number Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtEmail" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdEmail" SetFocusOnError="true" Text="*" ValidationGroup="smryUpdate" ErrorMessage="Email is required" ControlToValidate="txtEmail" runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z0-9]+[\w-]+\.)+[a-zA-Z]{1}[a-zA-Z0-9-]{1,23})$" ControlToValidate="txtEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtPhone" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdPhone" ValidationGroup="smryUpdate" Text="*" ErrorMessage="Phone is required" ControlToValidate="txtPhone" runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorPhone" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^[0-9.()\-+/]{2,20}$" ControlToValidate="txtPhone" ErrorMessage="Invalid Phone Number Format"></asp:RegularExpressionValidator>

<asp:TextBox runat="server" ID="txtWebsite" MaxLength="50" Width="150px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorWebsite" runat="server" ValidationGroup="smryUpdate" ValidationExpression="^(https?:\/\/[a-zA-Z0-9\-_\.]{1,32}\.[a-zA-Z0-9\-_]{2,9}|[a-zA-Z0-9\-_.]{1,40}\.[a-zA-Z0-9\-_]{2,9})$" ControlToValidate="txtWebsite" ErrorMessage="Invalid Website Format"></asp:RegularExpressionValidator>

<Button runat="server" ID="btnSubmit" Text="Update" ValidationGroup="smryUpdate" Width="100px" OnClick="btnSubmit_Click" >

Useful Sources:

Note:

If validation doesn’t work on client-side, try adding these lines into web.config:

<configuration>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>
</configuration>

Session state best practices:

  • Reconfigure the default session id name in order to obfuscate the true meaning of the cookie value. In the case of ASP.NET, the default name is ASP.NET_SessionId. This immediately gives away that the application is ASP.NET and that that cookie contains the session id value.
  • Ensure the length of the session id is long enough to prevent brute force attacks. Recommended length is 128 bits.
  • Ensure the session id is created in a truly random way. This ensures that attackers can’t guess the session id due to some predictability analysis.
  • Ensure that the session id does not contain any additional sensitive data. Instead, the value should be nothing more than a random string of characters with no meaning other than the session id as a whole.
  • HTTPS should be employed for all session based applications handling sensitive data.
  • Session cookies should be created with the Secure and HttpOnly attributes set.
  • Prevent concurrent sessions where possible.
  • Destroy sessions upon timeout, logoff, browser close or log-in from a separate location.

Cookie best practices:

  • Do not store any critical information in cookies. For example, do not store a user’s password in a cookie, even temporarily. As a rule, do not keep anything in a cookie that, if spoofed, can compromise your application. Instead, keep a reference in the cookie to a location on the server where the information is.
  • Set expiration dates on cookies to the shortest practical time you can. Avoid permanent cookies if possible.
  • Consider encrypting information in cookies.
  • Consider setting the Secure and HttpOnly properties on the cookie to true.

.
Code examples

In order to implement best practices for cookies, add the code lines below into your application.

Web.config file:

<system.web>
   <sessionState regenerateExpiredSessionId="false" cookieless="UseCookies" cookieName="id" />
</system.web>

Code-behind file:

Response.Cookies.Add(new HttpCookie("id", ""));
Response.Cookies["id"].HttpOnly = true;
Response.Cookies["id"].Secure = Convert.ToBoolean(ConfigurationManager.AppSettings["SecureCookie"]);

References: