Thursday, August 26, 2010

Phone Validation

//class represent the Rules Violation

    #region
  
    public class RuleViolation
    {
        public string ErrorMessage
        {
            get;
            private set;
        }
        public string PropertyName
        {
            get;
            private set;
        }

        public RuleViolation(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }
        public RuleViolation(string errorMessage, string propertyName)
        {
            ErrorMessage = errorMessage;
            PropertyName = propertyName;
        }
    }

//-------------------------------------------------//
//class represent the phone validation

    #region
    public class PhoneValidator
    {
        static IDictionary countryRegx = new Dictionary()
        {
            {"IN",new Regex("^[0-9]+$")},
            {"USA",new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}$")},
            {"Netherlands",new Regex("(^\\+[0-9]{2}|^\\+[0-9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-\\s]{10}$)")}
        };
        public static bool IsValidNumber(string phoneNumber, string country)
        {
            if (country != null && countryRegx.ContainsKey(country))
                return countryRegx[country].IsMatch(phoneNumber);
            else
                return false;
        }
        public static IEnumerable Countries
        {
            get { return countryRegx.Keys; }
        }
    }

Thursday, June 24, 2010

Read/Write Web.config File

To modify the web.config [AppSettings] keys value at runtime
in grid like format using asp.net 2.0

1) Create a class in App_Code and copy & paste the below code

//Create an entity to store the config key and value

    public class AppSettingsKeys
    {
      
        int _configID;
       
        int _conID;
        string _conName;
        string _conValue;

        string _configName;
        string _configValue;

        public AppSettingsKeys()
        {
            this._configID = 0;
            this._configName = string.Empty;
            this._configValue = string.Empty;
           
            this._conID = 0;
            this._conName = string.Empty;
            this._conValue = string.Empty;
        }

        public int ConID
        {
            get { return _conID; }
            set { _conID = value; }
        }

        public string ConnectionName
        {
            get { return _conName; }
            set { _conName = value; }
        }

        public string ConnectionValue
        {
            get { return _conValue; }
            set { _conValue = value; }
        }

        public int ConfigID
        {
            get { return _configID; }
            set { _configID = value; }
        }
        public string ConfigName
        {
            get { return _configName; }
            set { _configName = value; }
        }
        public string ConfigValue
        {
            get { return _configValue; }
            set { _configValue = value; }
        }

        public void SetInfo(int id, string configName, string configValue)
        {
            this.ConfigID = id;
            this._configName = configName;
            this._configValue = configValue;
        }
    }
 
//2) Create a collection class like the below:

    public class AppSettingsKeysList : List
    { }

    public class AppSettingsOperations
    {
        //get all keys

        public AppSettingsKeysList getAllAppSettingsKeys()
        {
            AppSettingsKeys appSettingKey = null;
            AppSettingsKeysList appSettingKeyList = new AppSettingsKeysList();
            int idCount = 0;

            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appSettingsSection = (AppSettingsSection) configuration.GetSection("appSettings");

            ConnectionStringsSection ConStringSection = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
           
            if (appSettingsSection != null)
            {
                foreach (string key in appSettingsSection.Settings.AllKeys)
                {
                    idCount++;
                    appSettingKey = new AppSettingsKeys();
                    appSettingKey.ConfigID = idCount;
                    appSettingKey.ConfigName = key;
                    appSettingKey.ConfigValue = appSettingsSection.Settings[key].Value;

                    appSettingKeyList.Add(appSettingKey);
                }
            }
            return appSettingKeyList;
        }

        //modify the key List

        public bool ModifyKey(AppSettingsKeys appSettingKeys)
        {
            try
            {
                Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
                AppSettingsSection appSettingsSection =(AppSettingsSection) configuration.GetSection("appSettings");

                if (appSettingsSection != null)
                {
                    appSettingsSection.Settings[appSettingKeys.ConfigName].Value = appSettingKeys.ConfigValue;
                    configuration.Save();
                }
            }
            catch (Exception errorObject)
            {
                return false;
            }
            return true;
        }

    }


