Showing posts with label Tweeting-Troubleshooting. Show all posts
Showing posts with label Tweeting-Troubleshooting. Show all posts

Sunday, December 16, 2012

NHibernate Filter value not set

If you received this kind of error...

Filter [Filters] parameter [LanguageCode] value not set


...chances are you have this kind of code:

s.EnableFilter("Filters").SetParameter("LanguageCode", "zh");             

s.EnableFilter("Filters").SetParameter("FallbackLanguageCode", "en");


Must rewrite that to this:


s.EnableFilter("Filters")
    .SetParameter("LanguageCode", "zh")                        
    .SetParameter("FallbackLanguageCode", "en");

Wednesday, May 30, 2012

Troubleshooting: There was no endpoint listening.

If you received this kind of error:


There was no endpoint listening at http://localhost:9384/Forumer.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.



Chances are your WCF is using a different port number (or it is Auto-assigned), right click your WCF project, then look at the Web tab, then select the Specific port, put a number there, e.g. 9384

Sunday, November 27, 2011

$.post returns incorrect empty string

You'll receive [object XMLDocument] in your jQuery $.post's data ...

var $xhr2 = $.post( 
 options.init_src,
 {
  'lookupId': theValue,
  'field': options.field,
  'primary_key': options.primary_key,
  'db_table': options.db_table
 },
 function (data) {
  $input.val(data); // textbox receives [object XMLDocument]  
 }
);


..., when you return empty string from your controller:

public string Caption(string lookupId)
{
 return "";
}


In order to prevent that problem, just add "text" parameter to your $.post method return type


var $xhr2 = $.post( 
 options.init_src,
 {
  'lookupId': theValue,
  'field': options.field,
  'primary_key': options.primary_key,
  'db_table': options.db_table
 },
 function (data) {
  $input.val(data); // receives "" string now.  
 },
 "text"
);

Sunday, August 21, 2011

Entity Framework troubles on WCF

If you have this recurring error..

The underlying connection was closed: The connection was closed unexpectedly.

.., and has accompanying error message similar to this (debug WCF effectively):
There was an error while trying to serialize parameter http://tempuri.org/:OpenQuestionResult. The InnerException message was 'Type 'System.Data.Entity.DynamicProxies.Question_67CF6019AA09770B428CB66B12E25E67E057C1CE1AF042237C78DD56D4B495D9' with data contract name 'Question_67CF6019AA09770B428CB66B12E25E67E057C1CE1AF042237C78DD56D4B495D9:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.

even you turned off ProxyCreation in your OnModelCreating of your Entity Framework mapping:

public class EfDbMapper : DbContext
{
   
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Question>().Property(x => x.RowVersion).IsRowVersion();

        modelBuilder.Entity<Question>().HasMany(x => x.Comments).WithRequired(x => x.Question).Map(x => x.MapKey("Question_QuestionId"));
        
        modelBuilder.Entity<Question>().HasMany(x => x.Answers).WithRequired(x => x.Question).Map(x => x.MapKey("Question_QuestionId"));

        modelBuilder.Entity<Answer>().HasMany(x => x.Comments).WithRequired(x => x.Answer).Map(x => x.MapKey("Answer_AnswerId"));

        this.Configuration.ProxyCreationEnabled = false;

    }
}


.., but the error still occurs, that mean ProxyCreationEnabled was reset to true. I noticed when I plug the NHibernate repository, there's no WCF error happening, by then we can infer that the error doesn't lie in WCF. It has something to do with the ORM (in this case, Entity Framework) woes.


I noticed, it's better to turn off proxy in constructor. There's no more dreaded underlying connection was closed after I moved the disabling of ProxyCreation to Entity Framework constructor


public class EfDbMapper : DbContext
{
    public EfDbMapper() 
    {
        this.Configuration.ProxyCreationEnabled = false;        
    }
    

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Question>().Property(x => x.RowVersion).IsRowVersion();

        modelBuilder.Entity<Question>().HasMany(x => x.Comments).WithRequired(x => x.Question).Map(x => x.MapKey("Question_QuestionId"));
        
        modelBuilder.Entity<Question>().HasMany(x => x.Answers).WithRequired(x => x.Question).Map(x => x.MapKey("Question_QuestionId"));

        modelBuilder.Entity<Answer>().HasMany(x => x.Comments).WithRequired(x => x.Answer).Map(x => x.MapKey("Answer_AnswerId"));


    }
}

Thursday, August 11, 2011

Handling Sql Server script errors gracefully

I think there's nothing we can do about Sql Server treatment with DDL error severity, some of it are handled automatically (forcibly rolling back transaction for example) by Sql Server itself.

