How To Fix Archives - Page 6 of 12 - Digital Tool Factory blog How To Fix Archives - Page 6 of 12 - Digital Tool Factory blog

The Digital Tool Factory Blog

How to fix problems with asp.net mvc 3 and jQuery UI AutoComplete

The Problem:

You’re tooling along, using the jQuery library to write some great search feature, and you write some great Linq to Sql code.  Being an awesome coder your use the extension method syntax.  Your action result (in the appropriate controller) looks like this

public ActionResult QuickSearch(string term)
{
var lst = context.Contacts.Select(xx => new {FullName= xx.FirstName +” ” + xx.LastName }).Where(xx => xx.label.ToUpper().Contains(term.ToUpper())).ToList();
return Json(lst,JsonRequestBehavior.AllowGet);
}

And for no good reason, you get no results when you try to search for a contact.  All you get is a blank drop down.  Why has jQuery UI failed you?  Why must javascript code always be so finicky?

The Cause:

For good reason Jquery UI Autocomplete uses JSon for remote data.  It looks for a predefined format, and it wants that name to be called “label”.  It is case sensitive.

The Solution:

Just change your ActionResult to look like this

public ActionResult QuickSearch(string term)
{
var lst = context.Contacts.Select(xx => new {label= xx.FirstName +” ” + xx.LastName }).Where(xx => xx.label.ToUpper().Contains(term.ToUpper())).ToList();
return Json(lst,JsonRequestBehavior.AllowGet);
}

and you will be golden.  Please note I changed FullName to label.  Jquery UI Autocomplete is a very nice and useful tool, but it demands to work on it’s own terms.  Beyond that I have never had a problem with this wonderful bit of ajax goodness.


29
Mar 12


Written By Steve French

 

How to fix the “Could not read metadata, possibly due to insufficient access rights” error in Sql Server 2008

The Problem

You are doing the responsible thing and make a backup before you make any crazy changes to your Sql Server 2008 database.  You choose the option that gives you the most flexibility and decide to script your backup.  Who knows where this backup will eventually go?

You go through the Tasks>Script Database, and you get the following error

Microsoft.SqlServer.Management.Smo.SmoException: Could not read metadata, possibly due to insufficient access rights. at Microsoft.SqlServer.Management.SqlScriptPublish.GeneratePublishPage.worker_DoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

The Cause

If I had to guess, I would say that the scripting engine is assuming too much in terms of login.  In any case, just try the option below.

The Solution

Instead of having the “Script Entire Database and Database Objects” radio button checked, instead select “Select specific database options” and just check all three options.  That gives you a large text file containing your database scheme and all of the data that your database contains.


21
Mar 12


Written By Steve French

 

How to fix yet another You must set this property to a non-null value of type ‘Double’ problem with Entity Framework

The Problem

You are coding happily away in Visual Studio 2010, working on your asp.net project, using the entity framework and sql server and you get and you get the following error

The ‘Amount’ property on ‘SomeTable’ could not be set to a ‘Decimal’ value. You must set this property to a non-null value of type ‘Double’.

What you say?  Why do I have to set it to non-nullable? It looks something like

public double? Amount { get; set; }

The Cause

The root problem is in your database schema  – something in how that table is set up is not gibing correctly with entity framework.

The Solution

Just set the property to a non-nullable decimal type, for example

public decimal Amount { get; set; }

It’s not a perfect solution, but Entity Framework does not like all sql server data types, and I have yet to find an explanation as to why or a list of things to avoid.  If anyone does know please leave a link in the comments.  This is a persistent problem for me when working with ourside databases, and I’m sure I’m not the only this happens to.  Your input would be quite helpful here Microsoft.  It would be a nice improvement in the next version of Entity Framework.


13
Mar 12


Written By Steve French

 

How to fix the Entity Framework Code First problem – Model compatibility cannot be checked because the database does not contain model metadata problem

The Problem

So, you are tooling around in asp.net mvc 3 Entity Framework Code First, and you make a change to your underlying model.  you then get the following error when Entity Framework tries to recreate the database in Sql Server or Sql Server Express

Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.

The Cause

