Showing posts with label ASP.NET-MVC. Show all posts
Showing posts with label ASP.NET-MVC. Show all posts
Saturday, March 10, 2018

Solution: (Error)Unable to Correct problems, You have held broken packages–Install .NET Core on Ubuntu

Recently, I have been using Linux(Ubuntu) machine on my virtual box quite a bit and as  Microsoft.NET Developer I want to install .NET Core on Ubuntu. So I tried following the instruction from below link to install .NET core on Ubuntu 16.04.

https://docs.microsoft.com/en-us/dotnet/core/linux-prerequisites?tabs=netcore2x

But I was not unable to install .NET Core and I was getting following errors.

The following packages have unmet dependencies:
  dotnet-sdk-2.1.4 : Depends: dotnet-runtime-2.0.5 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
You can see the same error in the following screenshot.

error-ubuntu-net-core-214

I was a little bit curious about that and then I have read carefully the documentation mentioned on the above link and I have found that .NET Core require following require following Ubuntu distributions as Prerequisites.

  • libunwind8
  • liblttng-ust0
  • libcurl3
  • libssl1.0.0
  • libuuid1
  • libkrb5-3
  • zlib1g
  • libicu52 (for 14.X)
  • libicu55 (for 16.X)
  • libicu57 (for 17.X)

Most of the time it should be installed by default with sudo apt-get update and sudo apt-get upgrade command but sometimes it does not. So what I did install all these distributions one by one via sudo apt-get install command and in my case, I was not having liblttng-ust0 distribution on my machine. So I have installed it via the following command.

sudo apt-get install liblttng-ust0
You can also see below screenshot for the same.

install-ubuntu-distribution-for-netcore

Then I was able to install .NET Core on my machine via following above link on documentation.

install-netcore-ubuntu

And now it’s running .NET Core v 2.1.4 on my Ubuntu VirtualBox as you can see it in below dotnet version command.

net-core-version-command

I was able to solve my problem this and so I thought it will be a good idea to share it on my blog so it will help people who are having the same problem.

Stay tuned for more there is a lot more coming for asp.net core and node.js on Linux on future blog posts.
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, May 20, 2014

Learning resources for ASP.NET MVC

I am getting lots of question regarding where to learn ASP.NET MVC. So I thought it will beneficial to write a blog post so that everyone get advantages of it. Today there are multiple resources available to learn ASP.NET MVC here I have listed some of the my favorite resources to learn ASP.NET MVC.

Videos:


Videos are great way to learn any technology and there are many video resources are available.

1) Pluralsight free videos on www.asp.net/mvc:

On the official asp.net mvc site Pluralsight has provided 8 free videos It it a great resource for any to get started with ASP.NET MVC. Some videos are there for ASP.NET MVC 3.0 but still it is worth learning it.

Share:
Sunday, April 27, 2014

Enum support for views in ASP.NET MVC 5.1

Recently before some time Microsoft has announced release of ASP.NET MVC 5.1. It’s comes with tons of feature and  Enum support is one of them. In the earlier release of ASP.NET MVC there was no direct support for the Enums and in the views but with ASP.NET MVC 5.1 Microsoft is providing directly @html.EnumDropDownList for which directly creates a dropdown from the Enum itself. So What we are waiting for. Let’s take an example.

Example of Enum support for views in ASP.NET MVC 5.1:

Let’s create a new empty project for ASP.NET MVC from Visual Studio 2013 like following from File Menu-> New Project

Share:
Saturday, November 30, 2013

Getting started with ELMAH and ASP.NET MVC

We all need a framework to log exceptions in our web application. Today, We are going to learn about same. ELMAH(Error Logging Modules and Handlers) is an application wide error logging framework. How we can install it in ASP.NET MVC.

What is ELMAH:


ELMAH(Error logging Modules and Handlers) is an application wide error logging facility that is an pluggable framework. It can dynamically added to running an ASP.NET application. You also have Nuget package for the same.
You can find more information about on following link.

https://code.google.com/p/elmah/

