Sunday, April 17, 2016

Global Azure Bootcamp 2016 Ahmedabad–Awesome event recap

Yesterday, Ahmedabad User group has organized the Global Azure Bootcamp 2016 event. It was a fun to be there. The event was very well received and attended by the group of people excited about Azure cloud platform.  Thanks for hosting is Ahmedabad User Group.

AUGLogo3

Event Recap:

In the morning, Event is started around 10:00 am. Mahesh had made all attendees comfortable and given some insights about Azure platform.

DSCN5888

After that, It was my time to present some. I have shared my knowledge about DocumentDB with my presentation about Introduction to DocumentDB.

DSCN5893
DSCN5891

There well lots of interest in the audience and we had lots of conversation about it. Here is the presentation link for the same.

Here was the agenda for my presentation.

  • What is document databases?
  • What is DocumentDB?
  • Why we should use DocumentDB?
  • How we can use DocumentDB?
You can also find demo code for the presentation at the following location.
https://github.com/dotnetjalps/gab16augdemo

Due to the huge interest in people, We promise them to have some advanced level sessions about DocumentDB in forthcoming months.

After that Jagdish has taken over the stage and had presented about Azure mobile services. He presented how we can leverage Azure mobile services with Windows Phone Application and some other cool insights for Azure mobiles services.

DSCN5894

Then we had lunch and we had some great interaction and conversation about cloud technologies during lunch.

DSCN5897DSCN5895DSCN5905DSCN5896

After lunch, there was post lunch session. It was time for Sanket Shah to rock the stage. He has presented about Architecting Modern solution on Azure.  He had some cool demo and audience was amazed about his demo.

DSCN5900
DSCN5901

After that, we had another back to back session from Kaushal Bhavsar. He had presented about how we can create a secure two factors authentications with  Azure technologies. He had some given some cool demo using Azure Active directory and Office 365 account authentication about it.

DSCN5906
DSCN5907

After that we had tea and It’s time for Ahmedabad User group president Mahesh Dhola to rock the stage. Instead of giving demo he chooses to use WhiteBoard and given presentation DevOps and Microsoft Azure. It was fun watching is him presenting the topic that we all love.

DSCN5912
DSCN5914

After the presentation, it was the time where everybody wants to get some prize. We had the lucky draw and almost everybody gets price.

DSCN5917DSCN5924
DSCN5925DSCN5921
DSCN5926DSCN5927

And this guy was an inspiration for all us.

DSCN5919

Then we has some photos of all the speakers. We missed Jagdish here as he needs to go home for some personal work.

DSCN5933

Overall, It was a fun event. We had some much fun hacking and learning something new. Thank you, Microsoft and Ahmedabad user group for hosting such a nice event.

Keep rocking!.
Share:
Thursday, April 14, 2016

Visual Studio 15 Next version of visual studio is available now

With Build 2016 event, Microsoft has announced the preview of next version of Visual Studio called Visual Studio 15. You can download the next version of VS from below link.

https://www.visualstudio.com/downloads/visual-studio-next-downloads-vs

There are two options available for there on above link for download. One is normal Installed which is traditional installer contains all the functionality of earlier version of visual studio.

The second option contains a new lightweight installer which a brand new install from the Microsoft focusing on making visual studio installation faster and-and less impactful. The smallest installation of the Visual studio is now under 500 MB and includes support for more than 20 languages. You can optionally add additional features like desktop development using  Windows forms and WPF.

visualstudiopreview
P.S. This is a preview still Microsoft is working on that so you will not see lots of new features and its in preview so you should never use it for production.
There are some new features announced like Open Folder, Improvements of the debugger and few other stuff. You can see the complete list of features in release note at the following link.

https://www.visualstudio.com/news/vs15-preview-vs

On the same page, you can see the list of new features. That’s it. Hope you like it. Stay tuned for more!.
Share:
Wednesday, April 13, 2016

Come join us at - Global Azure Bootcamp 2016 Organized by Ahmedabad User Group

Do you want to be part of largest community event is the world? If Yes, then Global Azure boot camp 2016 is there. Ahmedabad User group is going to organize Global Azure boot camp.


The global azure boot camp is going to be organized at more than 180 locations worldwide. They are going to have some cool Azure lab. So I would encourage you to participate in that.

You can find more information about that following link.

http://global.azurebootcamp.net/

If you want to participate in this one of the greatest event hosted by Ahmedabad User Group then you can register via the following  link.

gab16aug.eventbrite.com

Please create a pass for yourself and be there. I am also going to be there as a speaker and going to present about document DB.

So see you all there!
Share:
Thursday, March 31, 2016

Visual Studio 2015 update 2 is available for download now

Visual studio 2015 is a great IDE and I love that more and more. As we all know that visual studio update 1 was released few months ago, Yesterday at build conference Microsoft has announced  Visual studio 2015 update 2.

From where I can download Visual Studio 2015 update 2:


You can download Visual studio 2015 update 2 different editions from the following links.

Visual Studio 2015 Community Edition:
Web installer : https://go.microsoft.com/fwlink/?LinkId=532606&clcid=0x409
ISO  File: https://go.microsoft.com/fwlink/?LinkId=615448&clcid=0x409

Visual Studio 2015 Professional Edition:
Web Installer: https://go.microsoft.com/fwlink/?LinkId=615435&clcid=0x409
ISO File:https://go.microsoft.com/fwlink/?LinkId=615436&clcid=0x409

