Wednesday, 4 January 2017

WEB API in ASP.NET MVC - Simple Website to Cross domain

For This we have to create two project one project will return our data and other will read it using web api. So lets create first application after that we will create another.


start a new mvc4 Application 









Add an empty webapi controller by right clicking on Controller folder




Add following codes in controller

  Create some array,list or json return data from database.
In below code i am returning a list of datatable item through selectListItem.
You can use any return type.

Add below code in your controller these are default functions for a web api


   public IEnumerable<SelectListItem> Get()
        {
            System.Data.DataTable dt = WebapiTest.Models.Procedures.ProductList();
            List<SelectListItem> Status = new List<SelectListItem>();
            foreach (System.Data.DataRow drow in dt.Rows)
            {
                 Status.Add(new SelectListItem 
                   { Text = drow["productName"].ToString(),
                     Value = drow["ourPrice"].ToString() 
                    });
            }
            return Status;
        }
        public string Get(int id)
        {
            return "value";
        }
         //POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }


Get will be default for api controller.
as here my webapiConfig.cs contain 
  
config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

So our default routing will be

api/controllername/   for get
api/controllername/5   for get(id)
  
To see it in working we can directly browse with above url and it will return data in which format get will give like below:




More important of web api comes in use when we want to run it in cross domain sites whatever that is webapi or asp.net mvc4 sites.

One thing we have to keep remember we can't get our api data on cross domain(another website) without hosting it to iis so first host it.

To host just open IIS Internet Information Service by typing inetmgr on start. Once opened add new site name it. 



and browse on your port and ip as 

http://10.0.0.13:84/api/MyApi/

In case if it not runs open your window turn feature on off and switch asp.net services on then check. If still not run Go to your Apllication Pool in top of iis



double click on it 



Select your version in which your project was made or choose pipeline mode and click ok.

Then browse, In my case it run after fixing each small iis errors .


After that Create another MVC4 project name it as i make it apiReader.

For creating project we will follow same rule that i mentioned in start.
This time we will not add any api controller we will read our api data directly in this page.
To do that i have called api directly in an ajax call as

<script type="text/javascript">
    $(function () {
        $.getJSON('/api/MyApi/', function (contactsJsonPayload) {
            $(contactsJsonPayload).each(function (i, item) {
                $('#contacts').append('<li>' + item.Text + '</li>');
            });
        });
    });
</script>

But it didn't return anything incase it gives error



I had searched about it but google gives suggestion to use weapi.cors assemblies, and when i install it .It distroyed my api dll by version issues



Later i learned it is not so easy to get directly in javscript ajax or getjson or xhr. 
To use api data we have to read it with HttpWebRequest by below service i learned by seniors.

  public static string GetResponse(string sURL)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
            request.MaximumAutomaticRedirections = 4;
            request.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                string sResponse = readStream.ReadToEnd();
                response.Close();
                readStream.Close();
                return sResponse;
            }
            catch
            {
                return "";
            }
        }
They told me to keep it remember that by using 

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL)

we can do variours operations on request.
like security,pipeline,redirects and many more as
 request.ContentType , request.ClientCertificates, request.CachePolicy
request.AuthenticationLevel , request.AllowWriteStreamBuffering

Now just paste above function in controller

call it in any ActionResult like

 public ActionResult About()
        {
// Url with ip because we are reading cross domain api
            string sURL = "http://10.0.0.13:84/api/MyApi";

/////  Now a call to above function with our api url and it will return response
            string sResponse = GetResponse(sURL);

/////  Storing in viewbag.
            ViewBag.res = sResponse;

            return View();
        }
Now we can call it in our ajax also.
Let's check how we can now return it in ajax.
Add About view >>>>  Keep its  layout null >>> and does not give any space and only put your viewbag in it as given below:
@{Layout = null;}@ViewBag.res

If you open your about page directly you will get like this



Your data will look like json. But if you have keep extra space on about view with layout null then it comes a issue while reading json, so avoid spaces only write 
@{Layout = null;}@ViewBag.res



Now add another action result or just go with index page.
Here i am reading my api values on index page by below code.

<div id="body">
    <ul id="contacts"></ul>
</div>
<script src="/Scripts/jquery-1.8.2.min.js"></script>

<script type="text/javascript">

    $(function () {

        $.getJSON('/api/MyApi/', function (contactsJsonPayload) {
            $(contactsJsonPayload).each(function (i, item) {
                $('#contacts').append('<li>' + item.Text + '</li>');
            });
        });
    });
</script>

This will give:

And here we get our api from cross domain sites to another domain sites.

This is the whole basic i have to do with web api.
I will return soon with some web api nice stuffs..




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