Saturday, December 1, 2018

Postman testings on WEB API

1) Get - WEB API method signature


    Get - Postman Call


2) Post WEB API method signature


      Post - Postman Call


  • Body part of the call



  • Header and Result




3) Post - Multipart request, including Image file




  • WEB API method signature


Postman call -  Multipart, including Image file


Capturing the HTTP multi-part requests data within the WEB API method:

                if (HttpContext.Current.Request.Params["FirstName"] != null)
                {
                    newUser.FirstName = HttpContext.Current.Request.Params["FirstName"];
                }

Capturing the image file sent:

var imageFile = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;


Querying Database tables using Linq


Join two tables. Check for boolean values in columns. Select multiple columns 

var eventFBQuestions = (from FQ in db.FeedbackQuestions join FT in db.FeedbackTypes on FQ.FeedbackTypeId equals FT.Id where (!FQ.Archived && !FT.Archived && FT.Name == "Event") select new { FQ.Id, FQ.Question }).ToList();

Get the count

var countForOne = (from Fb in db.Feedbacks where (Fb.FeedbackQuestionId == question.Id && Fb.FeedbackScore == 1) select Fb.Id).Count();


Join more than two tables. Alter the select columns by concatenating the select fields

            var sessions = (from s in db.Sessions
                        join t in db.Tracks on s.TrackId equals t.Id
                        join e in db.Events on t.EventId equals e.Id
                        where (!s.Archived && !t.Archived && !e.Archived)
                        select new {s.Id, Name = t.Name + " - " +  s.Name }).ToList();

same thing into a dictionary

            var sessions = (from s in db.Sessions
                        join t in db.Tracks on s.TrackId equals t.Id
                        join e in db.Events on t.EventId equals e.Id
                        where (!s.Archived && !t.Archived && !e.Archived)
                        select new {ID=s.Id.ToString(), NAME = t.Name + " - " +  s.Name }).ToDictionary(dic => dic.ID, dic => dic.NAME);

Saturday, November 24, 2018

D3 - Donut Chart

Here  I do a WEB API call and get the required data.


Sample code is as below

$(document).ready(function () {

    var jsonDataTshirt = {};
    var tshirts = [];

    jsonDataTshirt.tshirts = tshirts;
.
.
.


    //1) get tshirt sizes
    $.getJSON("API/MyWEBAPICall",
        function (Data) {

            $.each(Data, function (key, val) {

                if (key != "$id") {
                    var uCategory = { "fruit": key, "count": Number(val) };
                    jsonDataTshirt.tshirts.push(uCategory);
                }
            });

            // margin
            var margin = { top: 20, right: 20, bottom: 20, left: 20 },
                width = 400 - margin.right - margin.left,
                height = 400 - margin.top - margin.bottom,
                radius = width / 2 - 20;

            // color range
            var color = d3.scaleOrdinal()
                .range(["#BBDEFB", "#90CAF9", "#64B5F6", "#42A5F5", "#2196F3", "#1E88E5", "#1976D2"]);

            // donut chart arc
            var arc2 = d3.arc()
                .outerRadius(radius - 10)
                .innerRadius(radius - 70);

            // arc for the labels position
            var labelArc = d3.arc()
                .outerRadius(radius - 40)
                .innerRadius(radius - 40);

            // generate pie chart and donut chart
            var pie = d3.pie()
                .sort(null)
                .value(function (d) { return d.count; });

            // define the svg donut chart
            var svg2 = d3.select("#pie-tshirts-male").append("svg")
                .attr("width", width)
                .attr("height", height)
              .append("g")
                .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

            var data = jsonDataTshirt.tshirts;
            // parse data
            data.forEach(function (d) {
                d.count = +d.count;
                d.fruit = d.fruit;
            })

            // "g element is a container used to group other SVG elements"
            var g2 = svg2.selectAll(".arc2")
                .data(pie(data))
              .enter().append("g")
                .attr("class", "arc2");

            // append path
            g2.append("path")
                .attr("d", arc2)
                .style("fill", function (d) { return color(d.data.fruit); })
              .transition()
                .ease(d3.easeLinear)
                .duration(2000)
                .attrTween("d", tweenDonut);

            // append text
            g2.append("text")
              .transition()
                .ease(d3.easeLinear)
                .duration(2000)
              .attr("transform", function (d) { return "translate(" + labelArc.centroid(d) + ")"; })
                .attr("dy", ".35em")
                .text(function (d) { return d.data.fruit; });

            //Add the count in outside the arc
                g2.append("text")
                    .transition()
                    .ease(d3.easeLinear)
                    .duration(2000)
                    .attr("transform", function(d) {
                        var _d = labelArc.centroid(d);
                        _d[0]*= 1.4; //multiply by a constant factor
                        _d[1] *= 1.4; //multiply by a constant factor
                        return "translate(" +_d + ")";
                        })
                    .attr("dy", ".35em")
                    .text(function (d) {
                       return d.data.count;
                        })
                    .style("font-size", "10px");;

            function tweenDonut(b) {
                b.innerRadius = 0;
                var i = d3.interpolate({ startAngle: 0, endAngle: 0 }, b);
                return function (t) { return arc2(i(t)); };
            }

        });
.
.
.
});


