Friday

t-sql unit testing

Here is simple t-sql unit testing approach by writing sql script that will do all testing work.
I like this solution the most because it's very flexible and doesn't require additional installations on sql server.


Also I think the best way to write sql unit tests is to make them independent from data.And validate logic but not data.
Such unit tests can be run on development or qa and even production environment.
 
--Unit Test example
--SETUP
declare @ActualData varchar(10) , @ExpectedResult varchar(10)

-- RUN
SET @ActualData ='a'
Set @ExpectedResult ='b'

-- VALIDATE
IF @ActualData!= @ExpectedResult
RAISERROR('>> Unit Test FAILED: Returned data doen''t match expected: %s instead of %s ', 11, 0, @ActualData ,@ExpectedResult )

Also there are another sql unit test frameworks .

Tuesday

jquery textbox change event not firing

Try to use live event instead of change or onchange as follows:
 
$('#myTextBoxId').live('input', function () {
MyFunction();
});


Monday

jquery select add remove item


to add new option to select control with DropDownId id :
 
$('#DropDownId').append(new Option('text','val'));



to remove option to select control with DropDownId id:
 
$("#DropDownId option[value='val1']").remove();
$("#DropDownId option:contains('val1')").remove();


mvc model not updating

To resolve this issue try to add this instruction before calling view and see if it works ModelState.Clear();
  
public ViewResult SomeAction(SomeModel model)
{
var newModel = new SomeModel { SomeString = "some value" };
ModelState.Clear();
return View(model);
}


Friday

jquery ajax post form values

      
<script type="text/javascript">
$(document).ready(function () {

$("#SaveReportButton").click(function (event) {
event.preventDefault();
var $form = $(this).parents('form');
$.ajax({
type: "POST",
url: '@Url.Action("SaveDistributionReport")',
data: $form.serialize(),
error: function(xhr, status, error) {
//do something about the error

},
success: function(response) {
//save selected value

}
});
});
});
</script>


vim show tabstops

 
" highlight tabs and trailing spaces
set listchars=tab:>-,trail:-
set list
set tabstop=4


Monday

html.radiobuttonfor onclick for tracking change event

here is example how to use onclick event for tracking changes in radio button group.
 
@Html.LabelFor(m => m.BoolProperty)
@Html.RadioButtonFor(m => m.BoolProperty, true, new { onclick= "onPropertyChanged(true);" })
@StringResources.Submitted
@Html.RadioButtonFor(m => m.BoolProperty, false, new { onclick = "onPropertyChanged(false);" })
@StringResources.Fulfillment

so when radio button control will be changed , onPropertyChanged javascript function will be called passing value of radio button as argument.

Sunday

кожа для вордпресс, которую купили 27 тыс раз на сумму 1.5 мегабакса

кожа для вордпресс, которую купили 27 тыс раз на сумму 1.5 мегабакса
 Вот тема для вордпресса, стоит $55. Ее продали 27+ тыс раз, на сумму 1.485 килобаксов (чуть менее 1.5 мегабакса). Самая продаваемая тема для вордпресса. Начало продаж 4 июня 2011.

Шароварщики нервно курят в сторонке (уж по соотношению доход/"затраты на разработку").

ЗЫ: попал на ту страничку увидев adwords на сайте sdelanounas.ru, сидя в инете с немецкого IP адреса. То есть магазин themeforest дает рекламу своих самых продаваемых продуктов.

Friday

developer productivity metrics



  • Productivity

    • Does the developer get a reasonable amount of work done in a given period of time?

    • Is the developer's velocity on bug fixing sufficient?





  • Engagement

    • Is the developer dedicated to his/her craft?

    • Is the developer committed to delivering software on time?

    • Is the developer dedicated to company success?



  • Attention to Quality

    • To what degree does the developer's code work as designed?

    • Does the developer thoroughly test code and believe it to be correct before checking it in?

    • Do a minimal number of bugs get reported against his/her code?

    • Does the developer write unit tests for all new code?

    • Does the developer follow the Boy Scout Rule and leave a module cleaner than it was before he or she worked on it?



  • Code Base Knowledge and Management

    • To what degree does the developer understand the code base assigned to him/her?

    • Does the developer take responsibility for his/her team's code base, improving it at every opportunity?



  • Adherence to coding guidelines and techniques

    • Does developer's code routinely meet coding standards?

    • Do code reviews reveal a minimum of problems and discrepancies?

    • Does the developer use Dependency Injection to ensure decoupled code?



  • Learning and Skills

    • Is the developer constantly learning and improving his/her skills?

    • Does the developer show a passion for the craft of software development?



  • Personal Responsibility

    • Does the developer first assume that the error lies within his or her code?

    • Does the developer understand that he or she is solely responsible for their code working correctly?

    • Does the developer take pride in their code, ensuring it is clean, tested, easy to read, and easy to maintain?







