A day with .Net

My day to day experince in .net

Angular2 Development With Visual Studio Code

Posted by vivekcek on October 24, 2016

In this post, i will show you how we can use VS Code for Angular2 development.
The main thing is how to configure VS Code to transpile typescript to js files and lunch the app.

1. Install NodeJs
2. Install visual studio code.
3. Install TypeScript via NPM (Visual studio code may normally install TypeScript).
4. Create a folder in E, E:\Angular2
5. Open this folder through VS Code.
6. Go to https://angular.io/docs/ts/latest/quickstart.html
7. Create 3 files in VS Code , package.json, tsconfig.json, systemjs.config.js.
1
8. From angular site copy the codes for these files and save.
2
9. Go to NPM and change your directory to E:\Angular2, and issue below command

npm install

3

10. Now create a folder named app, and create below files (Refer angular2 quick start).

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: '<h1>My First Angular App</h1>'
})
export class AppComponent { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

4

11. So everything is ready, now important step to configure TypeScript compiler.
12. Ctrl+Shift+P will open command pallette.
13. Type task and select Configure Task Runner
5
14. Selecet tsconfig.json
6
15. This will create a file named tasks.json, update args section as shown in image (args:[])
7
16. Now click on build and configure launch.json file.
8
17. Update program section as shown.
9
18. Run the app now

Posted in Uncategorized | Tagged: , | Leave a Comment »

Write ECMAScript 6 (JavaScript 6) in VS Code.

Posted by vivekcek on October 9, 2016

In this post i will show you how to write and debug EcmaScript6 in VS Code.

1. Install NodeJs (Check the configure path option during install).
2. Install VS Code.
3. Restart your machine/Inspect path has been set for NodeJs.
4. Start VS Code.
5. From menu select Open Folder(File->Open Folder).
1

6. Create a New Folder.
2

7. Create a new file named “jsconfig.json” and paste below code.

{
    "compilerOptions": {
        "target": "ES6"
    }
}

3

8. Now create a javascript file Hello.js and paste below code.

class Car {
    constructor(make) { //constructors!
        this.make = make;
      this.currentSpeed = 25;
    }

    printCurrentSpeed(){
          console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
}

class RaceCar extends Car { //inheritance
    constructor(make, topSpeed) {
        super(make); //call the parent constructor with super
        this.topSpeed = topSpeed;
    }

    goFast(){
          this.currentSpeed = this.topSpeed;
    }
}

let stang = new RaceCar('Mustang', 150);

stang.printCurrentSpeed();
stang.goFast();
stang.printCurrentSpeed();

4

9. From menu select Debug (View->Debug).

5

10. Click on green start debug button, which will ask to configure the settings.
Select NodeJs

6

11. When we select NodeJs,VS Code will open launch.json. Update it with our file name Hello.js

7

12 Agin click on that Green Play button and enjoy.

8

Posted in javascript | Tagged: , , , | Leave a Comment »

Restart Amazon AWS EC2 instance from PowerShell

Posted by vivekcek on July 25, 2016

In this post i will show you how can we restart a windows ec2 instance by using powershell.

1. Go to your account, select Security Credentials and create an AWS access key and secret key.

2

3

2. Open Power-Shell for AWS, which will ask your AWS Access key and Secret Key.

1

3. If Power-Shell not prompted for keys go to “C:\Users\Administrator\AppData\Local\AWSToolkit” and delete the Registered Account Jsonfile and open Power-Shell again.

4. Now get your instance id by using this url from EC2 instance

http://169.254.169.254/latest/meta-data/instance-id

5. Now from powershell give below command

Restart-EC2Instance -InstanceId i-12345678

Posted in Amazon AWS | Tagged: , , , | Leave a Comment »

C# Different Types Of Heap Memory

Posted by vivekcek on July 10, 2016

You might be heard that, reference objects are stored in heap:).
Do you know how many types of heaps are available in CLR.
Do you know that, you can pass data to another app domain with out marshaling:)

These all are .NET CLR implementation details, know to Bill Gates:)

