Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, April 26, 2016

Easy Admin Dashboard with MVC

Today I'm going to introduce you create responsive , mobile friendly admin dashboard with MVC project.

There are multiple bootstrap admin dashboard templates and one of the most commonly used and strongest one is Admin LTE. This is totally open source project.

This will provide you great UI with documentations. Click here to see documentations.

This project is owned to Almsaeed Studstudio . 




What i'm doing is removing some dependencies with 3rd party API's and make them call internally.



Lets begin with Visual studio



1. Start new empty MVC project 
2. Install Nuget Admin_Dashboard from nuget
3. Create Home empty controller and run



Now You are up and running this awsome template 



 Then afterwards you are on your own and find the relevant UI documentations form AdminLTE and use the components. all elements automatically will found with your project


You can use this template on MVC / Angular projects using visualstudio easyly 


**please ignore if there are some script error if it comes when installing nuget

Enjoy  :)








Sunday, February 28, 2016

Mongo DB With C# API V2

Let's start and check the latest  MongoDb Driver for C# (Mongo V2).

If you are not still configured your Mongo Server yet. see this Post

If you need some guide on old MongoDb Driver V1. See this Post

New Features In V2

  •  Async Support 
  • Method Naming convention with helpful names ( SelectOne, InsertOne etc) 
  • Legacy API Support 

Here is the Db Structure and Sample Data I'm going to Use 

 DB Structure : Create Collection in Mongo Server With name of  Students

















Here is some sample Json Data for Students Collection 

/* 1 */
{
    "_id" : ObjectId("56c3206ddaa3d39f5a130bcc"),
    "StudentId" : 1,
    "Name" : "Saman kumara",
    "Address" : "Sample"
}

/* 2 */
{
    "_id" : ObjectId("56c69ed3926ffb2c80ed00bb"),
    "StudentId" : 2,
    "Name" : "Piyal kumara",
    "Address" : "adadasd"
}


1. Create New MVC Website from Visual Studio

2. Add New Class to the models called Student

public class Student
    {
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { getset; }
        public int StudentId { getset; }
        public string Name { getset; }
        public string Address { getset; }
    }
 
 
 
3. Install MongoCsharpDriver Nuget package from the Nuget
















4. Create ConnetcionString  and Database Variables for mongodb by  R-click on Project -> Properties -> Settings Add relevant values of variables.













5.  Create DbContext Class MongoDbContext 

public class MongoDbContext
    {
        public IMongoDatabase Database;
 
        public MongoDbContext()
        {
            var client = new MongoClient(Settings.Default.ConnectionString);
            Database = client.GetDatabase(Settings.Default.Database);
        }
 
        public IMongoCollection<Student> Students
        {
            get { return Database.GetCollection<Student>("Students"); }
        }
    }


Get data From Mongo

1. Add following code to the HomeController
 Create Private property of Context and initialize it

private MongoDbContext _context { getset; }
 
       public HomeController()
       {
           _context = new MongoDbContext();
       }
       // GET: Home
       public  ActionResult Index()
       {
           //Get Data from Db
           ViewBag.Data = _context.Students.AsQueryable().Select(a=>new Student { Name=a.Name,Address=a.Address ,StudentId=a.StudentId}).ToList();
           return View();
       }

2. Edit The View as following

@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
@Html.ActionLink("Create""Create")
 
 
<table class="table">
    <tr>
        <th>
            Student Id
        </th>
        <th>
            Name
        </th>
        <th>
            Address
        </th>
        <th>
 
        </th>
    </tr>
 
    @foreach (var stu in ViewBag.Data)
    {
        <tr>
            <td>
               @stu.StudentId
            </td>
            <td>
                @stu.Name
                
            </td>
            <td>
               @stu.Address
            </td>
            <td>
                @Html.ActionLink("Edit""Edit"new { id = @stu.StudentId }) | 
                @Html.ActionLink("Delete""Delete"new { id = @stu.StudentId }) 
            </td>
        </tr>
    }
 
</table>


3. Run and see the result ..

Add Documents


Here is sample async code for insert element to the Mongo Context

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Create([Bind(Include = "StudentId,Name,Address")] Student student)
       {
           try
           {
               //Insert one item 
               await _context.Students.InsertOneAsync(student);
               return View();
 
           }
           catch (Exception)
           {
               return View(student);
           }
 
       }
 