What we can just do is make our script code cope around it and provide script users with descriptive error.

An example:

--	drop table thetransformersmorethanmeetstheeye
--	select * from thetransformersmorethanmeetstheeye



--	first batch begins here			

	begin tran
			
	create table thetransformersmorethanmeetstheeye(i int); -- non-erring if not yet existing
	
	-- even there's an error here, @@ERROR will become 0 on next batch
	ALTER TABLE [dbo].[Table1]  WITH CHECK ADD  CONSTRAINT [FK_constraint] FOREIGN KEY([field1], [field2])
	REFERENCES [dbo].[Table2] ([field3], [field4]);				
	
go	-- first batch ends here



--	second batch begins here

	if @@TRANCOUNT > 0 begin		
		PRINT 'I have a control here if things needed be committed or rolled back';
		
		-- @@ERROR is always zero here, even there's an error before the GO batch. 
		-- @@ERROR cannot span two batches, it's always gets reset to zero on next batch
		PRINT @@ERROR; 
		
				
		-- But you can choose whether to COMMIT or ROLLBACK non-erring things here
		-- COMMIT TRAN;
		-- ROLLBACK TRAN;
			
	end
	else if @@TRANCOUNT = 0 begin
		PRINT 'Sql Server automatically rollback the transaction. Nothing can do about it';
	end
	else begin
		PRINT 'Anomaly occured, @@TRANCOUNT cannot be -1, report this to Microsoft!';
	end
	
--	second batch implicitly ends here	

Monday, August 8, 2011

Max problem with empty IQueryable

Max receives an error on IQueryable if it has no rows

decimal ny = _repoProduct.GetAll()
    .Where(x => x.ProductId != x.ProductId)
    .Max(x => x.MinimumPrice);

On IQueryable obtained from array or anything in-memory list, this is the error:

System.InvalidOperationException: Sequence contains no elements

On IQueryable obtained from NHibernate:
NHibernate.Exceptions.GenericADOException: Could not execute query[SQL: SQL not available] ---> System.ArgumentNullException: Value cannot be null.

On IQueryable obtained from Entity Framework:
System.InvalidOperationException: The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

The easiest way to rectify that problem is to make the MinimumPrice in your model class as nullable decimal. But that could be a problem if your views has dependent logic on the nullness of the property of your model. Another approach is to cast the target element to nullable type before passing it to aggregate function.

decimal nx = _repoProduct.GetAll()
    .Where(x => x.ProductId != x.ProductId)
    .Select(x => new { TheMinimumPrice = (decimal?)x.MinimumPrice })
    .Max(x => x.TheMinimumPrice) ?? 0;

Since we have only one element on Select, the Linq can be shortened to:
decimal nx = _repoProduct.GetAll()
    .Where(x => x.ProductId != x.ProductId)
    .Select(x => (decimal?)x.MinimumPrice)
    .Max() ?? 0;

Wednesday, July 20, 2011

Class don't appear on Add View dialog

If your class don't appear in Create a strongly-typed view, compile your code first, then try to Add a View again, the class will appear in Model class dropdown list then

Monday, July 18, 2011

Entity Framework: AsNoTracking() and context.DbSet.Find(pk), a dangerous combo

