Popular Posts

Monday, October 24, 2016

HttpClient - consuming the Web Api Service in .net

Here is an example of consuming Web Api in .Net client using pure HttpClient:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WebApiClient
{
    class Program
    {

        private static void Main(string[] args)
        {
            MainAsync().Wait();

            Console.ReadLine();
        }
     
        static async Task MainAsync()
        {
            await ReadValues();
            await AddValue();
            await ReadValue(1);
            await DeleteValue(2);

            await DeleteValue(111); // Delete with Error

            Console.ReadLine();
        }

        private async static Task DeleteValue(int id)
        {
            var url = "http://localhost:13628/api/Values/" + id;
            using (var client = new HttpClient())
            {
                var response = await client.DeleteAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    await ReadValues();
                }
                else
                {
                    Console.WriteLine(response.ReasonPhrase);
                    Console.WriteLine(response.StatusCode);
                }
            }
        }

        private async static Task ReadValue(int id)
        {
            var url = "http://localhost:13628/api/Values/" + id;

            using (var client = new HttpClient())
            {
                var httpResponseMessage = await client.GetAsync(url);

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    var jsonString = httpResponseMessage.Content.ReadAsStringAsync().Result;
                    var result = JsonConvert.DeserializeObject<ObjectToStore>(jsonString);
                    Console.WriteLine("Getting one value->" + result.Value);
                }
                else
                {
                    Console.WriteLine(httpResponseMessage.StatusCode);
                    Console.WriteLine(httpResponseMessage.ReasonPhrase);
                }
            }
        }

        private async static Task AddValue()
        {
            var url = "http://localhost:13628/api/Values/";
            using (var client = new HttpClient())
            {
                var value = new ObjectToStore() {Id = 3, Value = "value 3"};
                var content = JsonConvert.SerializeObject(value);
                var stringContent = new StringContent(content, Encoding.Default, "application/json"); // Note: need to include media type
                var result = await client.PostAsync(url, stringContent);

                if (result.IsSuccessStatusCode)
                {
                    await ReadValues();
                }
                else
                {
                    Console.WriteLine(result.StatusCode);
                    Console.WriteLine(result.ReasonPhrase);
                }
            }
        }

        private static async Task ReadValues()
        {
            var url = "http://localhost:13628/api/Values";
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var jsonString = response.Content.ReadAsStringAsync().Result;
                var values = JsonConvert.DeserializeObject<List<ObjectToStore>>(jsonString);

                foreach (ObjectToStore value in values)
                {
                    Console.WriteLine(value.Value);
                }
            }
        }
    }

    public class ObjectToStore
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }
}

Wednesday, October 19, 2016

mvc custom exception handler

custom error and message handling or global filters:

https://www.asp.net/web-api/overview/error-handling/exception-handling


Just a dirty example!!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mail;
using System.Web.Mvc;
using System.Web.Routing;

namespace KidsWear.Shop.Filters
{
    /// <summary>
    /// Handle all exception in application level.
    /// Deal with exceptions based on type.
    /// Note: only handles Controller related exceptions i.e 500 code
    /// </summary>
    public class ExceptionActionFilter : FilterAttribute, IExceptionFilter
    {

        public EmailSender Emailer { get; set; }

        public ExceptionActionFilter()
        {
            if (Emailer == null)
            {
                Emailer = new EmailSender();
            }
        }

        public void OnException(ExceptionContext filterContext)
        {
                    // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                HandleJasonException(filterContext);
            }

            // Handle the business exception
            if (filterContext.Exception is BusinessException)
            {
                HandleBusinessException(filterContext);
            }

            // Handle security exception
            else if (filterContext.Exception is FluentSecurity.PolicyViolationException)
            {
                HandleSecurityException(filterContext);
            }
            else
            {
                HandleUnExpectedExceptions(filterContext);
            }

            filterContext.ExceptionHandled = true;
        }

        private void HandleUnExpectedExceptions(ExceptionContext filterContext)
        {
            // Log the error using Elmah
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            // If all the other exceptions then show a friendly message and exception will be logged by Elmah
            var msg =
                "An error has happened. We appologise for any inconveniences...The system Administrator will be notified who will look at the issue and will resolve it ASAP....";
            var emailData = new EmailData().WithDefaults();
            emailData.Subject = filterContext.Exception.Message;
            emailData.Body = filterContext.Exception.StackTrace;
            filterContext.Controller.Notify(msg, NotificationType.Error);

            filterContext.Result = new RedirectToRouteResult(new
                System.Web.Routing.RouteValueDictionary(new
                {
                    Controller = "Error",
                    Action = "Index"
                }
                ));

            Emailer.SendEmail(emailData);
        }

        private static void HandleSecurityException(ExceptionContext filterContext)
        {
            // Log the error using Elmah
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            filterContext.Result = new RedirectToRouteResult(new
                System.Web.Routing.RouteValueDictionary(new
                {
                    Controller = "Account",
                    Action = "Login"
                }
                ));
        }

        private static void HandleBusinessException(ExceptionContext filterContext)
        {

            filterContext.Controller.Notify(filterContext.Exception.Message, NotificationType.Error);

            filterContext.Result = new ViewResult
            {
                ViewName = filterContext.RouteData.Values["action"].ToString(),
                TempData = filterContext.Controller.TempData,
                ViewData = filterContext.Controller.ViewData
            };
        }

        private static void HandleJasonException(ExceptionContext filterContext)
        {
            // Log the error using Elmah
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    error = true,
                    message = filterContext.Exception.Message
                }
            };
        }

    }

}

Thursday, October 13, 2016

Github - Notes

****************************************
GitHub
****************************************

Adding existing project to github:
https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/

