Thursday, 3 August 2017

All check box check on click one check box in JQUERY




Html:
<input class='allcheck'  name="check_all" type='checkbox' />All check box


<input class='check'   type='checkbox' />on
<input class='check'   type='checkbox' />of
<input class='check'   type='checkbox' />yes

Jquery function:
 <script>

        $(document).on('click change', 'input[name="check_all"]', function () {
            var checkboxes = $('.check');
            if ($(this).is(':checked')) {
                checkboxes.each(function () {
                    this.checked = true;
                });
            } else {
                checkboxes.each(function () {
                    this.checked = false;
                });
            }
        });
    </script>

Wednesday, 2 August 2017

Image upload, Crop, rotate and Resize( PDF file convert into Image) in VB.net

Html
===================================================================

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="CroprResizeJquery.aspx.vb" Inherits="CropResizeImgInVB.CroprResizeJquery" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
             <%-- Now I Will add some js & css file Here. This is required for select crop area --%>
            <%-- you can download this Jcrop.css & jquery.Jcrop.js file from Here : https://github.com/tapmodo/Jcrop --%>
         
              <link href="Scripts/Jcrop.css" rel="stylesheet" />
              <script src="Scripts/jquery-1.10.2.min.js"></script>          
              <script src="Scripts/Jcrop.js"></script>
              <script src="Scripts/pdf.js"></script>
              <script src="Scripts/pdf.worker.js"></script>
         
            <script language="javascript">
                $(document).ready(function () {
                    $('#<%=imgUpload.ClientID%>').Jcrop({
                        onSelect: SelectCropArea
                    });  
                });
                function SelectCropArea(c) {                  
                    $('#<%=X.ClientID%>').val(parseInt(c.x));
                    $('#<%=Y.ClientID%>').val(parseInt(c.y));
                    $('#<%=W.ClientID%>').val(parseInt(c.w));
                    $('#<%=H.ClientID%>').val(parseInt(c.h));
                    $('#<%=btnCrop.ClientID%>').prop('disabled', false);
                   
                }
         
                function uploadimg(input) {    
                      PDFJS.disableWorker = true;
                      var pdf = $('#FU1');
                      var url = input.value;
                      var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                      if (ext == "pdf") {
                         if (file = input.files[0]) {
                             alert("File upload")
                             fileReader = new FileReader();
                             fileReader.onload = function (input) {                              
                                 PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {                                
                                    // Fetch the first page                                                            
                                     pdf.getPage(1).then(function getPageHelloWorld(page) {
                                         var scale = 1.5;
                                         var viewport = page.getViewport(scale);                                    
                                         // Prepare canvas using PDF page dimensions                                  
                                         var canvas = document.getElementById('thecanvas');
                                         var context = canvas.getContext('2d');
                                         canvas.height = viewport.height;
                                         canvas.width = viewport.width;                                      
                                         // Render PDF page into canvas context
                                         var task = page.render({ canvasContext: context, viewport: viewport })
                                         task.promise.then(function () {
                                             var block = canvas.toDataURL('image/jpeg').split(";");
                                             // Get the content type of the image
                                             var contentType = block[0].split(":")[1];// In this case "image/gif"
                                             // get the real base64 content of the file
                                             var realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."
                                             //Save base 64 into hidden file
                                             $('#<%=hdnpdfimgurl.ClientID%>').val(realData);
                                             //click btn
                                             $('#<%=SavePdfImg.ClientID%>').click();
                                         });
                                     });
                                 }, function (error) {
                                     console.log(error);
                                 });
                             };
                             fileReader.readAsArrayBuffer(file);
                         }
                     }
                     else
                     {
                                 $('#<%=btnUpload.ClientID%>').click();  
                     }
                                                       
                }
            </script>