You can explore, if you want to know more, Later i will post about memory management in CLR.

For the time being have a look at the types of heap’s below.

Loader Heap: contains CLR structures and the type system
High Frequency Heap: statics, MethodTables, FieldDescs, interface map
Low Frequency Heap: EEClass, ClassLoader and lookup tables
Stub Heap: stubs for CAS, COM wrappers, PInvoke
Large Object Heap: memory allocations that require more than 85k bytes
GC Heap: user allocated heap memory private to the app
JIT Code Heap: memory allocated by mscoreee (Execution Engine) and the JIT compiler for managed code
Process/Base Heap: interop/unmanaged allocations, native memory, etc

Usually, the “heaps” that most people refer to or know about are the “GC Heap” and the LOH.
GC Heap is shared among app-domains and GC will work only on that.

Capture

Posted in c#.net | Tagged: , , , , , , , , | Leave a Comment »

Filter datatable based on coulmns

Posted by vivekcek on June 26, 2016

If you want to build a new table from an existing table, with some columns try this

var selectedColumns = new[] {"Coulmn1","Coulmn2" };
var newTable = new DataView(oldTable).ToTable(false, selectedColumns);

Posted in c#.net | Tagged: | Leave a Comment »

Get non empty rows from a datatable

Posted by vivekcek on June 26, 2016

If you want to filter out empty rows from a datatable try this tipe

var nonEmptyRows = MyTable.Rows.Cast<DataRow>()
                                            .Where(
                                                row =>
                                                    !row.ItemArray.All(
                                                        field =>
                                                            field is System.DBNull ||
                                                            string.Compare((field as string).Trim(), string.Empty) == 0));
            MyTable = nonEmptyRows.Any() ? nonEmptyRows.CopyToDataTable() : MyTable.Clone();

Posted in c#.net | Tagged: , | Leave a Comment »

Return Json from a Web Api via HttpResponseMessage

Posted by vivekcek on June 26, 2016

This is a small tip to send json data through HttpResponseMessage.

First create the helper class in your Web Api Controller.

public class JsonContent : HttpContent
    {

        private readonly MemoryStream _Stream = new MemoryStream();
        public JsonContent(object value)
        {

            Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var jw = new JsonTextWriter(new StreamWriter(_Stream));
            jw.Formatting = Formatting.Indented;
            var serializer = new JsonSerializer();
            serializer.Serialize(jw, value);
            jw.Flush();
            _Stream.Position = 0;

        }
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            return _Stream.CopyToAsync(stream);
        }

        protected override bool TryComputeLength(out long length)
        {
            length = _Stream.Length;
            return true;
        }
    }

Now try this in your Action method.

public HttpResponseMessage Delete(int id)
        {
            return new HttpResponseMessage()
            {
                Content = new JsonContent(new
                {
                    Name = "Vivek",
                    Address = "Address",
                    Message = "Any Message" //return exception
                })
            };
        }

Posted in MVC, Web API | Tagged: , , | Leave a Comment »

Instance members of an ActionFilter attribute is not thread safe – MVC

Posted by vivekcek on June 26, 2016

I was trying to inject a dependency to my filter attribute via Ninject’s property injection.The injected instance was using a database connection too.
And one of the ajax polling call was hitting this attribute every 10 seconds.
Strange i got some thread concurrency issue and site went down.
Later i found that in MVC for each request a controller is created, but for each request the same instance of filter attribute is reused.

You can test this via putting break points in the constructor of controller and attribute.

1

2

Posted in MVC | Tagged: | Leave a Comment »

File upload and usability – Upload by a single click

Posted by vivekcek on June 26, 2016

Today i was just filing my tax via HRBlock India, and the experience was good.As you know for filing tax, you should upload your Form 16 docs to Hrblock.
They provide the below screen for uploading each document.Here you need to select each document and click the upload button, that is 2 click per upload.

Can we change this to single click, No i think because we may need to provide password for each file, if present.
So this screen is valid.

1

