Sunday, February 26, 2017

Uploading images using WebApi and JSON

Hi All,

I recently had a requirement to create a Web API to work with a mobile phone. I was required to create a method to upload images. So I did it the following way hope you like it.

1) Class Definitions
 public class AuthData
    {
        public string auth_token { get; set; }

    }
  
    public class ImageSetData : AuthData
    {
        public string Name { get; set; }
        public List<Image> Images { get; set; }
    }

    public class Image
    {
        public string FileName { get; set; }
        public string Extension { get; set; }
        public byte[] ImageData { get; set; }
    }

2) WebApi Method

public ReturnMsg SaveFile([FromBody] ImageSetData imageData)
        {
            ReturnMsg objReturnMsg = new ReturnMsg();

            try
            {
                if (APIHelper.AuthenticateToken(imageData.auth_token))
                {

                    foreach (var image in imageData.Images)
                    {
                        File.WriteAllBytes(string.Format("{0}\\{1}.{2}", HttpContext.Current.Server.MapPath("~/App_Data") , image.FileName, image.Extension), image.ImageData);
                    }  
                  




                }
                else
                {
                    objReturnMsg.success = false;
                    objReturnMsg.msg = "Invalid Token. Please Login to continue";
                }
            }
            catch (Exception ex)
            {

                objReturnMsg.success = false;
                objReturnMsg.msg = "Internal Server Error. Contact Admin.";
                APIHelper.Log(ex.Message, ex.StackTrace);
            }


            return objReturnMsg;
        }

3) Post Man Screen shot and Image




Wednesday, January 25, 2017

WCF Service and TLS 1.2


Hi All,

I worked on a WCF Service (.NET 3.5) which consumed an external web service and was working fine. Until recently it started giving the following error.

An error occurred while making the HTTP request to
{url}.This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case.This could also be caused by a mismatch of the security binding between the client and the server.

This made a big issue as the WCF was already being consumed by number of other systems. Later we got to know the external web service was upgraded to use TLS 1.2 and the .NET 3.5 doesn't support TLS 1.2 (.NET 4.5 or greater supports TLS 1.2). So I had to change the version of the .NET version to 4.5 and add the following code to enforce it to use TLS 1.2. And everything started to work the way they used to.


1) .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.
2) .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

3) .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

4) .NET 3.5 or below. TLS 1.2 is not supported (*) and there is no workaround. Upgrade your application to more recent version of the framework.


Sources : http://blogs.perficient.com/microsoft/2016/04/tsl-1-2-and-net-support/

Tuesday, August 16, 2016

Bilingual Dynamic Survey

Hi Guys,

I created a bilingual Dynamic Survey application using ASP.NET. Hope you like it.























Sunday, May 15, 2016

Request String Encryption in MVC 5

Hi Guys,

This time I had a requirement to Encrypt the request string parameters before passing them to the Controller's method. After referring this solution, I made this solution I hope you like it.

1) SecurityHelper 

public class SecurityHelper
    {
        public static string Encrypt(string plainText)
        {
            string key = "jdsg432387#";
            byte[] EncryptKey = { };
            byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
            EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
            cStream.Write(inputByte, 0, inputByte.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }

        public static string Decrypt(string encryptedText)
        {
            string key = "jdsg432387#";
            byte[] DecryptKey = { };
            byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
            byte[] inputByte = new byte[encryptedText.Length];

            DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByte = Convert.FromBase64String(encryptedText);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByte, 0, inputByte.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }

        public static string MakeQueryString(string queryString)
        {          

            return "p=" + Encrypt(queryString);

        }
    }

2) EncryptedActionParameterAttribute 

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class EncryptedActionParameterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            Dictionary<string, object> decryptedParameters = new Dictionary<string, object>();
            if (filterContext.HttpContext.Request.QueryString.HasValue)
            {
                string encryptedQueryString = filterContext.HttpContext.Request.QueryString.Value.Substring(filterContext.HttpContext.Request.QueryString.Value.IndexOf("=")+1);
                string decrptedString = SecurityHelper.Decrypt(encryptedQueryString.ToString());
                string[] paramsArrs = decrptedString.Split('&');

                for (int i = 0; i < paramsArrs.Length; i++)
                {
                    string[] paramArr = paramsArrs[i].Split('=');
                    decryptedParameters.Add(paramArr[0], paramArr[1]);
                }
            }
            for (int i = 0; i < decryptedParameters.Count; i++)
            {
                filterContext.ActionArguments[decryptedParameters.Keys.ElementAt(i)] = decryptedParameters.Values.ElementAt(i);
            }
            base.OnActionExecuting(filterContext);

        }

   
    }

3) Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}



<div class="row">
    <div class="col-md-12">
        <ul>
            @foreach (var person in PeopleHelper.GetPeople())
            {
                <li> @person.Name
                    <a href="/Home/Person?@SecurityHelper.MakeQueryString("id="+person.ID+"&name="+@person.Name)">
                        Click Here
                    </a>
                </li>
            }
        </ul>
     
    </div>
 
</div>

4) HomeController

 public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [EncryptedActionParameter]
        public IActionResult Person(string id, string name)
        {
            return View(new Person() { ID = int.Parse(id),Name = name } );
        }



        public IActionResult Error()
        {
            return View("~/Views/Shared/Error.cshtml");
        }
    }





Wednesday, March 30, 2016

Current Weather App using Google Maps and forecast.io

Hi Guys,

This time I made a real time whether application which uses the phone's GPS coordinates and Google Map's GPS coordinates to fetch whether information. I hope you will like it.







Saturday, February 27, 2016

JQuery Calendar : Ummul Qura and Gregorian

Hi Guys,

I had a requirement to create a calendar which lets user select ummul qura and gregorian dates for bootstrap theme. So I found this jquery calendar and modified it to achieve it. I hope you like it.














Javascript

<script type="text/javascript">
    


  


    var calendarHijri,
        calendarGreg;
    var minHijriYear,
            minHijriMonth,
            minHijriDay,
            maxHijriYear,
            maxHijriMonth,
            maxHijriDay;
    /*Update Panel Fix*/
    function pageLoad()
    {
        //Handle Uniform
        if (!jQuery().uniform) {
            return;
        }
        var test = $("input[type=checkbox]:not(.toggle, .make-switch), input[type=radio]:not(.toggle, .star, .make-switch)");
        if (test.size() > 0) {
            test.each(function () {
                if ($(this).parents(".checker").size() == 0) {
                    $(this).show();
                    $(this).uniform();
                }
            });
        }


        calendarHijri = $.calendars.instance('ummalqura');
         calendarGreg = $.calendars.instance('gregorian');

         <% if (MinDate.HasValue) { %>            
                var date = calendarGreg.parseDate('',<%= "'"+ MinDate.Value.ToString("dd-MM-yyyy",new System.Globalization.CultureInfo("en-US")) +"'" %>);
                var cdate = calendarHijri.fromJD(calendarGreg.toJD(date)); 
                minHijriDay = cdate.day();
                minHijriMonth = cdate.month();
                minHijriYear = cdate.formatYear(); 
               
             <% } %>
               <% if (MaxDate.HasValue) { %>
                var date = calendarGreg.parseDate('',<%= "'"+MaxDate.Value.ToString("dd-MM-yyyy",new System.Globalization.CultureInfo("en-US"))+"'" %>);
                var cdate = calendarHijri.fromJD(calendarGreg.toJD(date)); 
                maxHijriDay = cdate.day();
                maxHijriMonth = cdate.month();
                maxHijriYear = cdate.formatYear(); 
               
             <% } %>

        

         <% if (CalendarEnabled)
    { %>
         
         $(<%= "'#" + ClientIDHijri + "'" %>).calendarsPicker({ calendar: calendarHijri,
             <% if (MinDate.HasValue) { %>
             minDate : calendarHijri.newDate(minHijriYear,minHijriMonth,minHijriDay),              
             rangeSelect: true,
             <% } %>
               <% if (MaxDate.HasValue) { %>
             maxDate : calendarHijri.newDate(maxHijriYear,maxHijriMonth,maxHijriDay),            
             <% } %>
             onSelect: function(dates) { 
                 
                 var date = dates[0]; 
                 var cdate = calendarGreg.fromJD(calendarHijri.toJD(date)); 
                 var day = (cdate.day()>=10)?cdate.day() + "":"0" + cdate.day();
                 var month = (cdate.month()>=10)?cdate.month() + "":"0" + cdate.month();

                 document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value = day  + '-' + month + '-' + cdate.formatYear();

                 <% if (ExposeSelect)
                { %>
                 OnSelectChanged(document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value);
                <% }%>

             } });
         $(<%= "'#" + ClientIDGrogorian + "'" %>).calendarsPicker({ calendar: calendarGreg,
               <% if (MinDate.HasValue) { %>
             minDate : calendarGreg.newDate(<%= MinDate.Value.Year %>,<%= MinDate.Value.Month %>,<%= MinDate.Value.Day %> ),              
             rangeSelect: true,
             <% } %>
               <% if (MaxDate.HasValue) { %>
             maxDate : calendarGreg.newDate(<%= MaxDate.Value.Year %>,<%= MaxDate.Value.Month %>,<%= MaxDate.Value.Day %> ),            
             <% } %>
             onSelect: function(dates) { 
                
                 var date = dates[0]; 
                
                 var cdate = calendarHijri.fromJD(calendarGreg.toJD(date)); 
                 var day = (cdate.day()>=10)?cdate.day() + "":"0" + cdate.day();
                 var month = (cdate.month()>=10)?cdate.month() + "":"0" + cdate.month();
                 document.getElementById(<%= "'" + ClientIDHijri + "'" %>).value = day  + '-' + month + '-' + cdate.formatYear();
               <% if (ExposeSelect)
                { %>
                 OnSelectChanged(document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value);
                 <% } %>
             } });
         <% } %>

         <%if( ShowHijry ) {%>
         DateChanged_<%= this.ClientID %>('<%= ClientIDGrogorian%>','<%= ClientIDHijri %>');
     <%
        } 
        %>
<%if(ShowGregorian ) {%>
         DateChanged_<%= this.ClientID %>('<%= ClientIDHijri%>','<%= ClientIDGrogorian %>');
    <%
        } 
        %>
         
    }

    // $.calendars.picker.setDefaults({renderer: $.calendars.picker.themeRollerRenderer}); // Requires jquery.calendars.picker.ext.js
    

    jQuery(document).ready(function(){
        calendarHijri = $.calendars.instance('ummalqura');
         calendarGreg = $.calendars.instance('gregorian');
         var date,cdate;
         var hijriYearDif,gregDateDif;
         <% if (MinDate.HasValue) { %>            
                 date = calendarGreg.parseDate('',<%= "'"+ MinDate.Value.ToString("dd-MM-yyyy",new System.Globalization.CultureInfo("en-US")) +"'" %>);
                 cdate = calendarHijri.fromJD(calendarGreg.toJD(date)); 
                minHijriDay = cdate.day();
                minHijriMonth = cdate.month();
                minHijriYear = cdate.formatYear(); 
                
             <% } %>
               <% if (MaxDate.HasValue) { %>
                 date = calendarGreg.parseDate('',<%= "'"+MaxDate.Value.ToString("dd-MM-yyyy",new System.Globalization.CultureInfo("en-US"))+"'" %>);
                 cdate = calendarHijri.fromJD(calendarGreg.toJD(date)); 
                maxHijriDay = cdate.day();
                maxHijriMonth = cdate.month();
                maxHijriYear = cdate.formatYear();              
             <% } %>
        <% if (MinDate.HasValue && MaxDate.HasValue) { %>
        hijriYearDif = maxHijriYear - minHijriYear;
        
        gregDateDif = <%= (MaxDate.Value.Subtract(MinDate.Value).Days / 365) %>;
        <% } %>
        

         <% if (CalendarEnabled)
    { %>
         
         $(<%= "'#" + ClientIDHijri + "'" %>).calendarsPicker({ calendar: calendarHijri,
             <% if (MinDate.HasValue) { %>
             minDate : calendarHijri.newDate(minHijriYear,minHijriMonth,minHijriDay ),              
             yearRange: minHijriYear+':'+maxHijriYear+'',
             <% } %>
               <% if (MaxDate.HasValue) { %>
             maxDate : calendarHijri.newDate(maxHijriYear,maxHijriMonth,maxHijriDay ),            
             <% } %>
             onSelect: function(dates) { 
                 
                 var date = dates[0]; 
                 if(date != undefined)
                 {
                     var cdate = calendarGreg.fromJD(calendarHijri.toJD(date)); 
                     var day = (cdate.day()>=10)?cdate.day() + "":"0" + cdate.day();
                     var month = (cdate.month()>=10)?cdate.month() + "":"0" + cdate.month();

                     document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value = day  + '-' + month + '-' + cdate.formatYear();

                     <% if (ExposeSelect)
                    { %>
                     OnSelectChanged(document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value);
                     <% }%>
                 }
                 else
                     document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value = '';

             } });
         $(<%= "'#" + ClientIDGrogorian + "'" %>).calendarsPicker({ calendar: calendarGreg,
               <% if (MinDate.HasValue) { %>
             minDate : calendarGreg.newDate(<%= MinDate.Value.Year %>,<%= MinDate.Value.Month %>,<%= MinDate.Value.Day %> ),  
             
             <% } %>
               <% if (MaxDate.HasValue) { %>
             maxDate : calendarGreg.newDate(<%= MaxDate.Value.Year %>,<%= MaxDate.Value.Month %>,<%= MaxDate.Value.Day %> ),            
             <% } %>
       <% if (MinDate.HasValue && MaxDate.HasValue) { %>
            
             yearRange: 'c-'+ gregDateDif+':c+'+ gregDateDif+'',
        <% } %>

            

             onSelect: function(dates) { 
                
                 var date = dates[0]; 
                 if(date != undefined)
                 {
                     var cdate = calendarHijri.fromJD(calendarGreg.toJD(date));
                     console.log(calendarGreg.toJD(date));
                     var day = (cdate.day()>=10)?cdate.day() + "":"0" + cdate.day();
                     var month = (cdate.month()>=10)?cdate.month() + "":"0" + cdate.month();
                     document.getElementById(<%= "'" + ClientIDHijri + "'" %>).value = day  + '-' + month + '-' + cdate.formatYear();
                     <% if (ExposeSelect)
                { %>
                     OnSelectChanged(document.getElementById(<%= "'" + ClientIDGrogorian + "'" %>).value);
                     <% } %>
                 }
                  else
                     document.getElementById(<%= "'" + ClientIDHijri + "'" %>).value = '';
             } });
         <% } %>

         <%if( ShowHijry ) {%>
         DateChanged_<%= this.ClientID %>('<%= ClientIDGrogorian%>','<%= ClientIDHijri %>');
     <%
        } 
        %>
<%if(ShowGregorian ) {%>
         DateChanged_<%= this.ClientID %>('<%= ClientIDHijri%>','<%= ClientIDGrogorian %>');
    <%
        } 
        %>
         
    }
   );

     


    function DateChanged_<%= this.ClientID %>(controlChanged,controlToUpdate) {
    var changedDate = document.getElementById(controlChanged).value;
    if (changedDate != '') {
        try {
            var changedVal = <%= "'"+ClientIDHijri+"'" %>;
            if(controlChanged == changedVal)
            {
                var date = calendarHijri.parseDate('', changedDate);
                var cdate = calendarGreg.fromJD(calendarHijri.toJD(date)); 
                 var day = (cdate.day()>=10)?cdate.day() + "":"0" + cdate.day();
                 var month = (cdate.month()>=10)?cdate.month() + "":"0" + cdate.month();

                 document.getElementById(<%= "'"+ClientIDGrogorian+"'" %>).value = day  + '-' + month + '-' + cdate.formatYear();
             
            }
            else
            {
                var date = calendarGreg.parseDate('', changedDate);
                var cdate = calendarHijri.fromJD(calendarGreg.toJD(date)); 
                 var day = (cdate.day()>=10)?cdate.day() + "":"0" + cdate.day();
                 var month = (cdate.month()>=10)?cdate.month() + "":"0" + cdate.month();
                 document.getElementById(<%= "'"+ClientIDHijri+"'" %>).value = day  + '-' + month + '-' + cdate.formatYear();
         
            }
            
        }
        catch (e) {
            console.log(e);
        }
    }
}

    



</script>

Wednesday, February 3, 2016

Facebook Login in Apache Cordova using Angular JS

Hi Guys,

I wanted to integrate facebook login within mobile apps. I found very useful blog from the internet and managed to do that. Hope you like it.

http://blog.brunoscopelliti.com/facebook-authentication-in-your-angularjs-web-app/