Blog

My blog serves as a way for me to post solutions to problems I solve at work or during the long hours of freelance work.


ASP.NET vNext

by Ezekiel 4. July 2014 12:50

 

http://www.hanselman.com/blog/IntroducingASPNETVNext.aspx

ASP.NET vNext will take things to the next level. Today, you run ASP.NET using the same CLR that desktop apps use. We’re adding a cloud-optimized (my cloud, your cloud, their cloud - server stuff) version optimized for server scenarios like low-memory and high-throughput.

ASP.NET vNext will let you deploy your own version of the .NET Framework on an app-by-app-basis. One app with new libraries can’t break an app next door with a different version. Different apps can even have their own cloud-optimized CLR of their own version. The CLR and cloud-optimized libraries are NuGet packages!

I can run ASP.NET vNext apps within Visual Studio, of course, and within IIS, but I can also easily "self-host" them from the command line or within my own application. This alpha includes command line tools for running and managing ASP.NET vNext apps.

One of the great aspects of environments like node or rails is that they are "no compile." Just change some code and hit refresh. With the next version of ASP.NET you get the power and throughput of the .NET runtime plus the "Roslyn" compiler-as-a-service for a "no-compile compile." That means means during development time you can just change your C# classes and hit Refresh in the browser. It's the power of .NET with the dynamism of a refresh-and-go development experience.

You’ll be able to put ASP.NET vNext on your existing servers, any hoster, and Azure of course.

You can opt in or out of the cloud optimized framework for compatibility. The next version of ASP.NET is modular and all about choice. your choice of framework, your choice of runtime, your choice of operating system, your choice of text editor.

ASP.NET VNEXT IS:

Cloud and server-optimized
ASP.NET MVC and Web API have been unified into a single programming model
No-compile developer experience
Dependency injection out of the box
Side by side - deploy the runtime and framework with your application
NuGet everything - even the runtime itself
All Open Source via the .NET Foundation and takes contributions
Oh, and by the way

ASP.NET vNext (and Rosyln) runs on Mono, on both Mac and Linux today. While Mono isn't a project from Microsoft, we'll collaborate with the Mono team, plus Mono will be added to our test matrix. It's our aspiration that it "just work."

Tags: ,

asp.net vnext

Maximum request length exceeded.

by Ezekiel 10. June 2012 16:27

 

I was getting this error message when uploading more then two image files.

 

Add this to your web.confg -

<httpRuntime requestValidationMode="2.0" maxRequestLength="20192" />

 

 

Tags: , ,

.NET 4.0 | ASP.NET | MVC

File Upload Error Cannot Access a Closed File .NET 2.0

by Ezekiel 4. April 2012 05:07

 

To fix this I changed the httpRuntime node in the web.config

Changed From - 

<httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="8192" />

 

Changed To -

<httpRuntime executionTimeout="90" maxRequestLength="20000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>

 

Works perfectly now!!!

Tags: , ,

ASP.NET | C#

DotNetNuke Object Reference not Set to an Instance of an Object

by Ezekiel 16. February 2012 03:30

 

We had to moved an application which was developed about 10 years ago in .NET 1.1 and DotNetNuke. I'm not sure what version of DotNetNuke. We had to upgrade the .NET Framework to use 2.0. The app ran fine on the old servers, but on the new servers the app was erroring every time the user hit the database. I spent about 3 days trying to figure out what is wrong with this dumb thing. Well, turns out it was a very simple fix.

 

I added the following to the web.config and BOOM it works!

 <system.web>
  <pages validateRequest="false" enableEventValidation="false" enableViewStateMac="true" />
 </system.web>

adding enableEventValidation="false" to the pages node did the trick.

 

 

 

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

  <%@ Page Language="C#" Debug="true" %>

or:

2) Add the following section to the configuration file of your application:

<configuration>
   <system.web>
       <compilation debug="true"/>
   </system.web>
</configuration>

 

 

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario. 

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
   System.Web.Util.StringUtil.GetStringHashCode(String s) +32
   System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() +288
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +59
   System.Web.UI.WebControls.RadioButtonList.LoadPostData(String postDataKey, NameValueCollection postCollection) +293
   System.Web.UI.WebControls.RadioButtonList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +13
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +373
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2054

