Monday 19 February 2018

When we want to communicate from component class to template ,we can use interpolation which use the {{ expression }} to render the bound value to the component’s template.

Step 1 : Create an angular 5 project  from here https://programmergangtuts.blogspot.com/2018/02/creating-first-angular-5-project.html and copy and paste the following code in src->app->app.component.ts 
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstName:string="Mani"; //defining first name field in typescript
  lastName:string="Rai";  //defining last name field in typescript
  getFullName():string //method returning first name and last name
  {
    return this.firstName +" " +this.lastName;
  }
}
Step 2 : paste the following code in src->app->app.component.html 
Full Name : {{getFullName()}} //interpolation

Step 3 :  app.module.ts is root module which is shown below and AppModue is route modules which bootstraps and launches the angular application.



Step 4 : Go to View -> Integrated terminal then terminal will open .


Step 5 : type 'ng serve -- open ' in open terminal in step 5 


Step 6 : Output is shown below :

 Happy Coding !!!
In this article ,I will show you about nested component in angular 5.

Step 1 : First create the angular 5 project https://programmergangtuts.blogspot.com/2018/02/creating-first-angular-5-project.html .Go to cmd and run as administrator->navigate to your project folder and in project folder type 'ng g c customer' .Here AngularDemo is our project which was previously created and shown below :


Step 2 : When you run above command ,customer folder and necessary files are created inside it which is as shown below :


Step 3 : When you run the above command ,it will automatically register the newly generated component inside declarations array of @NgModule which is shown below :


Step 4 : Go to src->app->customer->customer.component.ts and paste the following code ;
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
  customerName:string;
  customerCode:string;
  constructor() { 
    this.customerName="Manichandra Rai";
    this.customerCode="1001";
  }

  ngOnInit() {
  }

}
Step 5 : Go to src->app->customer->customer.component.html and paste the following code :
<table>
  <tr>
    <td>Customer Code</td>
    <td>Customer Name</td>
  </tr>
  <tr>
    <td>{{customerCode}}</td>
    <td>{{customerName}}</td>
  </tr>
</table>

Step 6 : Go to src->app->customer->customer.component.css and paste the following code :
table{
    color:black;
    font-family: Arial, Helvetica, sans-serif;
    font-size: large;
    border-collapse: collapse;
}
td{
    border: 1px solid black;
}
Step 7 : Go to src->app->app.component.ts and paste the following code :
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Customer Info.';
}
Step 8 : Go to src->app->app.component.html and paste the following code :
<!--The content below is only a placeholder and can be replaced.-->
<P class="customstyle">
  {{title}}
</P>
<p><app-customer></app-customer></p>

Step 9: Go to src->app->app.component.css and paste the following code :
.customstyle{
 font-weight:bold;
 color:red;
font-style:italic;
text-decoration: underline;
font-size: x-large;
}
Step 10 : Go  to cmd  and type 'ng serve --open' and hit enter and you will get the following output :

Happy Coding !!!
In this article, I will explain How to create  first RESTfull  API using WCF.

Step 1 :  Open visual studio and Go to File->New->Web Site



Step 2 : Enter Project name and location and Hit Ok


Step 3 : Right click on project WCFDemoApp->Add New Item->Add


Step 4 :  Select WCF Service and Enter Hello.svc and Hit Ok


Step 5 :  Now our project structure is as shown below .IHello.cs ,Hello.cs and Hello.svc fill will be added 


Step 6 : Open IHello.cs file and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IHello" in both code and config file together.
[ServiceContract]
public interface IHello
{
    [WebInvoke(Method = "GET",
     ResponseFormat = WebMessageFormat.Json,
     RequestFormat = WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Wrapped,
     UriTemplate = "HelloService")]
    [OperationContract]
   List<Employee> Hi();
}
[DataContract]
public class Employee
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
}


Step 7 : Open Hello.cs file and paste the following code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Hello" in code, svc and config file together.
public class Hello : IHello
{
    public List<Employee> Hi()
    {
        List<Employee> employeeList = new List<Employee>
        {
            new Employee
            {
                FirstName="Manichandra",
                LastName="Rai"
            },
            new Employee
            {
                FirstName="Sengson",
                LastName="Rai"
            }
        };
        return employeeList;
    }
}


