Tuesday, January 22, 2013

Display images using entity framework along with MVC4


Create a table in SQL server as follows

USE [forumDB1]
GO

/****** Object:  Table [dbo].[users]    Script Date: 01/23/2013 11:25:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[users](
            [userID] [int] NOT NULL,
            [EmailID] [varchar](50) NOT NULL,
            [Password] [varchar](50) NOT NULL,
            [FirstName] [varchar](50) NOT NULL,
            [LastName] [varchar](50) NULL,
            [JoinedDate] [datetime] NOT NULL,
            [usrImage] [image] NULL,
PRIMARY KEY CLUSTERED 
(
            [userID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
            [EmailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO










After all select your HomeController and change as follows

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

namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        forumDB1Entities dbentity = new forumDB1Entities();
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View(dbentity);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


Also change your view as follows

 @model displaydatausingEF.Models.forumDB1Entities
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
       
    </p>
    <table>
        <tr>
            <th>
                Employee ID
            </th>
            <th>
                Email ID
            </th>
            <th>
                Password
            </th>
            <th>
                &nbsp;First Name
            </th>
            <th>
                &nbsp;Last Name
            </th>
            <th>
                Joined Date
            </th>
            <th>
                Picture
            </th>
        </tr>
        @foreach (var item in Model.users)
        {
            <tr>
                <td>
                    &nbsp;&nbsp;@item.userID
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.EmailID
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.Password
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.FirstName
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;@item.LastName
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.JoinedDate
                </td>
                <td>
                    <img src="@Url.Action(" temp_src="@Url.Action("GetPhoto", new { photoId = item.userID })" />
                </td>
            </tr>
        }
    </table>
</body>
</html>


This will initially give output as follows



Now we will implement the code to show image, add this code to your HomeController

 public ActionResult GetPhoto(int usrID)
        {
            byte[] photo = null;
            var v = dbentity.users.Where(p => p.userID == usrID).Select(img => img.usrImage).FirstOrDefault();
            photo = v;
            return File(photo, "image/jpeg");
        }

Now re-run the application


Happy coding cheers

Monday, January 21, 2013

Online Forum application using Entity Framework


In this article I would like to share how we can build up a forum application which is similar to c# corner. I used the css from the site as I am not well familiar with css.
This application is done using Entity Framework.
Application mainly covers
  •          Registering users.
  •          Checking availability of users.
  •          Posting questions & replies for the questions.
  •          Like the posted questions.
  •          Will not allow self Likes (no chance for liking his own questions).
  •            Will not allow user to like the same question for multiple times.



Sample Images:
Home page:



Home, Questions, Ask Question was developed.


Register


After Login:

Latest Questions:

Post a question:


After successful post questions will display in descending order

Selecting on question will redirect to display page where we can like and post answers

Self Like:

Login as different user and click like will display as follows

Liking the same question by the same user for multiple times

Post a reply


With replies

Multiple likes by different user

Friday, January 4, 2013

Cascading Dropdown List for Country/State/City in ASP.Net using Entity Framework


In this blog I am going to show how we can work with cascading dropdown list for country/state/city in asp.net using Entity Framework.


Create three tables as per our need
CREATE TABLE country
  (
     countryID     INT NOT NULL,
     countryName   varchar(50) NOT NULL,
     PRIMARY KEY (countryID ),
  );
CREATE TABLE state
  (
 stateID     INT NOT NULL,
 countryID INT NOTNULL,
 stateName   varchar(50) NOT NULL,
 PRIMARY KEY (stateID ),
 FOREIGN KEY (countryID ) REFERENCES country (countryID));

CREATE TABLE city
  (
cityID     INT NOT NULL,
 stateID INT NOTNULL,
 cityName   varchar(50) NOT NULL,
 PRIMARY KEY (cityID),
 FOREIGN KEY (stateID) REFERENCES state (stateID));

First create an empty web application



Add model as per we did in earlier for entity framework do the necessary




Add a web page to the solution and copy paste this in .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="cascading.aspx.cs" Inherits="counrtybasedropdown.cascading" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <h3>
                Cascading DropDownList for Country/State/City in ASP.Net</h3>
            <table>
                <tr>
                    <td>
                        Select a Country :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a State :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlState" runat="server" Enabled="false" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a City :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCity" runat="server" Enabled="false">
                        </asp:DropDownList>
                    </td>
                </tr>
            </table>
        </center>
    </div>
    </form>
</body>
</html>
Your .aspx.cs should be as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace counrtybasedropdown
{
    public partial class cascading : System.Web.UI.Page
    {
        Database1Entities dbEntity = new Database1Entities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var country = from c in dbEntity.countries select new { c.countryID, c.countryName };
                ddlCountry.DataSource = country.ToList();
                ddlCountry.DataValueField = "countryID";
                ddlCountry.DataTextField = "countryName";
                ddlCountry.DataBind();
                ddlCountry.Items.Insert(0, "--Select--");
            }
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            int countyID = Convert.ToInt16(ddlCountry.SelectedValue.ToString());
            var state = from s in dbEntity.states where s.countryID.Equals(countyID) select new { s.stateID, s.stateName };
            ddlState.DataSource = state.ToList();
            ddlState.Enabled = true;
            ddlState.DataValueField = "stateID";
            ddlState.DataTextField = "stateName";
            ddlState.DataBind();
            ddlState.Items.Insert(0, "--Select--");
        }

        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            int stateID = Convert.ToInt16(ddlState.SelectedValue.ToString());
            var city = from c in dbEntity.cities where c.stateID.Equals(stateID) select new { c.cityID, c.cityName };
            ddlCity.DataSource = city.ToList();
            ddlCity.Enabled = true;
            ddlCity.DataValueField = "cityID";
            ddlCity.DataTextField = "cityName";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "--Select--");
        }
    }
}

Happy coding..
Feel free to ask queries...

Thursday, January 3, 2013

Dynamic Data Entities Web Application with Entity Framework


In this article I will explain how we can work with Dynamic Data Entities Web Application which is available at the time of creating a project.
In this article I will show how we can implement CRUD operation without writing a single line of code, and by just un-commenting a line in Global.asax file.
The only thing you have to do is to add a reference in Global.asax file with your project name you created. As my project name dynamicdataentities I will add this as a reference as follows
using dynamicdataentities;


The only thing you have to do after this is to un-comment this line of code from Global.asax file
DefaultModel.RegisterContext(typeof(YourDataContextType), new ContextConfiguration() { ScaffoldAllTables = false });

You have to replace this with the following
DefaultModel.RegisterContext(typeof(codeDBEntities), new ContextConfiguration() { ScaffoldAllTables = true });

Here codeDBEntities is nothing but the connection string which is available in Web.config file or you can find it in Model.edmx

First let us create a project by selecting ASP.NET Dynamic Data Entities Web Application as follows



This will create a project with a Master page, a Default page, a Global.asax file along with script and css.
Now let us add Ado.NET Entity Data Model as we did in our last article



As I am already having an connection I am not showing how to add connection, I will proceed with what I have







Open Global.asax file from the solution explorer



You can find some code with comments, we will un-comment the one we needed as follows



Here in place of YourDataContextType you have to replace your context type which will be available in web.config or in Model.edmx





Now run your application



As I integrated 2 tables it is showing those tables, select the required to perform CRUD operations.
I selected Employee and the details are as follows


In the department dropdown you can find out the entire department listed as follows



If I select any that corresponding details were shown as follows



Inserting details to Employee table, if you select Insert New Item it will display as follows



Edit Update screen



Deleting a record:

Before delete: I will delete one of the record


Delete:


After delete:


 Viewing Employees from Department



Details of selected Employee


Any comments welcome..

Please do feel free to ask for any queries...

Popular Posts