Thursday, May 30, 2019

Password validation on Asp.Net using regular expration

Case 1: Validation for 8-10 characters with alphabets,numbers and no special characters.

<asp:regularexpressionvalidator controltovalidate="txtPassword" display="Dynamic" errormessage="Password must be 8-10 characters long</br> with at least one numeric character." forecolor="Red" id="RegularExpressionValidator3" runat="server" validationexpression="(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"> </asp:regularexpressionvalidator></asp:textbox>  

Case2: Validation for 8-10 characters with characters,numbers and special characters.
 
<asp:textbox id="txtpasswordwithNoUpperCharacter" runat="server" /> <asp:regularexpressionvalidator :="" display="Dynamic" errormessage="Password must be 8-10 characters long with at least one numeric,</br> one alphabet and one special character." forecolor="Red" id="RegularExpressionValidator2" validationexpression="(?=^.{8,10}$)(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*()_+}{">.<,])(?!.*\s).*$" controltovalidate="txtpasswordwithNoUpperCharacter" runat="server"> </asp:regularexpressionvalidator>  

Case3: Validation for 8-10 characters with characters,numbers,1 upper case letter and special characters.

 <asp:textbox id="txtPasswordWithSpecialCharacter" runat="server"/> <asp:regularexpressionvalidator :="" display="Dynamic" errormessage="Password must be 8-10 characters long with at least one numeric,</br>one upper case character and one special character." forecolor="Red" id="RegularExpressionValidator1" validationexpression="(?=^.{8,10}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{">.<,])(?!.*\s).*$" controltovalidate="txtPasswordWithSpecialCharacter" runat="server"/>

Important Notes in Csharp and SQL

The break, goto, continue, return and throw statements are known as jump statements.

An Abstract class can has access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.

Abstract Class :Need to to provide default behaviors as well as common behaviors that multiple derived classes can share and override
http://www.dotnettricks.com/learn/csharp/a-deep-dive-into-csharp-abstract-class

Unlike fields, properties do not denote storage locations and you cannot pass a property as a ref or out paramete

Auto-implemented properties was introduced with C# 3.0, which make property declaration more concise. Unlike standard property, in auto-implemented property, wrapped or backing field is automatically created by the compiler but it is not available for use by
public int Name { get; set; }

A try block is used to throw multiple exceptions that can handle by using multiple catch blocks

More specialized catch block should come before a generalized one. Otherwise specialized catch block will never be executed

Implicit conversion of derived classes to base class is called Upcasting and
Explicit conversion of base class to derived classes is called Downcasting.

Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature

delegate which holds the reference of more than one method is called multi-cast delegate. A multicast delegate only contains the reference of methods which return type is void. The + and += operators are used to combine delegate instances

There are following types of decision making statements in C#
If statement
If-Else statement
If-Else-If statement or ladder
Switch statement

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#

--==============================------------

Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.Example : Primary key, Unique key, Alternate key are subset of Super Keys

A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.

Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key

A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key

Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key

Unique key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It is like Primary key but it can accept only one null value and it can not have duplicate values

Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values

Views are virtual tables that are compiled at run time. The data associated with views are not physically stored in the view, but it is stored in the base tables of the view. We make views for security purpose since it restricts the user to view some columns/fields of the table(s)

-------=================================-----------------
Data Annotation Validator Attributes 
DataType, DisplayName, DisplayFormat, Required, ReqularExpression, Range, StringLength,
MaxLength, Bind, ScaffoldColumn(specify fields for hiding from editor forms)

 Partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication

The main difference between two methods is that the Partial helper method renders a partial view into a string while RenderPartial method writes directly into the response stream instead of returning a string

We can enable the jQuery intellisense support in Visual Studio with MVC Razor by adding vsdoc.js (jquery-1.7.1-vsdoc.js)

