Solved

ASP.net mvc application reference error

Posted on 2014-09-11
3
440 Views
Last Modified: 2014-09-15
I saw this ASP.NET MVC example  on using jqgrid

http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx/

In this example they are using Lind database model.

I switched up the data model in my example to use Entity Database First model. So my data model is called HaackOverflowEF.edmx.

The example code in the link above was done using Visual Studio 2010.

So when I used Visual Studio 2010 and ran my application, it works just fine.  
My Visual Studio 2010 directory looks like this:

my visual studio 2010 directory
The code for my HomeController.cs in my Visual Studio 2010 application looks like this:

// The example is a modification of the example created by Phil Haack
// see http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx
using System.Linq;
using System.Web.Mvc;
using jqGridWeb.Models;
using System.Data.Objects;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Text;
using System;
using System.Reflection;

namespace jqGridWeb.Controllers
{
    // to send exceptions as json we define [HandleJsonException] attribute
    public class ExceptionInformation {
        public string Message { get; set; }
        public string Source { get; set; }
        public string StackTrace { get; set; }
    }
    public class HandleJsonExceptionAttribute : ActionFilterAttribute {
        // next class example are from the http://www.dotnetcurry.com/ShowArticle.aspx?ID=496
        public override void OnActionExecuted(ActionExecutedContext filterContext) {
            if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null) {
                filterContext.HttpContext.Response.StatusCode =
                    (int)System.Net.HttpStatusCode.InternalServerError;

                var exInfo = new List<ExceptionInformation>();
                for (Exception ex = filterContext.Exception; ex != null; ex = ex.InnerException) {
                    PropertyInfo propertyInfo = ex.GetType().GetProperty ("ErrorCode");
                    exInfo.Add(new ExceptionInformation() {
                        Message = ex.Message,
                        Source = ex.Source,
                        StackTrace = ex.StackTrace
                    });
                }
                filterContext.Result = new JsonResult() {Data=exInfo};
                filterContext.ExceptionHandled = true;
            }
        }
    }

    public class Filters {
        public enum GroupOp {
            AND,
            OR
        }
        public enum Operations {
            eq, // "equal"
            ne, // "not equal"
            lt, // "less"
            le, // "less or equal"
            gt, // "greater"
            ge, // "greater or equal"
            bw, // "begins with"
            bn, // "does not begin with"
            //in, // "in"
            //ni, // "not in"
            ew, // "ends with"
            en, // "does not end with"
            cn, // "contains"
            nc  // "does not contain"
        }
        public class Rule {
            public string field { get; set; }
            public Operations op { get; set; }
            public string data { get; set; }
        }

        public GroupOp groupOp { get; set; }
        public List<Rule> rules { get; set; }
        private static readonly string[] FormatMapping = {
            "(it.{0} = @p{1})",                 // "eq" - equal
            "(it.{0} <> @p{1})",                // "ne" - not equal
            "(it.{0} < @p{1})",                 // "lt" - less than
            "(it.{0} <= @p{1})",                // "le" - less than or equal to
            "(it.{0} > @p{1})",                 // "gt" - greater than
            "(it.{0} >= @p{1})",                // "ge" - greater than or equal to
            "(it.{0} LIKE (@p{1}+'%'))",        // "bw" - begins with
            "(it.{0} NOT LIKE (@p{1}+'%'))",    // "bn" - does not begin with
            "(it.{0} LIKE ('%'+@p{1}))",        // "ew" - ends with
            "(it.{0} NOT LIKE ('%'+@p{1}))",    // "en" - does not end with
            "(it.{0} LIKE ('%'+@p{1}+'%'))",    // "cn" - contains
            "(it.{0} NOT LIKE ('%'+@p{1}+'%'))" //" nc" - does not contain
        };
        internal ObjectQuery<T> FilterObjectSet<T> (ObjectQuery<T> inputQuery) where T : class {
            if (rules.Count <= 0)
                return inputQuery;

            var sb = new StringBuilder();
            var objParams = new List<ObjectParameter>(rules.Count);

            foreach (Rule rule in rules) {
                PropertyInfo propertyInfo = typeof (T).GetProperty (rule.field);
                if (propertyInfo == null)
                    continue; // skip wrong entries

                if (sb.Length != 0)
                    sb.Append(groupOp);

                var iParam = objParams.Count;
                sb.AppendFormat(FormatMapping[(int)rule.op], rule.field, iParam);

                ObjectParameter param;
                switch (propertyInfo.PropertyType.FullName) {
                    case "System.Int32":  // int
                        param = new ObjectParameter ("p" + iParam, Int32.Parse (rule.data));
                        break;
                    case "System.Int64":  // bigint
                        param = new ObjectParameter ("p" + iParam, Int64.Parse (rule.data));
                        break;
                    case "System.Int16":  // smallint
                        param = new ObjectParameter ("p" + iParam, Int16.Parse (rule.data));
                        break;
                    case "System.SByte":  // tinyint
                        param = new ObjectParameter ("p" + iParam, SByte.Parse (rule.data));
                        break;
                    case "System.Single": // Edm.Single, in SQL: float
                        param = new ObjectParameter ("p" + iParam, Single.Parse (rule.data));
                        break;
                    case "System.Double": // float(53), double precision
                        param = new ObjectParameter ("p" + iParam, Double.Parse (rule.data));
                        break;
                    case "System.Boolean": // Edm.Boolean, in SQL: bit
                        param = new ObjectParameter ("p" + iParam,
                            String.Compare(rule.data, "1", StringComparison.Ordinal) == 0 ||
                            String.Compare(rule.data, "yes", StringComparison.OrdinalIgnoreCase) == 0 ||
                            String.Compare(rule.data, "true", StringComparison.OrdinalIgnoreCase) == 0?
                            true:
                            false);
                        break;
                    default:
                        // TODO: Extend to other data types
                        // binary, date, datetimeoffset,
                        // decimal, numeric,
                        // money, smallmoney
                        // and so on

                        param = new ObjectParameter ("p" + iParam, rule.data);
                        break;
                }
                objParams.Add (param);
            }

            ObjectQuery<T> filteredQuery = inputQuery.Where (sb.ToString ());
            foreach (var objParam in objParams)
                filteredQuery.Parameters.Add (objParam);

            return filteredQuery;
        }
    }

    //[HandleError]
    [HandleJsonException]  
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
        }

        public JsonResult DynamicGridData(string sidx, string sord, int page, int rows, bool _search, string filters)
        {

            var context = new HaackOverflowEntities();
            var serializer = new JavaScriptSerializer();
            Filters f = (!_search || string.IsNullOrEmpty (filters)) ? null : serializer.Deserialize<Filters> (filters);
            ObjectQuery<Question> filteredQuery =
                (f == null ? context.Questions : f.FilterObjectSet (context.Questions));
            filteredQuery.MergeOption = MergeOption.NoTracking; // we don't want to update the data
            var totalRecords = filteredQuery.Count();

            var pagedQuery = filteredQuery.Skip ("it." + sidx + " " + sord, "@skip",
                                                new ObjectParameter ("skip", (page - 1) * rows))
                                         .Top ("@limit", new ObjectParameter ("limit", rows));
            // to be able to use ToString() below which is NOT exist in the LINQ to Entity
            var queryDetails = (from item in pagedQuery
                                select new { item.Id, item.Votes, item.Title }).ToList();

            return Json(new {
                            total = (totalRecords + rows - 1) / rows,
                            page,
                            records = totalRecords,
                            rows = (from item in queryDetails
                                    select new[] {
                                        item.Id.ToString(),
                                        item.Votes.ToString(),
                                        item.Title
                                    }).ToList()
                        });
        }

        public ActionResult About ()
        {
            return View();
        }
    }
}

