Tuesday, 27 December 2016

Observer Pattern in javascript

   In daily life we always need to do a add,edit,delete,update operation in our development life.
   to better go with it and to adopt a nice way of coding it is important to identify how structured our code is. So today i am going to do this with nice page operation in JavaScript through Observer design patterns.



Var Page = function(){ 
   this.Pages =[];
 

   return{
    addPage : function(pageid,pagename,pagecontent){

      this.Pages.push(pageid);
    /////function to ajax request to save new pages to database through backend

      },

   deletePage: function(pageid){
    ////checking page if contain in array Pages or not for some other use
    var index = this.Pages.indexOf(pageid);
    if(index >-1){
            this.Pages.splice(index,1)
      or

    //// Ajax to delete pages functions

    },


  update: function(pageid,pagecontent){
           //An ajax to check and update
      },

   selectAll: function(){
  // this is where you can select all pages and go through each one//
     for(var i=0; i< this.Pages.length; i++){
         // print div of pages on somehtml
         document.body.append(this.Pages[i]);

           };
      }
 };
};


var observer = function(){
  //here you can get page id from controls and put in external variables 
 // pageid = $('#pageid).val(),pagecontent= $('#pagecontent).val(),pagename= $('#pagename).val();

}

var pageid,pagecontent,pagename;

var pages = new Page();
pages.addPage(pageid,pagename,pagecontent);

////on deleting 

pages deletePage(pageid);

////on deleting 

   pages.update(pageid,content);

////page select function wherever need

 pages.selectAll();



if really said this is not a better design pattern but while writing codes we should accept a basic pattern so that our code looks clear.
we always do button operation in same way if we remove only Page keywords in this topics with button. we can go large function factory in that way. Remove all pages with button provide button id detail and do click or write click event and do click operation in that way.
In fact it seems clear if not i will try to improve it.

Monday, 26 December 2016

Strategy Pattern In MVC4

08:57 Posted by Nikesh No comments



 Creating a form which on post do calculation based on different shipping types.We will learn how these calculations occurs in Strategy Pattern


We are creating very simple form in which we can enter price and based on shipping service we can do calculation.


<form action="/home/myform" method="post">


    <input type="text" value="" name="Address1" />
    <input type="text" value="" name="Address2" />
    <input type="text" value="" name="price" />

    <select name="shipingservice">
        <option value="Fedex">Fedex</option>
        <option value="UPS">UPS</option>
        <option value="Shenker">Shrinker</option>
    </select>

    <input type="submit" />
</form>



Creating Action result. Create your action and add Post codes on your Action Post.

        public ActionResult myform()
        {
          
            return View();
        }


         [HttpPost, ValidateInput(false)]
        public ActionResult myform(   Address a)
        {
          

        //////////Accepting Values from Forms///////////////
          
            Int64 price  =  Convert.ToInt64(Request.Params["price"].ToString());
            String Address1 = a.Address1 = Request.Params["Address1"].ToString();
            String Address2 = a.Address2 = Request.Params["Address2"].ToString();
            String shipingservice = Request.Params["shipingservice"].ToString();


       ///////////////A call to shipcostcalculation class which passes our data based on strategy for calculations.////


            Shipcostcalculator sc  =  new Shipcostcalculator();
                      
            sc.pricefiller = price;   //// // Passing price to class by Setting price to shipcalculatior getter setter

           //////////// //checking shipping type and based on form values//////////////////////.


            switch (shipingservice)
            {

                case "Fedex":
                    

          /////////////A call to strategy/////////////

                    sc.strategy = new FedexShippingStrategy();

                    break;

                case "UPS":

                    sc.strategy = new UPSshippingStrategy();

                    break;

                case "Shenker":

                    sc.strategy = new ShrenkShippingStrategy();

                    break;

             

                default:

                    throw new ArgumentException("Unexpected value in drop down");

            }
            
            ///// //In last call to custom strategies fucntion to start calculation///////////
          
            Int64 result = 0;
            result = sc.CalulateCost();

           
////////Saving data to database after calculation done////////////////

            Int64 id = Address.AddProductData(a, result);

            return View();
        }



We have noticed little annoying codes in Myform action post but soon you will recover what is happening.

To use strategy we need interface.
Create an interface by right clicking on Model -->> Add -->> Interface. Name it Strategy. 





Strategy Interface

namespace strategypattern.Models
{
    public interface Strategy
    {
        Int64 Calculate(Int64 price);
    }
}




Add Class Adress.cs  by right click on model. In side that add string fields which later we can use to validate and enum which will say about our shipping. one thing i have not bounded relation with enum in that example because i am trying to make it easy as much it can.

Add class Adress.cs


namespace strategypattern.Models
{
    public class Address
    {
        public string Name { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }

        static public int AddProductData(Address a, Int64 ad)
        {        
                return 2;
        }
    }
    public enum shipOtions
    {
        UPS,
        Fedex,
        Shenker
    }
   }



Add Three classes FedexShippingStrategy.cs,ShrenkShippingStrategy.cs,UPSshippingStrategy.cs

which will work based on our strategy of calculations we have.We will parse our price inputted in strategy Calculate function which is implemented by interface.


FedexShippingStrategy.cs

namespace strategypattern.Models
{
    public class FedexShippingStrategy : Strategy
    {
             public  Int64 Calculate(Int64 price)
        {
          Int64 prices = price;
          Int64 calculation = prices - 4;

          return calculation;    ////We always have to give return type same that interface has.
        }
    }
}



ShrenkShippingStrategy.cs

namespace strategypattern.Models
{
    public class ShrenkShippingStrategy : Strategy
    {
       public Int64 Calculate(Int64 price)
        {
            return (price -  6);
        }
    }
}



UPSshippingStrategy.cs


namespace strategypattern.Models
{
    public class UPSshippingStrategy : Strategy
    {
       public Int64 Calculate(Int64 price)
        {
            return (price -  2);
        }
    }
}


 Now this is our main calculation service which directs which strategy have to use and pass parameters to that strategy.

Add a class Shipcostcalculator for calculation service

Shipcostcalculator.cs


namespace strategypattern.Models
{
    public class Shipcostcalculator
    {
        //Defining Strategy Interface as variable( Note we have not make this variable readonly because we have to pass parameters)//
     
        private  Strategy _mystratigies;


       /// // A mandatory constructor which is calling fedexstrategy default//////
        public Shipcostcalculator()
        {
            _mystratigies = new FedexShippingStrategy();
        }

        //variable which will retrieve value from our controls for calculations
        private Int64 price;

        ////////////Setter Getter through which we can pass our parameters to this class.////////

        public Int64 pricefiller
        {
            get { return price; }
            set { price = value; }
        }

       ////////// //Defining a getter setter for strategy which will pass from home controller.////////

        public Strategy strategy
        {
            get { return _mystratigies; }
            set { _mystratigies = value; }

       ///////////////By this we can get strategy name in _mystratigies variable.////////////////
        }

 /////////////A function which will call to our custom strategies with parameters.////////////////////
        public Int64  CalulateCost()
        {
            return _mystratigies.Calculate(price);  ////We can pass multiple parameters from here.
        }
    }
}

Sunday, 25 December 2016

C# Dictionary

03:39 Posted by Nikesh , No comments

Dictionary class is a data structure which represents a collection of keys and values pair of data

this resides in name space using System.Collections.Generic;

Dictionary work faster than list collections because it indexes with key and value pair.

 key -- Value through which you want to use as a pointer  
Value -- This is which will give you result of that pointer.  
                  
Dictionary<key, value> capitals = new Dictionary<key, value>();

 
Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add("Assam", "Dispur");
capitals.Add("Bihar", "Patna");
capitals.Add("Goa", "Panaji");
capitals.Add("Haryana", "Chandigarh");




Calling:

Getting Result Directly By Indexing


string capitalResult = capitals["Goa"];

This will result captialResult = "Panji"


Using Dictionary with classes:




public class State
{
    public string Capital {get; set;}
    public int Educations {get; set;}
    public int Size  {get; set;}


   public State(string capital, int educ, int size)
   {
       Capital = capital;
       Population = pop;
       Size = size;
    }


Method which bind objects to dictionary

          
    public static Dictionary<string, State> GetStates()

      {                   //Referencing State Class
     var states = new Dictionary<string,State>();
     var myState1 = new State("Dispur",1234567,123);
      states.Add("Asam", mystate1)
     var myState2 = new State("Banglore",1234567,123);
      states.Add("Bihar", mystate2)
       };

}
   
Calling Part...

we can call it as

  var stateResult = State.GetStates();

  string capitalofBihar = stateResult["Bihar"].Capital;

Result:-  "Banglore".


Above are simple steps for working with dictionary.

Working Objects with List<object>


State st1 = new State(){State="Banglore",Capital="Patna",Educations = 12345,Size=123}

State st2 = new State(){State="Asam",Capital="Dispur",Educations = 12345,Size=123}
State st3 = new State(){State="Goa",Capital="Punji",Educations = 12345,Size=123}

List<State> listStates = new List<State>();
listStates.Add(st1);
listStates.Add(st2);
listStates.Add(st3);


Calling Part...



  State result = listStates.Find(state => state.Capital == capitalnamevalue);
     if(result == null)
       {
          ...do whatever you want
       }
   else{

       result.State,result.Capital,result.Size;
       }


   

For Indexing we can also bind object attributes in dictionary based on its type and make indexing fast.

Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add(st1.Capital, "Dispur");
capitals.Add(st2.Capital, "Patna");
capitals.Add(st3.Capital, "Panaji");
capitals.Add(st4.Capital, "Chandigarh");


Normal text field Sanitizing Using C# (Regex Part 2)

02:28 Posted by Nikesh No comments
               

1. In our daily programming as we play with form we always need a validator which can validate our text like "Names" , "School", "Organization". 
So we need to sanitize this type of input, so that it can't accept (‘@’, ‘-‘ and ‘.’:) values.

For this i have got an regex which i have posted below:

private static string removeUnwantedCharacters(String inputvalue)
{
    return Regex.Replace(inputvalue, @"[^\w\.@-]", string.Empty);
}



we can test this regex as:

 string getResult = removeUnwantedCharacters("()hi{ev??er#'y>>one<<");
…returns “hieveryone”. 




2. Many times we also have to face problem with Date correct formats.

Here's a regex which can be changed as per your format needs.
 


private static string FormatMyDate(String dateInputvalue)
{
    return Regex.Replace(dateInputvalue, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b" ,    "${day}-${month}-${year}");
}



Or In Clear way

using System.Text.RegularExpressions;

string datepattern = @"(?<mm>\d{2}).(?<dd>\d{2}).(?<yyyy>\d{4})";
string replaceStr = @"${yyyy}-${mm}-${dd} or ${dd}.${mm}.${yyyy}"
 
Regex myRegEx =  new Regex(datepattern); 
 
string datevalue = Request.Params["GetDateFromControlName"].ToString() 
string myNewDateWithPattern = datevalue.ReplaceAll(myRegEx, replaceStr);
 
and further we can convert our date to datetime datatype. 


this will act as same as image given below we can use this to replace all with correct format too

 












 

Saturday, 24 December 2016

Find all href link value in HTML string posted in c# (Regex Part1)

08:08 Posted by Nikesh No comments
Let assume you have passed full html on form post to your action and you come with a need where you have to find all href link in that html string.

Assume you have got an string which contin links like 

 <html>
      <p>
          <a href="http://www.codesgonecrazy.com\">Crazy Codes </a>
      </p>
     <div>
         <a href="http://www.othersites.com\">Other sites links</a>
     </div>
</html>

To this in better way we can use regex i got in c#:

   Regex regex = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))", RegexOptions.IgnoreCase);


    Match i;

