середа, 12 жовтня 2011 р.

EF 4.1 Code-First: remove all conventions

        protected override void OnModelCreating(DbModelBuilder db)
        {
            var types = typeof(IConvention).Assembly.GetTypes()
                .Where(x => x.IsClass && !x.IsAbstract && typeof(IConvention).IsAssignableFrom(x))
                .ToList();

            var remove = typeof(ConventionsConfiguration).GetMethod("Remove");

            types.ForEach(x => remove.MakeGenericMethod(x).Invoke(db.Conventions, null));
        }

Полный список аннотаций, поддерживаемый в EF 4.1

    KeyAttribute

    StringLengthAttribute

    MaxLengthAttribute

    ConcurrencyCheckAttribute

    RequiredAttribute

    TimestampAttribute

    ComplexTypeAttribute

    ColumnAttribute
    Атрибут свойства для указания имени столбца, ординарного типа и типа данных

    TableAttribute
    Атрибут класса для указания имени таблицы и схемы

    InversePropertyAttribute
    Атрибут свойства навигации для указания свойства, которое представляет другой конец связи

    ForeignKeyAttribute
    Placed on a navigation property to specify the property that represents the foreign key of the relationship

    DatabaseGeneratedAttribute
    Атрибут свойства для указания того, как база данных будет вычислять  значение поля (Identity, Computed or None)

    NotMappedAttribute
    Атрибут свойства или класса для его исключения из базы данных
source

неділя, 9 жовтня 2011 р.

MVC: Cascading Dropdown

Action Methods:
[HttpPost]
public JsonResult GetCategories()
{
    Thread.Sleep(1000);

    return Json(categoriesList);
}

[HttpPost]
public JsonResult GetProducts(int? category)
{
    Thread.Sleep(1000);

    var list = category.HasValue ? productsList.Where(x => x.CategoryId == category).ToList() : productsList;

    return Json(list);
}
HTML:
<lable for="category">Category</lable>
<select id="category" name="category">
<option value="-1">Select...</option>
@foreach (var item in Model)
{
    <option value="@item.Id">@item.Title</option>
}
</select>
<lable for="product">Product</lable>
<select id="product" name="product">
    <option value="-1">Select cetegory...</option>
</select>
Script:
$(function () {
        var categories = $('#category');
        var products = $('#product');

        products.change(function () {
            console.log(products.val());
        });

        categories.change(function () {
            var id = categories.val();

            if (id != -1) {
                products.empty();
                products.append($('<option/>', {
                    value: -1,
                    text: "Loading..."
                }));

                $.ajax({
                    type: 'POST',
                    url: "/Products/GetProducts",
                    data: { category: id },
                    success: function (resp) {
                        var items = eval(resp);

                        products.empty();
                        products.append($('<option/>', {
                            value: -1,
                            text: "Select product..."
                        }));

                        $.each(items, function (index, item) {
                            products.append($('<option/>', {
                                value: item.Id,
                                text: item.Title
                            }))
                        });
                    },
                    error: function () {
                        console.log('Error');
                        console.log(arguments);
                    }
                });
            } else {
                products.empty();
                products.append($('<option/>', {
                    value: -1,
                    text: "Select cetegory..."
                }));
            }
        });
    });

четвер, 15 вересня 2011 р.

C#: Draw string with custom font

var fonts = new PrivateFontCollection();
fonts.AddFontFile(Server.MapPath("~/Alix2.ttf"));

using(var bm = new Bitmap(300, 100))
{
	using(var font = new Font(fonts.Families.First(), 22))
	{
		using(var g = Graphics.FromImage(bm))
		{
			g.DrawString("Hello fonts", font, Brushes.White, 50, 20);
		}
	}

	bm.Save(Server.MapPath("img.jpg"), ImageFormat.Jpeg);
}

вівторок, 30 серпня 2011 р.

C#, read sheets names from Excel (*.xls) file


var file = Server.MapPath("file.xls");
var cs = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", file);
using(var conn = new OleDbConnection(cs))
{
conn.Open();
var table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheets = table.Rows.Cast().Select(x => x["TABLE_NAME"]).ToList();
grid.DataSource = sheets;
grid.DataBind();
}

четвер, 4 серпня 2011 р.

MVC 3: disable browser cache


public class NoCache : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();

base.OnResultExecuting(filterContext);
}
}

ExtJS 4: Wrap Renderer


wrapRenderer: function (value, metadata) {
metadata.style = 'white-space: normal';
return value;
}