Header add


In today's world we all are focused managed and custom works. URL shortening is one of them; it enable us instead of share long URL make the URL to short and share easily among social media platform as well as email and SMS provider. For more details follow What is URL shortening?

In the previous article  we seen that how the URL Shorten to be made (What is URL shortening?). But in today's topic we cover how we use it in C# MVC application. Instead of going to the provider URL and shorten the URL manually how we convert the long URL to short in C# just of following below steps.

Where URL Shortening is most require ?

Suppose you want to send the BULK SMS with some text content and link, but URL is too long and more than 160 chars. then that time URL shortening is more vital work. Now-a-days almost all websites are URL Shortening technique to send the SMS.

Let's take the example how the URL Shortening will work dynamically in C# MVC. Many Service provider are there that they allow to use URL Shorten. We consider "bit.ly" the famous among of all service provider.

The Output should like the below image; When we input our long URL and hit Submit it convert the long URL to Short using "bit.ly" in C# dynamically. So follow step by step to achieving this result :

Step-1: Open VS 2017 >> File New Project >> ASP .NET Web Application


Choose Empty Project
As we are going to present the demo in MVC, so add the Controllers, Models and Views folder accordingly and build the project,after building the Project structure look like below;
Step-2:As we see the output demo containing input/output URL, So add a class under "Models" folder of both input/Output properties.
     public class CustomURL  
       {  
         public string FullUrl { get; set; }  
         public string shortUrl { get; set; }  
       }  
Step-3: Add the controller named "URLShortController"
Step-4: Add Scaffold of model class and create a view page like below.

Step-5: Modify the view page and add the require CSS and create the Submit form as like below
    @model URLShortner.Models.CustomURL  
     @{  
       Layout = null;  
     }  
     <!DOCTYPE html>  
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">  
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>  
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
     <link href="~/Content/css/cover.css" rel="stylesheet" />  
     <html>  
     <head>  
       <meta name="viewport" content="width=device-width" />  
       <title>Index</title>  
     </head>  
     <body>  
       <div class="container">  
         <div class="panel-group" style="margin-top:50px;">  
           @using (Html.BeginForm("Index", "URLShort", FormMethod.Post, new { enctype = "multipart/form-data", id = "MainForm" }))  
           {  
             <div class="panel panel-default">  
               <div class="panel-heading">URL Shortening</div>  
               <div class="panel-body">  
                 <div class="col-md-8">  
                   @Html.EditorFor(model => model.FullUrl, new { htmlAttributes = new { @class = "form-control" } })  
                 </div>  
                 <div class="col-md-4">  
                   <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" class="btn btn-primary" />  
                 </div>  
               </div>  
             </div>  
             if (Model != null)  
             {  
             <div class="panel panel-default">  
               <div class="panel-body">  
                 <div class="row">  
                   <div class="col-md-3">Input long URL is</div>  
                   <div class="col-md-9">  
                     <a href="@Model.FullUrl" target="_blank">@Model.FullUrl</a>  
                   </div>  
                 </div>  
                 <div class="col-xs-12"><hr></div>  
                 <div class="row">  
                   <div class="col-md-3"> Output Shortening URL is</div>  
                   <div class="col-md-9">  
                     <a href="@Model.shortUrl" target="_blank">@Model.shortUrl</a>  
                   </div>  
                 </div>  
               </div>  
             </div>  
               }  
             }  
         </div>  
       </div>  
     </body>  
     </html>  