[PageLoadException: Object reference not set to an instance of an object.]
   DotNetNuke.Exceptions.ProcessPageLoadException(Exception exc, String URL) in C:\Projects\DOTNetNuke\components\Exceptions\Exceptions.vb:181
   DotNetNuke.BasePage.Page_Error(Object Source, EventArgs e) in C:\Projects\DOTNetNuke\components\BasePage.vb:41
   System.Web.UI.TemplateControl.OnError(EventArgs e) +107
   System.Web.UI.Page.HandleError(Exception e) +84
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6219
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +369
   System.Web.UI.Page.ProcessRequest() +200
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +23
   System.Web.UI.Page.ProcessRequest(HttpContext context) +201
   ASP.default_aspx.ProcessRequest(HttpContext context) +5
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +406
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +76

 

 

 

 

Tags: , ,

ASP.NET | C# | DotNetNuke

C# How to Test a Website is Working or not With HttpWebRequest HttpWebResponse

by Ezekiel 24. January 2012 03:38

 

public static bool WebSiteIsAvailable(string Url)
{
  string Message = string.Empty;
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
 
  // Set the credentials to the current user account
  request.Credentials = System.Net.CredentialCache.DefaultCredentials;
  request.Method = "GET";
 
  try
  {
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
      // Do nothing; we're only testing to see if we can get the response
    }
  }
  catch (WebException ex)
  {
    Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
  }
 
  return (Message.Length == 0);
}

Tags: , ,

C#

C# How to Cache Data Using Generic Method

by Ezekiel 9. December 2011 03:31

 

using System;
using System.Web;
using System.Web.Caching;
using System.Collections.Generic;
using System.Linq;
using RoboticsDataCapture.Model;

namespace MyNameSpace
{
    /// <summary>
    /// Cache wrapper to handle caching data
    /// </summary>
    public static class CacheWrapper
    {
        /// <summary>
        /// Generic cache method
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="expiration">When cache expires</param>
        /// <param name="fetcher">Generic method to search cache</param>
        /// <returns></returns>
        public static T CacheFetch<T>(string key, DateTime expiration, Func<T> fetcher) where T : class
        {
            Cache DataCache = HttpContext.Current.Cache;

            // Cache if the key is not null or blank
            if ((key ?? "").Length <= 0)
            {
                return fetcher();
            }

            T result = DataCache[key] as T;

            if (result == null)
            {
                result = fetcher();

                if (result == null)
                {
                    DataCache.Remove(key);
                }
                else
                {
                    DataCache.Add(key, result, null, expiration,
                        Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null);
                }
            }

            return result;
        }
    }

    /// <summary>
    /// Class using generic caching of entityframe database calls
    /// </summary>
    public class MyClass
    {
        public int Id { get; set; }
        public string Name { get; set; }

        // Set cache expiration
        private static DateTime expiration = DateTime.Now.AddHours(24);

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static List<MyClass> GenericList()
        {
            return CacheWrapper.CacheFetch<List<MyClass>>("CachedDataName", expiration, () =>
            {
                using (Entities entities = new Entities())
                {
                    var databaseReturn = from t in entities.Table
                                         select new MyClass
                                          {
                                              Id = t.Id,
                                              Name = t.Name
                                          };

                    return databaseReturn.ToList();
                }
            });
        }
    }
}

Tags: , , , ,

ASP.NET | C# | Generics | Cache | LINQ to EntityFrame

C# ASP.NET How Make All Controls Readonly on Web Form

