Thứ Tư, 6 tháng 7, 2016

Error: XMLHttpRequest on the main thread is deprecated

To avoid this warning, do not use:
async: false
in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.
The default is async: true, so if you never use this option at all, your code should be safe if the feature is ever really removed (it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years).

Another reason (In my case):
- using : async: false
- Call CountAsync() (Iqueryable):
        public virtual int Count(Expression<Func<TEntity, bool>> where)
        {
              return where == null ? _dbSet.AsQueryable().CountAsync().Result :            _dbSet.Where(where).CountAsync().Result;
        }
Read More »

Thứ Năm, 16 tháng 6, 2016

the differences between using a static lock object (code A) and a non-static lock object (code B) for a synchronized block

The difference is simple: if the locked-on object is in a static field, then all instances of MyClass*will share that lock (i.e. no two objects will be able to lock on that object at the same time).
If the field is non-static, then each instance will have its own lock, so only calls of the method on the same object will lock each other.
When you use a static lock object:
  • thread 1 calls o1.foo()
  • thread 2 calls o1.foo(), will have to wait for thread 1 to finish
  • thread 3 calls o2.foo(), will also have to wait for thread 1 (and probably 2) to finish
When you use a non-static lock object:
  • thread 1 calls o1.foo()
  • thread 2 calls o1.foo(), will have to wait for thread 1 to finish
  • thread 3 calls o2.foo(), it can just continue, not minding thread 1 and 2
Which one of those you'll need depends on what kind of data you try to protect with your synchronized block.
As a rule of thumb, you want the lock-object to have the same static-ness than the operated-on value. So if you manipulate non-static values only, you'll want a non-static lock object. If you manipulate static values only, you'll want a static lock object.
When you manipulate static and non-static values, then it'll become complicated. The easy way would be to just use a static lock object, but that might increase the size of the synchronized-block more than absolutely necessary and might need to more lock contention than desired. In those cases you might need a combination of static and non-static lock objects.
In your particular case you use the lock in the constructor, which will only ever be executed once per instance, so a non-static lock-object doesn't make any sense here.

http://stackoverflow.com/questions/18356795/static-versus-non-static-lock-object-in-synchronized-block

Read More »

Chủ Nhật, 29 tháng 5, 2016

Expression vs Func with Entity Framework

Sometimes developers don't know whether they should use a Func<> or an Expression<Func<>> with the Entity Framework and LINQ. The distinction was critical in a situation I faced today.
Our application was having performance problems, and Red Gate's excellent ANTS profiling tool pointed to a method that, reduced to its essence, was like what you see below. Context is an Entity Framework context, and MyEntities is one of the entity tables in the context. 

IEnumerable<MyEntity> LoadMyEntities(Expression<Func<MyEntity, bool>> predicate)
{
    return Context.MyEntities.Where(predicate);
}

The idea is that a caller can pass in a predicate in the form of a Lambda. The compiler will turn the Lambda into a LINQ Expression, which can be passed to the method in the 'predicate' parameter.

int id;
// Set the id somehow and then...
var theEntity = LoadMyEntities(e => e.UniqueId == id).Single();

The profiler told us that LoadMyEntities was being called many, many times and it was taking a large fraction of our CPU time. The simple change below solved the problem. Can you guess why?

public IEnumerable<MyEntity> LoadMyEntities(Func<MyEntity, bool> predicate)
{
    return Context.MyEntities.Where(predicate);
}

The parameter is now a Func<> instead of an Expression<Func<>>. The reason this makes a difference is that a predicate that's in the form of an Expression is passed to SQL server, but a predicate that's passed as a Func is not. Normally, you'd want SQL Server to do as much for you as possible, and an Expression would be the right choice, but in this case we'd like to pre-load the entire table in the context -- which is exactly what a Func will do. (This the same point I made in Falling in Love with LINQ, Part 7.) Step by step...
  1. The Where extension method has two flavors. One extends IQueryable and takes an Expression parameter. The other extends IEnumerable and takes a Func.
  2. Because 'predicate' is now a Func, the Where that extends IEnumerable is used.
  3. The Entity Framework's fluent interface for constructing SQL queries is based on IQueryables, not IEnumerables. Therefore, the fluency stops just before the Where. The part of the statement that gets passed to the Entity Framework is just Context.MyEntities.
  4. Context.MyEntities therefore returns the entire table to the context.
  5. The entire table is now filtered with the predicate, and the value we really want is returned.
  6. The next time the method is called, the Entity Framework realizes that the record we want is already in the context. (In my case, we were querying by the primary key, and EF is apparently smart enough to know that if there's a record in the context with that ID, it won't find an additional such record in the database.) Since we don't go out to SQL Server, we save lots of time. Obviously there are occasions when you would not want this, but in our case it was exactly what we wanted. The table was relatively small, and the same context was queried hundreds of times.
In the original version, the predicate was an Expression, so the compiler used the Where that extends IQueryable. The predicate was thus passed to SQL Server, which dutifully returned just one row to the context. The next time we called LoadMyEntities, Entity Framework had to call SQL Server again.
The change from Expression to Func gave us a 6-fold reduction in CPU usage! But again, your situation may call for an Expression. The important thing is to know the difference, and now you do!

Link: http://fascinatedwithsoftware.com/blog/post/2012/01/10/More-on-Expression-vs-Func-with-Entity-Framework.aspx
Read More »

Thứ Năm, 26 tháng 5, 2016

Handler "has a bad module "ManagedPipelineHandler" in its module "