- Setting Git email address
git config --global user.email "rahman.mahmoodi@gmail.com"

or environment variables:
GIT_COMMITTER_EMAIL=rahman.mahmoodi@gmail.com
GIT_AUTHOR_EMAIL=rahman.mahmoodi@gmail.com

- check user and email configurations
git config --global --list

- Deleting the repository from github
[githutrepositoryurl]/settings and then under the danger zoon delete the repo.

- Find what Remote URL a local git is connected to
git config --get remote.origin.url

- git folder is stored in the root of the repository (project folder), though it is hidden. Just delete that file and it will reset the things

- Adding an existing folder to new github
echo "# ASP.NetWebAPIAdvancedTopics" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/RahmanM/ASP.NetWebAPIAdvancedTopics.git
git push -f origin master


- **** WAS getting unauthorized error for rahmanx **** needed to update the .config file in the git folder of the repository to include the user name and password in th eurls like
 https://rahmanm:abcccccccc@github.com/RahmanM/ASP.NetWebAPIAdvancedTopics.git

 - Adding formatting to github read me file https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

 - git text editor
 > press i to go to insert mode
 > type the comments
 > press Esc to exit insert mode
 > :wq (to save the text file and exit)

- Creating branch
git branch my-branch-name
git checkout my-branch-name

- To merge
> Go to destination branch eg master
> git merge my-branch-name

- git mergetool

Web Layout - Notes

***************************************
Website layouts design
***************************************

> Layouts
- Forms
- Carousels
- Gallaries
- Header, Navigation,Logo, Side, Footer, Hero

> Progressive enhancements
> Sectioning elements
- Div, header, footer, nav, address
> CSS Reset
- Normalize.css
> Typographic and font sizes
> Free fonts
- GoogleFonts -> https://fonts.google.com/?authuser=0

> CSS Cascading
- Inheritance : e.g. all the child elements inherit the parent element's properties
- Source e.g User Agent, Users, Authors
- Specifity e.g. classes, ids, inline styles to apply css to specific elements
 >> Order of specifity is -> Universal Selectors (*) -> Type Selectors (p, h1) -> Classes (.heading) -> Attribute selectors (input[type="text"]) -> Psydo classes (:hover, :focus, :visited) -> Id selectors (#myid) -> inline selectors!!
- Importance (!important)
> Specifity Formula
- Put a number for each specifity that is found and add the numbers e.g. for
  Inline Ids Class/Psuedo-class/Attribute Type Selector/Psuedo
  0 1 2 1 -> #hero .myclass nth-of-type(2) h1
  0             2 2 1 -> #homepage #landing h1 a:hover .red-color

> Dreamweaver css designer


- animate.css
- bootstrap popover
-- use under score templates to populate the content
- relative parent and absolute children?

- css2less.co
- CanIUse.com => Browser compatibility

***************************************
- LESS Summary
***************************************

>> Create variables @variable-name : red;
>> Create heirarchy of elements rather than repeating them many times
>> Add comments
>> Import CSS or other Less files @Import "filename.css"
>> Functions
>>> color : darken(@variable-name + 10%) , lighten, saturate, etc
>> Operations
>>> color : @font-size + 12;
>> Mixen -> functions that accepts parameter and is reusable
>>> .my-first-mixin(@size){
border-radius : @size;
}

and use it as:
#form {
broder-radius : my-first-mixin(5px);
}

CSS Positioning
====================
- Default position is Static e.g elements stack on each other in the document
- Position: Relative
-> Sets the position of the element based on its original position.
- Position: Absolute
-> Sets the position of the elements as it does not have any width and height e.g. all the other elements will move up.
-> Absolute positioning is based on document
-> Its relevant to the document, when scrolling it will move up or down
- Position : Fixed
-> Fixed position is based on the browser window. I.e. even with scrolling it will remain there

HTML5 - Notes

***************************************
HTML 5
***************************************

New Semantic Elements in HTML5
- <article>
- <aside>
- <details>
- <figure>
- <footer>
- <header>
- <main>
- <mark>
- <nav>
- <section>
- <summary>
- <time>

New Form elements
- Datalist, output

New Javascript
-

New Input types
- color
- date
- datetime
- datetime-local
- email
- month
- number
- range
- search
- tel
- time
- url
- week

New Media
- Audio
- Video
- Track

Bootstrap - Notes

********************
Bootstrap
********************

- setting up of the viewport is required for the responsive
*** Mostly Fluid Pattern ***
- container-fluid is to fill the whole page rather than the margins
- move the columns in different view ports
*** Layout Shifter Pattern ***
> Desing the page based on mobile
> push the columns and pull the columns on different sizes
  col-sm-push-2 and then col-sm-pull-8
> Push and pull are related to left side of the browser
*** Layout Drop Pattern ***
- Visible-mid and hide-mid to hide and show columns based on different ports
*** Content Reflow Pattern ***
> Using media query to move the text around the image and make the <a> tag block
iamge-list a{
display: block;
}

iamge-list img{
display: inline;
}

- Same size columns in a three layout columns
> minimit.com that has the article on how to do it - basically change the display to table!!!

> img-responsive to make image responsive

Octopus Deploy - Notes


********************
Octopus Deploy
********************

Physical Architecture:
- SQL Database
- Octopus Deploy Server
- Deployment Targets (client machines) [Tentacles (windows services that communicates to server) AND Calamari (Command line tool that execute the messages)]

Logical Concept:
- Environments e.g. Dev, Prod etc
- Roles e.g. Todo.Web and Todo.Services
- Packages e.g nuget packages
- Projects e.g a recipe for deployment i.e. Deploy project, notify users, notify in slack
- Releases