Visual Studio 2015 Enterprise Edition:
Web Installer : https://go.microsoft.com/fwlink/?LinkId=615437&clcid=0x409
ISO File: https://go.microsoft.com/fwlink/?LinkId=615436&clcid=0x409

Also, You can download visual studio update 2 only without whole editor from the following link.
https://blogs.msdn.microsoft.com/visualstudio/2016/03/30/visual-studio-15-preview/


There are lots functionalities new features provided for new updates. You can find a complete list of features the following link.

https://www.visualstudio.com/en-us/news/vs2015-update2-vs.aspx

I am going to post about some new features in visual studio update 2 in forthcoming blog posts. Hope you like it and Stay tuned for more!.
Share:
Wednesday, March 30, 2016

Build 2016 Conference Live streaming

Microsoft continues to focus on enabling developers to do amazing work as businesses and industries transform in support of the shift to a cloud-first, mobile-first world. At Build 2016 Microsoft will present the latest tools and technologies and how they can help today’s developers be their most creative and productive.

From here you can see the live streaming  of build conference 2016.

Share:
Friday, March 25, 2016

How to use syntax highlighter with open live writer

Microsoft has open sourced windows live writer as “Open Live Writer” and is now part of .NET Foundation, It was a great move but as a part of modernizing the windows live writer they have started removing the functionality and adding some new functionality. Eventually, they are going to add the plugins but right now there is no support for that. I have been using windows live writer for more than 5 years now and I was using syntax highlighter for highlighting code on this blog. If you are not familiar with syntax highlighter you can find more information on the following link.

http://alexgorbatchev.com/SyntaxHighlighter/

It is a fully functional self-contained code syntax highlighter developed in  JavaScript. As now Open writer does not support plugin for the time being, I have to find another solution to write the blog post and do some syntax highlighting. So, I have found a way to do this and I would like to share this with you. In this blog post, we are going to learn how we can use syntax highlighter other way.

I was using preCode syntax highlighter plugin. It’s an open source plugin and provides a great plugin for syntax highlighter.

http://precode.codeplex.com/

But as Open Live Writer does not support plugin, There is no way to directly Integrate that plugin, But fortunately, precode syntax highlighter plugin comes with a desktop application was so now you can run that desktop application via finding it on windows 10 like below.

precode-syntax-highlighter

Once you run the preCode Code manager desktop app, It will run the application like following.

preCode-code-manager-syntaxhighlighter

Here you can put your code make settings as per your choice on the right side like below.

precode-code-manager-syntaxhighlighter-with-code

Then just click on the copy to clipboard and close. It will copy syntax highlighter code in the memory.  Now click on source tab at the bottom on the open live writer like below.

source-code-plugin

Then paste that code like below.

sourc-code-source

And now publish your post and it will look like below.
function helloWorld{
    alert("hello world");
}
That's it. It is very easy to use precode code manager with the open live writer. Hope you liked it. Stay tuned for more!.
Share:
Friday, November 27, 2015

TypeScript configurations in Visual Studio Code

Before sometime I have blogged about - Why It's the right time to learn Typescript and It does get lot of buzz. Typescript getting every day more popular due to reason I have mentioned in above blog post.  So now in this blog we are going to learn how we can use TypeScript with new Visual Studio Code editor.

TypeScript support in Visual Studio Code:


As you know Visual Studio Code is in beta now and provide great support for typescript. Here you can operate TypeScript in two modes.

1) File Scope:

In this mode Visual Studio Code will treat each typescript file as separate unit. So if you don't reference the typescript files manually with reference or external modules it will not provide intellisense as well as there will not common project context for this.

2) Explicit Scope:

In this scope we are going to create a tsconfig.json which will indicate that folder in which this file exist is a root of TypeScript project. Now you will get full intellisense as well as other common configurations on tsconfig.json file.

You can create a new file via File->New file from Visual Studio Code and add following code about TypeScript configuration under compiler operations.
{
    "compilerOptions": {
        "target": "ES5",
        "module": "amd",
        "sourceMap": true
    }
}

Converting TypeScript into JavaScript files automatically(Transpiling ):

Now as we all know that TypeScript is a super set of JavaScript and this files we can not directly put into html page. As browser will not understand the typescript itself. So we have to convert it into JavaScript. So to convert TypeScript file into JavaScript file we need to configure a in built task runner which will automatically convert all the TypeScript files into JavaScript.

To configure Task Runner you can either press F1 or Ctrl+Shift+P and type task runner. Configure Task runner will popup.

task-runner-vs-code

Once you press enter it will create a .vscode folder and create file called task.json which will have following code.
{
    "version": "0.1.0",

    // The command is tsc. Assumes that tsc has been installed using npm install -g typescript
    "command": "tsc",

    // The command is a shell script
    "isShellCommand": true,

    // Show the output window only if unrecognized errors occur.
    "showOutput": "silent",

    // args is the HelloWorld program to compile.
    "args": ["HelloWorld.ts"],

    // use the standard tsc problem matcher to find compile problems
    // in the output.
    "problemMatcher": "$tsc"
}

Now when you build your project it will create a JavaScript file automatically. Now Let's create a TypeScript file like following.
class HelloWorld{
     PrintMessage(name:string){
        console.log("Hello world:" + name);
    }
}

Here you can right now there is only one file there in explore section.

typescript-file-in-visual-studio-code