Once you install ELMAH, You can have following advantages
  1. You can log almost all unhandled exceptions in the system.
  2. An RSS feed of last 15 errors from the log
  3. An email notification of each error occurs.
  4. A remote web page to log all the exceptions.
  5. You can insert log a various locations like files text file, SQL Server, Oracle etc.

ELMAH NuGet Package:


There is a nuget package also available for ELMAH. You can find at following link.

http://www.nuget.org/packages/elmah/

and Following Command you have to run for installing NuGet Pacakge.

ELMAHNuGetPackageASP.NETMVC

Getting Started with ASP.NET MVC and ELMAH:


So Let’s first create a new project with ASP.NET MVC  from Visual Studio via File->New Project –>ASP.NET MVC 4 Application.

ELMAHNewProjectMVC

Once you click OK it will ask you for type of application like following. We are going to select internet application here.

TypeofApplicationELMAHMVC

Once you click on OK it will create new ASP.NET MVC 4 Application. Once our ASP.NET MVC 4 application is ready. It’s time to add ELMAH to ASP.NET MVC4 Application. The best way to add ELMAH is nuget package so we don’t have to worry about the configuration settings in web.config. So Let’s go to Tools-> Library Package Manager-> Package Manger Console and run the NuGet Command like following.

PackageManagerConsoleNuGetPacakgeELMAH

So now if you see in web.config all configuration is added.
Web.ConfigErrorHandlingSection
Now let’s run our asp.net application via pressing f5.

ElMAHASP.NETMVCSite

Now let’s create some unhandled errors for example test Action Result does not exist in our ASP.NET MVC application. So Let’s write that in URL and it will give error like following.

ErrorElMAHASPNETMVC

Now let’s see whether this error is logged by ELMAH or not. Here you go

ErrorLogELMAH

Once you click on details. It will show details error like following.

DetailErroLogELMAH

That’s it. You can see now it’s very easy to log errors and unhandled exceptions in ELMAH. There are various options to log errors in ELMAH we will see that in future posts.

Hope you like it. Stay tuned for more..
Share:
Saturday, July 13, 2013

Compile time view checking for ASP.NET MVC.

While developing an ASP.NET MVC application, you need to create lots of views. At that time it does not compile the view. So if you have some typo in your view like namespace or any where you will get to know when you load that view in browser. At that time ASP.NET Complier will compile the complete view. 

We all are humans and we tends to make spelling mistakes and sometimes it a productivity loss when you create a very big view or complicated view. So I was searching on internet that whether there is a tool available to compile view also. After digging into it. I have found that there is a setting where we can tell whether its compile view or not. So once you enable that settings It will also compile views.
Share:
Sunday, June 9, 2013

Creating PDF with ASP.Net MVC and RazorPDF

Update: I have written a new blog post about better approach to create a PDF with asp.net mvc- You can find that following location.- A Better Solution to create PDF with Rotativa and ASP.NET MVC

In this post we are going to learn how we can easily create PDF from ASP.Net application with the help of Razor PDF NuGet package.

About Razor PDF:


This NuGet package is created by Al Nyveldt It internally uses ITextSharp an open source PDF convertor library. RazorPDF uses Razor View engine to create iTextXML which is in tern used to produce PDF file. You can get more information about that at below link.

https://www.nuget.org/packages/RazorPDF

Example(Creating PDF with ASP.Net MVC):


So what we are we waiting for ? Let’s create a simple example. To create example first thing we need to a create and ASP.Net MVC application.
Share:
Friday, February 1, 2013

Getting started with Twitter Bootstrap and ASP.Net MVC


Update: Now with ASP.NET MVC5 you don't need to install twitter bootstrap nuget package now its by default available with default template.

In this blog I am going explain how we are  going integrate Twitter Bootstrap library with ASP.Net MVC.

What is Twitter bootstrap:

Twitter Bootstrap is open source library created by Twitter. As per twitter it’s Sleek, intuitive, and powerful front-end framework for faster and easier web development. It’s full featured framework for creating web sites. It includes CSS framework, JavaScript, JavaScript plug-ins,typography, Html scaffolding. There are lots of themes also available that are available so you can use that right away.

