Thursday, 13 December 2018

Nunit installation in visual studio

1.open visual studio editor
2.click tools menu
3.select Nuget package Manager >package manager console
4. In console it will show PM>prompt
5.create your unit test project i,e library project where u going to write unit test case.
6.choose unit test project name from package manager console window
7.execute following commands one by one
PM>Install-Package Nunit -Version 3.8.1
PM>Install-Package Nunit3TestAdapter -Version 3.8.0
PM>Install-Package Nunit.ConsoleRunner -Version 3.8.0

Sample example program here:

using NUnit.Framework;
using Prime.Services;

namespace Prime.UnitTests.Services
{
    [TestFixture]
    public class PrimeService_IsPrimeShould
    {
        private readonly PrimeService _primeService;

        public PrimeService_IsPrimeShould()
        {
            _primeService = new PrimeService();
        }

        [Test]
        public void ReturnFalseGivenValueOf1()
        {
            var result = _primeService.IsPrime(1);

            Assert.IsFalse(result, "1 should not be prime");
        }
    }
}

Saturday, 28 July 2018

Regular Expression for validate Multiple Email




<!DOCTYPE html>
<html>
<body>


<form action="/action_page.php">
Email Id's(For multiple use';' Ex: arul@mail.com;arul2@mail.com) 
<input type="text" name="EmailId" 
pattern="^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;]{0,1}\s*)+$" 
required title="Email id's">
<input type="submit">
</form>


<p><strong>Note:</strong> The pattern attribute of the input tag is not supported in Internet Explorer 9 and earlier versions
or Safari 10 and earlier.</p>


</body>
</html>

Tuesday, 19 September 2017

QR code generation in C# and CShtml

Libraries Required.

Install these packages into project file or service file using NuGet Package manager.
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using ZXing;
using ZXing.Common;
//Helper class file for generate QR code
namespace QRHelper
{
    public static class QRHelper
    {
        public static IHtmlString GenerateQrCode(this HtmlHelper html, string Content, string alt = "QR code", int height = 150, int width = 150, int margin = 0)
        {
            var qrWriter = new BarcodeWriter();
            qrWriter.Format = BarcodeFormat.QR_CODE;
            qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };

            using (var q = qrWriter.Write(Content))
            {
                using (var ms = new MemoryStream())
                {
                    q.Save(ms, ImageFormat.Png);
                    var img = new TagBuilder("img");
                    img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
                    img.Attributes.Add("alt", alt);
                    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
                }
            }
        }

        public static IHtmlString GenerateQrCode(string Content, string alt = "QR code", int height = 150, int width = 150, int margin = 0)
        {
            var qrWriter = new BarcodeWriter();
            qrWriter.Format = BarcodeFormat.QR_CODE;
            qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };

            using (var q = qrWriter.Write(Content))
            {
                using (var ms = new MemoryStream())
                {
                    q.Save(ms, ImageFormat.Png);
                    var img = new TagBuilder("img");
                    img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
                    img.Attributes.Add("alt", alt);
                    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
                }
            }
        }
    }
}
----------------------------------------------View Part(CShtml page)--------------------------------------------
@using QRHelper

 <!--Directly call from Html elements it will call first function-->
@Html.GenerateQrCode("{\"BookingID\":\"2541-12454-0154-545121855\"}", "QR code", 150, 150)<span>QR Code</span>

---------------------------------------------Call from controller--------------------------------------------
using System.Web;
 public class HomeController : Controller
    {
              public ActionResult Index()
        {
//It will second method in helper class
IHtmlString  _qrCode=
GenerateQrCode("Your text here", "QR code", 150, 150);
        }
}

Monday, 18 September 2017

A-Map (china map) with auto complete textbox in web

Controller like: 

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
      [HttpPost]
        public ActionResult Index(string Address, string LatLong)
        {
            ViewBag.Message = "Address: " + Address+ " Lat Long: " + LatLong;
            return View();
        }
 }

CShtml page :

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>

   
    <script>
        $(function () {
            $("#Address").autocomplete({
                source: function (request, response) {
                    var Address = [];
                    $.ajax({
                        url: 'http://restapi.amap.com/v3/place/text',
                        data: { key: "Your API key", keywords: request.term },
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            var results = jQuery.parseJSON(JSON.stringify(data));
                            var i;
                            var items = results.pois;
                             //declare a new object.
                        for (i = 0; i < items.length; i++) {
                                var objectInResponse = items[i];
                                var listobj = { label: objectInResponse.address + "," + objectInResponse.cityname, val: objectInResponse.location }
                              
                            
                                Address.push(listobj)
                            }
                            ///alert(JSON.stringify(Address));
                            response($.map(Address, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("#LatLong").val(i.item.val);
                },
                minLength: 1
            });
        });
    </script>


    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" id="Address" name="Address" />
        <input type="hidden" id="LatLong" name="LatLong" />
        <br /><br />
        <input type="submit" id="btnSubmit" value="Submit" />
        <br /><br />
        @ViewBag.Message
    }
  
</body>
</html>

Passing Antiforgery token in Ajax

Controller have function like

[HttpPost]
[ValidateAntiForgeryToken]
 public JsonResult ActionName(int Id)
{
    //do your stuff
}

Cshtml Page 

@Html.AntiForgeryToken()
<!--Include ajax script render section for ajax call--> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

<script>
 $.ajax({
                    url: '../Controllername/ActionName',
                    type: "Post",
                   data: {
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
Id: 1},
                    success: function (response) {
                      //do your stuff
                    },
                    error: function (errorcode, textStatus, errorThrown) {
                        // alert("Error '" + errorcode.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                    },
                    complete: function () {
                        // do your stuff after complete                    }
                });
</script>

Saturday, 16 September 2017

Distance calculation function between lat and long in c#

 public class DistanceCalculationHelper
    {
        public static double GetDistance(decimal lat1, decimal long1, decimal lat2, decimal lon2,char unit='K')
        {
            try
            {
                //const double PI = 3.1415926535897931;
                //double rlat1 = Math.PI * double.Parse(lat1.ToString()) / 180;
                //double rlat2 = Math.PI * double.Parse(lat2.ToString()) / 180;
                //double theta = double.Parse(long1.ToString()) - double.Parse(lon2.ToString());
                //double rtheta = Math.PI * theta / 180;
                //double dist =
                //    Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) *
                //    Math.Cos(rlat2) * Math.Cos(rtheta);
                //dist = Math.Acos(dist);
                //dist = dist * 180 / Math.PI;
                //dist = dist * 60 * 1.1515;

                //switch (unit)
                //{
                //    case 'K': //Kilometers -> default
                //        return dist * 1.609344;
                //    case 'N': //Nautical Miles
                //        return dist * 0.8684;
                //    case 'M': //Miles
                //        return dist;
                //}

                //return dist;

                var sCoord = new GeoCoordinate(double.Parse(lat1.ToString()), double.Parse(long1.ToString()));
                var eCoord = new GeoCoordinate(double.Parse(lat2.ToString()), double.Parse(lon2.ToString()));
                return Math.Round((sCoord.GetDistanceTo(eCoord) / 1000), 2);
                        }
            catch
            {
                return 0;
            }
        }
    }