Wednesday, June 29, 2016

Html Reporting

Print Preview 


http://etimbo.github.io/jquery-print-preview-plugin/example/index.html

Example




report.cshtml file


    <script src="http://kendo.cdn.telerik.com/2016.2.607/js/kendo.all.min.js"></script>
    <script src="~/assest/grid/Comman.js"></script>
    <script src="~/assest/grid/Reporting.js"></script>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div class="container" id="content">
    <h2 data-bind="text:Titile"></h2>
    <p data-bind="text:Date"> </p>
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody id="detailTableGrid">
         
        </tbody>
    </table>
    Total Amount <h3 data-bind="text:total"></h3>
</div>

<script type="text/x-kendo-template" id="booking-details">

                        # for(var key=0; key < data.e.Report.length; key++){#
                        <tr>
                            <td>
                                #= data.e.Report[key]["Id"] #
                            </td>
                            <td>
                                #= data.e.Report[key]["Name"] #
                            </td>
                            <td>
                                #= data.e.Report[key]["Address"] #
                            </td>
                            <td>
                                #= data.e.Report[key]["Payment"] #
                            </td>
                        </tr>

                        #}#

</script>

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

Reporting.ts file


/// <reference path="comman.ts" />

module Reporting {

    $(function () {

        new serverCaller().callservice("/Reporting/GetReportInfo", null).done(function (e) {

            console.log(e);

            const template = kendo.template($('#booking-details').html());
            var data: any = {
                e: e
            };
            var xxx: any = {
                total: getTotal(data.e.Report),
                Titile: data.e.ReportHeader.Titile ,
                Date : data.e.ReportHeader.Date 
            };
            kendo.bind($("#content"), xxx);
            $('#detailTableGrid').html(template(data));
        });


        function getTotal(e): number {

            var total: number = 0;
            $.each(e, function (i, d) {
                total += Number(d["Payment"]);
            });

            return total;
        }
    });

  
    class serverCaller extends JTypeScipt.apiConnector { }
}

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