Integrating Twitter bootstrap with ASP.Net MVC:

Earlier we have to manually integrate Twitter bootstrap into the ASP.NET MVC like here. But now We have Twitter.Bootstrap.MVC4 Nuget packages that saves lots of time to adding bootstrap to MVC4 template. It’s very easily combines bootstrap into ASP.NET MVC application thanks  to it’s authors Matt Hinze and Eric Hexter.

As per Eric Hexter It’s provide following features.
  • JS and CSS bundling/minification of Twitter Bootstrap files the MVC4 way
  • Incorporate a jQuery validation fix to work with the bootstrap javascript
  • Razor Layout templates using Twitter Bootstrap markup.
  • Menus using Navigation Routes, including submenus and hiding menus by context(logged in vs anonymous)
  • Runtime Scaffolding – default Index, Edit and Detail views.. You provide thePOCOs and we will render the CRUDviews.
  • Post Redirect Getsupport using the Bootstrap Alert styles.
  • A Sample to show how to use all of this stuff
Share:
Saturday, July 28, 2012

Multiple file upload with asp.net mvc and HTML5

Few days I have written a blog post about Multiple file upload with asp.net 4.5 and Visual studio 2012. It was greatly appreciated by the community and also been part of www.asp.net community daily spot light.  On that post one of my reader Ciwan Kurd has requested the asp.net mvc version of that post. So in this post I will explain how we can do multiple file upload with HTML5.

For this post I am going to use asp.net mvc 3 with HTML5 template and visual studio 2012 but you can use same techniques in any version of asp.net mvc.  First things we needs to do create a HTML form for the uploading file in asp.net mvc view so following is a code for that.

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <label for="file">Upload Image:</label>
    <input type="file" name="files" value="" multiple="multiple"/>
    <input type="submit" value="Upload Image" />
}

In above code that I have use @HTML.BeginForm to create a HTML form with multipart as this attribute is required to upload any kind of files on the server. I have mapped that form to upload action result. Also I have used the file input control with HTML5 multiple attribute which allow us to upload multiple files on the server. Now its time to write code in asp.net mvc controller. Following is a code for that.
Share:
Friday, May 25, 2012

ASP.NET Web API Basics

We have seen that now web is really becoming cross plate form and you can see your services or API can be exposed to any client. Till now one of big challenges is to choose platform for this kind of service. There are so many options available like web services, WCF services,Generic Handlers, directly writing responses on aspx page etc. There are plenty of options available and each one has their own pros and cons.  But now we have one simpler answer for that is ASP.NET Web API.

What is Web API?

ASP.NET Web API is a framework for building web API on the top of .NET framework. It’s a framework for building and consuming web services that can be use at broad range of clients like browsers,tablets phones etc. You can expose JSON or XML whatever you want to use.

Why to use Web API?

Think about a situation where a jQuery script that is making a ajax request and we need some thing who can expose data from the server to the client at that time WEB API can be very handy you can expose server data in XML or JSON form and you can make that call with simple http request. No lengthy code required to call WEB API.
Share:
Wednesday, August 17, 2011

Creating Basic RSS Reader in ASP.NET MVC 3

In this post I am going to explain you how we can create a basic RSS Reader with the help of Linq-To-Xml and ASP.NET MVC3 Razor. Those who are writing or reading Blogs already knows what is RSS Reader. But those who does not know What is RSS. Below is the definition for RSS as per Wikipedia.