Ran command:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
If I had been on a 32 bit system, it would have looked like the following:
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i
Read More »

Thứ Năm, 24 tháng 3, 2016

ProxyCreationEnabled and LazyLoadingEnabled

If DbContext.Configuration.ProxyCreationEnabled is set to false, DbContext will not load child objects for some parent object unless Include method is called on parent object. Setting DbContext.Configuration.LazyLoadingEnabled to true or false will have no impact on its behaviours.

If DbContext.Configuration.ProxyCreationEnabled is set to true, child objects will be loaded automatically, and DbContext.Configuration.LazyLoadingEnabled value will control when child objects are loaded.
Read More »

Thứ Hai, 14 tháng 3, 2016

Sửa lỗi update-database code first "there is already an object named"

update-database -verbose doesn't work because your model has been changed after your data table already existed.
First, make sure there are no changes to the UserProfile class. Then, run:
Add-Migration InitialMigrations -IgnoreChanges
This should generate a blank "InitialMigration" file. Now, add any desired changes to the UserProfile class. Once changes are added, run the update command again:
update-database -verbose
Now the automatic migration will be applied and the table will be altered with your changes
Read More »

Thứ Hai, 15 tháng 2, 2016

Resolved: configuration system failed to initialize

Obviously, the solution is to either repair or simply delete the user.config file, but we have to find it before we can do that. I won't get into repairing, since there's no simple way that I know of to do this. In most cases, deleting the user's application settings, while inconvenient, is not the end of the world, so long as the user is given fair warning that this is about to happen. You're free to take other measures, of course.

It turns out, the path to the user.config file was in the exception all along! But, it's sneakily hidden inside an InnerException, and maybe this is why it eluded me at first. So, allow me to present a block of code that will basically handle this occurrence in a universal manner. You should place this block somewhere near the beginning of your application startup, before any call to Settings is made:

try
        {
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
        }
        catch (ConfigurationErrorsException ex)
        {
            string filename = string.Empty;
            if (!string.IsNullOrEmpty(ex.Filename))
            {
                filename = ex.Filename;
            }
            else
            {
                var innerEx = ex.InnerException as ConfigurationErrorsException;
                if (innerEx != null && !string.IsNullOrEmpty(innerEx.Filename))
                {
                    filename = innerEx.Filename;
                }                   
            }

            if (!string.IsNullOrEmpty(filename))
            {
                if (System.IO.File.Exists(filename))
                {
                    var fileInfo = new System.IO.FileInfo(filename);
                    var watcher
                         = new System.IO.FileSystemWatcher(fileInfo.Directory.FullName, fileInfo.Name);
                    System.IO.File.Delete(filename);
                    isReset = true;
                    if (System.IO.File.Exists(filename))
                    {
                        watcher.WaitForChanged(System.IO.WatcherChangeTypes.Deleted);
                    }
                }
            }
        }

ConfigurationErrorsException is the correct exception to throw in the situation you describe. An earlier version of the MSDN documentation for ConfigurationErrorsException makes more sense.
The earlier MSDN summary and remarks are:
  • The exception that is thrown when a configuration-system error has occurred.
  • The ConfigurationErrorsException exception is thrown when any error occurs while configuration information is being read or written.
Since CLR 2.0, the .NET Framework offers an extensive configuration module in System.Configuration. It differentiates between program and user settings:
TypeFileLocationOccurrenceUsage/Administration
Applicationapp.configProgram Folder1 per installationVisual Studio Project Properties: Settings
Useruser.configUser Profile Folder1 per userDerivation of ApplicationSettingsBase
The usage scenario determines which type of setting to choose:
Criterion/RequirementApplication SettingUser Setting
Setting is the same for all users (e.g., database connection)x
Setting can vary per user (e.g., theme)x
Temporary/local setting (e.g., location and size of a window)x
Storage of user input or selection (e.g., text alignment)x
Necessity to store settings fine grained (e.g., per plug-in)x

Control over the user settings is gained through inheriting from the class ApplicationSettingsBase. A single setting value can be defined via a property and a property attribute. The methods Reload()Reset()Save(), and Upgrade() determine the runtime behavior. The following illustration shows the data flow of the .NET user configuration:
User Settings Data Flow
The 'Default Value' is defined through the property attribute DefaultSettingValueAttribute. The value 'Init Value' is controlled by the .NET Framework. Access to the value of 'Session Value' occurs through the property which is marked with the UserScopedSettingAttribute, which in turn usesApplicationSettingsBase.Item.
The methods Reload() and Reset() support freshly loading all settings and setting them back to their 'Default Values, respectively.
When performing the first Save(), all user settings get stored in the XML file user.config. With every following program launch, the .NET Framework automatically loads them again (action Start). Where that configuration file will be located is influenced by several factors:
  • Profile Directory: The local or roaming profile directory (e.g., C:\Documents and Settings\MyName)
  • Company Name: The value of the AssemblyCompanyAttribute in AssemblyInfo.cs
  • App Name: The value of the AssemblyProductAttribute in AssemlyInfo.cs
  • Evidence Type and Evidence Hash: Information derived from the app domain evidence
  • Version: The value of the AssemblyVersionAttribute in AssemblyInfo.cs
If any of these factors change, the user settings will be stored (and looked for) in a different folder. The methodUpgrade() offers some support for migrating user settings from previous versions. Care should be taken, however, when changing either the company or the application name, as these changes will prevent future upgrades.

Read More »