c# datetime beginning of day

This extension adds EndOfDay StartOfDay methods to DateTime so it's possible to call
DateFrom.Value.StartOfDay() or dateTo.Value.EndOfDay()

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AwesomeExtensions
{

public static class Extension
{
public static DateTime EndOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
}

public static DateTime StartOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
}
}
}


selenium popup example in c#

 
// waiting for popup to open
while (this.driver.WindowHandles.Count == 1)
{
this.WaitASec();
}

this.WaitASec();

// save the current window handle.
String parentWindowHandle = driver.CurrentWindowHandle;
IWebDriver popup = null;
var windowIterator = driver.WindowHandles;
bool onefound = false;

//enumerate through all windows to make sure at least one contains required text
foreach (var windowHandle in windowIterator)
{
popup = driver.SwitchTo().Window(windowHandle);
if (textPresent != "")
{
onefound=Regex.IsMatch(popup.FindElement(By.CssSelector("BODY")).Text, "^[\\s\\S]*" + textPresent + "[\\s\\S]*$");
}
}
Assert.IsTrue(onefound,"No text was found "+textPresent);


Wednesday

accessed from a thread other than the thread it was created on.

This happends when you are trying to modify control from another thread.You cannot do this directly it could be done only by invoker.
In order to resolve this situation please do following:
step 1: Create following extension
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

public static class Extension
{
public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
if (control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}
}


step2.Using developed extension:
Now in other thread instead of calling control directly like :
 
htmlPanel1.Text = resml;

You have to call it as follows:
 
htmlPanel1.InvokeIfRequired(() =>{ htmlPanel1.Text = resml; });



Tuesday

@html.dropdownlistfor onchange


here is how to add javascript onchange function to DropDownListFor MVC helper:
     
@Html.DropDownListFor(m => m.SettingValue, new SelectList(Model.globalTypes, "TypeCode", "TypeName"), new { onchange = "SettingChanged()" })



Friday

jquery save and restore form data

Here is sample how to store and retrieve form and retrieve data
 
// get all form values into json
var s2=$('form').values();
// restore all forms values back
$('form').values(s2);


Here is the function
    
/* function for form saving restoring code */
$.fn.values = function (data) {
var els = $(this).find(':input').get();

if (typeof data != 'object') {
// return all data
data = {};
$.each(els, function () {
if (this.name && !this.disabled && this.type != "hidden") {
if (this.type == 'checkbox') {
data[this.name] = $(this).is(":checked");

} else if (this.type == 'radio') {
if ($(this).is(":checked")) {
data[this.name] = $(this).val();
}
} else {
data[this.name] = $(this).val();
}

}
});
return data;
} else {
$.each(els, function () {
if (this.name && data[this.name] != null) {
//console.log(">" + this.name + " " + data[this.name]);
if (this.type == 'checkbox') {
$(this).attr("checked", data[this.name]); //(data[this.name] == $(this).val())
//console.log("checkbox");
} else if (this.type == 'radio') {
$(this).attr("checked", data[this.name] == $(this).val());
} else {
$(this).val(data[this.name]);
}
}
});
return $(this);
}
};


Product Opportunity Assessment

1. Exactly what problem will this solve? (value proposition)
2. For whom do we solve that problem? (target market)
3. How big is the opportunity? (market size)
4. What alternatives are out there? (competitive landscape)
5. Why are we best suited to pursue this? (our differentiator)
6. Why now? (market window)
7. How will we get this product to market? (go-to-market strategy)
8. How will we measure success/make money from this product? (metrics/revenue strategy)
9. What factors are critical to success? (solution requirements)
10. Given the above, what’s the recommendation? (go or no-go)

Wednesday

