Writing Entity Framework (EF) Code-First

ASP.NET C#, Info.Tech, Web Development Comments Off on Writing Entity Framework (EF) Code-First

Few days ago, I’ve been solving the issue of my project’s EF Code First. Thanks to Decker Dong’s tips in ASP.net and Ladislav Mrnka in stackoverflow.com. I solved the issue but not sure its the best answer/solution. I am not an expert in EF, Code-First nor ASP.NET. But so far, it works fine. Correction is welcome. 🙂

Here are the common errors I always encounter;

Introducing FOREIGN KEY constraint 'FK_dbo.Requestors_dbo.Projects_ProjectId' on table 'Requestors' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

and …

Unable to determine the principal end of an association between the types 'QICSkillsForce.Models.Requestor' and 'QICSkillsForce.Models.Project'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Honestly, I do not understand much on EF, Code-First, Poco and etc. But trying to learn them. My reference are;

  • http://stackoverflow.com/questions/5368029/need-some-help-trying-to-understand-entity-framework-4-1s-code-first-fluent-api
  • http://stackoverflow.com/questions/4442915/entity-framework-inserting-into-multiple-tables-using-foreign-key

My very question or problem is about relationship, defining them to EF.

Defining the following relationships:

  • 1 Team has 0-many Users. (and a User is in 1 Team)
  • 1 User has 0-or-1 Foo’s (but a Foo has no property going back to a User)
  • 1 User has 1 UserStuff

Answer in Entity Framework (sample):

public class User
{
    public int Id { get; set; }
    ...
    public Foo Foo { get; set; }
    public Team Team { get; set; }
    public UserStuff UserStuff { get; set; }
}

public class Team
{
    public int Id { get; set; }
    ...
    public ICollection<User> Users { get; set; }
}

public class Foo
{
    public int Id { get; set; }
    ...
}

public class UserStuff
{
    public int Id { get; set; }
    ...
}

public class Context : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Team> Teams { get; set; }
    public DbSet<UserStuff> UserStuff { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasRequired(u => u.Team)
            .WithMany(t => t.Users);

        modelBuilder.Entity<User>()
            .HasOptional(u => u.Foo)
            .WithRequired();

        modelBuilder.Entity<User>()
            .HasRequired(u => u.UserStuff)
            .WithRequiredPrincipal();
    }
}

And the result is;

EDMX View

EDMX View

Just as I wanted! Wew!

In addition, I’m also bothered how to insert data to both tables that is related. So I learn that this is how I to do it;

public void populate_projects()
{
            AppDbEntities db = new AppDbEntities();

            var proj = new Project { ProjectName = "Test Project", Description = "description here", DesiredCompletionDate = DateTime.Now, Notes = "notes here", Deleted = false, RemoteJob = true, RequestStatus = "Completed", SkillSet = "ASP.NET, C#", UserId = 1 };
            var req = new Requestor { Name = "User sample", Email = "user@sample.com", DeptId = 2, ApprovedBy = "Admin" };

            proj.Requestor = req;
            db.Projects.Add(proj);
}

I think that’s it.. I have a lot of learning for 3 days straight solving the issues. There are more problems ahead and I eager to solve them. Yeah! (Somehow, there’s some point thinking to give up and use ADO.NET and pure SQL commands! hahahahaa!)

— after couple of hours —

And this is how to query the rows…

CONTROLLER:

        public ActionResult Index()
        {
            // auto insert sample data to the db... [start]
            var count = db.Projects.ToList().Count().ToString();

            var proj = new Project { ProjectName = "Test Project " + count, Description = "description here", DesiredCompletionDate = DateTime.Now, Notes = "notes here", Deleted = false, RemoteJob = true, RequestStatus = "Completed", SkillSet = "ASP.NET, C#", UserId = 1 };
            var req = new Requestor { Name = "User " + count, Email = "user@sample.com", DeptId = 6, ApprovedBy = "Quack" };
            proj.Requestor = req;
            db.Projects.Add(proj);
            db.SaveChanges();
            // auto insert sample data to the db... [end]

            var projects = db.Projects.ToList();
            return View(projects);
        }

MODEL:

            <table border="0" width="100%">
                <tr>
                    <th>Project Name</th>
                    <th>Description</th>
                    <th>Requestor</th>
                    <th>Status</th>
                </tr>
                @foreach (var proj in Model) {
                    <tr>
                        <td>@proj.ProjectName</td>
                        <td>@proj.Description</td>
                        <td>@proj.Requestor.Name</td>
                        <td>@proj.RequestStatus</td>
                    </tr>
                }
            </table>

As you noticed, I access the extended table from Project to Requestor to get its Requestor Name by calling @project.Requestor.Name and it will show the related row from Requestor table.

I found that handy… W00t!

ASP.NET: Guestbook App

ASP.NET C#, Info.Tech, Web Development 2 Comments »

Finally, I created a simple app in ASP.NET with my own, after reading a bunch of guides and tutorials… The app is Guestbook and written in MVC3 C#. Guestbook data is stored in SQL Server Database (mdf) and I use Entity Framework (EF) as my Object Relational Mapping (ORM). Here’s the screenshot;