Controller.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace XXXZX.Controllers
{
    public class ReportingController : Controller
    {
        // GET: Reporting
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetReportInfo() {

            return Json(new ReportRepo().GetReport(), JsonRequestBehavior.AllowGet);
        }
    }


    public class ReportRepo{


        public View GetReport() {

            Random rd = new Random();
            var x = new List<Report>();
            for (int i = 0; i < 5; i++)
            {
                x.Add(new Report {
                     Address = $"address {i}",
                     Id = i,
                     Name = $"name {i}",
                     Payment = rd.Next(100,500)
                });
            }

            return new View {
                Report = x,
                ReportHeader = new ReportHeader {
                    Date = DateTime.Today.ToShortDateString(),
                    Titile = "Simple Report",
                }
            };
        }

    }

    public class View {

        public ReportHeader ReportHeader { get; set; }
        public List<Report> Report { get; set;}
    }

    public class ReportHeader {

        public string Titile { get; set; }
        public string Date { get; set; }
    }

    public class Report {

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

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


Sample Json


{"ReportHeader":{"Titile":"Simple Report","Date":"6/29/2016"},"Report":[{"Id":0,"Name":"name 0","Address":"address 0","Payment":218},{"Id":1,"Name":"name 1","Address":"address 1","Payment":246},{"Id":2,"Name":"name 2","Address":"address 2","Payment":135},{"Id":3,"Name":"name 3","Address":"address 3","Payment":318},{"Id":4,"Name":"name 4","Address":"address 4","Payment":483}]}



Print Content




function printTicket() {
           var mywindow = window.open('', 'PRINT', 'height=400,width=600');
           mywindow.document.write('<html><head><title>' + document.title + '</title>');
 
           mywindow.document.write('</head><body>');
           mywindow.document.write($('#ticket-report').html());
           mywindow.document.write('</body></html>');
 
           mywindow.document.close(); // necessary for IE >= 10
           mywindow.focus(); // necessary for IE >= 10*/
 
           mywindow.print();
           mywindow.close();
           return true;
   }


Report Attachment as Email

nuget :
 HtmlRenderer.PdfSharp

[HttpGet]
      public FileResult GetTicketAttachmetPreview()
      {
          Byte[] res = null;
          using (MemoryStream ms = new MemoryStream())
          {
              var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.
GeneratePdf($"<html>{TempData["content"]}</html>", PdfSharp.PageSize.A4);
              pdf.Save(ms);
              res = ms.ToArray();
          }
          return File(res, System.Net.Mime.MediaTypeNames.Application.Octet, 
Guid.NewGuid() + ".pdf");
      }




Sunday, June 26, 2016

fluentmigrator


Name space

using FluentMigrator;



ADD COLOM AS SQL STATEMENT 


Execute.Sql(@" IF NOT EXISTS(SELECT * FROM sys.columns  WHERE Name = 'CreditCode' 
AND OBJECT_ID = OBJECT_ID('RecFacility'))
                  BEGIN
                      ALTER TABLE RecFacility
                      ADD   CreditCode VArchar(10)  NULL ;
                      END;");



Sample class model


using System;

using System.Collections.Generic;
using System.Text;
using FluentMigrator;
using System.Security.Cryptography;
using System.Reflection;

namespace WebDbMigrations.Migrations
{
    [Migration(16180)]
    public class Step16180 : FluentMigrator.Migration
    {

        public override void Up()
        {
            Update.Table("DatabaseInfo").Set(new { VersionID = "1.618.0" }).AllRows();
            System.Console.WriteLine("Running migration 1.618.0");

           
        }

        public override void Down()
        {
            Update.Table("DatabaseInfo").Set(new { VersionID = "1.617.0" }).AllRows();
        }

    }
}


create new table


 var existsPlastiqHostedPayment = Schema.Table("PlastiqHostedPayment").Exists();
            if (!existsPlastiqHostedPayment)
            {
                Create.Table("PlastiqHostedPayment")
                    .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
                    .WithColumn("TimeCreated").AsDateTime().NotNullable()
                    .WithColumn("Merchant").AsString(50).NotNullable()
                    .WithColumn("Plastiq").AsString(50).NotNullable()
                    .WithColumn("UserPlastiqEmail").AsString(250).NotNullable()
                    .WithColumn("UsersPlastiqId").AsString(50).NotNullable()
                    .WithColumn("CardName").AsString(50).NotNullable()
                    .WithColumn("CardBrand").AsString(50).NotNullable()
                    .WithColumn("Zip").AsString(50).NotNullable()
                    .WithColumn("Amount").AsDecimal().NotNullable()
                    .WithColumn("MerchantAmount").AsDecimal().NotNullable()
                    .WithColumn("PlastiqAmount").AsDecimal().NotNullable()
                    .WithColumn("TotalAmount").AsDecimal().NotNullable()
                    .WithColumn("WebTransId").AsInt32().NotNullable()
                    .WithColumn("UserId").AsAnsiString(10).Nullable()
                    .WithColumn("CustCode").AsAnsiString(8).Nullable();

                Create.ForeignKey("FK_PlastiqHostedPayment_Users")
                    .FromTable("PlastiqHostedPayment").InSchema("dbo").ForeignColumns("UserId")
                    .ToTable("Users").InSchema("dbo").PrimaryColumns("UserId");
            }


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



Create table and insert values 

 var existsTownSiteInfoPaymentsPlastiq = Schema.Table("TownSiteInfoPaymentsPlastiq").Exists();
            if (!existsTownSiteInfoPaymentsPlastiq)
            {
                Create.Table("TownSiteInfoPaymentsPlastiq")
                    .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
                    .WithColumn("Code").AsString(10).NotNullable()
                    .WithColumn("MerchantId").AsString(50).NotNullable()
                    .WithColumn("IsEnabled").AsBoolean().NotNullable();

                Insert.IntoTable("TownSiteInfoPaymentsPlastiq").Row(new {
                    Code = "REC",
                    MerchantId=-1,
                    IsEnabled = false
                });

                Insert.IntoTable("TownSiteInfoPaymentsPlastiq").Row(new
                {
                    Code = "CP",
                    MerchantId = -1,
                    IsEnabled = false
                });

            }


Update table value


Update.Table("DatabaseInfo").Set(new { VersionID = "1.560.0" }).AllRows();



Execute sql query


   Execute.Sql("insert into RoleAccess(RoleId, Tag) select 'Staff', Tag from RoleAccess where RoleId = 'Employee' and tag not in (select tag from RoleAccess where RoleId = 'Staff');");










Wednesday, June 15, 2016

Web Optimazation


GZip

public class CompressContentAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var response = HttpContext.Current.Response;
            if (response.IsRequestBeingRedirected) return;
            var encoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            var isSupported = !string.IsNullOrEmpty(encoding) && (encoding.Contains("gzip") || encoding.Contains("deflate"));
            if (isSupported)
            {
                var acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
                if (acceptEncoding.Contains("gzip"))
                {
                    response.Filter = new System.IO.Compression.GZipStream(response.Filter, System.IO.Compression.CompressionMode.Compress);
                    response.Headers.Remove("Content-Encoding");
                    response.AppendHeader("Content-Encoding", "gzip");
                }
                else
                {
                    response.Filter = new System.IO.Compression.DeflateStream(response.Filter, System.IO.Compression.CompressionMode.Compress);
                    response.Headers.Remove("Content-Encoding");
                    response.AppendHeader("Content-Encoding", "deflate");
                }


            }
            response.AppendHeader("Vary", "Content-Encoding");
        }
    }