javascript delete confirmation dialog box

 
function DeleteSpecificClient(gridId, gridModel) {
var ac2del = 0;
var allVals = 'dels='; $('#' + gridId).find('.idCheckbox:checked').each(function () {
allVals += $(this).attr("id") + ","; ac2del += 1;
});
if (ac2del == 0) return; // exit if no group selected
var dia = $('#deleteClientsPopup').html(ac2del + " @StringResources.DeletingDialogMessage" + ".<br>");
var xhr;
dia.dialogInit({
title:"@StringResources.DeleteDialogTitle",
modal: true,
resizable: false,
autoResize: true,
autopen:true,
buttons: [
{
id: "SaveButton",
text: "Delete",
click: function (event) {
var grid = $find(gridModel.gridId());
grid.ShowWaitingPopup();
dia.dialog("close");
xhr= $.ajax({
type: 'POST',
url: '@Url.ApplicationAction("DeleteClientsFromList", "LoggingSettings")',
data: allVals,
cache: false,
success: function (data) {
ReloadSelectedClientsGrid();
DisableDelButton();
},
error: function (xhr, data, message) {
//console.log(data + ": " + message);
},
dataType: "json"
});
}
},
{
id: "CancelButton",
text: "Cancel",
click: function () {
try {
xhr.abort();
} catch (err) {
}
dia.dialog("close");
}
}
]
});

dia.dialog("open");
return false;
};


css cellpadding cellspacing border table

following css settings are equivalent to cellpadding='0' cellspacing='0'
 
.ReportFormsFieldSet{
border:0;
border-spacing:0;
border-collapse:collapse;
}


jquery drag over element

    
<html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script language='javascript'>

$(document).ready(function () {
$(".cell").draggable({
over : function(event, ui) {
alert('');
},
helper: 'clone'
});

$('.cell').droppable({
over : function(event, ui) {
alert( $(this).attr("id"));
}
});

});
</script>
</head>
<body>

<table border='1'><tr>
<td class='cell' id='base' >
[ one ]
</td>
<td class='cell' id='detail'>
[ test ]
</td>
</tr></table>
</body>


jquery get first link in div

this expression returns text of first link in div
 
$('#dvPaymentStatus a:first').text()


jquery all except one

here is jquery how to get all elements except one:
 
$('#dvPaymentStatus').find("input[type=checkbox]:checked").not('#PaymentStatus_SelectAll').size()


Monday

mvc get html from view

add method below to controller then you will be able to get html from any view by:
this.RenderView("myView");
 
/// <summary>
/// get html from view
/// </summary>
public string RenderView(string ViewName)
{
var content = string.Empty;
var view = ViewEngines.Engines.FindView(ControllerContext, ViewName, null);
using (var writer = new StringWriter())
{
var context = new ViewContext(ControllerContext, view.View, ViewData, TempData, writer);
view.View.Render(context, writer);
writer.Flush();
content = writer.ToString();
}
return content;
}


Wednesday

asp.net mvc ajax post model

If model contain variable of class Class1 with properties Property1,Property2.
Submitted parameters must be named:
"Class1.Property1"
"Class1.Property2"

If model has property as List<Record> submitted values must be :
"Class1[0].Property1"
"Class1[0].Property2"
"Class1[1].Property1"
"Class1[1].Property2"
"Class1[2].Property1"
"Class1[2].Property2"

Here are samples of two functions that creates this values dynamically before submitting form.

     
//this function create parameters for sending them over AJAX
function ConvertJSONIntoPostableHTML() {
var params = {
param1 : 'myvalue',
};

if (Jsonrecord != null) {
for (var i = 0; i < Jsonrecord.length; i++) {
var rec = Jsonrecord[i];
$.each(Object.keys(rec), function(j, value) {
params["Records[" + i + "]." + value] = rec[value];
});
}
}

return params;
}


        

//this function add parameters to form , then form can be submitted
function SelectedNodes(frm) {
$(".tslct").remove();
var i = 0;
$.each(myJsonCollection, function () {
var obj = "Nodes[" + i + "].";
addElem(frm, obj + "Id", this.Id);
addElem(frm, obj + "Value", this.Type);
i++;
}
);
}


jquery add element to form dynamically

 
//function that adds element to form
function addElem(frm, id, val) {
$('<input>').attr({
type: 'hidden',
id: id,
name: id,
value: val,
class: 'tslct'
}).appendTo(frm);
}

//example of using of this function
var frm = $(this).closest('form');
addElem(frm, "myId", "myvalue");


Tuesday

use of hashtable in javascript

here is an example of usage of hashtable in javascript.For example I want to asociate specific buttonId
with specific grid Id I could create following hashtable:
 
var GridsButtons = {
'AGroupsListGrid' :'DelA',
'BGroupsListGrid' :'DelB'
};