GuestbookApp

 If you check the codes of this Guestbook App, it demonstrate the following;

  • ASP.NET MVC3 pattern (Visual C# coding)
  • Entity Framework
  • Calling Function from View to Controller
  • Creating custom HELPER in the VIEW (Razor Helper)
  • Clean form-passed variables against XSS attacks (I guess? that’s what they said :))
  • RegEx and its pattern, in this case is about email address

 

 

Download Source code of ASP.NET MVC3 C# below: GuestbookApp (1138)

Use Email as Username with ASP.NET Membership

ASP.NET C#, Info.Tech, Web Development Comments Off on Use Email as Username with ASP.NET Membership

Couple of guides in the internet on using email as username with the ASP.NET Membership but the guide is too long and its a maze and crazy as hell for me.

I found my own answer as simple as I wanted to. In my case, I created my own form.

Form (View):

            <form action="/home/authenticate" method="post" name="login">
                <label>Email</label>
                <input type="text" name="email" />
                <br class="clear" />
                <label>Password</label>
                <input type="password" name="passwd" />
                <br class="clear" />
                <input type="submit" name="submit" value="Login" />
            </form>

 

Authentication (Controller):

        [HttpPost]
        public ActionResult Authenticate()
        {
            Regex regex_email = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");

            var email = Request.Form["email"];
            var passwd = Request.Form["passwd"].Trim();

            if ((!regex_email.IsMatch(email)) || (passwd.Length < 6))
            {
                return RedirectToAction("Index", "Home", new {
                    msg = "Invalid username or password!"
                });
            }
            else 
            {
                string username = Membership.GetUserNameByEmail(email);

                if (Membership.ValidateUser(username, passwd))
                {
                    FormsAuthentication.SetAuthCookie(username, true);
                    return RedirectToAction("Index", "Project");
                }
                else
                {
                    return RedirectToAction("Index", "Home", new {
                        msg = "Invalid username or password!"
                    });
                }
            }
        }

 

I just call the Membership.GetUserNameByEmail() then validate with Membership.ValidateUser().

That’s it! Hope this help to others too.. 🙂

HowTo: Access Controller method/function from a View

ASP.NET C#, Info.Tech, Web Development Comments Off on HowTo: Access Controller method/function from a View

I’ve been wondering how to access the controller method/function from a View. I found a solution from Jeffrey Palermo which he explain it in details. Though, my case that I want to happen is about random numbers.

Controller Codes:

        public ActionResult Welcome(string name, int num = 1)
        {
            ViewBag.Message = "Hello " + name;
            ViewBag.Num = num;
            ViewBag.GetRandom = new Func<int, int, int>(getRandomNumber);

            return View();
        }

        private int getRandomNumber(int min, int max)
        {
            Random rand = new Random();
            return rand.Next(min, max);
        }

View Codes:

<ul>
    @for (int i = 0; i < ViewBag.GetRandom(3, 100); i++)
    {
        <li>@ViewBag.Message</li>
    }
</ul>

or…

@{ ViewBag.Num = ViewBag.GetRandom(3, 100); }

<h2>Welcome</h2>
Generated Random Number: @ViewBag.Num
<ul>
    @for (int i = 0; i < ViewBag.Num; i++)
    {
        <li>@ViewBag.Message</li>
    }
</ul>

One thing that confusing about this sample codes is; During the method declaration from the Controller, you use the new Func<>(method_name) — the first int from <> is the minimum value, 2nd int is the maximum value and the third value is the return value.

Working on Html.ActionLink

ASP.NET C#, Web Development 1 Comment »

Few weeks ago, I’ve been studying Microsoft Visual Studio Web 2012 in my free time and focusing on Visual C# .Net since I have a background on desktop/window application development using Visual C#. I posted this just to remind the things that I took time to figure it out. I’ve been banging my head getting the good answers. Though there’s the MSDN but there’s no samples and I find it horrible documentation.

So, I’m working on ASP.NET MVC 3 Web Application and wondering how I could create the Request URI using Html.ActionLink(). It took me almost an hour to figure it out. Thanks to Gavin Coates for pointing it out what made my codes wrong.

The URI I want to have is;

http://localhost:xxxx/controller/action?task=view&xid=7

The syntax will be (according to http://msdn.microsoft.com/en-us/library/dd492124(v=vs.108).aspx);

public static MvcHtmlString ActionLink(
	this HtmlHelper htmlHelper,
	string linkText,
	string actionName,
	string controllerName,
	Object routeValues,
	Object htmlAttributes
)

And the right codes are;

@Html.ActionLink("Text Here", "ActionName", "ControllerName", new { task = "view", xid = 5 }, null)

That’s it.. It works fine with my app. Wehehe!

What when wrong before I solved was I didn’t put null at the last arguments. If you don’t put null, your object will become a RouteValueDictionary (I think and not sure about this terms yet) which it should be routeValues.

See http://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions(v=vs.108).aspx for more information about this.

Somehow, the link creation above was crossing to another Controller. What if creating a link within a current controller? The answer will be;

@Html.ActionLink("Text Here", "ActionName", new { task = "view", xid = 5 })

As you can see, I didn’t specify the Controller name because you are currently on the controller/page.

Hope this helps too to the newbies… 🙂

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in