by Ezekiel 21. November 2011 05:00

 

         private void MakeReadOnly(Control c)
        {
            foreach (Control childControl in c.Controls)
            {
                if (childControl.GetType() == typeof(TextBox))
                {
                    ((TextBox)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(CheckBox))
                {
                    ((CheckBox)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(DropDownList))
                {
                    ((DropDownList)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(Button))
                {
                    ((Button)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(RadioButtonList))
                {
                    ((RadioButtonList)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(ImageButton))
                {
                    ((ImageButton)childControl).Enabled = false;
                }
                if (childControl.Controls.Count > 0)
                {
                    MakeReadOnly(childControl);
                }
            }
        }

 

How to call -

MakeReadOnly((Control)this); 

Tags: , ,

ASP.NET | C#

ASP.NET 4.0 Web.config Transform

by Ezekiel 16. November 2011 02:18

 

If you are converting an old app which uses the old style of web.config. For example, having multiple config files named dev, qa, live etc. and you want to use the new transform build features.

You have go to the properties of the web.config, Build Action: Content. Otherwise, publishing will publish all the .config files. 

 

Tags: ,

.NET 4.0 | ASP.NET

Could not load file or assembly CrystalDecisions.Web Version=10.5.3700.0 or one of its dependencies. The system cannot find the file specified.

by Ezekiel 8. November 2011 07:20

 

Visual Studio 2008 has to be install. Then run this on your server.

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\CrystalReports10_5\CRRedist2008_x86.msi

 

Tags: ,

Crystal Reports

ASP.NET Routing to Default Page

by Ezekiel 25. October 2011 04:53

 

I was stunk on this problem for a while. I tried adding a route to the default page in route table in the global.asax. That didn't work. The solution is so simply

 

<asp:HyperLink ID="HomeLink" NavigateUrl="~/" runat="server">« Back to Home</asp:HyperLink> 

Tags: , , ,

ASP.NET

ASP.NET UpdatePanel Leaving Extra Spaces When Hidden

by Ezekiel 25. October 2011 03:14

 

I had a dropdownlist which when an certain option is selected it would trigger the updatepanel to show it's contents. The problem is when the user selected another option the panel is hidden, but it would leave extra spaces.


Solution:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" RenderMode="Inline">


Add RenderMode="Inline" should do the trick!

Tags: , , ,

ASP.NET | UpdatePanel

Block IPs from Website

by Ezekiel 19. June 2011 16:43

 

Master Page_Load function -

 

        protected void Page_Load(object sender, EventArgs e)
        {
            // Check for blocked IPs
            string userIP = HttpContext.Current.Request.UserHostAddress;
            string blockedIPs = ConfigurationManager.AppSettings["blockedIPs"];
            string[] ips = null;

            if (blockedIPs != null)
            {
                ips = blockedIPs.Split(',');
            }

            foreach (string ip in ips)
            {
                if (userIP == ip)
                {
                    HttpContext.Current.Response.StatusCode = 403;
                    HttpContext.Current.Response.End();
                    break;
                }
            }
        }

 

Web.config -

 

  <appSettings>
    <add key="blockedIPs" value="127.0.0.1" />
  </appSettings>

Tags: , ,

ASP.NET | C#

Add Tooltip To Checkbox List Using C#

by Ezekiel 21. February 2011 04:02

 

        <asp:CheckBoxList ID="CheckboxList" runat="server">
           <asp:ListItem Text="Option1&nbsp;<img src='App_Themes/Main/Images/information.png' alt='' />" Value="option1"></asp:ListItem>
           <asp:ListItem Text="Option2&nbsp;<img src='App_Themes/Main/Images/information.png' alt='' />" Value="option2"></asp:ListItem>
           <asp:ListItem Text="Option3&nbsp;<img src='App_Themes/Main/Images/information.png' alt='' />" Value="option3"></asp:ListItem>
        </asp:CheckBoxList>

 

        protected void Page_Load(object sender, EventArgs e)
        {
            // Set tool tips
            SetCheckBoxListToolTips();
        }


        /// <summary>
        /// Sets meds checkboxlist tool tips
        /// </summary>
        private void SetCheckBoxListToolTips()
        {
            Medications.Items[0].Attributes.Add("title", "Tooltip message here");
            Medications.Items[1].Attributes.Add("title", "Tooltip message here");
            Medications.Items[2].Attributes.Add("title", "Tooltip message here");
 }

Tags: , ,

ASP.NET | C#

Sorting Functionality in GridView

by Ezekiel 3. January 2011 10:25

 

        protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            Users.BindGridViewData(this, sort);
        }


        private string GetSortDirection(string column)
        {
            string sortDirection = "DESC";
            string sortExpression = ViewState["SortExpression"] as string;
           
            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                   
                    if ((lastDirection != null) && (lastDirection == "DESC"))
                    {
                        sortDirection = "ASC";
                    }
                }
            }
           
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

Tags: , ,

ASP.NET | C# | GridView

Change Control Background Color When Validator Fails

by Ezekiel 30. December 2010 05:43

 

Javascript -

function fnOnUpdateValidators()
{
   for (var i = 0; i < Page_Validators.length; i++)
   {
      var val = Page_Validators[i];
      var ctrl = document.getElementById(val.controltovalidate);
      if (ctrl != null && ctrl.style != null)
      {
         if (!val.isvalid)
            ctrl.style.background = '#FFAAAA';
         else
            ctrl.style.backgroundColor = '';
      }
   }
}

 

Put this in C# Page_Load method  -

Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");

 

Tags: , , ,

ASP.NET | C# | Javascript

ASP.NET Email Regular Expression Validator

by Ezekiel 10. December 2010 07:54

 

                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1"                            
                            ControlToValidate="ControlName"
                            Text="*"
                            Display="Dynamic" CssClass="redTextBlod" SetFocusOnError="true"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            runat="server"></asp:RegularExpressionValidator>

Tags: ,

ASP.NET

ASP.NET 4.0 SEO URL Routing

by Ezekiel 8. December 2010 06:44

 

Add this to your Global.asax.cs file -

 

        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        void RegisterRoutes(RouteCollection routes)

        {
            // Ignore request for resource files
            routes.Ignore("{resource}.axd/{*pathInfo}");

            // Register a route for forms/{formName}
            routes.MapPageRoute(
               "SignOnRequest",
               "forms/{formName}",
               "~/SignOnRequest.aspx"
            );
        }

 

 

There's many different ways to reference this route in your code -

 

Page.GetRouteUrl("SignOnRequest", new { formName = "signonrequest" });

http://www.yourdomain.com/forms/signonrequest

 

Tags: , , ,

.NET 4.0 | ASP.NET | C#

Radio Buttons not Showing in IE

by Ezekiel 24. November 2010 06:51

 

I was using this CSS class and my radio buttons wouldn't show in IE only.  Worked fine in Firefox.

table.data input
{
    margin: 0;
    color: #781351;
    background: #fffff;
    border-left: 1px solid #bdd3a5;
    border-right: 1px solid #bdd3a5;
    border-top: 0 none;
    border-bottom: 0 none;
    height: 100%;
}

 

You need to give height a value other then a percent.  Modified version.

table.data input
{
    margin: 0;
    color: #781351;
    background: #fffff;
    border-left: 1px solid #bdd3a5;
    border-right: 1px solid #bdd3a5;
    border-top: 0 none;
    border-bottom: 0 none;
    height: 20px;
}

Tags: , ,

ASP.NET | CSS

ValidateRequest="false" Doesn't Work in ASP.NET 4.0

by Ezekiel 19. November 2010 11:09

 

I just upgraded my site from 3.5 to 4.0.  Ran into a problem with adding entries to my blog.  When saving new posts with HTML the app was blowing up.  Here is the solution.

 

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime requestValidationMode="2.0" />
</system.web>

Tags: , ,

ASP.NET | .NET 4.0

Breadcrumb Using LINQ to SQL, Generic Class and Recursive CTE

by Ezekiel 12. November 2010 16:23
[No text]

Tags: , , , ,

ASP.NET | C# | LINQ to SQL | SQL

Disable Submit Button When the Submit Button is Clicked

by Ezekiel 12. October 2010 07:14

 

    <script type="text/javascript"><!--
    function doSubmit(btnSubmit) {
        if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
            return false;
        }   
        btnSubmit.disabled = 'disabled';
        btnSubmit.value = 'Processing. Please wait...';
        <%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>;   
    }
    //-->
    </script>

 

   <asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" CssClass="submit1" runat="server" />

 

Tags: ,

ASP.NET | Javascript

How to Get Website URL With Inline ASP.NET

by Ezekiel 15. January 2010 06:17

 

Use this to get the websites URL only.

<%= Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, String.Empty) %>

 

Return -

URL: http://www.ezekielonline.com/Portfolio.aspx

Gets Only: http://www.ezekielonline.com

 

How to use -

<a rel="#voverlay" href="videos/engine/swf/player.swf?url=<%= Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, String.Empty) %>/videos/videos.flv">

    <img src="images/video.jpg" width="369" height="278" align="left" alt="" />

</a>

 

So this will get the URL only.  You can use through out the development process. dev, stage, live.

Tags: , ,

ASP.NET

Populate an ASP.NET DropDownList Control

by Ezekiel 4. November 2009 10:11

 

HTML -

<asp:DropDownList ID="ddlStatus" runat="server">
</asp:DropDownList>

 

C# -

// Clear all items in drop down
ddl.Items.Clear();

// Populate the status filter
ddl.DataTextField = "dataFieldToShowToPublic";
ddl.DataValueField = "dataFieldToPassToMethod";

// Call to your data layer
ddl.DataSource = sqlObject.GetDropDownData();
ddl.DataBind();
           
// Blank item at the top of the list
ddl.Items.Insert(0, new ListItem("--", ""));

 

Data Layer Method -

public DataTable GetDropDownData()
{
    SqlConnection conn = GetConnection();
    SqlCommand cmd = conn.CreateCommand();
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);

    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM TableName ORDER BY dataField";
    da.Fill(ds);

    conn.Close();
    return ds.Tables[0];
}

 

 

