Tuesday, June 14, 2016

Google Map


<!DOCTYPE html>
<html>
<head>
    <title>Leaflet Layers Control Example</title>
    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
</head>
<body>
    <div id="map" style="width: 600px; height: 400px"></div>

    <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
    <script>

        
var cities = new L.LayerGroup();

var changeCoordinate = 0;
for (var i = 0; i < 10; i++) {

   L.marker([39.74 + changeCoordinate, -104.99 + changeCoordinate]).bindPopup('info ' + i).addTo(cities);
   changeCoordinate += 0.1;
}
         
   var mbAttr = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw';

   var grayscale   = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}),
   streets  = L.tileLayer(mbUrl, {id: 'mapbox.streets',   attribution: mbAttr});

var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
layers: [grayscale, cities]
});

var baseLayers = {
"Grayscale": grayscale,
"Streets": streets
};

var overlays = {
"Cities": cities
};

L.control.layers(baseLayers, overlays).addTo(map);

        
    </script>
</body>
</html>



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

Google map for multiple dragable location




<html xmlns="http://www.w3.org/1999/xhtml"><head>
  </head>
<body>
 
    <form method="post" action="" id="aspnetForm">
 
 
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    var markers = [
        {
            "title": 'Alibaug',
            "lat": '18.641400',
            "lng": '72.872200',
            "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
        },
        {
            "title": 'Lonavla',
            "lat": '18.750000',
            "lng": '73.416700',
            "description": 'Lonavla'
        },
        {
            "title": 'Mumbai',
            "lat": '18.964700',
            "lng": '72.825800',
            "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
        },
        {
            "title": 'Pune',
            "lat": '18.523600',
            "lng": '73.847800',
            "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
        },
        {
            "title": 'Thane',
            "lat": '19.182800',
            "lng": '72.961200',
            "description": 'Thane'
        },
        {
            "title": 'Vashi',
            "lat": '18.750000',
            "lng": '73.033300',
            "description": 'Vashi'
        }
    ];
    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var infoWindow = new google.maps.InfoWindow();
        var latlngbounds = new google.maps.LatLngBounds();
        var geocoder = geocoder = new google.maps.Geocoder();
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
loadMakers();
        
        var bounds = new google.maps.LatLngBounds();
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);
google.maps.event.addListener(map, 'click', function(event) {
       
alert(event.latLng);
 markers.push({ 
   titile:"",
description:"",
"lat": '28.750000',
            "lng": '71.033300',
 });
 loadMakers();
          //addMarker(event.latLng, map);
        });
function addMarker(location, map) {
var marker = new google.maps.Marker({
 position: location,
 label: labels[labelIndex++ % labels.length],
 map: map
});
    }
function loadMakers() {
for (var i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title,
                draggable: true,
                animation: google.maps.Animation.DROP
            });
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
                google.maps.event.addListener(marker, "dragend", function (e) {
                    var lat, lng, address;
                    geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            lat = marker.getPosition().lat();
                            lng = marker.getPosition().lng();
                            address = results[0].formatted_address;
                            console.log("Latitude: " + lat + "\nLongitude: " + lng + "\nAddress: " + address);
                        }
                    });
                });
            })(marker, data);
            latlngbounds.extend(marker.position);
        }
}
 }
</script>
<div id="dvMap" style="width: 500px; height: 500px; position: relative; overflow: hidden; background-color: rgb(229, 227, 223);">
  
 <table>
 <tr>
   <td> </td>
 </tr>
</table> 
  
</div>

</body></html>








Bootsrap Essential

Bootstrap Grid System

Bootstrap's grid system allows up to 12 columns across the page.
If you do not want to use all 12 column individually, you can group the columns together to create wider columns:
span 1span 1span 1span 1span 1span 1span 1span 1span 1span 1span 1span 1
 span 4 span 4 span 4
span 4span 8
span 6span 6
span 12


Grid Classes

The Bootstrap grid system has four classes:
  • xs (for phones)
  • sm (for tablets)
  • md (for desktops)
  • lg (for larger desktops)

Grid System Rules

Some Bootstrap grid system rules:
  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding
  • Use rows to create horizontal groups of columns
  • Content should be placed within columns, and only columns may be immediate children of rows
  • Predefined classes like .row and .col-sm-4 are available for quickly making grid layouts
  • Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows
  • Grid columns are created by specifying the number of 12 available columns you wish to span. For example, three equal columns would use three .col-sm-4