for (i = regex.Match(textcontrolvalue); i.Success; i = i.NextMatch())
    {
       //    Got groups of hrefs!!! ;

        foreach (Group gp in i.Groups)
        {
          
        string link = gp;

        } 
     }

Now further we can add each link in list from foreach.

enjoy!!




-------------------------------------------------

Regex For Phone And Zip checker in C#

 
-------------------------------------------------

In daily validation we always need right phone format and zip format checker.

Below regex will do this work very well!

Pass value of phone to IsValidPhone() and you will get result.


IsValidPhone(string phone)

private static bool IsPhoneValid(string phone)
{
    return Regex.IsMatch(phone, @"^\(?\d{3}\)?[\s\-]?\d{3}\-?\d{4}$");
}


this regex can be used with below types of formats:

(xxx)xxx-xxxx :- (987)654-3210
(xxx) xxx-xxxx :- (987) 654-3210
xxx-xxx-xxxx :- 987-654-3210
xxxxxxxxxx :- 9876543210


Now a regex for US ZIP checker:


private static bool IsZipValid(string zip)
{
    return Regex.IsMatch(zip, @"^\d{5}(\-\d{4})?$");
}


this will work with following formats:

xxxxx-xxxx: 98765-5678
xxxxx: 98765

            
 

Wednesday, 21 December 2016