Step-6: Add the "bitly.css" class with your unique login Id and API Key
    public class bitly  
       {  
         private string loginAccount;  
         private string apiKeyForAccount;  
         private string submitPath = @"http://api.bit.ly/shorten?version=2.0.1&format=xml";  
         private int errorStatus = 0;  
         private string errorMessage = "";  
         /// <summary>  
         /// Default constructor which will login with demo credentials  
         /// </summary>  
         /// <returns>A bitly class object</returns>  
         public bitly()  
           : this("********", "**************")  // Add the Login ID and API Key
         {  
         }  
         /// <summary>  
         /// Overloaded constructor that takes a bit.ly login and apikey (if applicable)  
         /// </summary>  
         /// <returns>A bitly class object</returns>  
         public bitly(string login, string APIKey)  
         {  
           loginAccount = login;  
           apiKeyForAccount = APIKey;  
           submitPath += "&login=" + loginAccount + "&apiKey=" + apiKeyForAccount;  
         }  
         // Properties to retrieve error information.  
         public int ErrorCode  
         {  
           get { return errorStatus; }  
         }  
         public string ErrorMessage  
         {  
           get { return errorMessage; }  
         }  
         /// <summary>  
         /// Shortens a provided URL  
         /// </summary>  
         /// <param name="url">A URL</param>  
         /// <returns>A shortened bit.ly URL String</returns>  
         public string shorten(string url)  
         {  
           errorStatus = 0;  
           errorMessage = "";  
           XmlDocument doc = buildDocument(url);  
           if (doc.DocumentElement != null)  
           {  
             XmlNode shortenedNode = doc.DocumentElement.SelectSingleNode("results/nodeKeyVal/shortUrl");  
             if (shortenedNode != null)  
             {  
               return shortenedNode.InnerText;  
             }  
             else  
             {  
               errorCode(doc);  
             }  
           }  
           else  
           {  
             this.errorStatus = -1;  
             this.errorMessage = "Unable to connect to bit.ly for shortening of URL";  
           }  
           return "";  
         }  
         // Sets error code and message in the situation we receive a response, but there was  
         // something wrong with our submission.  
         private void errorCode(XmlDocument doc)  
         {  
           XmlNode errorNode = doc.DocumentElement.SelectSingleNode("errorCode");  
           XmlNode errorMessage = doc.DocumentElement.SelectSingleNode("errorMessage");  
           if (errorNode != null)  
           {  
             this.errorStatus = Convert.ToInt32(errorNode.InnerText);  
             this.errorMessage = errorMessage.InnerText;  
           }  
         }  
         // Builds an XmlDocument using the XML returned by bit.ly in response   
         // to our URL being submitted  
         private XmlDocument buildDocument(string url)  
         {  
           XmlDocument doc = new XmlDocument();  
           try  
           {  
             // Load the XML response into an XML Document and return it.  
             doc.LoadXml(readSource(submitPath + "&longUrl=" + url));  
             return doc;  
           }  
           catch (Exception e)  
           {  
             return new XmlDocument();  
           }  
         }  
         // Fetches a result from bit.ly provided the URL submitted  
         private string readSource(string url)  
         {  
           WebClient client = new WebClient();  
           try  
           {  
             using (StreamReader reader = new StreamReader(client.OpenRead(url)))  
             {  
               // Read all of the response  
               return reader.ReadToEnd();  
               reader.Close();  
             }  
           }  
           catch (Exception e)  
           {  
             throw e;  
           }  
         }  
       }  
Step-7: Add the [HTTPPOST] method in controller class.
    public class URLShortController : Controller  
       {  
         bitly b = new bitly();  
         // GET: URLShort  
         public ActionResult Index()  
         {  
           return View();  
         }  
         [HttpPost]  
         public ActionResult Index(CustomURL Urls)  
         {  
           Urls.FullUrl = Urls.FullUrl;  
           Urls.shortUrl = b.shorten(Urls.FullUrl);  
           return View(Urls);  
         }  
       } 
Step-8: That's it we did all things and run our application and see the output as expected.


We consider "bit.ly" free version So it provides 1000/month URL shortening. If you want more than that then you can take business plan. please see the link https://bitly.com/pages/pricing

Please find the Source code in Github




Summary
In this tutorial we discussed about how to create dynamic URL using C#. If have any question related to this topic then give your comments.

Post a Comment

Previous Post Next Post