Then I could use it in code :
 var buttonid = GridsButtons[gid]; 


asp.net mvc ajax post from javascript

Following example demonstrate how to submit form in asp.net MVC for strict type view based on model:
(view has this instruction oin top:
@model MyModel
):

javascript part:
      
<script type="text/javascript">
$(document).ready(function() {
$("#GoButton").click(function() {
var frm = $(this).closest('form');
var params = frm.serialize();
$.ajax({
type: 'POST',
url: '@Url.ApplicationAction("MyPostAction", "myController")',
data: params,
cache: false,
success: function (data) {
alert('Completed');
},
error: function (xhr, data, message) {
//console.log(data + ": " + message);
},
dataType: "json"
});
return false;
});
});
</script>


on server side model variable will have updated with all values submitted in form and will have following parameters:
 
[HttpPost]
public ActionResult MyPostAction(MyModel model)
{

return Json("Ok");
}




jquery events with example

Following example demonstrate how to use jQuery events:
To trigger event use this code :

 $document.trigger('Grid_CheckBox_Click',gridId,this); 

Grid_CheckBox_Click is the name of my event.

to Subscribe to event use this code:
 
$(document).bind('Grid_CheckBox_Click', function (e, elem) {
MyFunction(e);
});


Thursday

mvc radiobuttonfor example

below is an example of creating mvc radio button control for boolean model myBoolProperty property
 
@Html.LabelFor( m => m.myBoolProperty)
@Html.RadioButtonFor(m => m.myBoolProperty, true)
@StringResources.Submitted
@Html.RadioButtonFor(m => m.myBoolProperty, false)
@StringResources.Fulfillment


Tuesday

mercurial server multiple repositories

Serving multiple repositories using hg serve.


Here's my hgweb.config file:


[paths]
project-a = C:/hg/project-a/
library-b = C:/hg/library-b/

I start hg serve with this command:


hg serve --address 127.0.0.1 --port 8000 --webdir-conf C:/hg/hgweb.config --encoding utf8



Monday

Уроки




Урок 1 (он же главный): Найдите наикратчайший из способов удовлетворить потребность и не напрягайте пользователей деталями.

Нам через день предлагают добавить ту или иную фишку. Первый вопрос которым мы задаемся — а какому проценту наших пользователей это понадобиться. Если меньше 5% — мы этого делать не будем.

Урок 2 (вообще-то продолжение первого): ненужная большинству функциональность вредна поскольку усложняет понимание.

Вот как мы расправились с некоторыми из сложностей:

  1. Программа должна была работать с несколькими проектами/работами. Однако для большинства достаточно создать только один проект выбрав несколько баз для бэкапа. Мы сделали так, что программа сама открывает тот же проект, что и в прошлый раз и соединяется с тем же SQL сервером — так что большинство даже и не задумывается, что можно работать с несколькими проектами.
  2. SQL Connection String — до сих пор самая сложная часть для пользователя. При первом запуске мы, не спрашивая пользователя, перебираем самые распространенные Connection String, так что, открыв программу, большинство пользователей уже подключились к серверу и видят список своих баз данных.
  3. Посылка писем — чтобы не напрягать пользователей с настройкой SMTP мы по умолчанию посылаем письма через веб-сервис на своем сервере. Для бесплатных пользователей фишка бесплатна на неделю, а потом можно либо купить платную версию либо пользоваться своим Gmail или другим SMTP сервером.
  4. Расписание — большинству требуется Full Backup один раз в день. Что и можно сделать на основной форме. Для более продвинутых все настройки спрятаны за кнопкой Settings.

Деньги


Поработав немного, мы сделали первую версию программки. Далее мы поставили ее во все shareware-сайты и оставили комментарии на форумах по этой теме. Понемногу пошли клиенты. Через два месяца после выпуска нас заметила одна большая компания, продукт которой был основан на SQL и его пользователи с небольшими техническими знаниями были сами ответственны за бэкап. Для них мы подходили идеально и они послали всех своих пользователей к нам. Кроме этого они даже взяли на себя заботу по тех поддержке. Деньги потекли рекой.