Basic Structure of a Bootstrap Grid

The following is a basic structure of a Bootstrap grid:
<div class="container">
  <div class="row">
    <div class="col-*-*"></div>
  </div>
  <div class="row">
    <div class="col-*-*"></div>
    <div class="col-*-*"></div>
    <div class="col-*-*"></div>
  </div>
  <div class="row">
    ...
  </div>
</div>
So, to create the layout you want, create a container (<div class="container">). Next, create a row (<div class="row">). Then, add the desired number of columns (tags with appropriate .col-*-* classes). Note that numbers in .col-*-* should always add up to 12 for each row.


Two Columns With Two Nested Columns

The following example shows how to get two columns starting at tablets and scaling to large desktops, with another two columns (equal widths) within the larger column (at mobile phones, these columns and their nested columns will stack):

Example

<div class="row">
  <div class="col-sm-8">
    .col-sm-8
    <div class="row">
      <div class="col-sm-6">.col-sm-6</div>
      <div class="col-sm-6">.col-sm-6</div>
    </div>
  </div>
  <div class="col-sm-4">.col-sm-4</div>
</div>

Mixed: Mobile And Desktop

The Bootstrap grid system has four classes: xs (phones), sm (tablets), md (desktops), and lg (larger desktops). The classes can be combined to create more dynamic and flexible layouts.
Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.

Example

<div class="row">
  <div class="col-xs-9 col-md-7">.col-xs-9 .col-md-7</div>
  <div class="col-xs-3 col-md-5">.col-xs-3 .col-md-5</div>
</div>

<div class="row">
  <div class="col-xs-6 col-md-10">.col-xs-6 .col-md-10</div>
  <div class="col-xs-6 col-md-2">.col-xs-6 .col-md-2</div>
</div>

<div class="row">
  <div class="col-xs-6">.col-xs-6</div>
<  div class="col-xs-6">.col-xs-6</div>
</div>

Mixed: Mobile, Tablet And Desktop

Example

<div class="row">
  <div class="col-xs-7 col-sm-6 col-lg-8">.col-xs-7 .col-sm-6 .col-lg-8</div>
  <div class="col-xs-5 col-sm-6 col-lg-4">.col-xs-5 .col-sm-6 .col-lg-4</div>
</div>

<div class="row">
  <div class="col-xs-6 col-sm-8 col-lg-10">.col-xs-6 .col-sm-8 .col-lg-10</div>
  <div class="col-xs-6 col-sm-4 col-lg-2">.col-xs-6 .col-sm-4 .col-lg-2</div>
</div>

Monday, June 13, 2016

Json Result return override

   return new JsonContractResult { Data = new { data = facilityDetails }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

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


public class JsonContractResult : JsonResult
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonContractResult"/> class.
        /// </summary>
        public JsonContractResult()
        {
            JsonRequestBehavior = JsonRequestBehavior.DenyGet;
        }

        /// <summary>
        /// Gets or sets the content encoding.
        /// </summary>
        /// <value>The content encoding.</value>
        private new Encoding ContentEncoding { get; set; }

        /// <summary>
        /// Gets or sets the type of the content.
        /// </summary>
        /// <value>The type of the content.</value>
        private new string ContentType { get; set; }

        /// <summary>
        /// Gets or sets the data.
        /// </summary>
        /// <value>The data.</value>
        public new object Data { private get; set; }

        /// <summary>
        /// Gets or sets a value that indicates whether HTTP GET requests from the client are allowed.
        /// </summary>
        /// <value>The json request behavior.</value>
        public new JsonRequestBehavior JsonRequestBehavior { get; set; }

        /// <summary>
        /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult" /> class.
        /// </summary>
        /// <param name="context">The context within which the result is executed.</param>
        /// <exception cref="System.ArgumentNullException">context</exception>
        /// <exception cref="System.InvalidOperationException">This request has been blocked.</exception>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("This request has been blocked.");
            }
            HttpResponseBase response = context.HttpContext.Response;
            if(response.StatusCode == 403) throw new UnauthorizedAccessException();
            response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data == null) return;
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            response.Write(JsonConvert.SerializeObject(Data, Formatting.Indented, jsonSerializerSettings));
        }
    }