4) Create an aspx page and paste the below code:


 protected void Page_Load(object sender, EventArgs e)
    {

        lblMsg.Text = string.Empty;

       
       
        if (!IsPostBack)
        {
            //calling the method for papulating all app Settings keys
            try
            {
                GetAppSettingsKeys();
            }
            catch (Exception ex)
            {
                ExceptionMethod(ex);
            }
        }
    }
    private void ExceptionMethod(Exception errorObject)
    {
        lblMsg.Text = errorObject.Message.ToString();
        lblMsg.ForeColor = System.Drawing.Color.Red;
    }

    private void BindGridView(AppSettingsKeysList allKeyList)
    {
        try
        {
            GVAppConfig.DataSource = allKeyList;
            GVAppConfig.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void GetAppSettingsKeys()
    {
        AppSettingsOperations appSettingsOperations = new AppSettingsOperations();
        AppSettingsKeysList appSettingsKeyList = new AppSettingsKeysList();

        try
        {
            appSettingsKeyList = appSettingsOperations.getAllAppSettingsKeys();
            if (appSettingsKeyList.Count > 0)
            {
                //calling the bind gridView Method
                BindGridView(appSettingsKeyList);
            }
            else
            {
                lblMsg.Text = ">> No Keys Avaliable..!";
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void GVAppConfig_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GVAppConfig.PageIndex = e.NewPageIndex;
            GetAppSettingsKeys();
        }
        catch (Exception ex)
        {
            ExceptionMethod(ex);
        }
    }
    protected void GVAppConfig_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            GVAppConfig.EditIndex = -1;
            GetAppSettingsKeys();
        }
        catch (Exception ex)
        {
            ExceptionMethod(ex);
        }
    }
    protected void GVAppConfig_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GVAppConfig.EditIndex = e.NewEditIndex;
            GetAppSettingsKeys();
        }
        catch (Exception ex)
        {
            ExceptionMethod(ex);
        }
    }
    protected void GVAppConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        AppSettingsKeys appSettings = new AppSettingsKeys();
        AppSettingsOperations appSettingOperation = new AppSettingsOperations();

        try
        {
            Label lblKey = (Label) GVAppConfig.Rows[e.RowIndex].Cells[2].Controls[1];
            TextBox txtValue =(TextBox) GVAppConfig.Rows[e.RowIndex].FindControl("txtConfigValue");
           
            appSettings.ConfigID = Convert.ToInt32(GVAppConfig.DataKeys[e.RowIndex].Value);
            appSettings.ConfigValue = txtValue.Text;
            appSettings.ConfigName = lblKey.Text;

            //Update the key with the user entered value
            if (appSettingOperation.ModifyKey(appSettings))
            {
                lblMsg.ForeColor = System.Drawing.Color.Green;
                lblMsg.Text = ">> Key has been sucessfully updated...!";
            }
            else
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = ">> There is some problem in updating the key ,try later....!";
            }

            GVAppConfig.EditIndex = -1;
            GetAppSettingsKeys();
        }
        catch (Exception ex)
        {
            ExceptionMethod(ex);
        }
    }

Wednesday, June 23, 2010

Read XML With Name Table Optimization

 protected ArrayList XmlReaderWithNTOptimization()
    {
        int bookCount = 0;
        decimal bookTotal =0;
        string Title = "";
        ArrayList arrList = new ArrayList();

        XmlReaderSettings settings = new XmlReaderSettings();
        NameTable nt = new NameTable();
        Object book = nt.Add("book");
        object price = nt.Add("price");
        object title = nt.Add("first-name");
        settings.NameTable = nt;

        string bookSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd");

        settings.Schemas.Add(null,XmlReader.Create(bookSchemaFile));
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;

        settings.ValidationEventHandler += new ValidationEventHandler(MyFunction);

        settings.IgnoreComments = true;
        settings.IgnoreWhitespace = true;


        string bookFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml");

        using (XmlReader reader = XmlReader.Create(bookFile, settings))
        {

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && book.Equals(reader.LocalName))
                    bookCount++;
                if (reader.NodeType == XmlNodeType.Element && title.Equals(reader.LocalName))
                    arrList.Add(reader.ReadElementContentAsObject());
            }
        }

        Response.Write("found:    " + bookCount+"  Total Book Count: "+Title);
        return arrList;
    }

    protected void MyFunction(object sender, ValidationEventArgs e)
    {
        Response.Write(e.Message);
    }