Factory Pattern In C#


Uses:- They have flexibility that can create documents flexible.

Create a console application name it anything paste all code given below;

Class MyApplication
{

Static void Main(String []args)
{

////////Constructor that calls factory method//////////////////////////

Document[] documents  = new Documents[2];
documents[0] = new Resume();
documents[1] = new Report();

    foreach( Documents doc in documents)
    {
     Console.WriteLine("\n"+ doc.getType().Name);

         foreach(Page p in documents.Pages)
          {
        Console.WriteLine("\n"+ page.getType().Name);

          }
     }

   Console.ReadLine();
  }


}





//***********************Product Abstract Class*************************************

abstract Class Page
{
}


//*********************Concrete product Classes*************************************


Class skillPage : Page {  }
Class EducationPage : Page {  }
Class ExperiancePage : Page {  }


//*****************************Abstract Class Creator*****************************


abstract Class Document
{
   private List<Page> _mypage =  new List<Page> ();

   public Document()
    {

    this.CreatePages();   ------- Call to Abstrac Factory Method
      
      }

  public List<Page> Pages
   {
     get { return _mypage; }
    }

//////////////////////Factory Method/////////////////

public abstract void CreatePages();
}
}


//********************Concrete Creator Class*********************************

Class Resume : Document
 {

  /////////////////Factory Method Implementation///////////
   public override void CreatePages()
    {
     Pages..add( new  skillPage () );
     Pages..add( new  EducationPage () );
     Pages..add( new  ExperiancePage () );
     }
}