Filter Elements

private Student GetStudent(int id)
        {
            //Filter element
            var std = _context.Students
                .Find(r => r.StudentId == id)
                .FirstOrDefault();
            return std;
        }


Update Or Replace Element 

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Edit([Bind(Include = "id,StudentId,Name,Address")] Student student)
       {
           //Full update /replace
           // await _context.Students.ReplaceOneAsync(r => r.StudentId == student.StudentId, student);
          
           //Partial Update
           var update = Builders<Student>.Update.Set(s => s.Name, student.Name);
           await _context.Students.UpdateOneAsync(r => r.StudentId == student.StudentId, update);
           return RedirectToAction("index");
       }


Delete element


public async Task<ActionResult> Delete(int id)
       { 
           //Delete element           
           await _context.Students.DeleteOneAsync(s=> s.StudentId==id);
           return RedirectToAction("index");
       }



Full code In Git ..

https://github.com/prabathsl/DI_Sample


 Enjoy Coding









Friday, January 22, 2016

Dependency Injection - Intro

This gonna be post series which I gonna continue .. Because this is bit complex and without theoretical part hard to understand.

Fist thing first.. Lets move with theoretical background of it with this post

 Assume this scenario.. - Entire Post sequence will use  this as example
There is student registration system we need to develop solution for student registration  

Here is our usual MVC code.


public class Student
   {
       public int StudentId { getset; }
       public string StudentName { getset; }
       public string RegId { getset; }
       public int Age { getset; }
 
 
       public IEnumerable<Student> GetStudents()
       {
           return new List<Student>();
       }
   }
 
Model Class 
 
public class StudentController : Controller
    {
        private readonly Student _student;
        public StudentController()
        {
            _student = new Student();
        }
        // GET: /<controller>/
 
        public IActionResult Index()
        {
            var data = _student.GetStudents();
            return View(data);
        }
    }
Controller Class 


In this way Model and controller is tightly coupled ( change of one class will effect other ) .  This way is not good in large scale projects a importantly. ( not recommend in any case )

You can find advantages and disadvantages of tight coupled code in OOP concepts.






  Dependency Injection


Dependency injection is the best way to create loose coupled code and resolve dependencies among the  classes .

In dependency injection some other class is responsible for injecting the dependencies in to client class(ex: Student Controller) we called it injector class at application run time.


here is object Diagram of it




Here is code how its look like with DI

public class Student:IStudent
   {
       public IEnumerable<Student> GetStudents()
       {
           return new List<Student>();
       }
   }
 
   public interface IStudent
   {
       IEnumerable<Student> GetStudents();
   }



public class StudentController : Controller
    {
        private readonly IStudent _student;
        public StudentController(IStudent student)
        {
            _student = student;
        }
        // GET: /<controller>/
 
        public IActionResult Index()
        {
            var data = _student.GetStudents();
            return View(data);
        }
    }
 
Enjoy Coding .. next post is on the way

Sunday, August 24, 2014

Back-end operations with Cloud Service (Worker Roles)

With my previous post about Creating Cloud Service I mentioned two Roles in Azure.
1. Web Role
2. Worker Role

With this Post we will working with Worker Role . I'm using the same code that I use in Creating Cloud Service  post

What is Worker Role ??

Worker role is the component that doing background operations in Azure web service. If you need to implement background service such as background listener with your cloud service this is the component for you.

With physically Worker role is the Virtual machine which running the Server OS (Windows Server 2012 R2) without configuring IIS.( check the Web Role definition in Creating Cloud Service ).
Actually both of the Web Role and Worker Roles are derived from RoleEntryPoint Base class.

According to the OOP principles, yes Web Role can do the same Task that Worker Role can do. ( I hope to make discussion about it with later post ). We just give the chance to handle Web related tasks to web role and use worker role to handle non web based tasks. Because Web role may be over loaded when it try to handle all within it. Then Web role is free to handle more web based requests with more speed.

 Lets Code
,

1. Open the code in visual studio and check it is working (Creating Cloud Service). Then go to the solution explorer

2. On the AzureServiceDemo -> Roles -> R - click -> New Worker Role Project














Then Select Worker Role and give name.. I'm giving PrabathslWorkerRole as name















After add the worker role you can see that it will add Worker Role project to your solution ans that project contains only one class called WorkerRole.cs