Open in new window


Like i said, my Visual Studio 2010 application ran just fine.

So since i'm using Visual Studio 2013 Ultimate , I tried to open my Visual Studio 2010 project with it but it would not let me upgrade it and said project not supported.

So then I figured I would create the exact same project from scratch in Visual Studio 2013 instead of converting it.

So then my Visual Studio 2013 ASP.NET MVC application looks like this and I'm using Entity Framework 6.

I have the exact same code and directory structure as in my Visual Studio 2010 project. I re-created the entity model in this visual studio 2013 project.

But now I'm getting one error. The image below shows the error.

error message
Anyone know why I'm getting this error or am I missing something?

The code is the same in both projects but I'm getting this one error.
0
Comment
Question by:maqskywalker
  • 2
3 Comments
 
LVL 1

Author Comment

by:maqskywalker
Comment Utility
I did a little more research.

So I created a different jqgrid exampl. This time i did a ASP.NET Web Forms example.

So I did my example using Visual Studio 2010 , C#, Web Forms and targeting .NET 4.
In my project i installed Entity Framework 6.1.1 by typing this at the console manager.    

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

Install-Package EntityFramework

So after I Installed Entity Framework 6.1.1 in my Visual Studio 2010 project I then created Northwind.edmx

My jqgrid just binds the Employees table from that model.
So then I ran my project and it works just fine.

This is what my model in solution explorer looks like:

my Northwind.edmx model in Visual Studio 2010 Solution Explorer
So then I created the exact same example in Visual Studio 2013 and I also used Entity Framework 6.1.1.

But I noticed one thing, in my Visual Studio 2013 when I created my Northwind.edmx model.  When I look at the structure in Solution Explorer it looks a little different than it does in Visual Studio 2010.

This is what it looks like in Visual Studio 2013:

my Northwind.edmx model in Visual Studio 2013 Solution Explorer
If you look at my picture of Northwind.edmx in Visual Studio 2010 above, that one has some items that containt ObjectSet  in it.
Whereas my Visual Studio 2013 model in solution explorer doesn't have these items and I believe that is why I'm getting the exact same error in both of my visual studio 2013 examples.

Both my examples work just when when I use EF 6.1.1 in Visual Studio 2010 but I get this same error in both my example when I use EF 6.1.1 in Visual Studio 2013.

Anyone know why I'm getting this error? How do i fix it?

The line of code I'm getting the error is this.

            ObjectQuery<Employee> filteredQuery =
                f == null ? context.Employees : f.FilterObjectSet(context.Employees);


Do I have to change the syntax on this line?
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
Your original code was using type inference. For whatever reason, 2013 cannot determine the types to plug in to the generic method's type parameters (during compilation). Just specify them yourself by including the angle brackets and an appropriate type.

e.g.

...  f.FilterObjectSet<[insert type her]>(context.Questions));

Open in new window

0
 
LVL 1

Author Comment

by:maqskywalker
Comment Utility
I'm confused, so what would i type inside the < >   ?

My Entity Model called Northwind.edmx just has the Employees table of the Northwind database modeled in the diagram.

The only columns I'm using in my grid are  EmployeeID which is Integer, LastName which is nvarchar(20), FirstName which is nvarchar(10) and Title which is nvarchar(30)
 

So would my line look like this? what would I type inside  the angle brackets?


ObjectQuery<Employee> filteredQuery =
                f == null ? context.Employees : f.FilterObjectSet<??????????>(context.Employees);




I saw this link, with possible solution, but that doesn't make sense to me.

http://www.trirand.com/blog/?page_id=393/help/using-jqgrid-with-dbcontext-code-first-techinques
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video discusses moving either the default database or any database to a new volume.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now