Using context.YourDbSetHere.AsNoTracking() (line #11), all your succeeding context.YourDbSetHere.Find(pk) (line #35) will always hit the database

Actually, it's the combo of context.YourSourceDbSetHere.AsNoTracking() and context.DestinationDbSetHere.Add(context.YourSourceDbSetHere.Find(pk)) that is dangerous.


There's no clean way for a stub/proxy object (an object with only had its ID property set, the rest of the properties are left with their default value(i.e. null, empty string, zero, etc)) to represent an entity on many-to-many inserts.




[HttpPost]
public ActionResult Save(MovieInputViewModel input)
{
 using (var db = new TheMovieContext())
 {
  try
  {
   bool isNew = input.TheMovie.MovieId == 0;

   input.SelectedGenres = input.SelectedGenres ?? new List<int>();                    
   input.GenreSelections = db.Genres.AsNoTracking().OrderBy(x => x.GenreName).ToList();


   var movie = !isNew ? db.Movies.Find(input.TheMovie.MovieId) : input.TheMovie;                    

   if (isNew)
    db.Movies.Add(movie);
   else
   {
    db.Entry(movie).Property("Version").OriginalValue = input.TheMovie.Version;
    db.Entry(movie).State = System.Data.EntityState.Unchanged;


    // dirty this all the time even this is not changed by the user, 
    // so we have a simplified mechanism for concurrent update 
    // when the associated Genre(s) is modified. 
    // June 3, 2012: Above comment is stale already. For detecting concurrent update, use TimeStamp attribute instead of dirtying-technique+Concurrency attribute combo technique.
    // Read the concurrent update technique using Timestamp at this post: http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-with_16.html
    db.Entry(movie).Property("MovieName").IsModified = true;
   }


   movie.Genres = movie.Genres ?? new List<Genre>();
   movie.Genres.Clear();
   foreach (int g in input.SelectedGenres)
   {
    movie.Genres.Add(db.Genres.Find(g));    
   }

   UpdateModel(movie, "TheMovie", includeProperties: null, excludeProperties: new string[] { "Version" });


   db.SaveChanges();

   db.Entry(movie).Reload();
   input.TheMovie.Version = movie.Version;

   
   ModelState.Remove("TheMovie.MovieId");

   // No need to remove TheMovie.Version, ASP.NET MVC is not preserving the ModelState of variables with byte array type.
   // Hence, with byte array, the HiddenFor will always gets its value from the model, not from the ModelState
   // ModelState.Remove("TheMovie.Version"); 


   input.MessageToUser = input.MessageToUser + " " + string.Format("Saved. {0}", isNew ? "ID is " + input.TheMovie.MovieId : "");

  }
  catch (DbUpdateConcurrencyException)
  {
   ModelState.AddModelError("", 
    "The record you attempted to edit was already modified by another user since you last loaded it. Open the latest changes on this record");
  }
 }

 return View("Input", input);
}



To solve that problem, monitor your context's ChangeTracker, line #35 to 47. Even you are using AsNoTracking, line #35 to 47 will not make a database roundtrip to fetch the Genre's row(s), inserting into many-to-many table will be streamlined.

[HttpPost]
public ActionResult Save(MovieInputViewModel input)
{
 using (var db = new TheMovieContext())
 {
  try
  {
   bool isNew = input.TheMovie.MovieId == 0;

   input.SelectedGenres = input.SelectedGenres ?? new List<int>();                    
   input.GenreSelections = db.Genres.AsNoTracking().OrderBy(x => x.GenreName).ToList();


   var movie = !isNew ? db.Movies.Find(input.TheMovie.MovieId) : input.TheMovie;                    

   if (isNew)
    db.Movies.Add(movie);
   else
   {
    db.Entry(movie).Property("Version").OriginalValue = input.TheMovie.Version;
    db.Entry(movie).State = System.Data.EntityState.Unchanged;


    // dirty this all the time even this is not changed by the user, 
    // so we have a simplified mechanism for concurrent update 
    // when the associated Genre(s) is modified
    db.Entry(movie).Property("MovieName").IsModified = true;
   }


   movie.Genres = movie.Genres ?? new List<Genre>();
   movie.Genres.Clear();
   foreach (int g in input.SelectedGenres)
   {
    var cachedGenre = db.ChangeTracker.Entries<Genre>().SingleOrDefault(x => x.Entity.GenreId == g);

    Genre gx = null;
    if (cachedGenre != null)
     gx = cachedGenre.Entity;
    else
    {
     gx = new Genre { GenreId = g };
     db.Entry(gx).State = EntityState.Unchanged;
     input.MessageToUser = input.MessageToUser + "Not yet in cache " + g.ToString() + ";";
    }

    movie.Genres.Add(gx);
   }

   UpdateModel(movie, "TheMovie", includeProperties: null, excludeProperties: new string[] { "Version" });



   db.SaveChanges();

   db.Entry(movie).Reload();
   input.TheMovie.Version = movie.Version;


   ModelState.Remove("TheMovie.MovieId");

   // No need to remove TheMovie.Version, ASP.NET MVC is not preserving the ModelState of variables with byte array type.
   // Hence, with byte array, the HiddenFor will always gets its value from the model, not from the ModelState
   // ModelState.Remove("TheMovie.Version"); 


   input.MessageToUser = input.MessageToUser + " " + string.Format("Saved. {0}", isNew ? "ID is " + input.TheMovie.MovieId : "");

  }
  catch (DbUpdateConcurrencyException)
  {
   ModelState.AddModelError("", 
    "The record you attempted to edit was already modified by another user since you last loaded it. Open the latest changes on this record");
  }
 }

 return View("Input", input);
}


This article could have been titled:
Entity Framework: Representing an entity with a stub/proxy object is a one big exercise of leaky abstraction.

Microsoft could borrow some technology from NHibernate for their Entity Framework. They should implement context.Load<EntityHere>(pkHere). C'mon Microsoft, spare us the trouble of leaky abstractions of your Entity Framework :-)


Related to Using checkbox list on ASP.NET MVC with Entity Framework 4.1


Sample outputs

On first save:



On second save:



Monday, July 11, 2011

Form_Load exception troubleshooting

Don't put code in Form_Load event if possible, silent errors will creep in when you are running inside Visual Studio. Error will manifest only when the EXE is run directly

private void Form1_Load(object sender, EventArgs e)
{
    int n = 0;
    MessageBox.Show((7 / n).ToString()); // won't throw an Exception when run inside VS
}

private void Form1_Shown(object sender, EventArgs e)
{
    int n = 0;
    MessageBox.Show((7 / n).ToString()); // will throw an exception, regardless of where it is run
}

Saturday, July 2, 2011

WCF error. The underlying connection was closed: The connection was closed unexpectedly.

To trace the root of cause of that generic error more easily, put this in your WCF's web.config

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
      <listeners>
        <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "c:\_Misc\traces.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

Then double-click the traces.svclog in C:\_Misc folder

Tuesday, May 31, 2011

Learn to put up with Visual Studio, it's not perfect. Nothing is

An anecdote:

In VS, click Project (next to File,Edit,View), select Properties

then in Application tab (you'll notice you're already in 3.5), select the Target Framework to 2.0, then compile (it will error). then put it back again to 3.5, then compile again, the error will disappear

i think it is just a small glitch in Visual Studio, just fool the IDE :-)