I'll add that class here for explanation

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
namespace PrabathslWorkerRole
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("PrabathslWorkerRole entry point called", "Information");
            while (true)
            {
                Thread.Sleep(10000);
                Trace.TraceInformation("Working", "Information");
            }
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            return base.OnStart();
        }
    }
}

Simply public override bool OnStart() method is called when Role Started then it called public override void Run() Method. Run method should contain what we need to do in background. In here I'm going to configure HTTP listener.It take some inputs and generate output.  If it needed to do repeatedly you need to add it inside forever while (true) loop

Also web role can forward jobs to the Worker role and Worker Role can also get inputs directly by it self. For that we can also insert our WCF service i worker role as well .

Replace the Run() with following code to listen port=4488 with HTTP protocol  ...
public override void Run()
       {
           HttpListener listner = new HttpListener();
           //This will ping to Http://myserviceurl:4488 port
           listner.Prefixes.Add("http://+:4488/");
           listner.Start();
  
           //Set the response to transformable format
           string responseMessage = "<html><title>Response from Worker</title><body><h1>Prabathsl.blogspot.com</h1></body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseMessage);
  
  
           while (true)
           {
               HttpListenerContext context = listner.GetContext();
  
               //then set the response
               HttpListenerResponse response = context.Response;
               response.ContentLength64 = buffer.Length;
               Stream output = response.OutputStream;
  
               //write output stream
               output.WriteAsync(buffer, 0, buffer.Length);
               output.Close();
           }
       }

This is local for the Azure VM.


Currently our VM's are haven't any external access.To allow access to the worker role we need change some configurations.

 That called input end point. Lets define input endpoints. it allows traffic to go through our VM


3. Goto AzureServiceDemo Solution and Roles then double click on PrabathslWorkerRole

4. Click on Endpoints -> Add Endpoint button and add endpoint. I named it as prabathslEndpoint









External clients use this port to send traffic to service using public port

actually they send traffic through this port .  Here is how people send traffic http://mysitedomain:4080/

Azure load balancer send the traffic (re route the traffic to Worker Role) through the private port to the Virtual Machine that run the worker role (4488)

**You can use any port as you wish

Now we are done and run it ..

Here is what i get when Listen to localhost
(http://127.0.0.1:4080/) We need to listen public port



















Full Code In Media Fire 
http://bit.ly/worker_role

 



Thursday, August 14, 2014

Creating Azure Serice with Active Directory Login

When we are working with different requirements in a project there may be issues like this. Clients want to available all data in the application (with application) just for authorized users. Ex: All management portals may just only available for mangers

In this kind of scenario developers need to maintain separate authentication mechanisms to authenticate users. Specially those mechanisms may not be the perfect in security point of view.

Azure provide great solution for it with the help of Visual Studio. You can use Azure Active Directory (AD)  users to authenticate. It will very secure and its just use Azure portal log in to your application. You can use log ins in your on premises Active Directory too. You need to just make tunnel between Azure active directory and your on premises AD. Then all changes in your on premises AD is Sync with Azure AD with help of Active Directory Federation Service (ADFS)

Lets start our project


1. First Login to Azure Portal manage.windowsazure.com and then go to the Click on Active Directory












2. If you don't have AD User Directory to use  Then Click on New -> Active Directory -> Directory->Custom create











3. From the wizard you can use existing directory or create new directory. If you use existing directory to create new directory all the users in that directory will be added to the new one. In here I'm going to create new directory

















4. Once directory created click on it and go to users . It will automatically added created user as user.


5. If you need to add user to AD Click on ADD User button in bottom and add user. May be existing AD , From Microsoft account or may be company user. In later in this post I'll tell you how to add company user



















Im adding Microsoft Account




















Fill the required data and you are done

Create New User



















If you enabled Multi-Factor Authentication it will ask for phone number verification with SMS when user login . Its Nice feature .......
Just like in Microsoft Store Login ....Its free

Then Create temproy Password















If you need sent password to the user















And Done :)

Lets go back ..



Now we have Azure AD with required users ..

Now go to Visual studio and start Azure Cloud service project as in my previous post Creating  Cloud Service Up to Step 3

Here is step 3


















In here click on Change Authentication button.


Then use Organizational Account option












Select Single sign On (here we just use Azure AD)