Sample: Do nut chart is drawn as shown in the middle


Thursday, October 11, 2018

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.Int32]' to type 'System.IConvertible'

 Following is a sample linq query which might cause the problem:

int id = Convert.ToInt32(from ts in db.TShirtSizes where ts.Size == "S" select ts.Id);

You get an error as :

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.Int32]' to type 'System.IConvertible'

What happens is that, in the initial query you get a list of results. If you need to get a single value, do it by changing the code as shown below

int id = Convert.ToInt32((from ts in db.TShirtSizes where ts.Size == "S" select ts.Id).Single());



Thursday, September 6, 2018

Install the latest npm

npm install npm@latest -g



'ng' is not recognized as an internal or external command operable program or batch file

The error:

Cause: The environment variable is not set to pick up the ng file location.

The ng file location in you computer would be as shown below

Fix

Add the environment variable as shown below:

Update the Path variable. Add a semicolon at the end of the value and type in: %AppData%\npm


Now try ng again in the command line console




Sunday, September 2, 2018

Google Graphs - 3D Pie chart

In my pageMy page I have refered the below JS files in the header:


  • jquery-1.12.4.min.js
  • https://www.gstatic.com/charts/loader.js [Google Script file for graphing]
  • feedbacks.js [This is my custom JS file where all the code goes]


There is a div to load the graph inside:

   <div id="event-rating-1" style="width: 750px; height: 350px;"></div>

The script :

$(document).ready(function () {

    //variable declaration
    var jsonEventFeedback = {};
    var feedbacks = [];


    $.getJSON("API/Feedbacks/GetEventFeedbacks/",
    function (Data) {
     
        var questionListing = [];

        for(var i=0; i<Data.length; ++i){
            questionListing[i] = Data[i];
        }

        //Draw the google chart
        google.charts.load("current", { packages: ["corechart"] });
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Rating', 'Participants'],
              ['Bad', Number(questionListing[0].CountForOne)],
              ['Not Bad', Number(questionListing[0].CountForTwo)],
              ['Ok', Number(questionListing[0].CountForThree)],
              ['Good', Number(questionListing[0].CountForFour)],
              ['Excellent', Number(questionListing[0].CountForFive)]
            ]);

            var options = {
                title: questionListing[0].Question,
                is3D: true,
            };

            var chart = new google.visualization.PieChart(document.getElementById('event-rating-1'));
            chart.draw(data, options);
        }

    });

Sample Graphs:


Saturday, September 1, 2018

Using QRCoder

Download QRCoder from Git hub

Include the dll reference "QRCoder" and in your class specify the using directive as :

using QRCoder;


The simple code to generate the qr code is as shown in the below code snippet. Here payload is a string. The payload string was constructed from a StringBuilder.


QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(payLoad, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);


Thursday, August 30, 2018

JQuery Auxiliaries

Capture drop down selection change.
Here my drop down control's id is : SessionList

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

    $("#SessionList").on('change', function () {
        if ($(this).val() == 'selectionKey') {
            DoSomething();
        } else {
            DoSomethingElse();
        }
    });
.
.
.
});

Do a Call to Web API and capture the results

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

    $.getJSON("API/Feedbacks/GetEventFeedbacks/",
    function (Data) {
        
        var questionListing = [];
        for(var i=0; i<Data.length; ++i){
            questionListing[i] = Data[i];
        }
.
.
.
});

Wednesday, August 8, 2018

Angular UI Grid ui-grid.woff file not found When Published to Azure