In some other sites , i have seen you have to do 2 mouse click for an upload.Normally developers design a file upload like below, a file browse input and upload button.

3

So how we can save one click, with just a single button click.

4

For that you can use bootstrap and jquery.

First add this style to your page.

<style type="text/css">
    .btn-file {
        position: relative;
        overflow: hidden;
    }

        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }
</style>

Place your input control via below code snippet.

<span class="btn btn-default btn-file">
    Upload Files <input type="file">
</span>

Use the below script to upload.

@section scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $(document).on('change', '.btn-file :file', function () {
                var input = $(this);
                var files = input.get(0).files;
                if (files.length > 0) {
                    var data = new FormData();
                    for (i = 0; i < files.length; i++) {
                        data.append("file" + i, files[i]);
                    }
                    input.trigger("onclick");//Please keep this to fire the change event next time
  
                    $.ajax({
                        type: "POST",
                        url: "",
                        contentType: false,
                        processData: false,
                        data: data,
                        global: false,
                        success: function (response) {

                        },
                        error: function () {

                        }
                    });

                }
            });

            $(document).on('onclick', '.btn-file :file', function () {
                this.value = null;
            });
        });
    </script>
}

Posted in Jquery, MVC, SignalR | Tagged: , , , , | Leave a Comment »

SignalR in Web Farm or Web Garden Enviornment

Posted by vivekcek on May 23, 2016

I was trying to use SignalR 2 for one of my project and successfully implemented a progress bar using it.
Everything was working fine in our test server also. But fortunately i tested this SignalR 2 based progress bar in Web-garden mode of IIS,
Woww surprised nothing is working. Thanks God, because our production servers are load balanced Web Farm.

Any way found solution in Microsoft documentation. I will discuss that below.

Hope you have an understanding of SignalR.

1. Create an MVC 5 app.

2. Add Nuget package for SignalR.

Install-Package Microsoft.AspNet.SignalR

3.Now Paste the below code in your cshtml.

<input type="button" value="Submit" id="btnSubmit" />
<input type="hidden" id="connectionid" />

<div id="uploadModal"></div>

@section scripts
{
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <script type="text/javascript">

        $(document).ready(function() {
            var con = $.connection.uploaderHub;
            $.connection.hub.start().done(function() {
                $("#connectionid").val($.connection.hub.id);

            }).fail(function(e) {
                alert('There was an error');
                console.error(e);
            });
            con.client.print = function() {
                $("#uploadModal").append("Vivek");
            };

            $("#btnSubmit").click(function() {

                var connectionid = $("#connectionid").val();
                var url = '@Url.Action("Test", "Home")';
                url = url + '?connectionid=' + connectionid;
                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function(messages) {

                    },
                    error: function() {

                    }
                });

            });

        });
    </script>
}

4. Now create an action in your controller.

        [HttpPost]
        public ActionResult Test(string connectionid)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<UploaderHub>();
            hubContext.Clients.Client(connectionid).print();
            return Json(new { Success = "True" });
        }

5. Create a SignalR hub.

using Microsoft.AspNet.SignalR;

namespace SignalR.Controllers
{
    public  class UploaderHub:Hub
    {

    }
}

6. In your OWIN Startup.cs add the code below.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR.Startup))]
namespace SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
}

Deploy this to IIS and click submit button, Which will print the text defined in client side print method.

Now increase the worker process count in your application pool to 5, Also set processor affinity true.
Try the same after some refresh, You will found the messaging is not working.

1

To Solve this you can use another SignalR package for SQL Server

Install-Package Microsoft.AspNet.SignalR.SqlServer -Version 2.2.0

Then update your OWIN Startup.cs add this.

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR.Startup))]
namespace SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            string sqlConnectionString = "Connecton string to your SQL DB";
            GlobalHost.DependencyResolver.UseSqlServer(sqlConnectionString);
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
}

Which will create some tables, in the database you specified in your connection string.
And now debug…

Posted in AJAX, MVC, SignalR | Tagged: , , , | Leave a Comment »