</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3>Image Upload, Crop & Save using VB.NET & Jquery</h3>      
        <canvas id="thecanvas" style="display:none"></canvas>    
        <asp:Button  runat="server" ID="SavePdfImg" Style="display:none" OnClick="SavePdfImg_Click"/>
        <asp:HiddenField runat="server" ID="hdnpdfimgurl"/>
       
     
                <%-- HTML Code --%>
                <table>
                    <tr>
                        <td>
                            Select Image File :
                        </td>
                        <td>
                            <asp:FileUpload ID="FU1" runat="server"  onChange="uploadimg(this)" />
                            <asp:Button ID="btnUpload" runat="server" style="display:none" OnClick="btnUpload_Click" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <asp:Label ID="lblMsg" runat="server" ForeColor="green" />
                        </td>
                    </tr>
                </table>
                <asp:Panel ID="panCrop" runat="server" Visible="false">
                    <table>
                        <tr>
                            <td><div runat="server" id="rotatediv" visible="false" style="text-align: right;"><asp:Button runat="server" ID="rotatebtn" OnClick="rotatebtn_Click" Text="rotate"/></div>                        
                                <asp:Image ID="imgUpload"   runat="server" BorderStyle="ridge" />  
                               <div id="dimensions" runat="server" visible="false" style="text-align: center; margin-top: 11px;"><span id="width" runat="server"></span>x<span id="height" runat="server"></span></div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Button ID="btnCrop" Enabled="false" runat="server" Text="Crop & Save" OnClick="btnCrop_Click"  />                          
                            </td>
                        </tr>                      
                        <tr>
                            <td>
                                <%-- Hidden field for store cror area --%>
                                <asp:HiddenField ID="X" runat="server" />
                                <asp:HiddenField ID="Y" runat="server" />
                                <asp:HiddenField ID="W" runat="server" />
                                <asp:HiddenField ID="H" runat="server" />
                            </td>
                        </tr>                    
                    </table>
                </asp:Panel>    
    </div>
     
    </form>
</body>

</html>

=================================================================
 Code file
=================================================================

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Net

Public Class CroprResizeJquery
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub btnUpload_Click(sender As Object, e As EventArgs)

        ' Upload Original Image Here
        Dim uploadFileName As String = ""
        Dim uploadFilePath As String = ""
        If FU1.HasFile Then
            Dim ext As String = Path.GetExtension(FU1.FileName).ToLower()
            If (ext = ".jpg" Or ext = ".jpeg" Or ext = ".gif" Or ext = ".png") Then
                uploadFileName = Guid.NewGuid().ToString() + ext
                uploadFilePath = Path.Combine(Server.MapPath("~/Images"), uploadFileName)
                FU1.SaveAs(uploadFilePath)
                imgUpload.ImageUrl = "~/Images/" + uploadFileName
                panCrop.Visible = True
            Else
                lblMsg.Text = "In signature only jpg,jpeg,gif,png and Pdf"
            End If
        End If
    End Sub

    Protected Sub SavePdfImg_Click(sender As Object, e As EventArgs)

        Dim base64String As String = hdnpdfimgurl.Value
        Dim uploadFileName As String = Guid.NewGuid().ToString() + "GK.png"
        Dim uploadFilePath As String = Path.Combine(Server.MapPath("~/Images"), uploadFileName)

        'Convert Base64 Encoded string to Byte Array.
        Dim imageBytes As Byte() = Convert.FromBase64String(base64String)

        'Save the Byte Array as Image File.
        File.WriteAllBytes(uploadFilePath, imageBytes)
        imgUpload.ImageUrl = "~/Images/" + uploadFileName
        panCrop.Visible = True


    End Sub

    Protected Sub btnCrop_Click(sender As Object, e As EventArgs)
        'Crop Image Here & Save
        Dim fileName As String = Path.GetFileName(imgUpload.ImageUrl)
        Dim filePath As String = Path.Combine(Server.MapPath("~/Images"), fileName)

        Dim cropFileName As String = ""
        Dim cropFilePath As String = ""
        If (File.Exists(filePath)) Then
            Dim orgImg As Image = Image.FromFile(filePath)
            Dim CropArea As New Rectangle(Convert.ToInt32(X.Value),
                        Convert.ToInt32(Y.Value),
                        Convert.ToInt32(W.Value),
                        Convert.ToInt32(H.Value))

            Dim Bitmap As Bitmap = New Bitmap(CropArea.Width, CropArea.Height)
            Using g As Graphics = Graphics.FromImage(Bitmap)
                g.DrawImage(orgImg, New Rectangle(0, 0, Bitmap.Width, Bitmap.Height), CropArea, GraphicsUnit.Pixel)
            End Using

            filePath = ""
            cropFileName = "crop_" & fileName
            cropFilePath = Path.Combine(Server.MapPath("~/Images"), cropFileName)
            Bitmap.Save(cropFilePath)
            ' Toolkit.Imaging.ResizeImage(Server.MapPath("~/Images/" & cropFileName), 336, 144)
            'CropSaveImg.ImageUrl = "~/Images/" + cropFileName
            imgUpload.ImageUrl = "~/Images/" + cropFileName
            width.InnerText = W.Value
            height.InnerText = H.Value
            dimensions.Visible = True
            rotatediv.Visible = True

            'File.Delete(Path.Combine(Server.MapPath("~/Images"), fileName))
            lblMsg.Text = "Image Crop successfully"

        End If

    End Sub

    Protected Sub rotatebtn_Click(sender As Object, e As EventArgs)

        'get the path to the image
        Dim path As String = Server.MapPath(imgUpload.ImageUrl)

        'create an image object from the image in that path
        Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(path)
        'rotate the image
        img.RotateFlip(RotateFlipType.Rotate90FlipNone) ' .Rotate90FlipXY)

        'save the image out to the file
        img.Save(path)
        width.InnerText = img.Width
        height.InnerText = img.Height

        'release image file
        img.Dispose()
    End Sub