Основная версия (Standard) стоит сейчас $59. Для тех компаний для которых это не деньги — у нас есть Professional с добавкой AES encryption за $69. Для экономных — Lite (максимум 5 баз данных) за $29. С год назад я прочитал какую-то статью о том, что цены на странице Prices нужно подавать от больших к малым дабы пользователю, испуганному первыми большими цифрами, цифра в середине показалась относительно скромной. Мы подумали: что бы такого выпустить дорогого чтобы пугать пользователей? Так родилась идея Lifetime-версии за $199 (сейчас $149) с бесплатными пожизненными обновлениями. И мы очень удивились когда ее стали бодро покупать!

Потом товарищ подкинул другую идею, которая принесла тысячи долларов. В добавок к продуктам мы продаем за небольшие деньги еще и Extended Support (тем, кто его купил — особое внимание при поддержке) и бесплатное обновление на 1 год (по умолчанию — 1 месяц). Дополнительные усилия близки к 0, а деньги понемногу капают…

Урок 3 — дайте пользователю заплатить столько, сколько он хочет и может.

Пиратство и жадность


С первых дней существования мы решили тратить только минимум времени на борьбу с пиратством. В программе зашит алгоритм на проверку лицензионного ключа который несложно взломать. Идея такова: если человек запускает keygen для взлома — он вряд ли заплатил бы за программу без этого. А так — будет пользоваться и, возможно, когда остепенится, тогда и почувствует потребность заплатить.
Многие устанавливают ключик на несколько машин — мы просто посылаем вежливые письма с напоминанием, что это неправильно. Компании в цивилизованных странах стараются договоренности соблюдать и покупают недостающие лицензии. С менее цивилизованными мы могли бы справиться добавив активацию, но это усложнило бы жизнь для большинства честных клиентов. И опять же: нами пользуются и это уже хорошо.

Урок 4 — концентрируйтесь на продукте, а не на защите. Пират сегодня — клиент завтра.

Большинству вполне хватает бесплатной версии в которой можно делать то же самое, что и в стандартной, только с ограничением в две базы данных. Благодарный народ даже пожертвования предлагает. Да мы и рады: когда потребности вырастут, тогда и заплатят, а заодно боремся с бесплатными самоделками.
Недавно мы добавили бэкапы в Amazon S3, Google Drive и Dropbox. Сначала было желание брать дополнительные деньги. Но решили не напрягать пользователей и просто добавить к существующим версиям. Будет больше пользователей — значит и доходы вырастут.

Урок 5 — довольные клиенты важнее сиюминутного наполнения карманов.

Friday

py2exe mechanize

I've got problem with including mechanize into py2exe package.
I resolved this problem by
  1. uninstalling packages by running easy_install with -m key

easy_install -m mechanize
easy_install -m MultiPartPostHandler

  1. physically removing .eggs files from python2.X/site-packages/MYPACKAGE.egg
  1. installing packages with -Z key

easy_install.exe -Z mechanize
easy_install.exe -Z MultiPartPostHandler


Pomodoro technique game

Thursday

how to add new Service to reference.svcmap

Add a new MetadataSource into the file, save it, and Update the reference, all metadata files will be downloaded automatically.
MetaSource tag will be looking like this:
  
<MetadataSource Address="http://localhost/myservices/Services/Service1.svc?wsdl" Protocol="http" SourceId="1" />


Sunday

csharp post form data

     
public string POST(string url, string username,string password, string postParams)
{


//Our getVars, to test the get of our php.
//We can get a page without any of these vars too though.
//string getVars = "?var1=test1&var2=test2";
//Initialization, we use localhost, change if applicable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.UserAgent = GetRndUserAgent();

string Credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));

WebReq.Method = "POST";
WebReq.ContentType = "application/xml";
WebReq.AllowWriteStreamBuffering = true;

WebReq.Headers.Add("Authorization", "Basic " + Credentials);

WebReq.ServicePoint.Expect100Continue = false;



// string postParams = "name=some sort of value";
if (postParams != string.Empty)
{
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(postParams);
WebReq.ContentLength = buffer.Length;
using (Stream writer = WebReq.GetRequestStream())
{

writer.Write(buffer, 0, buffer.Length);

}
}

//From here on, it's all the same as above.
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
//_log(WebResp.StatusCode.ToString());
//_log(WebResp.Server);

//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
return _Answer.ReadToEnd();


}

user agent random

     
public static string GetRndUserAgent()
{
string UserAgnet = "";

Random r = new Random();
int i = r.Next(1, 20);

switch (i)
{
case 1:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.34; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30618)";
break;

case 2:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)";
break;

case 3:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser; .NET CLR 2.0.50727; MAXTHON 2.0)";
break;

