вівторок, 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 р.

вівторок, 21 червня 2011 р.

ExtJS State

Set provider:

Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 30))//30 days
}));


Field Example:

{
xtype: 'textfield',
fieldLabel: 'Логин',
name: 'UserName',
allowBlank: false,
validateOnBlur: false,
blankText: 'Введите логин',
stateful: true,
stateId: 'UserName',
stateEvents: ['blur'],
getState: function () {
return { value: this.getValue() };
},
applyState: function (state) {
this.setValue(state.value);
}
}

ExtJS получить параметры URL

Add ext-methods:

Ext.apply(Ext, {
urlParams: function () {
return Ext.Object.fromQueryString(location.search);
},
urlParam: function (name) {
return this.urlParams()[name];
}
});

Use:

var query = Ext.urlParams();
var p1 = query.p1;
//or
var p2 = Ext.urlParam('p2');

пʼятницю, 17 червня 2011 р.

ORA-01008: not all variables bound

Если код 100 раз проверен, а ошибка есть - лечит ошибку:

command.BindByName = true;

середу, 15 червня 2011 р.

ExtJS: 3 Value Checkbox

js:

{
xtype: 'checkbox',
fieldLabel: 'Active',
name: 'Active',
inputValue: 'true',
cls: 'value-undefined',
handler: function () {
if (!this.uncheckedValue) {
this.removeCls('value-undefined');
this.uncheckedValue = 'false';
}
},
reset: function () {
this.setValue(undefined);
this.addCls('value-undefined');
if (this.uncheckedValue) this.uncheckedValue = undefined;
}
}

css:

.x-field.value-undefined input
{
opacity:0.4;
}

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

Ext JS 4: localize grid loading message


Ext.view.AbstractView.prototype.loadingText = "Загрузка...";

MVC 3 Content with no cache

Simple helper:

public static class UrlHelperExtensions
{
public static string ContentNoCache(this UrlHelper url, string path)
{
return url.Content("{0}?_dc={1}".FormatWith(path, DateTime.Now.ToFileTime()));
}
}

where FormatWith:

public static string FormatWith(this string input, params object[] args)
{
return string.Format(input, args);
}

Use:
<script src="@Url.ContentNoCache("~/Scripts/app.js")" type="text/javascript"></script>
Result:
<script src="/Scripts/app.js?_dc=129520920501677826" type="text/javascript"></script>

пʼятницю, 3 червня 2011 р.

Sql paging in Oracle


select t.*
from (select t.*, row_number() over (order by t.aps_id desc) rn
from pds_sales.tbl_all_pds_sales t) t
where t.rn > :first and t.rn <= :last

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

ExtJs 4 dateFormat M$

ExtJS 3:
{ name: 'SaleDate', type: 'date', dateFormat: "M$" }


ExtJS 4:
{ name: 'SaleDate', type: 'date', dateFormat: "MS" }

понеділок, 30 травня 2011 р.

Some w3s css rules

background: #f00 url(background.gif) no-repeat fixed 0 0;
// по W3C: цвет картинка повторение аттачмент координаты

font: italic small-caps bold 1em/140% "Lucida Grande",sans-serif;
// по W3C: style variant weight size/line-height family

середу, 25 травня 2011 р.

Default ASP.NET Membership Provider Settings

Code to view settings:

protected void Page_Load(object sender, EventArgs e)
{
var type = typeof(Membership);

var infos = type.GetProperties(BindingFlags.Public | BindingFlags.Static);

foreach (var p in infos)
{
PrintProp(p);
}
}

private void PrintProp(PropertyInfo p)
{
var value = p.GetValue(null, null);

Response.Write(string.Format("<b>{0}</b>: {1}<br />", p.Name, value));
}


Result:

EnablePasswordRetrieval: False
EnablePasswordReset: True
RequiresQuestionAndAnswer: True
UserIsOnlineTimeWindow: 15
Providers: System.Web.Security.MembershipProviderCollection
Provider: System.Web.Security.SqlMembershipProvider
HashAlgorithmType: HMACSHA256
MaxInvalidPasswordAttempts: 5
PasswordAttemptWindow: 10
MinRequiredPasswordLength: 7
MinRequiredNonAlphanumericCharacters: 1
PasswordStrengthRegularExpression:
ApplicationName: /