You still have some lock on the database in some way, perhaps you still have the database open in Visual Studio (it is very easy to do this in Visual Studio 2010) or perhaps you have it open in a Sql Server Management Studio window.  Perhaps Windows just doesn’t like you.  In any case, it’s that database is open, and Entity Framework Code First will not drop the database if anyone is still using it.

The Solution

You have to release all locks and holds on the database before Entity Framework Code First will drop the database.  To do that, open up Sql Server Management Studio and paste in the following code

USE [master]
GO

/****** Object: Database [MyDBname] Script Date: 02/24/2012 13:54:40 ******/
ALTER DATABASE [MyDBname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE [MyDBname] SET SINGLE_USER WITH NO_WAIT
DROP DATABASE [MyDBname]
GO

That will isolate your database (please note that “MyDBName” is where you should put your database name) and allow Entity Framework CodeFirst to drop and recreate the database and implement your changes.  Doing this WILL drop the database, so be careful.


06
Mar 12


Written By Steve French

 

How to fix the Entity Framework error “could not be set to a ‘Int16’ value. You must set this property to a non-null value of type ‘Boolean’.”

The Problem

You are writing a lovely Entity Framework web application and all of a sudden you get the following error:

The ‘Status’ property on ‘SomeTable’ could not be set to a ‘Int16’ value. You must set this property to a non-null value of type ‘Boolean’.

You go ahead and set the Status Property type of Boolean and that does not work either.

The Cause

The Data Type on something in one of your models (or business objects as the cool kids would call them) it set to “SmallInt” in the Sql Server database.  There is no direct crossover in C# for it.

The Solution

Explicitly declare that property to be an Int16, which will map it over to a boolean nicely.  You would think Visual Studio 2010 would warn you about such things but it doesn’t.


05
Mar 12


Written By Steve French

 

How to fix problems with Visual Studio 2010 Click Once publishing

The Problem

So, you’re trying to publish a desktop app via the Visual Studio 2010 Click Once publishing, and you’re having problems with Visual Studio 2010 Click Once publishing?  Are you getting errors like the part below

Following errors were detected during this operation.
* [2/22/2012 1:45:21 PM] System.Deployment.Application.DeploymentDownloadException (Unknown subtype)
– Downloading http://www.Domain.com/PublishFiles/SomeApp/Application Files/ReportingApp_1_0_0_8/App_Data/Reporting.sdf.deploy did not succeed.
– Source: System.Deployment
– Stack trace:
at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState)
at System.Deployment.Application.DownloadManager.DownloadDependencies(SubscriptionState subState, AssemblyManifest deployManifest, AssemblyManifest appManifest, Uri sourceUriBase, String targetDirectory, String group, IDownloadNotification notification, DownloadOptions options)
at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
— Inner Exception —
System.Net.WebException
– The remote server returned an error: (404) Not Found.
– Source: System
– Stack trace:
at System.Net.HttpWebRequest.GetResponse()
at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)

Even though you are not using a .sdf file

The Cause

Somewhere along the way you did have a .sdf file in the app_data folder, and the Click Once deploy manifest listed it. The manifest looks for it and does not find it, and would not find it anyway due to .sdf not being an accepted mime type on your server.

The Solution

Make sure that there are no .sdf files in the app_data folder, do a grep for any .sdf files, and then delete the web directories containing the files, the republish via click once.


22
Feb 12


Written By Steve French

 

How to fix problems the Mailbox unavailable. The server response was: 5.7.1 Message rejected as spam by Content Filtering error

The Problem:

You are trying to send an email in C# from your website (using Exchange as the email server), but you get the error message

Mailbox unavailable. The server response was: 5.7.1 Message rejected as spam by Content Filtering.

whenever you send the email.  It is clearly not spam.

The Cause:

You are triggering a spam filter based on the number of words and characthers in the sample email you’re sending.

The Solution:

You should increase the number of words in the body of your email by five or more.  It’s strange, but it works.


17
Feb 12


Written By Steve French

 

How to Fix Missing records in Linq to Entities

The Problem

You are attempting to use Linq to Entities in the standard way, your linq model does not seem to have any records attached.  You have missing records in Linq to Entities.