case 4:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; Media Center PC 3.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)";
break;

case 5:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)";
break;

case 6:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618)";
break;

case 7:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)";
break;

case 8:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/526.9 (KHTML, like Gecko) Version/4.0dp1 Safari/526.8";
break;

case 9:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.2a1pre) Gecko/20090402 Firefox/3.6a1pre (.NET CLR 3.5.30729)";
break;

case 10:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.8pre) Gecko/20070928 Firefox/2.0.0.7 Navigator/9.0RC1";
break;

case 11:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4 GTB5 (.NET CLR 3.5.30729)";
break;

case 12:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16";
break;

case 13:
UserAgnet = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7pre) Gecko/20070815 Firefox/2.0.0.6 Navigator/9.0b3";
break;

case 14:
UserAgnet = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.2) Gecko/20121223 Ubuntu/9.25 (jaunty) Firefox/3.8";
break;

case 15:
UserAgnet = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30";
break;

case 16:
UserAgnet = "Opera 9.7 (Windows NT 5.2; U; en)";
break;

case 17:
UserAgnet = "Opera/9.64 (X11; Linux x86_64; U; en) Presto/2.1.1";
break;

case 18:
UserAgnet = "Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1)";
break;

case 19:
UserAgnet = "Opera/9.70 (Linux i686 ; U; zh-cn) Presto/2.2.0";
break;

case 20:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; Tablet PC 2.0; MALC)";
break;

default:
UserAgnet = "MMozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0";
break;
}

return UserAgnet;
}

Thursday

Navigation to the webpage was canceled chm

To fix this problem :
Right-mouse click it in Windows Explorer on chm file and select Properties. Then click Unblock.
Here is article describes the how to work around it : http://support.microsoft.com/kb/896054

Wednesday

Strong name validation failed.

To resolve this issue run following command in Visual Studio command line:
sn -Vr "[PathToProblemDLL]\[ProblemDll].dll"


Tuesday

c# extensions

     
//A. allows value.In("one", "two" , "tree")
public static bool In<T>(this T source, params T[] list)
{
if(null==source) throw new ArgumentNullException("source");
return list.Contains(source);
}

//#B Enable quick and more natural string.Format calls
public static string F(this string s, params object[] args)
{
return string.Format(s, args);
}

// like this one "lala {1} ".F(one, two)

//#C nice comparison tool :
public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
{
return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0;
}

//Allows to have :
if (myNumber.Between(3,7))
{
// ....
}

//#D a map function
public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)
{
foreach (var item in @enum) mapFunction(item);
}

//allows to run function for every element
// like this one :
new { itemA, itemB, itemC }
.ForEach(item => {
item.Number = 1;
item.Str = "Hello World!";
});


Sunday

moving data between two list boxes +jquery

   

<select id="SelectLeft" multiple="multiple">
<option value="1">Australia</option>
<option value="2">New Zealand</option>
<option value="3">Canada</option>
<option value="4">USA</option>
<option value="5">France</option>
</select>

<input id="MoveRight" type="button" value=" >> " />
<input id="MoveLeft" type="button" value=" << " />

<select id="SelectRight" multiple="multiple">
</select>




<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#MoveRight,#MoveLeft").click(function(event) {
var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";

var selectedItems = $(selectFrom + " :selected").toArray();
$(moveTo).append(selectedItems);
selectedItems.remove;
});
});
</script>


Thursday

cross platform mobile development comparison

There's a detailed comparison of all these toolkits in this article here: Modern Cross Platform Development.
There are a number of other solutions around like
Rhodes,
Titanium,
PhoneGap,
JUCE,
MoSync,
Corona and
Moai.
Each of these use a bunch different languages, including HTML5/JS/CSS, Lua, Ruby, Python and C++. All except Corona are open source and free.

Tuesday