//************************Concrete Creator Class***************************

Class Report  : Document
 {
  public override void CreatePages() 
   {
     Pages..add( new  NewClassNameWhichYouNeed() );
     Pages..add( new  NEWCLASSNAME() );
   }
}
******************************************************************************

Tuesday, 20 December 2016

Seo - (Mobile Tel Link) click to call for phone numbers on website in javascript


While working with seo optimization, many times we need to include phone dialer on all valid phone on website for its better work.

Here I have created an script which can automatically add dialer to href with refrence of same number that phone is written in anchor tag.  With help of this we can reduce multiple hour of reentering or adding phone inside anchor dialer of phones.

For this we have created a regex which will identifies numbers on entire webpage.

For this we are focusing only on text which is matching phone number digits, To do this we are using javascript nodeType property of dom element, which will gives nodeType as(node type of element text in dom is 3) . We are also using regex to find matched string that has node type 3 and has anchor tag, then i have created a dialer element anchor tag and then replaced with original node text. You can use below script to filter some phone numbers in whole pages and create dialer for same or you can also do for all numbers too.



<script src="~/Scripts/jquery-1.8.2.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g;      ---Finding Phone Numbers

            var text = $("body:first").html();
       
            var textNodes = $("body:first").find('*').contents().filter(function () {
      if (this.nodeType == 3 && regex.test(this.nodeValue) && this.parentElement.tagName !== "A")           {
                    var anchor = document.createElement('a');


                    //********Tel No. Trimming************
                    var telno = this.nodeValue.match(regex)[0];
                    var telno1 = telno.replace(/\s/g, '');                 --  Replacing space with null
                    var telnot = telno1.replace(/[:,-,(,)]/g, '');        --  Replacing special characters with null
                    var FinalNo = telnot.replace(/\-+/g, '');           --  Getting Final Numbers 

------------------Trimming Text For Title-----

                    var trim1 = this.nodeValue.replace(/\s/g, '');            
                    var trim2 = trim1.replace(/\d+/g, '');
                    var trim3 = trim2.replace(/[:,-,(,)]/g, '');
                    var trim4 = trim3.replace('-', '');
                    var FinalTitle = "'" + trim4 + "'";

-------------------Matching Phone Numbers which you want to be act as a dialer---------------

                    if (FinalNo === '8002730713' || FinalNo === '8005100514') {
                        anchor.setAttribute('href', "tel:" + FinalNo);

                        var TitleLength = trim4.length;
                        if (TitleLength > 22)            --------------    Minimizing text to be shown on title
                        {
                            return false;
                        }
                        else
                        {
           anchor.setAttribute('onclick', "ga('send', 'event'," + FinalTitle + ", 'Click');");    setting a tracking on click

                        }
                     
                    }
--------------Appending to dom------------------

                    anchor.appendChild(document.createTextNode(this.nodeValue.match(regex)[0]));
                    if (this.nextSibling)
                        this.parentElement.insertBefore(anchor, this.nextSibling);
                    else
                        this.parentElement.appendChild(anchor);
                    this.nodeValue = this.nodeValue.replace(regex, '');
                }
                return this.nodeType == 3;
            });
        });
    </script>