and from machine.config

requiresUniqueEmail: false

суботу, 21 травня 2011 р.

Use the ref config option in ExtJS


var win = new Ext.Window({
layout: 'fit',
width: 300,
height: 200,
title: 'my window',
items: [{
ref: 'panel',
xtype: 'panel', layout: 'form',
frame: true, defaults: {xtype: 'textfield'},
items: [
{ref: '../nameField', fieldLabel: 'Name'},
{ref: 'age', fieldLabel: 'Age'}
]
}]
});

win.show();
//so now, with the above ref options, you can do:
win.nameField.setValue('name here');
win.panel.age.setValue(20);

source

Неплохой css reset


html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote,
pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd,
q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
border: 0 none;
font-family: inherit;
font-size: 100%;
font-style: inherit;
font-weight: inherit;
margin: 0;
outline: 0 none;
padding: 0;
text-decoration: none;
vertical-align: baseline;
}

пʼятницю, 20 травня 2011 р.

Base64 Helpers


public static string ToBase64(this string input)
{
if(string.IsNullOrEmpty(input)) return input;

return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(input));
}

public static string FromBase64(this string input)
{
if(string.IsNullOrEmpty(input)) return input;

return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(input));
}

Use:

var a = "input";
var b = a.ToBase64();
var c = b.FromBase64();

середу, 4 травня 2011 р.

Webmoney merchant form

On page:
<asp:Content ID="content" ContentPlaceHolderID="afterform" runat="server">
<uc:WebMoneyForm id="wmpay" runat="server" />
</asp:Content>
In code:
wmpay.Amount = 1.5;
wmpay.Description = "некий товар";
wmpay.OrderID = 1001;
wmpay.Purse = "Uxxxxxxxxxxxx";
wmpay.TestMode = true;


public class WebMoneyForm : System.Web.UI.Control
{
public string Action { get; set; }
public string Method { get; set; }
public double Amount { get; set; }
public string Description { get; set; }
public bool TestMode { get; set; }
public int OrderID { get; set; }
public string Purse { get; set; }

public Dictionary Params { get; private set; }

public WebMoneyForm()
{
Method = "post";
Action = "https://merchant.webmoney.ru/lmi/payment.asp";

Params = new Dictionary<string, string>();
}

public void AppParam(string name, string value)
{
if(Params.ContainsKey(name))
{
Params[name] = value;
}
else
{
Params.Add(name, value);
}
}

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.AddAttribute("id", ID);
writer.AddAttribute("name", ID);
writer.AddAttribute("action", Action);
writer.AddAttribute("method", Method);
writer.RenderBeginTag(HtmlTextWriterTag.Form);

AppParam("LMI_PAYMENT_AMOUNT", Math.Round(Amount, 2).ToString());
AppParam("LMI_PAYMENT_DESC_BASE64", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Description)));

AppParam("LMI_PAYMENT_NO", OrderID.ToString());
AppParam("LMI_PAYEE_PURSE", Purse);

if(TestMode) AppParam("LMI_SIM_MODE", "0");

foreach(var item in Params)
{
AddHidden(writer, item.Key, item.Value);
}

writer.RenderEndTag();
}

private void AddHidden(System.Web.UI.HtmlTextWriter writer, string name, string value)
{
writer.Write(string.Format("<input type='hidden' name='{0}' value='{1}' />\n", name, value));
}
}

вівторок, 19 квітня 2011 р.

CSS opacity

/* This works in IE */
filter: alpha(opacity=50);

/* Older than Firefox 0.9 */
-moz-opacity:0.5;

/* Safari 1.x (pre WebKit!) */
-khtml-opacity: 0.5;

/* Modern!
/* Firefox 0.9+, Safari 2?, Chrome any?
/* Opera 9+, IE 9+ */
opacity: 0.5;