// use
  [CompressContent]
        public ActionResult Details()
        {
            return this.RazorView();

        }

============================

use binders

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;

namespace TownSuiteWebPortals.App_Start
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
    
            bundles.Add(new ScriptBundle("~/bundles/loginpagescript").Include(
                "~/assets/javascript/notify.min.js",
                "~/assets/javascript/Encode-Decode.js",
                "~/assets/typescript/helpers_ts.js",
                "~/assets/typescript/tsmessage.js"));

            bundles.Add(new Bundle("~/bundles/loginpagestyle").Include(
               "~/assets/externals/tsbootstrap/tsbootstrap/app/css/bootstrap.css",
               "~/assets/externals/tsbootstrap/tsbootstrap/app/css/app.css"));
        }
    }
}
============= use
.cshtml

    @Styles.Render("~/bundles/loginpagestyle")

    @Scripts.Render("~/bundles/loginpagescript")





Manege large dataset in sql

Pass XML to the database using ADO

Table



CREATE TABLE [dbo].[Employee](
[ID] [int] NOT NULL,
[Name] [varchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


SP


CREATE PROCEDURE MY_XML
 @xml xml
AS
BEGIN
 INSERT INTO [dbo].[Employee]
      SELECT
      Customer.value('(ID/text())[1]','Int') AS Id, --TAG
      Customer.value('(Name/text())[1]','VARCHAR(100)') AS Name --TAG
      FROM
      @xml.nodes('/Customers/Customer')AS TEMPTABLE(Customer)
END
GO



xml File


<?xml version="1.0" standalone="yes"?>
 <Customers>
 <Customer>
    <ID>1</ID>
    <Name>Chamith</Name>
 </Customer>
   <Customer>
     <ID>4</ID>
     <Name>Saranga</Name>
 </Customer>
   <Customer>
     <ID>3</ID>
     <Name>Janson</Name>
   </Customer>
   <Customer>
     <ID>2</ID>
     <Name>Sajeeka</Name>
 </Customer>
</Customers>

C# Codes


static void UploadXML()
        {
            
            string xml = File.ReadAllText(@"E:\WB\back\2\WebPortals\ABCD\Customer.xml");
            string constr = @"Data Source=JET-DEV03\TOWNSUITE;Initial Catalog=MySP;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("MY_XML"))
                {
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@xml", xml);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

exact execution quay on db 

            exec MY_XML @xml=N'<?xml version="1.0" standalone="yes"?>
 <Customers>
 <Customer>
    <ID>1</ID>
    <Name>Chamith</Name>
 </Customer>
   <Customer>
     <ID>4</ID>
     <Name>Saranga</Name>
 </Customer>
   <Customer>
     <ID>3</ID>
     <Name>Janson</Name>
   </Customer>
   <Customer>
     <ID>2</ID>
     <Name>Sajeeka</Name>
 </Customer>
</Customers>'

=============================


Execute Table structure on database 

Table



CREATE TABLE [dbo].[Employee](
[ID] [int] NOT NULL,
[Name] [varchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

create customer type


-- Create the data type
CREATE TYPE CustomerType AS TABLE 
(
Id int,
Name varchar(50)
);
GO

SP


CREATE PROCEDURE sp_passtable
@CustomerT  as CustomerType   READONLY
AS
BEGIN
 
insert into [dbo].[Employee]
select Id,Name from @CustomerT;

END

GO


C# Code 

 static void UpdateDataTable() { 

        

            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            for (int i = 10; i < 15; i++)
            {
                dt.Rows.Add(i,$"name {i}");
  
            }
            string constr = @"Data Source=JET-DEV03\TOWNSUITE;Initial Catalog=MySP;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("sp_passtable"))
                {
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter parameter = new SqlParameter();
 
                    parameter.ParameterName = "@CustomerT";
                    parameter.SqlDbType = System.Data.SqlDbType.Structured;
                    parameter.Value = dt;
                    cmd.Parameters.Add(parameter);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

exact execution quay on db 

     
            declare @p1 dbo.CustomerType
                insert into @p1 values(N'0',N'name 0')
                insert into @p1 values(N'1',N'name 1')
                insert into @p1 values(N'2',N'name 2')
                insert into @p1 values(N'3',N'name 3')
                insert into @p1 values(N'4',N'name 4')
                insert into @p1 values(N'5',N'name 5')
                insert into @p1 values(N'6',N'name 6')
                insert into @p1 values(N'7',N'name 7')
                insert into @p1 values(N'8',N'name 8')
                insert into @p1 values(N'9',N'name 9')

                exec sp_passtable @CustomerT=@p1
          


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>








CS Events