Tags: , , ,

ASP.NET | C# | SQL

ImageButton OnClick Event Fires When Enter is Clicked

by Ezekiel 23. October 2009 08:09

 

I have this pagination control.  The problem was when the user entered a page number in the textbox it would fire the OnClick event of the first ImageButton.  This would only happen in FireFox.  Worked fine in IE.  To prevent this from happening I dropped an asp:button on the form in a panel.  Set the style visibility to hidden so the button wouldn't show and set the DefaultButton panel property to the hidden button.  Works great!


<asp:Panel ID="pnlPaginationCtrl" DefaultButton="btnPageNum" runat="server" Visible="true" CssClass="m_prevnext">
    <table>
        <tr>
            <td>
                <asp:ImageButton ID="imgBtnFirstPage" runat="server" AlternateText="|&lt;"
                    onclick="imgBtnFirstPage_Click" ImageUrl="~/Images/reporting/Beginning20x20.png" CausesValidation="false" />
                   
                <asp:ImageButton ID="imgBtnPrevPage" runat="server" AlternateText="&lt;&lt;" CausesValidation="false"
                    onclick="imgBtnPrevPage_Click" ImageUrl="~/Images/reporting/Back20x20.png" />
            </td>
            <td>      
                <asp:TextBox ID="tbPage" runat="server" AutoPostBack="True"
                    OnTextChanged="tbPage_TextChanged" Width="30px" CssClass="tbpadding"></asp:TextBox>
                   
                <asp:Button ID="btnPageNum" runat="server" style="visibility:hidden;display:none;" />
                   
                <asp:RangeValidator ID="rvPage" runat="server" ControlToValidate="tbPage" ErrorMessage="page is to big" MinimumValue="1" MaximumValue="25" Type="Integer" Display="None"></asp:RangeValidator>
                   
                <cc1:FilteredTextBoxExtender ID="tbPage_FilteredTextBoxExtender"
                    runat="server" Enabled="True" FilterType="Numbers" TargetControlID="tbPage" />

                <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="rvPage" />
               
                of&nbsp;<asp:Label ID="lblNumOfPages" runat="server" Text="##"></asp:Label>
            </td>
            <td>        
                <asp:ImageButton ID="imgBtnNextPage" runat="server" CausesValidation="false"
                    onclick="imgBtnnextPage_Click" AlternateText="&gt;&gt;"
                    ImageUrl="~/Images/reporting/next.png" />
                   
                <asp:ImageButton ID="imgBtnLastPage" runat="server" CausesValidation="false"
                    AlternateText="&gt;|" ImageUrl="~/Images/reporting/end.png"
                    onclick="imgBtnLastPage_Click" />
            </td>
        </tr>
    </table>    
</asp:Panel>

Tags:

ASP.NET

Credit Card Processing

by Ezekiel 19. October 2009 09:47

 

Populate Credit Card Year Expiration -

ddlExpYear.Items.Clear();

for (int i = DateTime.Now.Year; i <= DateTime.Now.Year + 11; i++)
 ddlExpYear.Items.Add(new ListItem(i.ToString(), i.ToString()));

// Blank item
ddlExpYear.Items.Insert(0, new ListItem("--", ""));

 

ASP.NET Credit Card Number Validator -

<asp:RegularExpressionValidator ID="revCardNumber" ControlToValidate="cardNumber" ValidationExpression="^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$" ErrorMessage="Please enter a valid credit card number." Display="Dynamic" cssClass="error" runat="server" SetFocusOnError="True"></asp:RegularExpressionValidator>

Tags: , ,

C#

RecentPosts