template method design pattern c#

      
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RulesDemo
{

/* messages */

public class MessageBase
{
public bool ClientActive { get; set; }
}


public class SPQMessage: MessageBase {
public bool Card {get;set;}
}

public class ACPMessage: MessageBase {
public bool URL {get;set;}
}


/* Ruule interface*/

public interface IRule {
string Evaluate (MessageBase messageBase);
string Evaluate (SPQMessage messageBase);
string Evaluate (ACPMessage messageBase);
}


/* rules */

/* rule base */
public class RuleBase: IRule {
public virtual string Evaluate(MessageBase messageBase)
{
throw new NotImplementedException();
}

public virtual string Evaluate(SPQMessage messageBase)
{
return Evaluate((MessageBase)messageBase);
}

public virtual string Evaluate(ACPMessage messageBase)
{
return Evaluate((MessageBase)messageBase);
}
}


/* concrete rules */
public class ClientIsActive : RuleBase
{
public override string Evaluate(MessageBase messageBase)
{
return "ClientIsActive";
}
}

public class UrlIsPresent : RuleBase
{
public override string Evaluate(ACPMessage messageBase)
{
return "UrlIsPresent";
}

}

/* */

class Program
{
static void Main(string[] args)
{

ArrayList list = new ArrayList();
list.Add(new ClientIsActive());
list.Add(new UrlIsPresent());


ACPMessage message = new ACPMessage();
foreach (IRule rule in list)
{
Console.WriteLine(rule.Evaluate(message));
}

/* this will crash because ACP rule doesn't know how to process SPQ message*/
/*
SPQMessage message2 = new SPQMessage();
foreach (IRule rule in list)
{
Console.WriteLine(rule.Evaluate(message2));
}
*/
Console.ReadLine();

}
}
}

msmq set permissions c#

 
private void CreateQueue(string qname)
{
try
{
if (!MessageQueue.Exists(qname))
{
MessageQueue.Create(qname);
MessageQueue messageQueue = new MessageQueue(qname);
//messageQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
messageQueue.SetPermissions("Local Service", MessageQueueAccessRights.FullControl);

}
}
catch (Exception e)
{

Debug.Write("Failed to setup queue:" + qname + ":" + e.ToString());
}

}


windows service installer class with event source creation

      
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
namespace ProcessingService
{
[RunInstaller(true)]
public partial class MyProcessorInstaller : System.Configuration.Install.Installer
{
private readonly ServiceProcessInstaller _processInstaller;
private readonly ServiceInstaller _svcInstaller;
public MyProcessorInstaller()
{
InitializeComponent();
_processInstaller = new ServiceProcessInstaller();
_svcInstaller = new ServiceInstaller();

_processInstaller.Account = ServiceAccount.LocalService;

_svcInstaller.StartType = ServiceStartMode.Automatic;
_svcInstaller.Description = "Describe here what service is doing. ";
_svcInstaller.DisplayName = "Processing Service";
_svcInstaller.ServiceName = "ProcessingService";



//Create Instance of EventLogInstaller
EventLogInstaller myEventLogInstaller = new EventLogInstaller();

// Set the Source of Event Log, to be created.
myEventLogInstaller.Source = "ProcessingService";

// Set the Log that source is created in
myEventLogInstaller.Log = "Application";

// Add myEventLogInstaller to the Installers Collection.
Installers.Add(myEventLogInstaller);


Installers.Add(_svcInstaller);
Installers.Add(_processInstaller);

}
}
}


reset sa password sql 2008

How to recover SA password on Microsoft SQL Server 2008 R2

When you are using MS SQL Server in mixed mode, it is very important that you know your SA password.

There can be different reasons you lost the password

  • Person who installed the SQL Server knows the password but has left the building.
  • You did not write down the password in your password file
  • Password file is lost
  • …

Steps to recover the SA password

  • Start SQL Server Configuration Manager

  • Stop the SQL services

  • Edit the properties of the SQL Service

  • Change the startup parameters of the SQL service by adding a –m; in front of the existing parameters

  • Start the SQL services. These are now running in Single User Mode.
  • Start CMD on tthe SQL server
  • Start the SQLCMD command. Now you will see following screen

  • Now we create a new user. Enter following commands
    • CREATE LOGIN recovery WITH PASSWORD = ‘TopSecret 1′ (Remember SQL server has default strong password policy
    • Go
      • Now this user is created
  • Now we grant the user a SYSADMIN roles using the same SQLCMD window.
    • sp_addsrvrolemember ‘recovery’, ‘sysadmin’
    • go
  • Stop the SQL service again
  • Change the SQL service properties back to the default settings

  • Start the SQL service again and use the new created login (recovery in my example)
  • Go via the security panel to the properties and change the password of the SA account.

  • Now write down the new SA password.

Monday

get url c# and get url stream

       
public string Get(string url)
{
Debug.WriteLine(url);

HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.UserAgent = GetRndUserAgent();

//This time, our method is GET.
WebReq.Method = "GET";
//From here on, it's all the same as above.
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
_log(""+WebResp.StatusCode);
_log(WebResp.Server);

//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
return _Answer.ReadToEnd();
}


public StreamReader GetStream(string url)
{
Debug.WriteLine(url);

HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.UserAgent = GetRndUserAgent();

WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//_log("" + WebResp.StatusCode);
//_log(WebResp.Server);

Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
return _Answer;

}


jsonarray example in c#


public List<TwtAuthor> Search(string kw, int page)
{
List<TwtAuthor> ret = new List<TwtAuthor>();

string url =
string.Format(
"http://search.twitter.com/search.json?q={0}&rpp=100&include_entities=true&result_type=mixed&page{1}",kw.Replace(" ","%20"),page);

JsonObject jsonArray = JsonArray.Load(wl.GetStream(url)).ToJsonObject();

for (int i = 0; i < jsonArray["results"].Count; i++)
{

//jsonArray["results"][0]["created_at"]
TwtAuthor author = new TwtAuthor()
{
name = jsonArray["results"][i]["from_user"].ToString().Replace("\"",""),
UserID = jsonArray["results"][i]["from_user_id"].ToString(),
KwmimText = jsonArray["results"][i]["text"].ToString(),
// KwmimDate = DateTime.Parse(jsonArray["results"][i]["created_at"].ToString()), // entry.Published,
RecordCreated = DateTime.Now
};
ret.Add(author);
}


return ret;

}


Thursday

style for asp.net Gridview

This is part of css files that contains style description:
 
.mGrid {
width: 100%;
background-color: #fff;
margin: 5px 0 10px 0;
border: solid 1px #525252;
border-collapse:collapse;
}
.mGrid td {
padding: 2px;
border: solid 1px #c1c1c1;
color: #717171;
}
.mGrid th {
padding: 4px 2px;
color: #fff;
background: #424242 url(grd_head.png) repeat-x top;
border-left: solid 1px #525252;
font-size: 0.9em;
}
.mGrid .alt { background: #fcfcfc url(grd_alt.png) repeat-x top; }
.mGrid .pgr { background: #424242 url(grd_pgr.png) repeat-x top; }
.mGrid .pgr table { margin: 5px 0; }
.mGrid .pgr td {
border-width: 0;
padding: 0 6px;
border-left: solid 1px #666;
font-weight: bold;
color: #fff;
line-height: 12px;
}
.mGrid .pgr a { color: #666; text-decoration: none; }
.mGrid .pgrD A:link {color:#0466c1;}
.mGrid .pgr A:visited {color:#0466c1;}
.mGrid .pgr A:hover {color:#0466c1;}
.mGrid .pgr A:active {color:#0466c1;}
.mGrid .pgr a:hover { color: #000; text-decoration: none; }


images must be placed within style file
grd_alt.png
grd_head.png
grd_pgr.png

In grid this style can by defined as follows:
 
<asp:GridView ID=gv runat=server BorderWidth="0" CellPadding=0 CellSpacing=0 Width="100%" CssClass="mGrid"
AllowPaging=false AllowSorting=false AutoGenerateColumns="False" SkinID=gvSkinMergePeople>
<Columns>
<asp:TemplateField HeaderText="dealer#" >
<ItemTemplate>
<a href='Edit.aspx?id=<%#Eval("Id") %>'> <%#Eval("dealer_") %></a>
</ItemTemplate>


</asp:TemplateField>
<asp:BoundField HeaderText="Client Name" DataField="dealer_name" />
<asp:BoundField HeaderText="Group" DataField="group" />
<asp:BoundField HeaderText="industry" DataField="industry" />
<asp:BoundField HeaderText="status" DataField="dealer_status" />
<asp:BoundField HeaderText="service begins" DataField="service_begins" DataFormatString="{0:mm/dd/yyyy}" />
<asp:BoundField HeaderText="CommissionType" DataField="RevenueSegmentValue" />
<asp:BoundField HeaderText="BudRank" DataField="BudRank" />
<asp:BoundField HeaderText="ForecastRank" DataField="ForecastRank" />
</Columns>
<EmptyDataTemplate>
<table cellpadding=0 cellspacing=0 border=0 width=100% height=100%>
<tr>
<td align=center height="40">
<asp:Label ID=lblEmptyMessage runat=server Text="No Records Found" CssClass="NewPlainText"></asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>



make ubuntu business casual

to make ubuntu business casual - make it black remove background: gsettings set org.gnome.desktop.background picture-options ...