Friday, 25 August 2017

All command related angular 2 or 4

All command related angular 2 or 4:

node JS latest version=>  https://nodejs.org/en/download/current/
Angular js 2 or 4 CLI=>  https://cli.angular.io/
Angular js 2 or 4 API=>  https://angular.io/api





CMD Description
1 npm install –g @angular/cli
1. For install all dependences of angularJS 2 or 4 in your System.


2 ng new my-project-name
1. Default applications are created in a directory of the same name, with an
Initialized Angular application.
2. Scaffold and maintain Angular applications.
3 cd my-project-name 1. Go same location where you create project.
4 ng serve
or



ng serve --host 0.0.0.0 --port 4201
1. Ng serve builds the application and starts a web server.
2. Build using Ahead of Time compilation (AOT).
3. Default port value: 4200
4. Enable and define the file watching poll time period (milliseconds).
5. Start web pack dev server.
6. Change Port number of application.
5 ng generate [name] 1. Ng generates the specified blueprint (module, component, service, class, interface, directive, enum, guard, pipe, service).
6 ng –g controller [name] 1. This is also working same as above g stand for generate.
7 ng test
1. Compiles the application into an output directory.
2. Tests will execute after a build is executed via Karma, and it will automatically watch your files for changes
8 ng e2e 1. serves the application and runs end-to-end tests
9 ng build 1. Compiles the application into an output directory.
10 *ngFor
<li *ngFor="let user of list | async as users; index as i; first as isFirst"></li>
1. index: number: The index of the current item in the iterable.
2. first: boolean: True when the item is the first item in the iterable.
3. last: boolean: True when the item is the last item in the iterable.
4. even: boolean: True when the item has an even index in the iterable.
5. odd: boolean: True when the item has an odd index in the iterable.
11 *ngIf
ngIF=> <div *ngIf=”true”></div>
ngIF and else=> <div *ngIf=”true; else elseBlock ”></div>
12 [ngPlural]
Use as a switch statement.
<some-element [ngPlural]="value">
<ng-template ngPluralCase="=0">...</ng-template>
<ng-template ngPluralCase="other">...</ng-template>
</some-element>
13 [ngStyle] <H [ngStyle]="{'font-style': styleExp}">...</h>
14 [ngSwitch]
1. <div [ngSwitch]="expression"> <span ngSwitchCase="matchExp ">...</span></div>
2. <span *ngSwitchDefault>...</span>
15 async
1. The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.
2. <div><code>observable|async</code>: Time: {{ time | async }}</div>


16 date                  
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'jmZ'}}</p>
17 JSON <pre>{{object | json}}</pre>
18 lowercase <p>In lowercase: <pre>'{{value | lowercase}}'</pre>


uppercase <p>In lowercase: <pre>'{{value | uppercase}}'</pre>
19 currency
"number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]"
<p>A: {{a | currency:'USD':false}}</p>
<p>B: {{b | currency:'USD':true:'4.2-2'}}</p>
20 number <p>e (3.1-5): {{e | number:'3.1-5'}}</p>
21 percent
<p>A: {{a | percent}}</p>
<p>B: {{b | percent:'4.3-5'}}</p>
22 slice
<li *ngFor="let i of collection | slice:1:3">{{i}}</li>
<li string | slice:1:3">{{i}}</li>
23 titlecasepipe <li string | titlecasepipe "></li>


24 .  ng build    =>     using for build application and bundling all type script.

25.   npm uninstall -g angular-cli  => uninstall angular .

26.   npm uninstall --save-dev angular-cli => uninstall but save your development work.

27. update Angular CLI to a new version, you must update both the global package and your project's local package.

      A. Global package:
                            npm uninstall -g @angular/cli
                            npm cache clean
                            npm install -g @angular/cli@latest

      B. Local project package:
                          rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command                           Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
                          npm install --save-dev @angular/cli@latest
                          npm install

28. ng serve --host 0.0.0.0 --port 4201  => Change Port number of application.

29. npm install -g nodemon =>    Nodemon is a utility that will monitor for any changes in your                                                                 source and automatically restart your server

Thursday, 24 August 2017

Angular 2 or 4 startup project using CLI

Install Angular js2 or 4 https://cli.angular.io/

                            https://github.com/angular/angular-cli

CLI and generated project have dependencies that require Node 6.9.0 or higher, together with NPM 3 or higher.

So firstly we need to  install  node js: https://nodejs.org/en/download/

  1. Install the Angular CLI globally.
    Cmd=> npm install -g @angular/cli
  2. Create a new project
    Cmd=> ng new my-app
  3. Serve the application, Go to the project directory and launch the server
    Cmd=> cd my-app
    Cmd=> ng serve –open   OR  Cmd=> ng serve --host 0.0.0.0 --port 4201
Services using CLI in angular 2 or 4.

Use=>  localhost://4200

Component=> ng g component my-new-component
Directive=> ng g directive my-new-directive
Pipe=> ng g pipe my-new-pipe
Service=> ng g service my-new-service
Class=> ng g class my-new-class
Guard=> ng g guard my-new-guard
Interface=> ng g interface my-new-interface
Enum=> ng g enum my-new-enum
Module=> ng g module my-module


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