{ Dev Farm }

Web & Windows Development

23 luglio 2013
di max
0 commenti

Speed up Entity Framework large data inserting with SqlBulkCopy

5.00 avg. rating (94% score) - 2 votes

As known Entity Framework is quite slow when inserting items and almost unusable when you are insertin 1000+ items.
A very fast workaround is using SqlBulkCopy, it’s very fast and easy to use.

public static void saveData<T>(ref List<T> list, string destinationTableName, int batchSize)
{
	using (EntityDataReader<T> reader = new EntityDataReader<T>(list))
	using (System.Data.SqlClient.SqlBulkCopy sbc = new System.Data.SqlClient.SqlBulkCopy(PhoneLog.Core.Configurations.ConnectionString))
	{
		for (int i = 0; i < reader.FieldCount; i++)
		{
			string colName = reader.GetName(i);
			sbc.ColumnMappings.Add(colName, colName);
		}
		sbc.BatchSize = batchSize;
		sbc.DestinationTableName = destinationTableName;
		sbc.WriteToServer(reader);
	}
}

In this sample T should be a EntityFramework known object.

12 luglio 2013
di max
0 commenti

Quick fix for very slow to load “Downloads” folder in Windows 7 & 8

5.00 avg. rating (92% score) - 1 vote

I don’t usually post “tips” but this issue has frustrated me to no end for many months and I finally found a simple but instant effective solution. It’s too good not to spread the word about.

In the last couple of months, I started noticing that clicking the “Downloads” folders in Windows Explorer took around 15-20 seconds to load. This become quite annoying as I frequently access downloaded files from browsers. I tried deleting clearing out the folder but that didn’t have a lasting effect.

After a bit of research, it turns out apparently Windows 7 (and Windows 8) tries to guess-timate what the contents of the folder are and assigns special “rules” to them to optimize the view settings and sorting.

For some reason, the “Downloads” folder likes to be categorized as a “Pictures” folder (I’m guessing because people store a lot of JPGs in it). The problem with this view is that it tries to generate thumbnails for all the files in this folder, even if they’re not pictures.

downloadsfolderdownloadfolder-ita

The fix is to ensure the folder settings for “Downloads” is optimized for “General items”. This should have an instant effect (the next time you add files to the folder since the thumbnails are otherwise cached anyway).

Unfortunately, this change doesn’t seem to always stick as Windows may change the option as you download more files, so you may have to check this setting once in a while.

10 luglio 2013
di max
2 commenti

ASP.NET MVC CheckBox Validations (server and client side)

5.00 avg. rating (96% score) - 4 votes

A very annoing lack in Asp.Net MVC is the checkbox validation.
I need to validate Privacy acceptation in many websites. The best way is to validate both server side and client side, in this way you can make your websites it more usable.

First: add a new validation attribute MustBeTrueAttribute. you can use it besides the other attributes in your Models

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if ((bool)value)
                return ValidationResult.Success;
            return new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "checkrequired"
            };

            yield return rule;
        }
    }

Second: Extend jQuery validation to get client side check

    if (jQuery.validator) {
        // Checkbox Validation
        jQuery.validator.addMethod("checkrequired", function (value, element, params) {
            var checked = false;
            checked = $(element).is(':checked');
            return checked;
        }, '');
        if (jQuery.validator.unobtrusive) {
            jQuery.validator.unobtrusive.adapters.addBool("checkrequired");
        }
    }

With these two pieces you can now easily validate your checkbox with a simple attribute.
This is a sample how it’s used:

    public class FormContact
    {

        [Display(Name = "Name")]
        [Required]
        public string Name { get; set; }

        [Display(Name = "Email")]
        [DataType(DataType.EmailAddress)]
        [Required]
        public string Email { get; set; }

        [Display(Name = "Privacy")]
        [MustBeTrueAttribute(ErrorMessage = "Please Accept Privacy Policy")]
        public bool Privacy { get; set; }

    }

19 giugno 2013
di max
0 commenti

Correct Link SEO Migration from old Asp.Net WebForm to new Asp.Net Mvc Website

5.00 avg. rating (94% score) - 2 votes

When you are designing a new website you have to think about old website links migration.

This is very important to avoid tons of 404 errors and losing massive traffic.

First of all you’ll have to find out all your old link. Such as

/news/Default.aspx
/news/Default.aspx?id=123
/news/Default.aspx?id=456
etc..

and map them to

/news/
/news/new-website
/news/dismiss-old-website
etc..

Fortunately ASP.NET MVC made this translation quite simple.

In your global.asax (or RegisterRutes function) add the code to handle the 301 redirect

    routes.MapRoute(
        name: "News Redirect",
        url: "news/Default.aspx",
        defaults: new { controller = "Redirect", action = "News" }
    );

Than, I suppose you have a Redirect Controller, just convert the old link in the new website url system.

    public class RedirectController : Controller
    {

        public ActionResult News(int? id)
        {
            if (id &gt; 0)
            {
                // your code to find out your new permalink
                var permalink = "xxxxxxxxxxxxxxxxxxxx";
                // your code to find out your new permalink
                return RedirectPermanent("/News/" + permalink);
            }
            return RedirectPermanent("/News");
        }

    }

RedirectPermanent function will set301 as Response Status Code.
Http Status Code 301 means “Moved Permanently”, in this way the search engine will replace the old link with the new one without losing traffic and throwing annoying 404 errors.

Other Resources:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

http://msdn.microsoft.com/it-it/library/system.web.httpresponse.redirectpermanent.aspx