A typical scenario goes like  you have been using the Angular UI Grid in your local server. All the images in the grid were looking good (including the down & up arrows etc..). You published your web application to Azure and suddenly instead of the down & up arrows you get some text similar to Chinese fonts.

When you open up the developer console in the web browser, you get a 404 file not found error for ui-grid.woff.

The reason behind is that Azure does not have MIME types configured for several font file formats. Whereas, if you check on your local IIS the MIME file types are already configured


So the below entry must be added to web.config to include the mime types. If not Azure will simply return a 404 error even though the files are actually published to Azure.

<system.webServer>
    <staticContent>
        <mimeMap fileExtension="woff" mimeType="application/font-woff" />
    </staticContent>
</system.webServer>

Monday, August 6, 2018

Create Azure Storage and store images as blobs

1. Create a Storage Account

Connect to Azure portal.
In the left pane you can see the "Storage accounts". Click on the link.

On the top left hand side you can click on "Add" and add new storage account. Specify the storage name and etc.. You can either create a new resource group or use an existing group for your storage's resource group.

once created you get the below page, listing your storage accounts. click on the newly created storage account.

Note that you get a list of storage options which you can modify and add. You can  also get the connection string to the storage account under the "Access keys" section.

The next step is to create a container inside the storage to hold the blobs, in my care its going to be the images.


2. Create the container to store the blobs
Click on containers. create a new container. I have named it as "Images"


3. Now is the fun part. Coding to upload the images to Azure Blob Storage

        public string UploadImageUsingByteArray(byte[] byteArray, string fileNamewithGuid)
        {
            string blobUrl = string.Empty;
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); //here the storageConnectionString you can obtain from the storage properties under Access keys

                //Create a blob client
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobClient.GetContainerReference(imageContainerName); //my container name is image
                container.CreateIfNotExists();

                if (container.Exists())
                {
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileNamewithGuid);
                    blockBlob.Properties.ContentType = "image/jpeg";
                    blockBlob.UploadFromByteArray(byteArray, 0, byteArray.Length);


                    blobUrl = blockBlob.Uri.AbsoluteUri; //returns the blob's URL. How awesome is that
                }
            }
            catch (Exception)
            {
                throw;
            }
            return blobUrl;
        }

Here I have used the option to upload a byte array using the method UploadFromByteArray(). You can also use the method UploadFromStream() if your input is a stream. It works for a file stream as well.

Refresh the container when your code has run, and you get your images in Azure blob

Thursday, August 2, 2018

Publishing to Azure and view added files

1. Create a Web App in Azure

In Azure select Web App under app service's selection and create an app service

Once the Web App is created, download the publish profile available under the Overview section of the App Service.



2. Publish project from Visual Studio

Use the downloaded publish profile to do the publishing. Import it while doing the publishing


During initial publishing it will ask for the connection string for the Azure database. When you do the following deployments you can go to the Connection tab in the publishing window and check the settings, and even validate the connection prior to the publishing.

From the second publishing on wards you can even do a preview on the changes which are going to Azure



3. Viewing added files

Once the publishing is done and if you need to check on the items which were uploaded to Azure Web App, you can simply use the Azure Kudu service Dashboard.

For this example lets say my web app URL is "http://mysite.azurewebsites.net". Then you can simply navigate through the file system by using the Azure Kudu service Dashboard. For our example the dashboard  URL would be something like : "http://mysite.scm.azurewebsites.net"





Tuesday, July 31, 2018

Use of Linq when mapping between objects

The class which data is loaded from the database. Notice data is loaded through Entity Framework

    public class UserType : EntityBase
    {
        [DisplayName("User Type")]
        [Required]
        [Remote("IsUserTypeExist", "Validation", ErrorMessage = "user type already exist! ")]
        public string UserTypeName { get; set; }

        public virtual List<User> users { get; set; }
    }

The Data Transfer Object which is used in the system

    public class UserTypeDTO
    {
        public int Id { get; set; }
        public string UserTypeName { get; set; }
        public bool Archived { get; set; }
    }

Mapping inside the method

        public List<UserTypeDTO> GetUserTypes(AppContext db)
        {
            return db.UserTypes.Select(u => new UserTypeDTO()
            {
                Id = u.Id,
                UserTypeName = u.UserTypeName,
                Archived = u.Archived
            }
            ).ToList();
        }