End Class

'ElseIf 
'    Dim url As String = "http://localhost:54435/Images/" + uploadFileName
'    System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "Script", "imgtopdf('" + url + "');", True)

Wednesday, 26 July 2017

Bytes save and download as PDF in web API


In this obj.ValueType is a base 64 data Firstly we have to convert base 64 into Byte[] after that save in a folder or also direct download without saving the pdf file.


  public HttpResponseMessage updateprofileImage(info obj)
        {
            var httpRequest = HttpContext.Current.Request;
            string fileOriginalPath = "~/FileUploaded";
            var file64 = obj.ValueType;// httpRequest.Form[0];

            string strTutorImg = string.Empty;

            if (!string.IsNullOrEmpty(file64))
            {
                /*where you need to save 64 file*/
                string Base64file;
                Base64file = DateTime.UtcNow.Ticks + "-" + "base64-" + "decod.pdf";
                var filepath1 = httpRequest.MapPath(fileOriginalPath);
                /*end here */

                /*Convert base64 file into pdf file start here*/
                Byte[] bytes2 = Convert.FromBase64String(file64);

                //save into folder
                filepath1 = Path.Combine(filepath1, System.IO.Path.GetFileName(Base64file));
                File.WriteAllBytes(filepath1, bytes2);

                //direct download 
                HttpContext.Current.Response.Clear();
                MemoryStream ms = new MemoryStream(bytes2);
                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition",                 "attachment;filename=labtest.pdf");
                HttpContext.Current.Response.Buffer = true;
                ms.WriteTo(HttpContext.Current.Response.OutputStream);
                HttpContext.Current.Response.End();

             
                /*End here*/

                /*if you need to save this base64 into database so save this variable value=>   file64*/

            }
            return Request.CreateResponse(HttpStatusCode.OK, file64); ;
        }

Monday, 24 July 2017

Base64 Encode and Decode any file in web api.


Base64 Encode and Decode  any file using Postman and web API





namespace
===============================
using System.Net.Http;
using System.Web;
using System.Web.Http;



Action
===============================
        [HttpPost]
        public HttpResponseMessage updateprofileImage()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            var httpRequest = HttpContext.Current.Request;
            string FileName1 = string.Empty;
            string base64 = string.Empty;
            String file64 = string.Empty;
            if (httpRequest.Files.Count > 0)
            {
                HttpPostedFile file = httpRequest.Files[0];
                string fileOriginalPath = string.Empty;
                fileOriginalPath = "~/FileUploaded";
                string strTutorImg = string.Empty;

                if (file != null)
                {
                    string Customerfile;
                    Customerfile = DateTime.UtcNow.Ticks + "-" + 'C' + "-" + file.FileName;

                    var filepath = httpRequest.MapPath(fileOriginalPath);
                    var base63 = httpRequest.MapPath(base64);
                    if (!Directory.Exists(filepath))
                        Directory.CreateDirectory(filepath);
                    filepath = Path.Combine(filepath, System.IO.Path.GetFileName(Customerfile));
                    file.SaveAs(filepath);

                    /*Convert Pdf into base64 formate start here(Encode)*/
                    Byte[] bytes = File.ReadAllBytes(filepath);
                    file64 = Convert.ToBase64String(bytes);
                    /*end here*/

                    /*where you need to save 64 file*/
                    string Base64file;
                    Base64file = DateTime.UtcNow.Ticks + "-" + "base64-" + "decod.pdf";
                    var filepath1 = httpRequest.MapPath(fileOriginalPath);
                    filepath1 = Path.Combine(filepath1, System.IO.Path.GetFileName(Base64file)); 
                    /*end here */

                    /*Convert base64 file into pdf file start here(Decode)*/
                    Byte[] bytes2 = Convert.FromBase64String(file64);               
                    File.WriteAllBytes(filepath1, bytes2);
                    /*End here*/


                    FileName1 = file.FileName;
                    var CustomerImage1 = Customerfile;
                }
            }
            return Request.CreateResponse(HttpStatusCode.OK, file64); ;
        }

Pass Base64 data(Img,pdf,etc) into web API using Postman.




Decode base64 to pdf in web API





Web API:=>


