вівторок, 8 листопада 2011 р.

LINQ: left join

ffrom p in products
join c in categories on p.CategoryId equals c.Id into g
from c in g.DefaultIfEmpty()
select new
{
 CategoryTitle = c == null ? string.Empty : c.Title,
 ProductTitle = p.Title
};

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

Oracle: disable a trigger in an stored procedure

execute immediate 'ALTER TRIGGER tr_name DISABLE';

...

execute immediate 'ALTER TRIGGER tr_name ENABLE';

четвер, 20 жовтня 2011 р.

понеділок, 17 жовтня 2011 р.

ExtJS: delay/buffer event

listeners: {
    keyup: {
        fn: function () {
            //...
        },
        delay: 500 //buffer: 500
    }
}

четвер, 13 жовтня 2011 р.

EF 4.1 Code-First: generate model

private void WriteEdm()
{
    var settings = new XmlWriterSettings();
    settings.Indent = true;

    using (var ctx = new WebEntities())
    {
        using (var writer = XmlWriter.Create(Server.MapPath(@"Model.edmx"), settings))
        {
            EdmxWriter.WriteEdmx(ctx, writer);
        }
    }
}

середа, 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;
}

пʼятниця, 22 липня 2011 р.

Visual Studio: find invalid commas in *.js

Use find with regexp:

,[:b\n]*[\]\)\}]

середа, 13 липня 2011 р.

Oracle grant execute


grant execute on aspnetuser.goods_all_get_gtitle_by_gid to pds_sales;

Anonymous PL/SQL block


DECLARE
gid NUMBER(10):=5850802;
title varchar2(80);
BEGIN
IF gid is null THEN
DBMS_OUTPUT.PUT_LINE('GID is null');
ELSE
select t.g_name
into title
from typhoon.tbl_goods_all t
where t.g_id = gid;
DBMS_OUTPUT.PUT_LINE(title);
END IF;
END;

понеділок, 4 липня 2011 р.

C#, read data 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))
{
using(var cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", conn))
{
using(var adapter = new OleDbDataAdapter(cmd))
{
var table = new DataTable();

adapter.Fill(table);

grid.DataSource = table;
grid.DataBind();
}
}
}

пʼятниця, 1 липня 2011 р.

Ext: confirm dialog localization


if (Ext.window.MessageBox) {
Ext.window.MessageBox.prototype.buttonText = {
ok: "OK",
cancel: "Отмена",
yes: "Да",
no: "Нет"
};
Ext.MessageBox = Ext.Msg = new Ext.window.MessageBox();
}

четвер, 30 червня 2011 р.

Oracle RETURNING Clause - get identity of inserted row


PROCEDURE Ins
(pContactID OUT Contacts.ContactID%TYPE,
pFirstname IN Contacts.Firstname%TYPE,
pSurname IN Contacts.Surname%TYPE)
IS
BEGIN
INSERT INTO Contacts
(fname, sname)
VALUES
(pFirstname, pSurname)
RETURNING ContactID INTO pContactID;
END;

ExtJS 4.0 GridPanel double-click event

In ExtJS 4.0 you need to listen for events on the GridPanel’s view, via the “viewConfig”:

viewConfig: {
listeners: {
itemdblclick: function(dataview, index, item, e) {
console.log('itemdblclick');
}
}
}

середа, 22 червня 2011 р.