Monday, June 6, 2016

Pass Json Array/ List Any things to the server


Must Have HttpPost


Controller



 public class MyObjectPassController : Controller
    {
        // GET: Facility/MyObjectPass
        [HttpPost]
        public JsonResult Index(Request rq)
        {
            return Json(rq,JsonRequestBehavior.AllowGet);
        }
    }
    
    public class Request {

        public int RequestId { get; set; }
        public List<Person> Persons { get; set; }
        public List<Departments> Departments { get; set; }
        public List<string> OtherNames { get; set; }

    }
    public class Departments
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Person {

        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int DepId { get; set; }
    }

//////////////

Ts File


module PassObjectArray {
    $(document).ready(function () {

        var dep: Departments[] = [];
        var persons: Person[] = [];
        var otherNames: string[] = [];
        for (var index = 0; index < 5; index++) {

            dep.push({ Id: index, Name: "dep_" + index });
        }

        for (var index = 0; index < 5; index++) {
            persons.push({ Id: index, Name: "per_" + index, Age: index, DepId: 5 });
        }
        for (var index = 0; index < 10; index++) {
            otherNames.push("otherNames_" + index);
        }
        console.log(JSON.stringify({ RequestId: 1, Persons: persons, Departments: dep }));

        $.ajax({
            url: '/facility/MyObjectPass/Index',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            method: "POST",
            data: JSON.stringify({ RequestId: 1, Persons: persons, Departments: dep, OtherNames: otherNames }),
            success: (s) => {
                $('div').html(s);

            }
        });

    });
    class Departments {
        Id: number;
        Name: string;
    }

    class Person {

        Id: number;
        Name: string;
        Age: number;
        DepId: number;
    }

}

Web SQL

<!DOCTYPE HTML>
<html>

   <head>

      <script type="text/javascript">
 
         var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
         var msg;
 
         db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
            msg = '<p>Log message created and row inserted.</p>';
            document.querySelector('#status').innerHTML =  msg;
         });

         db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
               var len = results.rows.length, i;
               msg = "<p>Found rows: " + len + "</p>";
               document.querySelector('#status').innerHTML +=  msg;
   
               for (i = 0; i < len; i++){
                  msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
                  document.querySelector('#status').innerHTML +=  msg;
               }
            }, null);
         });
 
      </script>
 
   </head>

   <body>
      <div id="status" name="status">Status Message</div>
   </body>

</html>

Sunday, June 5, 2016

Auto Mapper


Nuget
Install-Package AutoMapper -Version 4.2.1

namespace :

using AutoMapper;

Must register dual ways.
Mapper.CreateMap<StudentBo, StudentViewModel>();
       Mapper.CreateMap<StudentViewModel, StudentBo>();

Bean Class

From
 public class Customer {

        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

To
  public class CustomerModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }

        public string Unique { get; set; }
    }



Simple Object Mapping

 public JsonResult SaveCustomer() {

            Customer c = new Customer
            {
                Name = "Chamith",
                Address = "Ganemulla"
            };

            // create map
            Mapper.CreateMap<Customer, CustomerModel>();

            // create object
            CustomerModel cc = Mapper.Map<CustomerModel>(c);
             
            return Json(cc,JsonRequestBehavior.AllowGet);
  }

List Mapping
  public JsonResult SaveCustomer2()
        {

            List<Customer> c = new List<Customer>
            {
                new Customer {
                Name = "Chamith",
                Address = "Ganemulla" },
                 new Customer {
                Name = "Kasun",
                Address = "Singa" },
                  new Customer {
                Name = "Sajee",
                Address = "Kandana" }
            };

           // Normal way 
            List<CustomerModel> cc = c.Select(x => new CustomerModel
            {
                Address = x.Address,
                Id = x.Id,
                Name = x.Name

            }).ToList();

          
            //Automapper way
            //Create a map
            Mapper.CreateMap<Customer, CustomerModel>();

            //create destination object using map
            List<CustomerModel> cc2 = c.Select(x =>                  AutoMapper.Mapper.Map<CustomerModel>(x)).ToList();
        


            return Json(cc2, JsonRequestBehavior.AllowGet);

        }