Stupid if you may ask.

source: http://stackoverflow.com/questions/205644/error-when-using-extension-methods-in-c/383517#383517

And when clicking Update Service reference is a no joy undertaking; sometimes you have to remove the service reference, and then re-add it again. Sometimes you have to restart Visual Studio to make things take in effect, ah.. the dev's life! :-)

Another anecdote(from me, a colleague experienced it too), the first time one installed a nuget on his/her Visual Studio, his/her Visual Studio will become very slow. So when the colleague installed nuget on his Visual Studio for the first time, he noticed Visual Studio became very slow; and even he restarted Visual Studio, it's still very slow, I told him to restart his computer. Voila! his Visual Studio became snappy again.


First refuge of those who easily give up: http://stackoverflow.com/questions/205644/error-when-using-extension-methods-in-c/338452#338452

Friday, May 27, 2011

WCF: "serviceActivations could not be found"

If you received this kind of error:

The type 'WcfService1.Service1', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.

It's trying to find Wcf1Service1.Service1. To change to your current service name, example:

public class TestService : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }

...from Solution Explorer, right-click Service1.svc, choose Open With..., select XML (Text) Editor, click OK, change this...

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.Service1" CodeBehind="Service1.svc.cs" %>


...To:
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.TestService" CodeBehind="Service1.svc.cs" %>

Thursday, April 21, 2011

NHibernate Error: "Could not initialize proxy - no Session"

If you happen to encounter this kind of error in NHibernate...