Step 8 : Hello.svc file has service name Hello which is required in web.config file.


Step 9 : Paste the following code in your web.config file just above the </configuration> . Here Service name "Hello" should be same as service in Hello.svc file and contract should be your interface "IHello".

<system.serviceModel>
    <services>
      <service name="Hello" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="IHello" address="" behaviorConfiguration="webHttp"/>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
 Now our final web.config file 
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.6.1"/>
      <httpRuntime targetFramework="4.6.1"/>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs"
                type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
                type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
        </compilers>
    </system.codedom>

  <system.serviceModel>
    <services>
      <service name="Hello" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="IHello" address="" behaviorConfiguration="webHttp"/>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
</configuration>
Step 10 : Right click on Hello.svc and browse with your browser



Step 11 : Now output is as shown below :


Step 11 :  Now type /HelloService after Hello.svc file which gives us json result :


Step 12 : Now run our WCF api on Postman gives output as shown below :


Sunday 18 February 2018

In this article, I will explain How to create first application in Asp.net MVC.

Step 1: Download and install visual studio community Edition from this link which is free  https://www.visualstudio.com/downloads/  .Remember Visual studio is IDE(Integrated development Environment)

Step 2 :  Open visual studio and Go to File->New ->Project


Step 3 :  Select Web->Asp.net web Application and enter project name and browse project location and hit Ok


Step 4 : Select MVC  and Leave uncheck to Add unit tests


Step 5 : Select No Authentication for this first application .we will discuss it later.Hit OK and again hit Ok


Step 6 : Now project will open and structure of our project looks like below


Step 7 : Delete HomeController.cs file because we are creating from scratch.


Step 8 : Delete Home folder inside view .Views->Home


Step 9 : Add Controller .For this Right click on Controller folder->Add->Controller


Step 10 : Select MVC5 Controller-Empty


Step 11 : Enter controller name as Home and do not delete the word controller.MVC works on convention so we always write controller name as HomeController. i.e. we append word controller.For now word controller is just like reserve word.Hit Add


Our controller code is shown below . Here Home is controller name and HomeController is class which is inherited from controller base class which is present inside System.Web.Mvc namespace.Inside HomeController class there  is Index action method which is always public whose return type is ActionResult(ActionResult is abstract class) . But here we are returning View() which  returns  ViewResult  class.This ViewResult class is inherited from  ViewResultBase and finally this ViewResultBase is inherited from ActionResult so ViewResult class is indirectly inheriting from ActionResult abstract class .Return type of action method is not always ViewResult so we make its reutrn type as base class ActionResult which is parent for different action results like JsonResult, PartialViewResult, ContentResult, FileResult etc.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DemoApp.web.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}
Step 12 : Now Run our application .Debug->Start without debugging


Step 13 :  When  we run our application it displays following error  because we have not created any view yet. View name is same as action method name in mvc and it searches with different file extensions  inside folder whose name is same as controller name and finally inside Shared folder.If we want to share our view among different controller's action method ,we should put that view inside Shared folder.Here View is not present inside Home and Shared folder so displays  error.


Step 14 : Now add view . Right click anywhere inside curley braces of action method and click add view .Leave view name as it is and view name is same as action method name but you can change the view name according to your choice .If we change the view name we should called explicitly call that view from action method giving its name as parameter to View("view name").Select Empty(without model) template for now and leave blank model class.Tick use layout page for setting common design to child page as well. Here Layout page is same as master page in asp.net webform. and finally hit Add


Step 15 : now Our view looks like below  and write <p>Hello World !!!</p> inside view
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<p>Hello World !!!</p>


Step 16 : Routing simplifies the URL. We have to write name as key ,url and defaults controller and action name  inside MapRoute method.Here Default is our key,url pattern is controller name /action name/ id (which is optional) . In our case Home is default controller and Index is default action.


Step 17 : Final output is as shown below .