RSS (originally RDF Site Summary, often dubbed Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.[2] An RSS document (which is called a "feed", "web feed",[3] or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship.
 

You can find more information about RSS from the following links.

Now let’s start writing code creating a Basic RSS Reader. So first We need two things to create RSS Reader. A RSS Entity class which hold properties for RSS and Another method which populate IEnumerable of particular RSS Class. We are creating this example with ASP.NET So I have create One Model class called RSS Like following.
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace CodeSimplified.Models
{
public class Rss
{
public string Link { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
}

Now our entity class is ready. Now we need a class and a method which will return IEnumerable of RSS Class. So I have created a Static Class RSS Reader which has “GetRSSFeed” Method which return RSS Feeds like following.

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace CodeSimplified.Models
{
public class RssReader
{
private static string _blogURL = "http://feeds.feedburner.com/blogspot/DotNetJalps";
public static IEnumerable<Rss> GetRssFeed()
{

   XDocument feedXml = XDocument.Load(_blogURL);
   var feeds = from feed in feedXml.Descendants("item")
               select new Rss
               {
                   Title = feed.Element("title").Value,
                   Link = feed.Element("link").Value,
                   Description = Regex.Match(feed.Element("description").Value, @"^.{1,180}\b(?<!\s)").Value

               };

   return feeds;

}
}
}

As you can see in above code. I am loading RSS feed with XDcoument Class with my Blog RSS feed URL and Then I am populating RSS Class Enumerable with the help of the Linq-To-XML. Now We are ready with Our Model classes so Now it’s time to Add ActionResult in Home Controller. So I have added Action Result which return View with RSS IEnumerable like following.

public ActionResult RssReader()
{
    return View(CodeSimplified.Models.RssReader.GetRssFeed());
}

Now everything is ready. So its time to create a view. So I have created strongly typed view for RSS Model class like following.

@model IEnumerable<CodeSimplified.Models.Rss>
@{
ViewBag.Title = "RssReader";
}

<h2>RssReader</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
   Title
</th>
<th>
   Description
</th>
<th>
   Link
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
   <a href="@item.Link" target="_blank">@Html.Encode(item.Title)</a>
</td>
<td>
  @System.Web.HttpUtility.HtmlDecode(item.Description)
</td>
<td>
   <a href="@item.Link" target="_blank">More</a>
</td>
</tr>
}
</table>

Let's run application via pressing F5 and Following is the output as expected.


RssReader

So that’s it. Isn’t that cool? With the few lines of code we have created a Basic RSS Reader. Hope you like it. Stay tuned for more.. Till then Happy Programming..

Shout itkick it on DotNetKicks.com
Share:
Tuesday, August 16, 2011

Setting default value for @Html.EditorFor in asp.net mvc

Yesterday one of my friend asked me to set default value for @HTML.EditorFor in ASP.NET MVC. So I decided to write this blog post. In this blog post I am going to Explain How we create Default values for model Entities. So Let’s start this via taking a simple example Model class called User. In User Model class I have created two properties UserName and UserJoinedDate. Following is a code for that.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;



namespace CodeSimplified.Models

{

public class User

{

    private DateTime _userJoinDate = DateTime.Now;



    public DateTime UserJoinDate

    {

        get

        {

            return _userJoinDate;

        }

        set

        {

            _userJoinDate = value;

        }

    }



    public string UserName

    { get; set; }

}

}
As you can see in above class username is default property while for UserJoinedDate I have used old method of declaring properties. Where I have assigned a private variable with System DateTime.
Now let’s Create a Action Result User in Home Controller like following where I am returning a new User View like following.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;



namespace CodeSimplified.Controllers

{

public class HomeController : Controller

{

    public ActionResult Index()

    {

        ViewBag.Message = "Welcome to ASP.NET MVC!";



        return View();

    }



    public ActionResult About()

    {

        return View();

    }



    public ActionResult User()

    { return View(new CodeSimplified.Models.User()); }

}

}

Now Let’s Create User View from the action right click Add view like following. Here I have created Strongly Typed view like following.


User

Once you click Add It will add a new View like following.

@model CodeSimplified.Models.User



@{

ViewBag.Title = "User";

}



<h2>User</h2>



<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>



@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

    <legend>User</legend>



    <div class="editor-label">

        @Html.LabelFor(model => model.UserJoinDate)

    </div>

    <div class="editor-field">

        @Html.EditorFor(model => model.UserJoinDate)

        @Html.ValidationMessageFor(model => model.UserJoinDate)

    </div>



    <div class="editor-label">

        @Html.LabelFor(model => model.UserName)

    </div>

    <div class="editor-field">

        @Html.te

        @Html.EditorFor(model => model.UserName)

        @Html.ValidationMessageFor(model => model.UserName)

    </div>



    <p>

        <input type="submit" value="Create" />

    </p>

</fieldset>

}



<div>

@Html.ActionLink("Back to List", "Index")

</div>


Now everything is ready so Let's run that in browser. Following is the output as expected.

Browser

So that’s it. It’s very easy. Hope you liked it. Stay tuned for more.. Till then happy programming.

Shout itkick it on DotNetKicks.com
Share:
Thursday, May 19, 2011

Insert with Dapper Micro ORM and ASP.NET MVC 3

As I have already posted about the how to fetch data in my earlier post for Dapper ORM. In this post I am going to explain how we can insert data with the dapper ORM. So let’s extend the earlier post project. As explained in earlier post I have already created a class called CustomerDB this class will contains all the operation with Dapper Micro ORM. So For inserting data let’s first create CREATE method like following in CutomerDB Class like following. In that I have create a simple Insert Query in string and then using connection.execute method to execute method. Following is code for that.
public class CustomerDB
{
  public string Connectionstring = @"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

  public IEnumerable<Customer> GetCustomers()
  {
      using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
      {
          sqlConnection.Open();
          var customer = sqlConnection.Query<Customer>("Select * from Customer");
          return customer;

      }
  }

   
  public string  Create(Customer customerEntity)
  {
      try
      {
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
          {
              sqlConnection.Open();
           
              string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
              sqlConnection.Execute(sqlQuery,
                                    new
                                        {
                                            customerEntity.FirstName,
                                            customerEntity.LastName,
                                            customerEntity.Address,
                                            customerEntity.City
                                        });

              sqlConnection.Execute(sqlQuery);
              sqlConnection.Close();

          }
          return "Created";
      }
      catch (Exception ex)
      {
          return ex.Message;
      }

  }

}
Now we are ready with Create Method for database now let’s create two ActionResult for the Creating customer like following in Customer Controller like following.
public ActionResult Create()
{
return View();
}

//
// POST: /Customer/Create

[HttpPost]
public ActionResult Create(Customer customer)
{
try
{
    // TODO: Add insert logic here
    var customerEntities = new CustomerDB();
    customerEntities.Create(customer);
    return RedirectToAction("Index");
}
catch
{
    return View();
}
}
Now we are ready with the both ActionResult. First ActionResult will return simple view of Create which we are going to create now and another ActionResult Create will get customer object from the form submitted and will call our create method of CustomerDB Class. Now it’s time to create a view for adding customer. Right Click return view Statement in Create Action Result and Click Add View and Just Create view like following.

CreateView
That’s it now we are ready. Now let’s test it in browser. Like following.

AddNew
Now let’s click and create and then it will redirect us to customer list page like following. Where you can see the newly added details.

View
So that’s it. Its very easy to Insert data with Dapper Micro ORM. Hope you like it…Stat tuned for more.

Note: For reference of this post you can also see my first post called -Playing with dapper Micro ORM and ASP.NET MVC 3.0.
kick it on DotNetKicks.com
Shout it
Share:
Monday, May 16, 2011

Playing with dapper Micro ORM and ASP.NET MVC 3.0

Some time ago Sam Saffron a lead developer from stackoverflow.com has made dapper micro ORM open source. This micro orm is specially developed for stackovewflow.com for keeping performance in mind. It’s very good single file which contains some cool functions which you can directly use in your browser. So I have decided to have a look into it. You can download dapper code from the following location it’s a single static class file called SQLMapper.

http://code.google.com/p/dapper-dot-net/

So once you download that file you can use that file into your project. So I have decided to create a sample application with asp.net mvc3. So I have created a simple asp.net mvc 3 project called DapperMVC. Now let’s first add that SQLMapper class file into our project at Model Folder like following.

SQLMapper

Now let’s first create sample table from which we will fetch the data with the help of dapper file. I have created sample customer table with following script.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
 [CustomerId] [int] NOT NULL,
 [FirstName] [nvarchar](50) NULL,
 [LastName] [nvarchar](50) NULL,
 [Address] [nvarchar](256) NULL,
 [City] [nvarchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
 [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Once I have created table I have populated some test data like following.

TestData

Now we are ready with database table Now its time to add a customer entity class. So I have created sample customer class with properties same as Database columns like following.

public class Customer
{
 public int CustomerId { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string Address { get; set; }
 public string City { get; set; }
}

Now we are done with the Customer Entity class then I have created a new class called CustomerDB and a created a GetCustomer Method where I have used Query Method of Dapper to select all customers with ‘select * from customer’ simple query. I know it’s not a best practice to write ‘select * from customer’ but this is just for demo purpose so I have written like this. Query method accepts query as parameter and returns IEnumerable<T> where T is any valid class. In our case it will be Customer which we have just created before. Following is the code for CustomerDB Class.

using System.Collections.Generic;

public class CustomerDB
{
 public string Connectionstring=@"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

 public  IEnumerable<Customer> GetCustomers()
 {
     using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
     {
         sqlConnection.Open();
         var customer = sqlConnection.Query<Customer>("Select * from Customer");
         return customer;

     }
 }

}

Now we are ready with our model classes now It’s time to Create a Controller so I have created a Customer Controller like following.

CustomerController

It will create customer controller in controller folder with by default ActionResult Index. I have modified Action Result just like to following to return customerEntities with IndexView.

public class CustomerController : Controller
{
 //
 // GET: /Customer/

 public ActionResult Index()
 {
     var customerEntities = new CustomerDB();
     return View(customerEntities.GetCustomers());

 }

}

Now we are ready with our Customer Controller and now it’s time to create a view from the customer entities. So I have just right clicked customer entities and Create a View like following.

AddingView

It will popup the following dialogbox where I have selected Razor View with Strongly Typed View. Also I have selected Customer Model class customer and selected list template like following.

RazorView

That’s it now we are done with all the coding and It’s now time to run the project and result is as accepted as following.

Browser

That’s it. Isn’t that cool? Hope you liked this. Stay tuned for more.. Happy programming

Shout it

kick it on DotNetKicks.com
Share:
Friday, May 13, 2011

Nav tag in HTML5

HTML5 is great new version of HTML with great features. I am exploring that in great details for our forthcoming projects. I found a great tag that can be used in all websites for the navigation. <nav> tag defines a area for navigation in whole HTML markup.

The HTML5 specification for nav tag is like following. You can find all the HTML 5 specification here.
The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links. Not all groups of links on a page need to be in a nav element only sections that consist of major navigation blocks are appropriate for the nav element. In particular, it is common for footers to have a list of links to various key parts of a site, but the footer element is more appropriate in such cases, and no nav element is necessary for those links.
<nav> tags can be used as navigation area and under it you can put the group of links that will use for navigation of area. For example if you have downloaded the ASP.NET MVC3 tool update with HTML5 then you can see they have defined the navigation area with nav tags like following.

<nav>
   <ul id="menu">
       <li>@Html.ActionLink("Home", "Index", "Home")</li>
       <li>@Html.ActionLink("About", "About", "Home")</li>
   </ul>
</nav>

As you can see in above they putted Home and About link in the navigation. So now its with the nag tag the html mark-up is more readable. Once its loaded in browser it and if you view source it will be populate as groups of link in nav tag like following.


<nav>
               <ul id="menu">
                   <li><a href="/">Home</a></li>
                   <li><a href="/Home/About">About</a></li>
               </ul>
</nav>

So that’s it You can see its very easy to use and now we have very readable and clear markup with HTML5. Stay tuned for more.. Happy Programming.

Shout it

kick it on DotNetKicks.com
Share:

HTML5 Intellisense in Visual Studio 2010/2008

Recently I was playing with HTML5 and I was in need of the HTML5 intellisense in Visual Studio 2010. I found a great extension which will provide me a great intellisense for HTML5. I thought its great to share with you all.  You can download that tool from following link.

http://visualstudiogallery.msdn.microsoft.com/d771cbc8-d60a-40b0-a1d8-f19fc393127d

Once you download install it. You need to change your validation to HTML5 in your Visual Studio 2010 configuration. For that you have to go to Tools->Options->Text Editor->HTML->Validation and there you need to select the HTML5 like following.

ToolsForVisualStudio2010

That’s it now your visual studio 2010 or 2008 will have intellisense for HTM5. Just like following.

Intellisense

That’s it. Hope you like it. Stay tuned for more..Happy programming.

Shout it

kick it on DotNetKicks.com
Share:
Monday, April 11, 2011

New search feature Navigate To in Visual Studio 2010

While you are doing code review then it is very necessary to search code and navigate code what you are reviewing and Navigate To feature of Visual Studio 2010 is made for the same. With the help of that feature you can easily navigate through code. You can go to Navigate Window via Edit-> Navigate To or you can directly apply Ctrl + , like following.

NavigateTo

After clicking on Navigate Too a window will open like following.

NavigateToWindow

Now you can navigate to any code with this window like following.It’s a incremental search so once you started typing it will automatically filter it self.

NavigateToSearch

So If you know the method name and anything related to project then it very easy to search with this feature. Hope you liked it. Stay tuned for more.. Happy Programming.

Shout it

kick it on DotNetKicks.com
Share:
Wednesday, March 23, 2011

Working with more then one web.config files in asp.net application.

Recently one of reader of my blog how we can work with more then one web.config files in asp.net application. So I decided to blog about that. Here is the my reply for that.

You can work with more then one web.config file in asp.net. But you can not put more then one web.config in each folder. Let’s first understand the hierarchy of web.config and other configuration file settings. On the top of the every configuration files you will have machine.config file which will have all system wide configuration settings.You can find this file in your OS drive like C: /windows/Microsoft.NET/vFrameworkNumber/Config folder. Here framework number with what ever framework you are using 1.1/2.0 or 4.0. You can override those settings in web.config file at the your application root folder. Same way you can add more web.config file in subfolder and can override the setting of parent folder web.config file. So we will hierarchy like below.

Hirerchay

Now let’s Create Project for it. In that I have create two web.config and 2 pages. First I have putted the web.config in root folder and then I have putted web.config in subfolder. Same way I have created a sub folder and then I have putted the web.config in sub folder. I have also putted one asp.net page in root as well as subfolder to use respective web.config settings. Here are my folder structure like below.

FolderStructure

Below is code for root folder web.config

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<appSettings>
<add key="root" value="This is from root web.config"></add>
<add key="MySetting" value="This my settings is from root web.config"></add>
</appSettings>

</configuration>

and following is code for sub folder web.config.

<?xml version="1.0"?>
<configuration>
<system.web>
</system.web>
<appSettings>
<add key="sub" value="This is from sub web.config settings"></add>
<add key="MySetting" value="This my settings is from sub folder web.config"></add>
</appSettings>
</configuration>


After that I have written a code in root asp.net page to print settings from web.config folder like this following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MoreWebConfig
{
public partial class Root : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Root"));
Response.Write("<BR>");
Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("MySetting"));

}
}
}

Same way I have wrriten code in subfolder like following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MoreWebConfig.SubFolder
{
public partial class SubFolderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Sub"));
Response.Write("<BR>");
Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("MySetting"));

}
}
}

Now let’s run the both pages in browser one by one and you can see root folder application page is fetching settings from root folder web.config while sub folder application page is fetching setting from subfolder web.config even if key ‘mysetting’ is same on both as expected. You can see out put in browser below.

Root.aspx

Root

SubFolderPage.aspx

SubFolder

So it’s very easy to work with multiple web.config. The only limitation of this you can not access sub folder web.config settings from root folder page. Except all you can use anything. Hope you liked it. Stay tuned for more..Happy programming..


Technorati Tags: ,
Shout it
kick it on DotNetKicks.com
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