-------------------------------------------------------------------------------------------------------------------------------

Seo Optimization - Fixing Trailing /// From Various Section In Asp.Net

Trailing slash commonly asked to manage while optimization, as this can treat content duplicate or can make url and seo friendly. 


we can obtain it by multiple ways, we can manage url in Action which will called on url browsing or we can use them Global.asax, or we can manage them by customizing inside custom error management classes. Here i have given some examples which can show some scenario of its uses:

1. Using in multiple places  (Actions, Classes) in mvc.

           
           if (url.LastIndexOf('/') > 0)
              {
                Regex reg = new Regex(@"^([^:]\/)\/+$");
                string result = reg.Replace(url, "");
                string urls= result.Remove(result.Length - 1);
           
               }
                else
                {
                   
                }



2. Using In View In MVC 



string url= HttpContext.Current.Request.RawUrl.ToLower().ToString();
string path = HttpContext.Current.Request.Url.Authority;
String Url= ViewBag.Url;

<script type="text/javascript">
    var slug = '@Url';
    var path = '@path';
    var urlredirect = 'http://' + path + '/' + slug;
      window.location = urlredirect;

</script>




3. Using In Global.asax file



               string requestedUrl = Request.Url.ToString();
                if (requestedUrl != null)
                {
                    if (requestedUrl.EndsWith("/"))
                    {
                        //Redirect with 301 Status Code if this contain trailing Slashess
                      
                            requestedUrl = requestedUrl.Substring(0, requestedUrl.Length - 1);
                            Response.RedirectPermanent(requestedUrl);
                        
                    }
                }

Manage File Path In Sql


Extracting file name from full file path


Suppose we have saved our images with their path name in sql as /root/subroot/image/image.jpg
And we need to extract only image name without their path.