You look in the database, and the proper record is there.  You do a

context.MyEntry.Count().ToString()

and it tells you there is one record there, but still when you attempt to actually retrieve a record, for example like

context.MyEntry.First().FirstName

you get a white screen.  What gives?

The Cause

It turns out the offending code looks like this

namespace MyProject.Models
{
	public class MyEntry
	{
		[Key]
		public int MyEntryId { get; set; }
                public string EmailAddress { get; set; }
                public string LastName { get; set; }
                public string FirstName;
	}
}

The Solution

Did you notice what was missing?  You don’t have the needed

{ get; set; }

after FirstName, so Linq To Entities will not retrieve the record for the database.  It’s always hard to see something missing, it took me about 20 minutes and lots of checking the wrong places to see the omission with this problem.


14
Feb 12


Written By Steve French

 

How to fix more problems with ASP.net MVC 3 RouteValues

The Problem

You want to create urls that look something like http://SomeSite.com/Categories/Industrial/Fasteners/3.8-MM-Titanium-Wrench-Bolts/ so your site can rank extra high when people search for those profitable 3.8 MM Titanium Wrench Bolts. And in natural, RESTful fashion, your site and database is structured so that the Wrench Bolts are in a subcategory of Fasteners, which are part of the Industrial Category

The Cause:

None really, I’m just listing how one does this sort of thing.

The Solution

Firstly you have to define your route in your global.asax file, in the Register Routes section

routes.MapRoute(
“ItemInd”, // Route name
“Categories/{CategoryName}/{SubCategoryName}/{id}”, // URL with parameters
new { controller = “Product”, action = “Details”, CategoryName = “”, SubCategoryName = “”, id = “” } // Parameter defaults
);

a
Then you have to set your Route Values
Here is an ActionLink helper –

@Html.ActionLink(p.Name, “Details”, new { controller = “Product”, action = “Details”, CategoryName = p.SubCategory.Category.Name, SubCategoryName = p.SubCategory.Name, id = p.Name })

And if you want to use the URL.Action helper, here is what that would look like.

<a href=”@Url.Action(“Details”, “Product”, new { controller = “Product”, action = “Details”, CategoryName = p.SubCategory.Category.Name, SubCategoryName = p.SubCategory.Name, id = p.Name })”>Some Text</a>

as you might suspect, the new { controller = “Product”, action = “Details”, CategoryName = p.SubCategory.Category.Name, SubCategoryName = p.SubCategory.Name, id = p.Name } maps exactly to the corresponding parts in the global.asax file.

This wasn’t really a how to fix problem, but really more about using asp.net mvc 3 RouteValues.  I’ve found a lack of documentation on how to make relatively complicated urls, so I thought this would be a start!


14
Feb 12


Written By Steve French

 

How to fix problems with Linq to Xml Namespaces

The Problem

You are trying to read data out of a standard xml file.  I found a great Linq to Xml tutorial here.  You get code that looks something like this

XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath("~/Invoices.xml"));
List<Invoice> lst = new List<Invoice>();
lst= (from c in data.Descendants("invoice")
select new Invoice
{
ClientName = c.Element("client").Value,
InvoiceDate = Convert.ToDateTime(c.Element("date").Value),
}).ToList();

and you get nothing but object type no found errors.  Why?  You have problems with linq to xml namespaces.

The Cause:

The xml file you are trying to read is using a NameSpace!

The Solution:

Add in the namespace declaration and append it to the file in the right places, your code should look something like the below.

XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath(“~/Invoices.xml”));
XNamespace ns = XNamespace.Get(“http://www.SomeProvider.com/api”);
List lst = new List();
lst= (from c in data.Descendants(ns + “invoice”)
select new Invoice
{
ClientName = c.Element(ns + “client”).Value,
InvoiceDate = Convert.ToDateTime(c.Element(ns + “date”).Value),
}).ToList();

Do you see the “ns + ” part?  That tells C# to keep your data and the xml data apart.  And please note, you have to use it everywhere you reference a part of the xml document (I spent an hour finding that out).

That’s it!  Happy Coding.


05
Feb 12


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.