Enter your  Azure AD Domain and select the required authorities from Access level













Then click Ok we are done .......


Debug Tips ..

If you found user credential verification failed azure  error with visual studio
  1. Shut down Visual Studio
  2. Go to your Azure management portal, and create a new user account within the Active Directory you created (I set mine as a Global Admin).
  3. Open up VS again and go through the steps of creating the WebApi project. This time, when you choose Organizational Accounts for authentication, use the credentials of the user that you just created - it should work now.



Enjoy





Monday, August 11, 2014

Publish Cloud Services

Lets see how to publish your cloud service to Azure with visual studio. In here I'm going to use same loud service that we build in my previous post Creating Cloud Service.

1. Open your solution in Visual Studio and select your project R-Click and then Publish


















2. Then it will prompt Publish Windows Azure Application windows. Then sign in to your Azure Account and select your subscription that you want to use and click Next


3. Then it will gives you Publish Settings form from it if you already have created Cloud service in Azure you can select that service to publish. If not you can create new Service (i'm creating new Service here )
















Create new will prompt new window and add name to your service and Select nearest data center for the location.












4. Then you have to select your created service name and Environment to host. In Azure it provide two environment to host your services.
  • Production Environment 
  • Staging Environment
Production Environment contains the actual running application. Production environment is trusted and currently our customers are accessed this environment if we already punished this service and it is up and running.

When we are updating new version of same Service directly to the production environment meanwhile we doing the update our application will not functional. Our users cant access the application. And another hand we don't know that our new version is exactly functioning well within hosted environment. Sometimes there may be bugs.

To avoid those problems Azure provide us concept called Staging Environment if we publish app to the staging environment it will gives us separate URL for the newly published app mean wile our Production environment is up and running. We can verify that our new version is up and running meanwhile  older version will serve our customers. Once we verify that our new version is ready to go its single click away. There is SWAP (VIP Swap) button in azure portal in staging application. It will automatically connect the traffic to Staging application.

What it does is it swap the IP address between selected staging environment and Production. now Our staging is production and production become staging. Its called VIP Swap.

Azure allows you to have maximum 5 staging's per Application


Lets back to subject :)
 In my case im going to publish brand new application and therefore i can directly publish to production environment . but after that if you make new version go with best practices

and I'm using Release binaries and use service configuration file as cloud version. And with enable remote desktop i can loginto VM's that my service web role's is hosted ad username and password if you need remote desktop enabled
















With Advanced tab you can define the service hosted storage and configurations as you need.
















Then you can publish your Cloud service


Here is my published service URL : http://prabathblogdemo.cloudapp.net/

Here is Some publisher logs and you can understand what is happened when publishing (* My web roles have 2 instances )

6:59:40 PM - Connecting...
6:59:40 PM - Verifying storage account 'portalvhdsjf2mmx92gk60l'...
6:59:41 PM - Uploading Package...
7:02:35 PM - Creating...
7:03:23 PM - Created Deployment ID: XXXXXXXXXXXXXXXX.
7:03:23 PM - Instance 0 of role PrabathslWebRole is stopped
7:03:23 PM - Instance 1 of role PrabathslWebRole is stopped
7:03:24 PM - Starting...
7:03:41 PM - Initializing...
7:03:42 PM - Instance 0 of role PrabathslWebRole is creating the virtual machine
7:03:42 PM - Instance 1 of role PrabathslWebRole is creating the virtual machine
7:04:47 PM - Instance 0 of role PrabathslWebRole is starting the virtual machine
7:04:47 PM - Instance 1 of role PrabathslWebRole is starting the virtual machine
7:06:25 PM - Instance 0 of role PrabathslWebRole is in an unknown state
7:06:25 PM - Instance 1 of role PrabathslWebRole is in an unknown state
7:07:00 PM - Instance 0 of role PrabathslWebRole is busy
7:07:00 PM - Instance 1 of role PrabathslWebRole is busy

7:08:07 PM - Instance 0 of role PrabathslWebRole is ready
7:08:07 PM - Instance 1 of role PrabathslWebRole is ready
7:08:07 PM - Created Website URL: http://prabathblogdemo.cloudapp.net/
7:08:07 PM - Complete.


Hosted App











Here is created instances in Azure Portal
















You can connect those Hosted VM's using Connect button via remote desktop using given credentials when you publish app



Enjoy :)