Copy:

filter: alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;

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

How to set Visual Studio default "company name"?

Set value in RegisteredOrganization under
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion

вівторок, 5 квітня 2011 р.

View LINQ Generated SQL

Write class:

public class LinqDebugger : System.IO.TextWriter
{
static readonly LinqDebugger _instance = new LinqDebugger();
static readonly string _separator = new String('_', 150);

public static LinqDebugger Instance { get { return _instance; } }

private LinqDebugger()
{
}

public override void WriteLine(string value)
{
System.Diagnostics.Debug.WriteLine(value);
if (!string.IsNullOrEmpty(value) && value.StartsWith("-- Context:"))
System.Diagnostics.Debug.WriteLine(_separator);
}

public override System.Text.Encoding Encoding
{
get { throw new NotImplementedException(); }
}
}

Use:

var db = new DBDataContext();
db.Log = LinqDebugger.Instance;

VS output:

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

ListView + DataPager + QueryStringField


protected void Page_Load(object sender, EventArgs e)
{
//page EnableViewState="true"
if(!IsPostBack) BindData();

//page EnableViewState="false"
//BindData();
}

private void BindData()
{
int page;
if(!int.TryParse(Request.QueryString[pager.QueryStringField], out page)) page = 1;

pager.SetPageProperties((page - 1) * pager.PageSize, pager.PageSize, false);

items.DataSource = _items;
items.DataBind();
}

неділю, 27 березня 2011 р.

Default Documents in IIS 7


<system.webServer>
<defaultDocument>
<files>
<clear/>
<add value="~/Default.htm"/>
</files>
</defaultDocument>
<system.webServer>

четвер, 24 березня 2011 р.

Маленький helper-метод


public static bool eq(this string s, string s2)
{
return string.Compare(s, s2, true) == 0;
}

Use:

if(url.eq("/Default.aspx"))
{
...
}

вівторок, 22 березня 2011 р.

CultureInfo

en-GB - специфическая
ro - нейтральная

var c = "ro";

//создаем специфическую с нейтральной
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(c);
//можно использовать нейтральную, например, Strings.ro.resx
Thread.CurrentThread.CurrentUICulture = new CultureInfo(c);

пʼятницю, 18 березня 2011 р.

.NET парсер HTML

Стояла задача: вытянуть данные из таблицы в .mht документе.
Сначала подумал решить на C#+Regex, но потом нарыл парсер Html Agility Pack. Спасибо автору:).


Вот как я это сделал:

private void MainForm_Load(object sender, EventArgs e)
{
try
{
var file = @"C:\демпинг.mht";

var contentHex = File.ReadAllText(file, Encoding.GetEncoding(1251));

var content = Regex.Replace(contentHex, @"=[0-9A-F]{2}", m => HexStringToUtf8(m.ToString().Substring(1)));

var doc = new HtmlAgilityPack.HtmlDocument();

doc.LoadHtml(content);

var table = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/table[1]");

if(table == null) throw new Exception("data not found");

var rows = table.SelectNodes("tbody/tr").Skip(1).ToList();

var data = (from r in rows
let tds = r.SelectNodes("td")
select new
{
N = tds[0].InnerText,
Group = tds[1].InnerText,
Product = tds[2].InnerText,
OurPrice = tds[3].InnerText,
AveragePrice = tds[4].InnerText,
Difference = tds[5].InnerText,
DifferencePercent = tds[6].InnerText,
Offers = tds[7].InnerText,
Shops = tds[7].Attributes["title"].Value,
MinPrice = tds[8].InnerText,
MaxPrice = tds[9].InnerText
}).ToList();

grid.DataSource = data;
}
catch(Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private string HexStringToUtf8(string hexString)
{
var bytes = new List();

for(int i = 0; i <= hexString.Length - 2; i += 2)
{
bytes.Add(byte.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
}

var str = Encoding.GetEncoding(1251).GetString(bytes.ToArray());

return str;
}

Результат:

четвер, 10 березня 2011 р.

Портативные версии основных браузеров

Портативные версии основных браузеров

Float blocks





/* Firefox 2 */
display: -moz-inline-stack;

/* IE 8, Firefox 3, Opera, Safari, Chrome */
display: inline-block;
vertical-align: top;

/* IE 6 и 7 */
zoom: 1;
*display: inline;


Source

пʼятницю, 4 березня 2011 р.

Несколько полезных примеров регулярок

foo – Слово foo
^foo – Наичнается с foo
foo$ - Кончается с foo
^foo$ - Точное совпадение с foo
[abc] – a, b или c
[a-z] – Любая строчная буква
[^A-Z] - Любой символ не в верхнем регистре
(gif|jpg) - Совпадает либо gif либо jpeg
[a-z]+ - Одна или более строчных букв
[0-9.-] - Любое число, точка или минус
^[a-zA-Z0-9_]{1,}$ – Любое слово, в котором как минимум одна буква, число или _
([wx])([yz]) - wy, wz или xy, xz
[^A-Za-z0-9] – Любой символ (не буква и не цифра)
([A-Z]{3}|[0-9]{4}) - Совпадает три буквы или четыре цифры

Взято тут

суботу, 26 лютого 2011 р.

Using ExtJs XTemplate


Ext.Ajax.ws({
url: "WebService.asmx/GetAllClients",
success: function(data) {
var tpl = new Ext.XTemplate(
'<table class="styled"><tr><th>№</th><th>ID</th><th>Name</th></tr>',
'<tpl for=".">',
'<tr><td>{#}</td><td>{ID}</td><td>{Name}</td></tr>',
'</tpl>',
'</table>'
);
tpl.overwrite(Ext.get('container'), data);
}
});

My result:

пʼятницю, 25 лютого 2011 р.

FBML not working in IE

Нужно добавить xmlns:fb="http://www.facebook.com/2008/fbml" в тег htlm:

<html xmlns="http://www.w3.org/1999/xhtml" mlns:fb="http://www.facebook.com/2008/fbml" >

середу, 23 лютого 2011 р.

Loading JavaScript Asynchronously

JQuery plugin:

(function($) {
jQuery.asyncJs = function(js) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = js;
document.getElementsByTagName('head')[0].appendChild(s);
}
})(jQuery);

Use:

$.asyncJs('http://connect.facebook.net/ru_RU/all.js');

понеділок, 21 лютого 2011 р.

Linq Paging Extensions


public static class PagingExtensions
{
//linq to sql
public static IQueryable Page(this IQueryable source, int page, int size)
{
return source.Skip((page - 1) * size).Take(size);
}

//linq to objects
public static IEnumerable Page(this IEnumerable source, int page, int size)
{
return source.Skip((page - 1) * size).Take(size);
}
}

четвер, 13 січня 2011 р.

Пример курсора


declare @Login nvarchar(255)
declare @Password nvarchar(255)
declare @i int

DECLARE curs CURSOR FOR
SELECT [Login], [Password]
FROM [UsersToCreate]

OPEN curs

FETCH NEXT FROM curs INTO @Login, @Password

set @i=1

WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
exec('CREATE LOGIN ['+@Login+'] WITH PASSWORD = '''+@Password+'''')
exec('CREATE USER ['+@Login+'] FOR LOGIN ['+@Login+'] WITH DEFAULT_SCHEMA = my_sc')
exec('EXEC sp_addrolemember ''my_role'', ['+@Login+']')
END TRY
BEGIN CATCH
print cast(@i as char(3))+ ') login: ' + @Login + ' - error:' + ERROR_MESSAGE()
set @i= @i+1
END CATCH;
FETCH NEXT FROM curs INTO @Login, @Password
END

CLOSE curs
DEALLOCATE curs

вівторок, 11 січня 2011 р.

C#, Get Current Path


public static class PathHelper
{
public static string GetCurrentPath()
{
string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
return System.IO.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
}

public static string CombineWithCurrent(string path)
{
return System.IO.Path.Combine(GetCurrentPath(), path);
}
}