Mvc is an architectural pattern that divides an application into three interconnected parts where as asp.net MVC is web application framework developed by Microsoft on the top of asp.net framework(Asp.net is part of .Net framework) for creating web applications which implements MVC(Model -View-Controller) pattern.
ASP.NET Web Form was a replacement for Microsoft’s Active Server Pages (ASP) but ASP.NET MVC is not a replacement for ASP.NET Web Forms and it’s just an alternate way of making an ASP.NET website.

ASP.NET MVC is open source!- In March 2012, Scott Guthrie announced ASP.NET MVC, Razor and Web API under an open source license (Apache License 2.0).

Request flow in Asp.net MVc :
1) When end user hits a URL on browser,the request is sent to the server through browser and this first request is received by controller (User interaction logic is handle by controller)
2) Controller request to the model for information and Model in turn calls the data access layer which fetches data in the model.
3) Finally controller updates view according to model and end user gets response as view .
Why Asp.net MVC

1) Follows Separation of Concerns Philosophy
   i)Components are only responsible for one thing
   ii)Loosely coupled
   iii)Modular components
2) Clean URL
3) Full Control Over the User Interface or the HTML
4) Better For Search Engine Optimization
5) Loosely Coupled so Each Component can be tested independently. Better Support For Test Driven Development.

Problems in Asp.net Webform
1) View Based architecture for an Action Based requirement.
HTTP protocol is action oriented that means when end user sends requests(i.e. actions) and get response .In asp.net web form when we want to perform an action by clicking on button,the request is sent to view(page having .aspx  extension)  which kicked off behind code having complicated page life cycle and finally executes the logic written in button click event.But in asp..net mvc end user request is directly sent to action within controller and depending up the logic it calls view.

2) Behind code is not reusable
Code behind page(page having .aspx.cs extention) in asp.net webform  is not reusable  but in asp.net MVC code behind logic is written in action of controller so same logic can be used for different view. 
 


3) Bandwidth consumption
Viewstate of asp.net webform generates extra bytes  which consumes more bandwidth even  it automatically saves states between post backs and reduces our development time.

4) Slow Response time
Browser can understand only HTML so every server controls of asp.net webform should be converted into HTML and there is some conversion logic in server due to which response time of asp.net webform is slower than asp.net MVC.


5) Default return response is always HTML
In asp.net webform default response time is HTMLso if we want to get string response we should create HTTP handler.But in Asp.net MVC it is very easy just return string.
References :
1) https://www.questpond.com/
2) https://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day

Saturday 17 February 2018

Component is a class with a template (User interface) and decorator (decorator is function that is invoked with a prefixed @symbol), which have the binding logic to bind the UI and the model. We can say component is binder/view model or binding code.

A component must belong to an NgModule in order for it to be usable by another component or application.Every Angular app has at least one NgModule class, the root module, conventionally named AppModule.
Most important properties of @NgModule are:

declarations: Registers particular components within this module

bootstrap: Tells the module which component to bootstrap

imports: Imports other modules into this module

Providers: creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app. These providers are for services. whatever you have services , that services should be add in the provider field. providers will tell to angular how to inject a service.
app.module.ts

Note : AppModue is route modules which bootstraps and launches the angular application.




Component decorator @Component must have the selector and template and component class must add export. then only it will available in the project. we need to add ‘export’ keyword before the component class.
app.component.ts


Selector :selector is name which is used in our view like html tag.css selector that identifies this component in a template
index.html

template: we can write html code in the template and we can write multi line code using backtick character.
app.component.ts


TemplateUrl :url to an external file containing a template for the view
app.component.ts

styleUrls: list of urls to stylesheets to be applied to this component's view.
app.component.ts
app.component.css

styles: inline-defined styles to be applied to this component's view.
app.component.ts

bootstrap – the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property.
Main.ts:
The main entry point for the application.This file contains the code to bootstrap the application root module.(i.e. AppModule)
import { platformBrowserDynamic } from '@angular/platform-browser';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);
Note : We can add component  by typing ng g component ‘component name’ or ng g c ‘component name’ in command prompt.
Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page