For this we are going to use two to three inbuilt functions as SUBSTRING(),CHARINDEX(),REVERSE()

 SUBSTRING(string, start postion, End positions )  --  For Splitting Strings

 CHARINDEX("Expression", string) --  For Getting Specified Postion

 REVERSE(string)     --   Usually used to reversed strings.

 CHARINDEX('/',REVERSE(@Path))   --   Finding last "/" string position in string

 Using it with string "/root/subroot/image/image.jpg" gives 10 th position.
LEN(@Path)  -- Total length of above string is 29.
 LEN(@Path) - CHARINDEX('/',REVERSE(@Path))  --  (29 - 10)   -->> which gives 19


SUBSTRING (@Path,1 , LEN(@Path) - CHARINDEX('/',REVERSE(@Path)) )

gives all part leaving image name from string. ex- It gives "/root/subroot/image"

Then we are using replace(string, part of string to replace, replace with)
replace(@Path, @splitted+'/','')  --  replace(' /root/subroot/image/image.jpg', '/root/subroot/image'+ '/', '')

By using this we got exact image name.

We can use it as a function to be clear and concise as given below.

 Create FUNCTION SplitImageFromPath
(
    @Path NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @FileName NVARCHAR(MAX)
    DECLARE @splitted NVARCHAR(MAX)
   DECLARE @result NVARCHAR(MAX)

     
 set  @splitted = SUBSTRING (@Path ,1 , LEN(@Path) - CHARINDEX('/',REVERSE(@Path)) )

 set @result =  replace(@Path, @splitted+'/','')

    RETURN @result
END





Monday, 19 December 2016

MVC C# Error Handling

1. Object Can't be cast from Db null to other types.

Soln.--  Mostly comes when working with database, when we execute our query but after execution we didn't return anything and we are trying to achieve query result through functions. Suppose we have a procedure which is inserting our data to database and simultaneously getting return in some variables or parsing as parameter and our procedure that has only query to  insert not to return, in that case we are achieving null data in some datatype.
 To solve this only give a return type from your query after insert and  it will solve.


2. Dangerous Request Errors.

Soln--  This error comes when we are inserting some html content or executing html content to render in browser in .net.
 To Solve this we have to give validation mode configuration in httpRuntime as given below:

<httpRuntime targetFramework="4.5" requestValidationMode="2.0" />


3. Dangerous value Error  when working with Content Editors.

Soln--   Add  [Validate Input(false)] above action Result when working with mvc or add
            <httpRuntime targetFramework="4.5" requestValidationMode="2.0" /> in Web.config file.


4. Error with loading images in html

Soln--  Correct way of using path url in images are:
1. Use Absolute Url "~/foldername/filename
2. Use "../foldername/filename
3 Use Direct routing /foldername/filename

5. Not All code path returns a value

Soln--  Return type is not provided or not used at correct place.


6. </blockquote> Not supports in some editors in design mode.

Soln--  Save html without going into html mode.


7. 403 Status Code Error

Cause--  Removal of file permission or restriction of access permission, Accidental misconfiguration                of Web Server.


8. Dynamic and static routing problem:

Soln-- always use dynamic routing after all static routing. 

Visual Studio Short Cuts

Visual Studio Shortcuts

Ctrl + C ---> Copy

Ctrl + X  --->  Cut

Ctrl + F  --->  Finding Words

Ctrl + H  --->  Find And Replace Words

Ctrl + Shift + i  --> Ctrl + C --> Copying lines on which cursor present 

Ctrl + M  ---> Collapse Selected Functions

Ctrl + [  --->  Reach to start braces of functions

Ctrl + ] --->  Reach to end braces of functions

Ctrl + Home  --->  Reach to start of page

Ctrl + End  --->  Reach to end of page

Home  --->  Reach the start of line

End  --->  Reach the end of line

Ctrl + Shift +Space ---> Show parameters of referred functions

Ctrl + G ---> Go to line Number

Ctrl + Shift + N ---> Create new file

Ctrl + Shift + B ----> Build Project