Map with Extra attributes
   public JsonResult SaveCustomer() {

            Customer c = new Customer
            {
                Name = "Chamith",
                Address = "Ganemulla"
            };

            // create map with extra attribute 
            Mapper.CreateMap<Customer, CustomerModel>()
                .ForMember(des => des.Unique, p2 => p2.MapFrom(sou                    => $"{sou.Id}_{sou.Name}"));

            // create object
            CustomerModel cc = Mapper.Map<CustomerModel>(c);
             
            return Json(cc,JsonRequestBehavior.AllowGet);

        }


}

Map List with Extra Items



 Mapper.CreateMap<ApprovalsData, FacilityApprovalsDataViewModel>()
                    .ForMember(des => des.StatusInfo, p2 => p2.MapFrom(sou => $"{((sou.IsApproved)?1:0)}%{(sou.IsRejected?1:0)}"));
               
                var data = response.ApprovalsData.Select(x => AutoMapper.Mapper.Map<FacilityApprovalsDataViewModel>(x)).ToList();

Enable Reverse Mapping

Mapper.CreateMap<SimpleLookupDetailsViewModelSimpleLookupDetailView>().ReverseMap();






Friday, June 3, 2016

Comman Ts


module JTypeScipt {

    $(document).ready(function () {
       

    });

    export class form {

        bindValues(val) {
            var f = new form();
            new apiConnector().callservice('/TTT/GetPosts', { begin: val })
                .done(function (data) {

                    console.log(data);

                }).fail(function () {
                    console.log('error');
                });
        }
    }

    export class apiConnector {

        callservice(url: string, data: any): JQueryDeferred<any> {
            var dfd = jQuery.Deferred();
            $.ajax({
                url: url,
                method: "GET",
                contentType: "application/json; charset=utf-8",
                data: data,
                dataType: "json",
                cache: false,
                success: function (data) {
                    var value = data;
                    dfd.resolve(value);
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log(textStatus);
                    dfd.reject();
                }
            });
            return dfd;
        }
    }

    export enum EMessageType {

        success = 0,
        error = 1,
        warning = 2

    }

    export class messages {
        
        getMessageType(msgType: EMessageType) {

            let message = "success";
            switch (msgType) {
                case EMessageType.success:
                    message = "success";
                    break;
                case EMessageType.error:
                    message= "error";
                    break;
                case EMessageType.warning:
                    message = "warning";
                    break;
            }
            return message;
        }

        basicMessage(text: string) {
            swal(text);
        }

        okMessage(title: string="success", text: string="") {
            swal(title, text);
        }

        messages(title: string, text: string, type: EMessageType) {
            swal(title, text, this.getMessageType(type));
        }

        successMessage(title: string="Success", text: string="") {
            swal(title, text, "success");
        }

        timeMessage(title: string="success", text: string="", timer: number=2000) {
            swal({ title: title, text: text, timer: timer, showConfirmButton: false });
        }
        errorMessage(title: string="error", text: string="") {
            sweetAlert(title, text);
        }

        confirmMessage(title: string = "are you sure", text: string = "", confirmButtonText: string = "Yes", cancelButtonText: string = "No", type: EMessageType) {

            swal({
                title: title,
                text: text,
                type: this.getMessageType(type),
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: confirmButtonText,
                cancelButtonText: cancelButtonText,
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                 if (isConfirm) { return true; }
                 else { return false; }
                });
        }
    }
     
    export class googleMap {

        initGoogleMap(lat: number, lan: number, info: string, elementId: string, mapType: google.maps.MapTypeId = google.maps.MapTypeId.ROADMAP) {

            const prop = {
                center: new google.maps.LatLng(lat, lan),
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                panControl: false,
                zoomControl: true,
                scrollwheel: false,
                mapTypeControl: true,
                scaleControl: true,
                streetViewControl: true,
                overviewMapControl: false
            };
            var marker = new google.maps.Marker({
                position: prop.center,
                animation: google.maps.Animation.DROP
            });
            var map = new google.maps.Map(<HTMLInputElement>$('#' + Location)[0], prop);
            marker.setMap(map);
           
            var infowindow = new google.maps.InfoWindow({
                content: info
            });

            google.maps.event.addListenerOnce(map, 'tilesloaded', () => {
                infowindow.open(map, marker);
            });
        }
    }
}

Sql server row level policy