Asp.net MVC Request Life Cycle
Browser
Request
Routing: Pattern matching system (RouteTable)
Mvc Handler: initiating the real processing (IHttpHandler)
Controller: MvcHandler uses the IControllerFactory instance and tries to get a IController instance (IControllerFactory )
Action Execution: Controller's ActionInvoker determines which specific action to invoke on the controller (ActionInvoker)
View Result: receives user input, prepares the appropriate response data, and then executes the result
View Engine: xecution of the View Result involves the selection of the appropriate View Engine
View: Action method may returns a text string,a binary file or a Json formatted data.
for more details https://www.dotnettricks.com/learn/mvc/aspnet-mvc-request-life-cycle

Procedure to Search an object in a database, Find a table used in how many Procedures




CREATE PROCEDURE [dbo].[spssearchcode]            
  @text varchar(250),            
  @dbname varchar(64) = 'admin'           
AS BEGIN           
SET NOCOUNT ON;            
            
if @dbname is null           
  Begin           
    --enumerate all databases.            
  DECLARE #db CURSOR FOR Select Name from master..sysdatabases            
  Declare @c_dbname varchar(64)            
            
  OPEN #db FETCH #db INTO @c_dbname            
  While @@FETCH_STATUS <> -1 --and @MyCount < 500            
   Begin           
     execute spssearchcode @text, @c_dbname            
     FETCH #db INTO @c_dbname            
   End              
  CLOSE #db DEALLOCATE #db            
 End --if @dbname is null            
Else           
 begin --@dbname is not null            
  declare @sql varchar(250)            
  --create the find like command            
  select @sql = 'select ''' + @dbname + ''' as db, o.name,m.definition '           
  select @sql = @sql + ' from '+@dbname+'.sys.sql_modules m '           
  select @sql = @sql + ' inner join '+@dbname+'..sysobjects o on m.object_id=o.id'           
  select @sql = @sql + ' where [definition] like ''%'+@text+'%'''           
  execute (@sql)            
 end --@dbname is not null            
END

REDIS Cache with C#, Learning Redis Cache, Capture DataTable into Redis Server

Redis Cache is a key-value cache that stores the information in a hash table format, providing the possibilities to store different types of structured data like strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs

1. Install Redis server (redis-server.exe) on your machine

2. Create RedisConnectorHelper class file

    public class RedisConnectorHelper
    {
        static RedisConnectorHelper()
        {
            RedisConnectorHelper.lazyConnection = new Lazy(() =>
            {
                return ConnectionMultiplexer.Connect("localhost");
            });
        }

        private static Lazy lazyConnection;

        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
    }


3. You will noticed here ConnectionMultiplexer is not found in your application, so add using NuGet Package manager, search "StackExchange.Redis"

4. After installation you are ready to work in Redis application

5. Create the connection object of Redis server like this
    var cache = RedisConnectorHelper.Connection.GetDatabase();

6.  Store your values in this way
     cache.StringSet($"Device_Status:{i}", "value");

7. Retrive Redis/Cached values this way
     var value = cache.StringGet($"Device_Status:{i}");

8.  Some time we need to store DataTable into session/cache object so same we can do in following way.

    Store Values in Redis server:
   
   string TableName = "GetEmpData";
   foreach (DataRow dr in GetEmpData().Rows)
   {
      cache.StringSet($"Device_Status:"+ TableName + "_" +dr["id"].ToString(), string.Format("{0} : {1} : {2} : {3}", dr["Id"].ToString(), dr["Name"].ToString(), dr["Mobile"].ToString(), dr["Date"].ToString()));
   }

    Retrive Values from Redis server:
 
  foreach (DataRow dr in GetEmpData().Rows)
   {
     var value = cache.StringGet($"Device_Status:" + TableName + "_" + dr["id"].ToString());
     Console.WriteLine($"New Valueeeeee={value}");
   }
 
9. Sample Code Download Here

10. For Details information you can also visit the below link,

https://www.c-sharpcorner.com/UploadFile/2cc834/using-redis-cache-with-C-Sharp/