NameSpace
==========================================================
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

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

        #region Upload Base64 formate and save into database and folder.
        [HttpPost]
        public HttpResponseMessage updateprofileImage()
        {          
                var httpRequest = HttpContext.Current.Request;  
                string fileOriginalPath = "~/FileUploaded";
                var file64 = httpRequest.Form[0];
           
                string strTutorImg = string.Empty;
           
                if (!string.IsNullOrEmpty(file64))
                {                        
                    /*where you need to save 64 file*/
                    string Base64file;
                    Base64file = DateTime.UtcNow.Ticks + "-" + "base64-" + "decod.pdf";
                    var filepath1 = httpRequest.MapPath(fileOriginalPath);
                    filepath1 = Path.Combine(filepath1, System.IO.Path.GetFileName(Base64file));
                    /*end here */

                    /*Convert base64 file into pdf file start here*/                  
                    Byte[] bytes2 = Convert.FromBase64String(file64);                   
                    File.WriteAllBytes(filepath1, bytes2);
                /*End here*/

                /*if you need to save this base64 in to database so save  this variable value=>   file64*/

            }
            return Request.CreateResponse(HttpStatusCode.OK, file64); ;
        }

        #endregion

Thursday, 22 June 2017

IntelliSense for angular in visual studio

There 3 simple steps to get better IntelliSense for angular in visual studio

Step 1: Download AngularJS extension for Visual Studio from the following link. The link displays the script in a web page.

https://raw.githubusercontent.com/jmbledsoe...

Step 2: Copy and paste the script into a new notepad. Name it angular.intellisense.js and save it to the following folder on your computer
C:\Program Files (x86)\Microsoft Visual Studio 12.0\JavaScript\References
Step 3 : Now drag and drop the following 2 files from Scripts folder onto script.js file
angular.min.js
angular-route.min.js

Visual Studio will automatically add references to the above 2 files in script.js
/// [reference path="angular.min.js" /]
/// [reference path="angular-route.min.js" /]


like this:

/// <reference path="angular.js" />
/// <reference path="angular-route.js" />

  var app = angular.module("demo", ["ngRoute"])

routing in angular js

Routing in Angular js and remove # in URL


Main.js:

  var app = angular
            .module("demo", ["ngRoute"])
            .config(function ($routeProvider, $locationProvider) {
                <!--$routeProvider.caseInsensitiveMatch = true;-->
                $routeProvider
                    .when("/home", {
                        templateUrl: "UI/home.html",
                        controller: "homeController"
                    })
                    .when("/courses", {
                        templateUrl: "UI/courses.html",
                        controller: "coursesController"
                    })
                    .when("/students", {
                        templateUrl: "UI/students.html",
                        controller: "studentsController"
                    })
                   .when("/students/:id", {    <!--using a parameter in routing-->
                         templateUrl: "/UI/studentsdetails.html",
                         controller: "studentsdetailsController"
                     })
                    .otherwise({
                        redirectTo: "/home"
                    })
                $locationProvider.html5Mode(true);
            })
            .controller("homeController", function ($scope) {
                $scope.message = "Home Page";
            })
            .controller("coursesController", function ($scope) {
                $scope.message = "courses Page";            
            })
            .controller("studentsController", function ($scope) {
                 $scope.message = "Student Page";          
             })
           .controller("studentsdetailsController", function ($scope, $routeParams) {
           $scope.message = "Student details Page" + $routeParams.id;  <!--get a parameter value -->       
             }

Index.html :


<!DOCTYPE html>
<html ng-app="demo">
<head>
    <title></title>
<meta charset="utf-8" />
     <base href="/" />      <!--this base href is alwase top of style sheets and js file --> 
    <script src="RoutingApp/angular.js"></script>
    <script src="RoutingApp/angular-route.js"></script>
    <script src="RoutingApp/main.js"></script>
    <link href="RoutingApp/Styles.css" rel="stylesheet" />  

</head>
<body>
    <table style="font-family: Arial">
        <tr>
            <td colspan="2" class="header">
                <h1>
                    WebSite Header
                </h1>
            </td>
        </tr>
        <tr>
            <td class="leftMenu">
                <a href="home">Home</a>
                <a href="courses">Courses</a>
                <a href="students">Students</a>
               <a href="students/1">Students using param</a> <!--pass a parameter in url -->
            </td>
            <td class="mainContent">
                <ng-view></ng-view>
            </td>
        </tr>
        <tr>
            <td colspan="2" class="footer">
                <b>Website Footer</b>
            </td>
        </tr>
    </table>
</body>

</html>


Partial HTML Pages:

home.html:

<h1>{{message}}</h1>

courses.html:

<h1>{{message}}</h1>

studentsdetails.html:

<h1>{{message}}</h1>

student.html:

<h1>{{message}}</h1>
Write a rules in Web config:

<system.webServer>
   <!--Routing URl rules start here-->
  <rewrite>
    <rules>
      <rule name="RewriteRules" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
        </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
   <!--Routing URl rules End here-->
  </system.webServer>