Initializing[JqueryAjaxComboBoxAspNetMvcHelperDemo.Models.Category#777]-Could not initialize proxy - no Session.

...even you already have a Fetch clause in your controller code:

public ViewResult Index()
{
 using (var s = SessionFactoryBuilder.GetSessionFactory().OpenSession())
 {
  return View(s.Query<Product>().Fetch(x => x.Category).ToList());
 }
}

Worry not much, if your code has a Fetch clause, the problem lies in the data, your data is inconsistent, your table has a foreign key that has no matching primary key in the table it is referring to. Typical of database with no foreign key capability (e.g. MySQL's MyISAM) or with foreign key but not enforced(I'm using Sqlite when I encountered that error)

In our example, there is no primary key 777 in Category table, so we just need to correct our data

You can also encounter the same error(verbatim) even if your data is correct, it happens when you forgot to include the Fetch clause in your query.


Again, NHibernate does a poor job on stating the root cause of error. Another example of vague error from NHibernate http://www.ienablemuch.com/2010/10/nhibernate-orm-how-to-object-relational.html, scroll the down to the last portion of the article

Sunday, April 17, 2011

A null was returned after calling the 'GetService' method on a store provider instance of type 'System.Data.SQLite.SQLiteFactory'

If you encounter this error:

A null was returned after calling the 'GetService' method on a store provider instance of type 'System.Data.SQLite.SQLiteFactory'. The store provider might not be functioning correctly.


Add System.Data.SQLite.Linq.dll to your project's References

The type or namespace name 'ModelBuilder' does not exist

If you encountered this error:


The type or namespace name 'ModelBuilder' does not exist in the namespace 'System.Data.Entity.ModelConfiguration' (are you missing an assembly reference?)

Just change...

System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder

...to:

System.Data.Entity.DbModelBuilder modelBuilder

Wednesday, March 16, 2011

Overlooked property getter on custom Model Binder of ASP.NET MVC will make your property unavailable on BindProperty method

If your custom property binder is not invoked on BindProperty method, chances are that you forgot to include a getter for your property. Though in my code's case, I remove the getter in purpose, so the consuming programmer cannot accidentally use the raw submitted values.

This code ...

[BindingName("show_field")]
public string ShowFieldRaw 
{ 
   set 
   { 
       _showFieldRaw = value; 
       ShowFields = _showFieldRaw.Split(','); 
   }  
}


...won't get invoked on BindProperty:

public class PropertyBinder : DefaultModelBinder
{

 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
 {
  base.BindProperty(controllerContext, bindingContext, propertyDescriptor);

  /* if (propertyDescriptor.Name == "ShowFieldRaw")
   throw new Exception(controllerContext.HttpContext.Request["show_field"]); */
  
  foreach (var p in propertyDescriptor.Attributes)
  {
   if (p.GetType() == typeof(BindingNameAttribute))
   {
    var b = p as BindingNameAttribute;
    object value = controllerContext.HttpContext.Request[b.Name];
    

    if (propertyDescriptor.PropertyType == typeof(int))
     propertyDescriptor.SetValue(bindingContext.Model, Convert.ToInt32(value));
    else
     propertyDescriptor.SetValue(bindingContext.Model, value);

    break;
   }
  }//foreach
  
 }
}// class PropertyBinder

So you must modify your model and put a getter on the property to make that property be included on BindProperty method:

[BindingName("show_field")]
public string ShowFieldRaw 
{ 
    set 
    { 
        _showFieldRaw = value; ShowFields = _showFieldRaw.Split(','); 
    } 
    get 
    { 
        return _showFieldRaw; 
    }  
}


Related to error on jQuery AJAX Combobox I debugged: http://code.google.com/p/asp-net-mvc-backed-jquery-ajax-combobox/downloads/list

Tuesday, March 8, 2011

Sqlite error of "Unable to find the requested .Net Framework Data Provider."

If you encountered this error...


Unable to find the requested .Net Framework Data Provider. It may not be installed.


...there are two ways around that error, the easiest way is to just install the .NET Framework Data Provider for Sqlite

Or if your system/network administrator won't allow you to install additional software, download the libraries only, after extracting it, add System.Data.SQLite.DLL and System.Data.SQLite.Linq.dll to your project's reference, then add this config file in your web.config (just after the <configuration> tag):

<system.data>
 <DbProviderFactories>
   <remove invariant="System.Data.SQLite"/>
   <add name="SQLite Data Provider" invariant="System.Data.SQLite"
     description=".Net Framework Data Provider for SQLite"
     type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
 </DbProviderFactories>
</system.data>


Rationale found here: http://sqlite.phxsoftware.com/forums/t/239.aspx

The default MS providers have their XML entries in the machine.config file in Windows\Microsoft.Net\Framework\v2.0.50727\config

It was decided early on that this was not a good place to put additional providers. It would've put a burden on anyone wanting to use DbProviderFactories on a client installation, and messing around with the machine.config is generally not a good way to go anyway.

Solution found here: http://stackoverflow.com/questions/4901198/how-to-make-entity-framework-ctp5-work-with-sqlite

Sqlite Error on ProviderIncompatibleException was unhandled by user code

If you encountered this error:

A null was returned after calling the 'GetService' method on a store provider instance of type 'System.Data.SQLite.SQLiteFactory'. The store provider might not be functioning correctly.

Just add the System.Data.SQLite.dll to your project reference

Get it here: http://sourceforge.net/projects/sqlite-dotnet2/files/SQLite%20for%20ADO.NET%202.0/1.0.66.0/SQLite-1.0.66.0-binaries.zip/download

Monday, February 14, 2011

Error on sqlite_open

If you encounter this error on IIS

PHP Fatal error: Call to undefined function sqlite_open()


Uncomment this:

extension=php_sqlite.dll

And this:

extension_dir = "ext"

Monday, December 27, 2010

Troubleshooting NUnit Testing of Linq on Mono 4.0

At the time of this writing(Mono 2.8.1), you might receive error (TestFixtureSetup failed in MyClass) when you perform NUnit testing of Linq on Mono targeting .NET framework version 4.0. This can be avoided by going back to framework version 3.5. If you don't intend to perform NUnit testing, Linq runs fine on Mono targeting framework version 4.0

The Video: http://www.youtube.com/watch?v=8hhxGVtaosY

Sigh.. Mono should just synchronize their version numbering on .NET framework version