Now when you build the project with Ctrl+Shift+B. It will create a JavaScript file.

typescript-and-javascript-both-vscode

and Following is a code for the same.
var HelloWorld = (function () {
    function HelloWorld() {
    }
    HelloWorld.prototype.PrintMessage = function (name) {
        console.log("Hello world:" + name);
    };
    return HelloWorld;
})();

Hiding JavaScript File from explore area in Visual Studio Code:


I don't like my JavaScript file to show in explore area as we already have TypeScript file. So we don't have to worry about JavaScript file. There is a way to hide JavaScript file and I have to add following code in my user settings file. Which you can get it via File->Preferences->UserSetting
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/*.js":{
    "when": "$(basename).ts"
}
Here in above I have written custom filter for excluding JavaScript file when TypeScript file is present. Now it will not JavaScript file even if they exists on disk.


typescript-file-in-visual-studio-code

That's it. Hope you like it. Stay tuned for more!!. In forthcoming post we are going learn a lot of TypeScript.
Share:
Sunday, November 8, 2015

My Entity framework blog series

Share:
Saturday, November 7, 2015

Working with transaction in Entity Framework 6

In  any Relation database, maintaining the integrity of the database is very important and Transaction is one way of maintaining database integrity. When you have the situation, where you need to insert data into multiple tables and if inserting a data in one of the table fails you should always rollback other inserts transaction becomes very useful. The Same scenario can occur for update or delete operations. If transactions are not there you will end up with lots of junk data in tables. Entity framework is one of most popular ORM in Microsoft.NET World. So in this post, we are going to learn how we can use transactions with Entity Framework 6.

Transaction and Entity Framework 6:


Entity framework internally maintains a transaction when you call SaveChanges() method. So all Inserts, update operation under single save changes method call will be in a single transaction. But when you want to wrap multiple SaveChanges() method under single transaction there was not inbuilt functionality in the earlier version of Entity framework. We have used to use TransactionScope class for the same.

But now with Entity Framework 6.0, We have two inbuilt APIs for Transaction.

DbContext.Database.BeginTransaction:

It allows us to Begin transaction for multiple save changes, You can combine as many operations as you want under the single transaction and hence either all will be performed successfully then the transaction will be committed  and if any exception occurred than transaction will be rollback.

DbContext.Database.UseTransaction :

Sometimes we need to use a transaction which is started outside of the entity framework. In this case, this option allows us to use that transaction with entity framework also.

In this blog post, We are going to use Begin Transaction. I will write a separate blog post about how to use existing transaction with entity framework.

So enough theory, let's create a console application understand it better.

ef6-with-transactions-console-application

We need entity framework. So I have added it via NuGet package.

entity-framework-transaction-nuget-package

In this application, we are going to use two model classes category and product. We will save them both in the single transaction and try to understand how the transaction works with Entity Framework.
namespace EFWithTransactions
{
    public class Category
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
    }
}
And here is product model.
using System.ComponentModel.DataAnnotations.Schema;

namespace EFWithTransactions
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        [ForeignKey("Category")]
        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
    }
}

Here you can see I have category id there in product and a product is belong to category and I have created my DB context class like following.
using System.Data.Entity;

namespace EFWithTransactions
{
    public class ProductDbContext : DbContext
    {
        public ProductDbContext()
            : base("ProductConnectionString")
        {

        }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
    }
}

And following code is for Main method of console application, Which illustrate real times scenario where exception might occurs during multiple save changes().
using System;

namespace EFWithTransactions
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ProductDbContext productDbContext = new ProductDbContext())
            {
                using (var transaction = productDbContext.Database.BeginTransaction())
                {
                    try
                    {
                        //saving category
                        Category category = new Category
                        {
                            CategoryName = "Clothes"
                        };
                        productDbContext.Categories.Add(category);
                        productDbContext.SaveChanges();

                        // Throw some error to check transaction
                        // Comment this to make transactions sucessfull
                        // throw new Exception("Custom Exception");

                        //saving product
                        Product product = new Product
                        {
                            ProductName = "Blue Denim Shirt",
                            CategoryId = category.CategoryId
                        };
                        productDbContext.Products.Add(product);
                        productDbContext.SaveChanges();
                        Console.Write("Cateogry and Product both saved");
                        transaction.Commit();
                    }
                    catch (Exception exception)
                    {
                        transaction.Rollback();
                        Console.WriteLine("Transaction Roll backed due to some exception");
                    }
                }

            }
            Console.ReadKey();
        }
    }
}
If you see above code carefully, you can see I have two save changes method one for category and another for the product. Also, I have used BeginTransaction method to initiate a new transaction. I have put one custom exception to illustrate something is wrong with that transaction. Also, try catch block is there so if any exception occurs catch block will rollback the transaction. If all went well it will commit the transaction.

Now let's run this application and following is an output as expected. As we have thrown an exception.

Transaction-roll-back-entity-framework

And there is no data inserted in database also.

sql-server-database-with-no-data

Now let's comment the throw new exception part.
//throw new Exception("Custom Exception");

And now let's run our application again and here is the output as expected.

transaction-committed-sql-server

And now we have data in the database there.

sql-server-database-with-data-transaction-commited

So now we have a really good way to use transaction in entity framework. Hope you like it. Stay tuned for more!.
You can find complete source code of above blog post on github at - https://github.com/dotnetjalps/EF6WithTransaction
Share:
Friday, November 6, 2015

How to use stored procedure with Entity Framework Code First

I'm getting lots of request from readers of my blog about writing blog post about how to use stored procedure with entity framework code first. So in this blog post we're going to learn about how we can use stored procedure with Entity framework code first.

To demonstrate that we are going to use create a table called Employee like following.

table-entity-framework-code-first-stored-procedure
And here is the create table script for the same.
CREATE TABLE [dbo].[Employee](
[EmployeeId] [int] NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Designation] [nvarchar](50) NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

And following is the data I have inserted there.

entity-framework-table-data

And here is the store procedure we are using for that.
CREATE PROCEDURE usp_GetAllEmployees
AS
SELECT EmployeeId,FirstName,LastName,Designation FROM Employee

Now we have already done with our database side, it's time to write some C# code. I'm going to use simple console application for the same.

console-application-ef-code-first-stored-procedure

Now It's time to add entity framework via nuget package .

nuget-package-entity-framework-code-first

Here is the model class I have created.
namespace CodeFirstStoredProcedure
{
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Designation { get; set; }
}
}
And then I have created entity framework dbcontext like following.
using System.Data.Entity;

namespace CodeFirstStoredProcedure
{
public class EmployeeDbContext : DbContext
{
public EmployeeDbContext()
: base("EmployeeConnectionString")
{

}
public DbSet<Employee> Employees { get; set; }
}
}
And following is a code for using stored procedure to get data from database via entity framework code first.
using System;
using System.Linq;

namespace CodeFirstStoredProcedure
{
class Program
{
static void Main(string[] args)
{
using (EmployeeDbContext dbContext = new EmployeeDbContext())
{
string commandText = "[dbo].[usp_GetAllEmployees]";
var employees = dbContext.Database.SqlQuery<Employee>(commandText).ToList();

Console.WriteLine("Printing Employee");
foreach (var employee in employees)
{
Console.WriteLine(employee.EmployeeId);
Console.WriteLine(employee.FirstName);
Console.WriteLine(employee.LastName);
Console.WriteLine(employee.Designation);
Console.WriteLine("-----------------");
}
}
Console.ReadKey();
}
}
}

Here in the above code, If you see care fully. I have used SQL Query function to execute stored procedure and that will return a list of employee. Then I have printed this list with console.writeline.  Now when you run this application, output will be as expected.

entity-framework-code-first-stored-procedure

That's it. It's very easy to use stored procedure with entity framework code first. Hope you like it. Stay tuned for more!!.
You can find complete source code of this sample application at - following location - https://github.com/dotnetjalps/EFCodeFirstStoredProcedure
Share:
Sunday, October 18, 2015

The Famous MongoDB Document Database: Operations and Benefits

This is a guest post from Jenny Richards. Jenny Richard is a content maker for RemoteDBA.com which is one of the leading companies in the country which provides remote DBA support Services. You can find more about her at following social profiles.
https://plus.google.com/u/0/114743495388960667319/posts https://www.linkedin.com/in/richardsjenny

Over the last few years, a lot of enterprise attention has been focused on data requirements and data management and administration. The reason for this is clear: proper management of an enterprise’s information assets is critical to effective operation. Enterprises stand to gain a lot if they have in place systems that facilitate proper management of data streaming in from all sources.

Improper storage and management of data also presents a challenge, particularly with subsequent management and analysis to inform decision making and business critical process management. as a result, countless technologies are being developed and churned into the market to enable data storage, analytics and management. These technologies are also constantly being upgraded according to user requirements to make them better suited for different enterprises’ needs.

image
Image credit: slidesharecdn.com

One such technology is the MongoDB, which is just about the best NoSQL, document storage-based database available on the market. If you are looking to implement a data storage solution, you will be interested in a few important qualities, which will explain why best one database is suited for your needs but not the other.

Among the most important considerations is the performance level of the database, as well as the level of availability. You would want to have a database that allows for the highest performance and also one that is available for a large portion of time. These are databases which offer replicated services, including master failover systems. In addition, enterprises need databases that offer seamless scalability, so that the database can be easily grown as organizations/ data volumes increase.

Enterprise requirements for a database solution


Every database must include capabilities to perform a few key functions. In addition, they should have fast learning curves, since the enterprise may have to take up initial and ongoing training for its IT staff if using in-house teams. Organizations that invest in implementation of new database systems without accounting for the training of management personnel are simply setting themselves up for failure.

Every database, MongoDB included, comes with a unique set of features and operational and maintenance requirements. This means that for you to derive maximum benefit and optimal performance from each, you must assign the time and resource allocation for training of the database handlers. If you are unable to, you can instead go with remote DBA services experts, who are already trained in management and can provide maintenance and administration support for a fixed fee payable periodically.

Of course, you should also consider how much data the enterprise needs to store, both in the short and longer term. You don’t want to invest in hardware and applications that will be obsolete just a few years into your investment. As the business grows and its data requirements increase, you need a database solution that can scale accordingly and allow you to manage the content effectively.

MongoDB offers easy, seamless scalability on implementation. In addition, being a NoSQL database storing data in BSON format, there is no need for schema definition which means faster data storage and retrieval. In addition, binary JSON allows fast performance of queries for effective content management.

Why MongoDB is superior to other document-based databases:


There are many features that make MongoDB a preferred NoSQL database solutions compared with other similar databases in the market:
  • The document-based storage method enables seamless object mapping onto various data types and programming languages. It includes documents and embedded arrays which significantly reduce the need for connectors.
  • Polymorphism is made simpler owing to its dynamic schema storage method. Dynamic schema in database terms means that documents found within one collection needn’t have the same structure, or a similar set of fields. In turn, similar/common fields within the same document collection can have different data types.
  • MongoDB is optimized for high performance. Read/write operations are faster because of embedding capability. In addition, keys from embedded arrays and documents can be included within indexes.
  • The database offers high availability owning to replicated servers and automated mater failover implementation.
  • ·High scalability made possible by auto-sharding features to distribute collection data along machines. Consistent reads can also be dispersed throughout the replicated servers.
image
Image credit: blogspot.com

Key features of MongoDB:


The main features of MongoDB are defined by its power, flexibility, ease of use and speed

1. Power

MongoDB offers most of the features included in traditional RDBMSs including: dynamic queries, secondary indexes, upsert operations (update existing documents, insert non-existent documents), rich updates, easy aggregation and sorting. This means you can enjoy the same level of functionality you would using an RDBMS, while still taking advantage of the scalability and flexibility benefits presented by non-relational models.

2. Flexibility

MongoDB stores data in JSON document format (JavaScript object notation) which is them serialized as BSON (Binary JSON). JSON offers a rich data model that can flawlessly map onto programming language types for native apps. In addition, its dynamic schema feature allows easier evolution of data models compared with RDBMS systems that have defined schema, rigid schemas.

3. Ease of use

MongoDB was designed by its creators to have easy installation, configuration, maintenance and usability functions. In this regard, MongoDB comes with few options for configuration, instead opting for the logically “right thing” according to the circumstance. As a result, MongoDB can be used straight out of the box, allowing you to concentrate on application development rather than spending countless hours tweaking vague database configurations

4. Scalability/speed

In MongoDB, related data is grouped into documents, which means that queries can be run much faster. This in comparison to relational databases; where related data may be separated in multiple tables because of different schema definition, necessitating connection prior to processing at a later time.

The auto-sharding feature in MongoDB allows for easy outward scaling - clusters can be linearly scaling by increasing the number of machines. In addition, the database can be scaled outwards without having any downtime. This is extremely important for enterprises with a web presence, since it eliminates the need to take down the website for maintenance, during which time the business sacrifices huge amounts in actual and potential revenue. 
Share:

Three way to activate state in UI-Router Angular.js

Before some time I have written a blog post about routing - Routing with UI-Router and Angular.js I have got few questions from my reader in email. One of question is to how we can activate state of UI-Router as UI-Router works with state instead of URLs. In this blog post we are going to explain, different ways to activate state in UI-Router.

There are three ways of activating state in UI-Router.

  1. Call $State.go
  2. UI-sref directive as link
  3. Navigate to URL associated with State
We are going to learn about this three ways in details.

Call $State.Go:


It is a one of convenient method of changing state, Returns a promise representing the state of transition. It calls underlying $State.Transition method internally but automatically sets option location: true , inheritance:true, relative: $state.$current and notify:true. This allows you to set easily update parameters with passing arguments. You can find more information about that at following location.

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options

UI-sref directive as link:


We have used this method already in previous example. It is a directive that bind a link to state. If the state has an associated URL, the directive automatically generate and update the href attribute via $State.href() method. Clicking on link will trigger a state transition with parameters.
You can use it in following way.
  • ui-sref='stateName' - Navigate to state, no params. 'stateName' can be any valid absolute or relative state, following the same syntax rules as $state.go()
  • ui-sref='stateName({param: value, param: value})' - Navigate to state, with params.
You an find more information about this at following location.

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref

Navigate to the URL associated with State:


As we have seen in previous blog post, most of the state will have URL associated with it. Now when user access the index.html/contactus, it will activate contactus state and load the template associated with this state. You can also pass the parameters with that. Following is documentation for the same.

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref

Hope you like it, Stay tuned for more!!.
Share:
Friday, October 9, 2015

Best way to do code review with GIT

Recently we had a discussion when you should do a code review when using GIT. As a general rule you should do code review often.There are two ways to do code review with GIT.

1) Classic way:

 

We all know that GIT is known for it's feature branch features. So each developer working on some feature should have created feature set. That features branch is accessible to all the peers working on same project. So when developer completes his changes and push to feature branch anybody from his/her peers can checkout branch and perform code review.  The problem with this method is we don't have any records for the code review in source control it self.

2) Integration Way:

 

This is best method for doing code review. As we all know GIT provides pull request feature. So we will have two type of branches one is master branch for project and another feature branches for each developer working on different features of project. So now once a developer completes his feature and feels that its ready to push developer will send a pull request to master branch. Now the person or lead who are managing master branch will perform a review of pull request and either accept pull request and merged into code or if he found a some issue with code he can also reject pull request also with proper comments. So here we can easily perform code review with GIT and all data remains same. Most of the open source project on Github maintained this way only.

Hope you like it. Stay tuned for the more!.
Share:
Thursday, October 8, 2015

Arguments in View Component : ASP.NET MVC 6

Recently before sometime, I have written a blog post about What's new in View Component : ASP.NET MVC 6. I have got lots of page view for that blog post and I am thank full to my readers for that. I got email from one of the readers that how we can pass arguments in View Component or how we can filter data in view component? I'm sure lots of people will have same question. So I thought it will a good idea to write a blog post about it.

I'm going to use same application which we have used for previous blog post. In previous application we created Product Categories View Component in this blog post I'm going to create a method in same view component which will display data based on category id passed.

So  now code for the view component will look like following.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using ViewComponentMVC.Models;

namespace ViewComponentMVC
{
    [ViewComponent(Name = "ProductCategoriesComponent")]
    public class CategoryViewComponent : ViewComponent
    {
        private readonly List<Category> _categories;
        private CategoryViewComponent()
        {
            _categories = new List<Category>()
           {
               new Category {CategoryId = 1, Name = "Clothes",Description = "Men and women's clothes"},
               new Category {CategoryId = 2, Name = "Elentronics", Description = "Eletronics"}
           };
        }
        public IViewComponentResult Invoke()
        {
          
            return View(_categories);
        }

        public IViewComponentResult Invoke(int categoryId)
        {
            var category = _categories.FindAll(c => c.CategoryId == categoryId).ToList();
           return View(category);
        }
    }
}

If you see above code then you will realize that I have made category list read-only and used in both invoke methods. And created a new Invoke method that expects a category id as parameter and based on category id it will filter categories list with linq and return a view.

Now I have putted same thing in about view like following.
@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p><div>
    @Component.Invoke("ProductCategoriesComponent",1)
</div></p>

Now when you run this application it load home page with both categories like following.



Now when you click on about and see same view filtration it will look like following.

about-view-component-asp-net-mvc6 

That's it. Hope you like it. You can see how its easy to pass argument and override invoke method in ASP.NET MVC 6. Stay tuned for more!.
You can find complete source code of this and earlier blog post  at following location on github-https://github.com/dotnetjalps/ViewComponentMVC6
Share:
Tuesday, October 6, 2015

What's new in View Component : ASP.NET MVC 6

There are lots of new features added with ASP.NET MVC 6 and View components is one of them.  In this blog post we are going to learn about View Component in ASP.NET MVC 6 in detail.

What is View Components and how it is different from partial views:


As per ASP.NET official web site
New to ASP.NET MVC 6, view components (VCs) are similar to partial views, but they are much more powerful. VCs include the same separation-of-concerns and testability benefits found between a controller and view. You can think of a VC as a mini-controller
So the first question comes in our mind is why we need a View Component as all? As partial views are there and its serving its purpose very well.  But if you have worked with partial views you know that there is a limitation for partial views you can not have controller associated with it. You have to use Child actions with partial views and as you now when you mark any actions with child actions it will only allow for child you can not use that as a complete action. Also it will make a extra server trip which could make your application slow if you have a very complex view.  That where View Component can help.  It's contains a view and backing class It's not a 100% controller but it acts like a controller.

Let's create a View component that can be reused at multiple places. Think about a ECommerce application where you have multiple product categories which can be displayed multiple places in ECommerce application. We are going to create a view component that will list multiple categories.

How to create View Component in ASP.NET MVC 6 Application:


So to create a View component we need a ASP.NET 5 ASP.NET MVC 6 application. So have created web application from Visual Studio 2015.

mvc-view-component-application

Then created a model class category for storing categories information.
namespace ViewComponentMVC.Models
{
    public class Category
    {
        public int CategoryId { get; set; } 
        public string Name { get; set; }
        public string Description { get; set; }
    }
}
Then created a View component with following code.
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using ViewComponentMVC.Models;

namespace ViewComponentMVC
{
    [ViewComponent(Name = "ProductCategoriesComponent")]
    public class CategoryViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
           var categories = new List<Category>()
           {
               new Category {CategoryId = 1, Name = "Clothes",Description = "Men and women's clothes"},
               new Category {CategoryId = 2, Name = "Elentronics", Description = "Eletronics"}
           };
            return View(categories);
        }

    }
}
Here there are three things to notice

  1. I have inherited class from ViewComponent from Microsoft.AspNet.MVC name space
  2. I have created a invoke method which will return data for the view. In our case we have created manual list as we don't need database for this example. But you can write any code for the same.
  3. See view component attribute on the top of class. We need to use same name when call this view component.
Now it's time to create a view for the view component. I have created this component under /Views/Home/Components/ProductCategoriesComponent/default.html as we have given same name in attribute. As this view component is used home/index.cshml I have putted there but if you have generic view than you can put that in share component also. Following is a code for the same. A simple ul-li listing.
@model IEnumerable<Category>
<ul>
   @foreach (var category in Model)
   {
       <li>@category.Name </li>
   }
</ul>
Now it's time to use this view component in one of view. I have putted following code in Views/Home/Index.cshtml.
<div>
    @Component.Invoke("ProductCategoriesComponent")
</div>
When you run this application, It will look like following in browser

view-component-mvc6-brower-rendering.

So you can see how our hard code categories renders under view. Even you can passed argument with view component invocation that we will see in future blog post.
You can find complete source code of this application at following location on github- https://github.com/dotnetjalps/ViewComponentMVC6
Hope you like it. Stay tuned for more!!
Share:
Saturday, October 3, 2015

Routing with UI-Router and Angular.js

In Today's world, Angular.js is one of best JavaScript framework available to create Single page applications. It's provides some great features and with the help of this features we can built great interactive apps. In any single page application routing is very important as in most of the time single page application will not have full post backs. So routing will be very important to give feel like normal page application and sometimes proper routing will increase search engine ranking also.

So in this blog post we are going to learn how we can create routes in Angular.js application with help of UI-Router.

What is UI-Router:


UI-Router is a routing frame work created Angular.js team and its not a part of Angular.js But it built on top of Angular.js. You can say it's a 3rd-Party module and is very powerful. It support most of things that we can do with ng-route and also do many other stuff that is not possible with ng-route.
You can find more information about UI-Router at following link.

https://github.com/angular-ui/ui-router
http://angular-ui.github.io/ui-router/site/#/api/ui.router

Here are few features that is provided by UI-Router.
  1. UI-Router allows nested views and multiple views
  2. It allows you to strong type linking between state based on state names.
  3. State allows you to map and access different information about different states and you can easily pass information between states via $Stateparams parameter.
  4. With states approach your views are not tied to the URL and it is tied to states. Which can be very useful in large applications as you can change UI part without changing URLs.
  5. You can also change Partial UI of application which is not possible with ng-route.

So what are we waiting for let's create a sample application with UI-Router and Angular.js.

Sample application with UI-Router:


I'm going to use visual studio for creating this sample application. So that we can use IIS local express to host this application. I'm going to create asp.net web application.

angular-Ui-route-demo-project

We are going to use empty asp.net web forms application as we are not going to use asp.net code here it's a simple HTML page application to demonstrate the power of UI-Router.

empty-web-application-angular-ui-route-demo
We are going to create sample application with 3 pages.
  1. Home
  2. About Us
  3. Contact Us

So for that we need three html pages which will acts as partial views just like ASP.NET MVC partial views or user control in ASP.NET Web Forms.
I'm going to create a very basic HTML pages with following code.
home.html page code:
<h1>Home</h1>
About Us HTML page code:
<h1>About us page</h1>
Contact Us HTML page code:
<h1>contact us </h1>
And now we are going create index.html and following is a code for that.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Angular UI Router Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="routerDemoApp">
    <ul >
        <li><a ui-sref="home">Home</a></li>
        <li><a ui-sref="aboutus">About us</a></li>
        <li><a ui-sref="contactus">Contact us</a></li>
    </ul>
<div>
    Angualr UI Router Demo
</div>
<div>
    <div ui-view></div>
</div>
</body>
</html>
If you see above code you can see I have added angular.js and angular-ui-router-min.js JavaScript files from the cloud flare CDN and then I have created a ng-app "routerDemoApp" with body tag of html page. I have used UL and Li ta and UI-Sref to create link for our routes. Here also notice ui-view tag in one of div where html pages will be rendered in this div.

So now basic infrastructure is ready now its time to create JavaScript code for our application. So lets create app.js file and write code like following.
// JavaScript source code
var routerDemoApp = angular.module('routerDemoApp', ['ui.router']);

routerDemoApp.config(function ($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/home");

    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })
        .state('aboutus', {
            url: '/aboutus',
            templateUrl: 'aboutus.html'
        })
        .state('contactus', {
            url: '/contactus',
            templateUrl: 'contactus.html'
        });

});
So if you see above code carefully, Here I have created a angular app module called routerDemoApp and I have injected dependency of UI-Router. Then in config function we have created different states for Home, About Us and Contact Us. You can see I have passed two parameter url and template url for each state with respective html pages. Also I have written otherwise function which will return home state by default.

Now let's run this application in browser.

demo-application-browser-ui-router-angularjs

So by default Home page is loaded as you can see and in URL also you have /home now when you click on About us it will load about us page like following.

about-us-demo-page-in-browser-ui-angular-js

So it's very easy to create routing with Angular UI-Router in future post we will see how we can use nested view and multiple view.
You can find complete source code of this application at github on- https://github.com/dotnetjalps/AngularUIRouter
Hope you like it. Stay tuned for more!.
Share:
Friday, October 2, 2015

Convert C# Object into JSON and vice versa using Jil

I have also written couple of posts about converting C# object into JSON and vice versa. Following is a list of post for the same.

Converting a C# Object into JSON string
How to convert C# object into JSON string with JSON.NET

In this blog post we will learn about how we can convert C# object into JSON with Jil- Fast .NET JSON (De)Serializer, Built On Sigil an open source library by stack exchange team.

What is Jil:


Jil is a open source (De) Serializer library written by Kevin Montrose and stack exchange team. It is built on Sigil- with a number of crazy optimization tricks.Sigil is also a custom fast validation helper for .NET CIL Generation. Jil is one of fastest Serializer and deserializer library. It is also open source. You can find more information about at following link.

https://github.com/kevin-montrose/Jil

Example:

So let's create example which demonstrate both Serializing and Deserializing object. So first we will create JSON string from C# object via serializing with Jil and then we again deserialize that string to C# object. I'm going to create a console application for this.

jil-jason-converter

After creating a application first thing we have to do is to add Nuget package from JIl via following command.

nuget-package-jil-json-serializer

I'm going to use a Employee class for this example which have four properties Employee Id, First Name, Last Name and Designation.
namespace CsharpJSON
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Designation { get; set; }
    }
}
Then I have created a function Get Employee function to initialize Employee class with some data.
private static Employee GetEmployee()
{
    var employee = new Employee
    {
        EmployeeId = 1,
        FirstName = "Jalpesh",
        LastName = "Vadgama",
        Designation = "Technial Architect"
    };
    return employee;
}
Now it's time to serialize that employee class into JSON string so I have created  Serialize Employee function.
private static string SerializeEmployee(Employee employee)
{
    using (var output = new StringWriter())
    {
        JSON.Serialize(
           employee,
            output
        );
        return output.ToString();
    }
}
Here you can see I have use JSON.Serialize function which serialize C# object into string writer. Same way I have created Deserialize Employee function to deserialize JSON string created by previous function.
private static Employee DeserializeEmployee(string employeeString)
{
    return JSON.Deserialize<Employee>(employeeString);
}

Here you can see I have used  JSON. Deserialize function to convert JSON string into C# object. Finally I have called this function in my console application Main method and print it with Console.Writeline method.
static void Main(string[] args)
{
    var employee = GetEmployee();
    string employeeSerializedString = SerializeEmployee(employee);

    Console.WriteLine("Serialize Employee");
    Console.WriteLine(employeeSerializedString);

    Console.WriteLine("\n\nDeserializing Employee");
    var employeeDeserialized = DeserializeEmployee(employeeSerializedString);

    Console.WriteLine(employeeDeserialized.EmployeeId);
    Console.WriteLine(employeeDeserialized.FirstName);
    Console.WriteLine(employeeDeserialized.LastName);
    Console.WriteLine(employeeDeserialized.Designation);

    Console.ReadKey();
}

Now when you run application it will generate output like following.

json-csharp-object


You can find complete source code of this application at following location on GitHub- https://github.com/dotnetjalps/CsharpJsonJil

Hope you like it. Stay tuned for more!
Share:

A Better Solution to create PDF with Rotativa and ASP.NET MVC

In most of the line of business application we need some kind of reports. Now days we need those reports as PDF format as it is the most convenient way of storing documents. I have written a post about creating a PDF in ASP.NET MVC with Razor PDF and it is one of the top visited page on my blog.

Creating PDF with ASP.NET MVC and RazorPDF

But now I have found a better way to create a PDF with ASP.NET MVC so I thought it will be a good idea to write a blog post about it. So in this blog post we are going to learn about creating PDF with ASP.NET MVC with the use of Rotativa as open source framework for creating PDF with ASP.NET MVC.

What is Rotativa:


It is a framework created by Giorgio Bozio with the purpose of creating PDF in ASP.NET MVC extremely easy way. It is based on wkhtmltopdf tool to create PDF from html content rendered on browser. It uses the web kit engine which is used by Safari and Chrome browser to render html. And support most of HTML tags and styles. It is a open source command line tools so Giogio has created a nuget package to use this tool as PDF creator. You can find more information about Rotativa from the following links.

http://letsfollowtheyellowbrickroad.blogspot.it/
http://www.codeproject.com/Articles/335595/Rotativa-how-to-print-PDF-in-Asp-Net-MVC

You can find source code of rotativa-

https://github.com/webgio/Rotativa

Now let's create example to demonstrate the power of Rotativa with ASP.NET MVC

Creating PDF with ASP.NET MVC and Rotativa:


So to create example, I have created a ASP.NET MVC application.

asp-net-mvc-pdf-application

The first thing we need to do is to add Rotativa Nuget Package in our application.

nuget-package-for-rotativ-asp-net-pdf
Here is the model class I have used to demonstrate power or Rotativa.
namespace MvcPdf.Models
{
    public class Customer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ProfileImage { get; set; }
    }
}
In this example, we are not going to use any database so we are going to hardcode data in customer. so We have done is hardcode list of customer in controller and returning it to a view.
using MvcPdf.Models;
using Rotativa;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MvcPdf.Controllers
{
    public class CustomerController : Controller
    {
        private List<Customer> _customers;

        public CustomerController()
        {
            var imagePath = "profile.jpg";
            _customers = new List<Customer>()
            {
                new Customer {CustomerId = 1, FirstName = "Jalpesh",
                               LastName = "Vadgama", ProfileImage = imagePath},
                new Customer {CustomerId = 1, FirstName = "Vishal", 
                               LastName = "Vadgama", ProfileImage = imagePath}
            };
        }

        // GET: Customer
        [HttpGet]
        public ActionResult Index()
        {
            return View(_customers);

        }
    }
}
And in view we has displayed this list as table like following.
@model List<MvcPdf.Models.Customer>

@{
    ViewBag.Title = "PDF Title";
  
}

<h2>Convert to  PDF</h2>

<table class="table">
    <tr>
        <td class="alert-success">First Name</td>
        <td class="alert-info">Last name</td>
        <td style="background-color: yellow;">Profile Image</td>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.FirstName</td>

            <td>@item.LastName</td>
            <td><img src="@Url.Content("~/content/" + Path.GetFileName(item.ProfileImage))" alt="" width="100" height="100" /></td>
        </tr>
    }

</table>    
          
@Html.ActionLink("Print", "Print", "Customer")
If you see in above code, I have used a image to display profile pic. I have also used different styles for td element in table to display power of Rotativa. Even I have used hardcoded style directly.  At bottom I have created  Html Action link to print this view as PDF and following is a code the printing this view as PDF in Action Result.
public ActionResult Print()
{
    return new ActionAsPdf("Index", _customers);
}
And when we run this application it looks like following.

browser-demo-pdf

Now when you click on Print it will create a PDF like following.

pdf-created-with-rotativa-with-browser

This was pretty basic demo but there are lots of options also available with Rotativa you can find that options in documentation on Github as well. I have shared same link above.
You can find source code of this sample application on github at following location - https://github.com/dotnetjalps/AspNetMvcPdfRotativa
Hope you like it. Stay tuned for more!!
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews