Friday

free online courses

Широко известный проект Coursera объявил о заключении партнерской программы со следующими университетами:

Курсы охватывают широкий круг вопросов, в том числе компьютерные науки, гуманитарные науки, медицину, биологию, социальные науки, математику, статистику, экономику, финансы, а также многие другие темы. В общей сложности доступно около 40 курсов, 6 из которых планируется начать в следующий понедельник, 23 апреля:

Классы, предлагаемые на Coursera, разработаны для того, чтобы помочь вам освоить материал. Вы сможете смотреть лекции профессоров мирового класса, учиться в своем собственном темпе, проверить и укрепить свои знания с помощью интерактивных упражнений. Регистрируясь в Coursera, вы также присоединяетесь к мировому сообществу тысяч студентов, занимающихся вместе с вами.

Thursday

javascript parse number from string

use parseFloat and parseInt functions like on samples below:

1 parseFloat('1.45kg') // 1.45
2 parseFloat('77.3') // 77.3
3 parseInt('123.45') // 123
4 parseInt('77') // 77
5

vim msbuild

1. create build.bat file for building your project

call "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
msbuild c:\myproject\Source\myProject.sln


2.Run following commands in VIM or add to .vimrc
:set makeprg=c:\myproject\Source\build.bat
:set errorformat=\ %#%f(%l\\\,%c):\ %m

3.execute following command to build your project
:make

4.Open output window by
:cope

Tuesday

combobox selectedvalue problem net

When I'm adding new items to combobox like in this post.
There was problem in reading this value on dserver side.
So here is solution how to do this.

string selectedValue = Request.Params[combobox.UniqueId]

Monday

jquery clear dropdown values

use this command to clear dropdown items:

$('#mySelect').empty()

asp.net jquery ajax data webmethod post


1.Code - behind class
  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Modules.MembershipModule;

namespace VoluntaryShop
{
public partial class jsonhub : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Test()
{
return "OK";
}

[WebMethod]
public static ArrayList MSearchVolunteersbyGroup(int Group)
{
Debug.Write("MSearchVolunteersbyGroup"+Group);
MembershipModuleController c = new MembershipModuleController();
return c.MSearchVolunteersbyGroup(Group);
}
}
}


2.ASPX Page:
   
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jsonhub.aspx.cs" Inherits="VoluntaryShop.jsonhub" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> </script>
<script type="text/javascript">
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
})
;
}
</script>

<script type="text/javascript">


function AjaxSucceeded(result) {
alert(result.d);
alert(result.d[0].FirstName);

}
function AjaxFailed(result) {

alert("failed"+result.d);
}

PageMethod("MSearchVolunteersbyGroup", ["Group","1"], AjaxSucceeded, AjaxFailed); //No parameters
</script>


</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

Tuesday

vs2010 the application cannot start

The fix that worked for me is:
Copy the following files from "C:\Program Files\Common Files\Microsoft Shared\MSEnv\" to "c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
dte80.olb
dte80a.olb
dte90.olb
dte90a.old
dte100.old

And then register them all in that location and the application now should works as both administrator and as a regular user.

regsvr32 DTE100.OLB
regsvr32 DTE80.OLB
regsvr32 DTE80a.OLB
regsvr32 DTE90a.OLB
regsvr32 DTE90.OLB

Monday

usb readonly win7

If USB device is readonly on your machine for some reason, here is one way how to fix this:
1. Open start menu, in the search bar type REGEDIT and press enter. This will open the registry editor.
2. Navigate to the following path:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies
Note: If the registry key StorageDevicePolicies does not exist, you will need to create it manually.

3. Highlight StorageDevicePolicies, and then create a New DWORD (32-bit) Value named as WriteProtect.
4. Double click the key WriteProtect in the right window and set the value to 0 in the Value Data Box and press OK button
5. Restart your computer and try copying files into your USB drives.
No restart was required in my case, but that adding registry key works.

Wednesday

binary serialization c#


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

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

// Serialization of String Object

String writeData = "Microsoft .NET Framework 2.0";
FileStream writeStream = new FileStream("C:\\Object.data", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(writeStream, writeData);
writeStream.Close();

// Deserialization of String Object

FileStream readStream = new FileStream("C:\\Object.data", FileMode.Open);
String readData = (String) formatter.Deserialize(readStream);
readStream.Close();
Console.WriteLine(readData);

Console.Read();
}
}
}

Friday

set selected value dropdown javascript

following script allows to set value in dropdown with javascript

<script language='javascript'>
function setSelected(s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].value == v ) {
s.options[i].selected = true;
return;
}
}
}
</script>

Tuesday

asp.net dynamic controls example

 
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Text
Imports System.Web.UI.WebControls
Imports System.Collections.Specialized
Public Class DevidedTextBox
'1. Inherits WebControl
Inherits WebControl
'2.implements IPostBackDataHandler if it's required to read Postback data
Implements IPostBackDataHandler
'3.implements IPostBackEventHandler if it's required to have events like "OnInit", "onChanged" etc.
Implements IPostBackEventHandler

Private ArraYOfTextBoxes As New Collection
Private m_AmountOfBoxes As Byte

Public Event ValidationError(ByVal ErrorId As Byte, ByVal ErrorDes As String)

Public Property AmountOfBoxes() As Byte
Get
m_AmountOfBoxes = ViewState(Me.ID & "_AmountOfBoxes")
Return m_AmountOfBoxes
End Get

Set(ByVal Value As Byte)
m_AmountOfBoxes = Value
ViewState(Me.ID & "_AmountOfBoxes") = m_AmountOfBoxes

End Set
End Property

'4.Must write this stuff 'case of implementation of the interfaces
Public Overridable Sub RaisePostBackEvent(ByVal eventArg As String) Implements IPostBackEventHandler.RaisePostBackEvent
End Sub
Public Overridable Sub RaisePostDataChangedEvent() Implements IPostBackDataHandler.RaisePostDataChangedEvent
End Sub


'5.Code procedure for reading postback data
Public Overridable Function LoadPostData(ByVal postdatakey As String, ByVal postCollection As NameValueCollection) As Boolean Implements IPostBackDataHandler.LoadPostData

For i As Byte = 1 To AmountOfBoxes
Dim txtBox As TextBox = ArraYOfTextBoxes(i)
txtBox.Text = postCollection(txtBox.ID)
Next

Return True
End Function

Private m_AllRequired As Boolean = True
Public Property AllRequired() As Boolean
Get
m_AllRequired = ViewState(Me.ID & "_AllRequired")
Return m_AllRequired
End Get
Set(ByVal Value As Boolean)
m_AllRequired = Value
ViewState(Me.ID & "_AllRequired") = m_AllRequired
End Set
End Property




Private Sub DevidedTextBox_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init
'6.Register controls as postback receiver, required !!!
Page.RegisterRequiresPostBack(Me)

Dim i As Integer

For i = 1 To m_AmountOfBoxes

Dim intTextBox As New TextBox
With intTextBox
.ID = Me.ID & "txt" & i
.MaxLength = 1
.Width = New Unit(15)
.BorderWidth = New Unit(1)

If i <> m_AmountOfBoxes Then
Dim nextname As String = Me.ID & "txt" & i + 1
.Attributes.Add("onkeypress", "ChangeFocus(this,'" & nextname & "');")
End If

End With

ArraYOfTextBoxes.Add(intTextBox, i)
Next

End Sub

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

'writer.WriteLine("<script language='javascript'>")
'writer.WriteLine(" function ChangeFocus(obj,fild)")
'writer.WriteLine("{")
'writer.WriteLine("")
'writer.WriteLine(" if(obj.value.length==obj.maxLength)")
'writer.WriteLine(" {")
'writer.WriteLine(" // CopyToHiddenFields(obj)")
'writer.WriteLine(" // MaskSSN(obj)")
'writer.WriteLine(" document.all[fild].focus()")
'writer.WriteLine(" document.all[fild].select()")
'writer.WriteLine("")
'writer.WriteLine(" }")
'writer.WriteLine("")
'writer.WriteLine("}")
'writer.WriteLine("")
'writer.WriteLine("</script>")
'writer.WriteLine("")

For Each txtBox As TextBox In ArraYOfTextBoxes
txtBox.RenderControl(writer)
Next
End Sub

Private Sub CollectValues()
Dim bUpdate As Boolean = False
Dim sValue As String
' Dim inChar(AmountOfBoxes) As Byte
m_Value = ""
For i As Byte = 1 To AmountOfBoxes
Dim txtBox As TextBox = ArraYOfTextBoxes(i)
'inChar(i) = txtBox.Text
m_Value += txtBox.Text

Next
End Sub

Private Sub SpreadValues()
If Not m_Value Is Nothing Then
For i As Byte = 1 To ArraYOfTextBoxes.Count
Dim txtBox As TextBox = ArraYOfTextBoxes(i)
If m_Value.Length < i Then
txtBox.Text = ""
Else
txtBox.Text = m_Value.Chars(i)
End If
Next
End If
End Sub

Private m_Value As String
Public Property Text() As String
Get
m_Value = ViewState(Me.ID & "_Value")
Return m_Value
End Get
Set(ByVal Value As String)
m_Value = Value
ViewState(Me.ID & "_Value") = m_Value
SpreadValues()
End Set
End Property

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
If Page.IsPostBack Then
CollectValues()
ViewState(Me.ID & "_Value") = m_Value
Else
m_Value = ViewState(Me.ID & "_Value")
SpreadValues()
End If
End Sub

End Class

Wednesday

visual studio 2010 crashes on startup

to solve this problem do following :

  1. Stop Windows Presentation Foundation Font Cache 4.0.0.0 service (or kill WPFFontCache_v0400.exe proc)

  2. Delete *.dat

    from XP - %SystemDrive%\Documents and Settings\LocalService\Local Settings\Application Data.

    Vista/Win7 - %windir%\ServiceProfiles\LocalService\AppData\Local\.

  3. Reboot and you should be able to use Visual Studio.


Saturday

how to be happy

1. Counting your blessings: Expressing gratitude for what you have (either privately – through contemplation or journaling or to a close other) or conveying your appreciation to one or more individuals whom you’ve never properly thanked.


2. Cultivating optimism: Keeping a journal in which you imagine and write about the best possible future for yourself, or practicing to look at the bright side of every situation.


3. Avoiding overthinking and social comparison: Using strategies (such as distraction) to cut down on how often you dwell on your problems and compare yourself to others.


4. Practicing acts of kindness: Doing good things for others, whether friends or strangers, either directly or anonymously, either spontaneously or planned.


5. Nurturing Relationships: Picking a relationship in need of strengthening, and investing time and energy in healing, cultivating, affirming, and enjoying it.



6. Doing more activities that truly engage you: Increasing the number of experiences at home and work in which you “lose” yourself, which are challenging and absorbing.)


7. Replaying and savoring life’s joys: Paying close attention, taking delight, and going over life’s momentary pleasures and wonders – through thinking, writing, drawing, or sharing with another.


8. Committing to your goals: Picking one, two, or three significant goals that are meaningful to you and devoting time and effort to pursuing them.



9. Developing strategies for coping: Practicing ways to endure or surmount a recent stress, hardship, or trauma.


10. Learning to forgive: Keeping a journal or writing a letter in which you work on letting go of anger and resentment towards one or more individuals who have hurt or wronged you.


11. Practicing religion and spirituality: Becoming more involved in your church, temple, or mosque, or reading and pondering spiritually-themed books.


12. Taking care of your body: Engaging in physical activity, meditating, and smiling and laughing.


Thursday

restart service remotely and copy service files bat file.


set comd=copy /V /Y /B
set srv_com=c:\tools\SysInternals\psservice.exe
set src=C:\ms_projects\mscore\EnterpriseBusinessSystem\Dev\BillingSchedule\src\Business.CustomerServices\bin\Debug\
set dest=\\development\c$\Program Files\Processing Services\
set srvname="Processing Service"

%srv_com% \\development stop %srvname%
sleep 10s

%comd% "%src%Business.CustomerServices.dll" "%dest%"
%comd% "%src%Business.CustomerServices.pdb" "%dest%"

rem %comd% "%src%*.dll" "%dest%"
rem %comd% "%src%*.pdb" "%dest%"



%srv_com% \\development start %srvname%

echo on
pause

Wednesday

sloniki

"Слоники, слоники, рожеві слоники! Райдуги, маленькі гномики бігають наввипередки зі слониками по різнокольорових райдугах!".

Thursday

script create table

It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.
         
declare @table varchar(100)
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)

-- create statement
insert into @sql(s) values ('create table [' + @table + '] (')

-- column list
insert into @sql(s)
select
' ['+column_name+'] ' +
data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=@table
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(@table) as varchar) + ',' +
cast(ident_incr(@table) as varchar) + ')'
else ''
end + ' ' +
( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

from information_schema.columns where table_name = @table
order by ordinal_position

-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
insert into @sql(s) values(' PRIMARY KEY (')
insert into @sql(s)
select ' ['+COLUMN_NAME+'],' from information_schema.key_column_usage
where constraint_name = @pkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' )')
end
else begin
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id

Tuesday

postback using javascript

         

<asp:UpdatePanel runat="server">
<ContentTemplate>
<div>
<asp:Literal runat="server" ID="ChildWindowResult" />
</div>
<hr />
<input type="button" value="Open Dialog" onclick="window.open('MyDialog.aspx', 'Dialog');" />
<asp:Button ID="HiddenButtonForChildPostback" runat="server"
OnClick="OnChildPostbackOccured" style="display: none;" />
<asp:HiddenField runat="server" ID="PopupWindowResult"/>
</ContentTemplate>
</asp:UpdatePanel>

The MyDialog page:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
function postData() {
var resultField = $("input[type='hidden'][id$='PopupWindowResult']", window.opener.document);
var parentPosDataButton = $("[id$='HiddenButtonForChildPostback']", window.opener.document);

resultField.val($("#<%= SomeValueHiddenField.ClientID %>").val());
parentPosDataButton.click();
}
</script>

<asp:TextBox runat="server" ID="SomeValueHiddenField" />
<asp:Button runat="server" OnClick="PostData" Text="Click Me" />



in code behind class:

protected void PostData(object sender, EventArgs e)
{
SomeValueHiddenField.Value = DateTime.Now.ToString();
ClientScript.RegisterStartupScript(this.GetType(), "PostData", "postData();", true);
}

postback example in asp.net


// On the button control, inside the event
// Check if indicating to continue or intercept, open the popup,
// and define the callback with the "sender" (the button itself)
if (!(bool)Session["IsAllowed"])
{
// Open popup to enter the password, and define a callback
Page.RegisterStartupScript(
"openwindow", "<script>window.open('http://myurl.aspx'" +
",'title');" +
"myPage_Callback = function(){" +
Page.GetPostBackEventReference((System.Web.UI.Control)sender,"") +
"};" +
"</script>"
);

return;
}
// On popup window, on event of the submit button
// Calls the __doPostBack callback js function on the opener and closes the popup.
Session["IsAllowed"] = true;
Page.RegisterStartupScript(
"closewindow", "<script>window.opener.window.myPage_Callback();" +
"window.close();" +
"</script>"
);


Friday

scrum google spreadsheet

Google Docs SCRUM templates

  1. A simple example (Product
    Backlog, Sprint Backlog and Burndown
    Charts) provided by Pyxis.

  2. A sample sheet (Product Backlog, Sprint Backlog, Burndown Charts, Impediments backlog) provided by Openbravo - and some more sheets at the end of this page.


  3. A basic Scrum template including a product backlog and sprint backlogs.

  4. A Scrum template inspired from Bas Vodde (see this blog post).

  5. A very simple starting-point for a scrum product backlog.




Thursday

Total commander and Winmerge

In order to use Winmerge as comparision tool add following line to wincmd.ini:
CompareTool="d:\Program Files\WinMerge\WinMerge.exe"

html5 mobile framework

Titanium -Appcelerator Titanium is a free and open source framework to develop easily native mobile and desktop apps with web technologies. It provides developers with over 100 customizable UI controls for native tables, views, tabs, alerts, dialogs, buttons, support for geolocation, social networks and multimedia.


Sencha Touch -Sencha Touch is a HTML5 mobile app framework that allows you to develop web apps that look and feel native on Apple iOS and Google Android touchscreen devices. It supports HTML5, CSS3, and Javascript for the highest level of power, flexibility, and optimization in developing your web applications.


JQTouch - (JQtouch has now moved on to Sencha Touch )- A jQuery plugin for mobile web development on the iPhone, Android, iPod Touch, and other forward-thinking devices.


Sproutcore Touch -Sproutcore Touch is the touch edition of the Sproutcore framework for developing HTML 5 web applications that includes complete support for touch events and hardware acceleration on the iPad and iPhone.


PhoneGap -PhoneGap is another interesting open source framework for building cross-platform mobile apps with web standars (HTML5, CSS3, JavaScript). This framework supports geolocation, vibration, accelerometer, camera, orientation change, magnetometer and other interesting features for iPhone, Android, Blackberry, Symbian and Palm.


Rhodes - Rhodes is another excellent open source framework to rapidly build native apps for all major smartphone operating systems (iOS, Windows Mobile, Symbian and Android). It supports GPS geolocation, PIM contact reading and writing, and camera image capture.


iUI -iUI is a framework consisting of a JavaScript library, CSS, and images for developing advanced mobile webapps for iPhone and comparable/compatible devices.


iWebkit -iWebkit 5 is the new version of the popular ultralight framework for easily creating iPhone and iPod touch applications. The current release has new improved features and is really easy to understand in order to develop in just a few minutes your own web apps.


XUI -XUI is another javascript framework for building simple web applications for mobile devices. No much documentation available but it worth to try it for not complex apps.


jQPad -jQPad is an iPad web development framework jQuery based with some features for quickly developing simple iPad applications.


jQuery Mobile -Closing I want to suggest you jQuery Mobile, the touch-optimized version of the popular jQuery framework for smartphones and tablets which will allow you to design a single highly branded and customized web application that will work on all popular smartphone and tablet platforms. The framework will support iOs, Android, Windows Phone, BlackBerry, Symbian, Palm webOS and other devices. The framework is under development and will be available in late 2010.


foneFrame - foneFrame Mobile Web Framework HTML5 CSS3 Mobile Template




preventing double form submission

Add this code , when btnSubmit form submittion button

btnSubmit.Attributes.Add("onclick", "this.disabled=true;");

Monday

dotnetnuke user control inside user control problem with resx file

to solve this problem create base class:

public partial class BaseUserControl : DotNetNuke.Entities.Modules.PortalModuleBase
{
// basically this will fix the localization issue
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string FileName = System.IO.Path.GetFileNameWithoutExtension(this.AppRelativeVirtualPath);
if (this.ID != null)
//this will fix it when its placed as a ChildUserControl
this.LocalResourceFile = this.LocalResourceFile.Replace(this.ID, FileName);
else
// this will fix it when its dynamically loaded using LoadControl method
this.LocalResourceFile = this.LocalResourceFile + FileName + ".ascx.resx";
}
}

Friday

learn mobile development online

Stanford University has released its mobile app development course online for free.

The university notes that the two Stanford prerequisite courses, Programming Methodology [Link] and Programming Abstractions [Link], are also available on iTunes U.

Wednesday

poznavatelno

шаблон сайта, проданный 2.5k раз за год, принесший $50k создателю Познавательно - вот этот (http://bit.ly/rttpQP) шаблон сайта принес авторам за год 50 килобаксов (при цене $20).
Здорово, что дизайнеры могут зарабатывать так же, как и шароварщики - ничего не делая.

Thursday

online lesson videos from stanford


Artificial intelligence (http://ai-class.org).

Databases (http://db-class.org)

Machine Learning (http://ml-class.org).




Monday

linq concatenate rows

we can use Aggregate methods to concatenate fields in rows as follow:

var profiles = (from b in invoiceContext.bills
join p in invoiceContext.PaymentProfiles on 1 equals 1
where b.ProfileID == p.Id || b.ProfileType == p.Id
select p.Name).ToList();

if (profiles.Count() > 0)
{
BillingMethodLabel.Text = profiles.Aggregate((current, next) => current + ", " + next);
}


Friday

hgignore visual studio example


# use glob syntax.
syntax: glob

# c-sharp
/bin
/obj
*.user
*.suo
_ReSharper.*
*.sln.cache

bin/**
bin/Debug/**
obj/*

linq join on multiple fields by OR sample

Linq doesn't allow to do on t1.field1=t2.field1 or t1.field2=t2.field2
therefor it can be done by using OR in where statement:
     
var profiles = (from b in invoiceContext.bills
join p in invoiceContext.PaymentProfiles on 1 equals 1
where b.ProfileID == p.Id || b.ProfileType == p.Id
select p.Name).ToList();

Wednesday

resharper templates


To add new user-template in resharper from top menu in visual studio click on Resharper / Live templates select File Templates tab.
Find "User templates" and click on new template in toolbar .
Below is sample of command template:
Namespace variable will be "Default namespace for the current file".
Class variable will be "Current file name without extension".


       
namespace $NAMESPACE$
{
/// <summary>
/// $CLASS$ Linq Command
// </summary>
public class $CLASS$ : BaseLinqCommand, ILinqCommand
{
public $CLASS$() {
//constructor add your incoming params here
}

public bool CanExecute(Scope scope)
{
//add aditional validation here
return base.CanExecute(scope);
}

public void Execute(Scope scope)
{
//oly: main execution code goes here
}

}
}

Monday

testing svc web service

First you have to create test project in visual studio and add service reference, than you will be able to create test like this:
      
[Test]
public void BusinessWebserviceServiceTest01()
{
BusinessWebservice.ServiceClient client= new ServiceClient();
Debug.Write(client.getOpenInvoicesCount(1006469, 1, 1292071, "0"));
}

Thursday

isnumeric c#

Following function works like analog to vb isNumeric function
and checks that every character entered into myTextField is digit.

if (myTextField.Text.All(Char.IsDigit)){
// is numeric
}else{
// is not numeric
}

Wednesday

resizable div in jquery-ui with error label in asp.net

1.add links to jquery and css files.

<link type="text/css" href="../themes/start/jquery.ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery-1.4.2.min.js "></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.2.custom.min.js"></script>


2. add in document initialisation

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

3.adding div in body below :

<div class='resizable' style='height:20px;overflow-x:hidden;overflow-y:hidden;width:100%'>
<asp:Label ID="ErrorLabel" runat='server' ForeColor=Red Font-Bold=true/>
</div>

Friday

software mistakes


  1. Don't bother with market research, because you just know lots of people are itching to buy your new product.

  2. Only release the product once it is perfect. However long that takes.

  3. Go into a market with very strong competition and compete with them head-on, because you only need a measly 1% of this market to get rich.

  4. Go into a market with no competition. How hard can creating a new market and educating all the potential customers be?

  5. Only think about marketing once the code is nearly complete.

  6. Write software for people who can't or won't buy software (e.g. 10 year olds, prisoners, Linux fanatics, people in developing countries, developers).

  7. Don' worry about marketing, because good software sells itself.

  8. Concentrate on the technology and impressing other developers.

  9. Don't listen to what your customers say, because you know best.

  10. Don't worry about usability. It took you thousands of hours to write the software. Surely the customer can spend an hour or two learning to use it.

  11. Embrace bleeding-edge technology.

  12. Don't worry about backups, because modern harddisks are very reliable.

  13. Don't even try. Just give your software away for free.



Saturday

My 7 principles to design the architecture for a software project

My 7 principles to design the architecture for a software project.

Making Good Software

Software architecture is quite a grey area. It involves taking decisions that you are not likely to revisit in the future. These decisions usually involve frameworks, programming languages, application servers, databases, e.t.c.


Software architecture is about coming up with the foundation from where developers are going to build up the application. This also includes: development environments: (source control, building tools, IDEs…), QA environments, Continuous integration environments, etc.


Bad architectural decisions can make the development of your project a complete failure, and are the most difficult decisions to revert.


Good architecture, in the other hand, for most projects, doesn’t really bring any advantage, it only allows for its normal development. Good architecture usually remains hidden under normal circumstances.



When designing the architecture, is essential to avoid bad decisions that are going to tax your development in the future. What follows is a list of principles to help you come up with safe and scalable architectures.


1.- Start with the minimal necessary architecture.


Avoid unnecessary complexity like unnecessary new technologies or frameworks.


Any architectural element needs to have a very good reason to be used in the project. If the benefits or necessity of an architectural element can’t be proved, then that architectural element should be removed.


2.- Consider the specifics of your project: Constraints and risks.


Defining the architecture is something that has to be adapted to the constraints and risks of your specific project.


You shouldn’t aim for the same kind of architecture if it is a start-up or a project for a multi-national company. You should also consider the expertise of your team, if they are very experienced in a particular programming language/framework… you should probably use it even if it is not the one you prefer.


Risk areas, like a requirement to have some service with a high availability, are going to require additional considerations in the architecture that you need to keep in mind.


Constraints and risks are the element that are going to move you away from your comfort zone, but they need to be looked at, to make sure that if necessary, they get addressed from the architecture.



3.- Grow as you need.


Delay any architectural element as much as you can, especially if they are complex.


Sometimes requirements seems to call for complex integrations/frameworks… like rules frameworks, ESBs… for these cases, I find it better to ignore them at the beginning and try to complete the first end-to-end scenario as soon as possible. When this first scenario is completed, then grow from there, one step at a time, adding new functionality as requested by the user. This way, it will become obvious if that architectural element is really necessary, and if it is, it will also be obvious how you should integrate it with the rest of the architectural elements in your project.


4.- Deliver continuously.


Continuous delivery is the vehicle to allow you to refine your architecture as you go.


Continuous delivery is based in four principles:


Deliver soon: The purpose of delivering soon is to shorten the feedback cycles with the customer, allowing for changes in the requirements if necessary.


Deliver many times: Delivering many times guarantees that the feedback cycle is smooth.


Bug free: The code must be clean of critical bugs.



Production ready: It should be deployable at any time.


 5.- Require a customer.


Having someone acting as a customer, making decisions about priorities and signing off releases is critical for the good development of your project.


Failure to have someone representing correctly the role of the customer causes misdirection in the development and consequently causes that the final product developed won’t meet expectations.


6.- Avoid waste.


Architecture can lead to an excess production of artefacts, inexperienced architects may pretend to foresee the entire architecture of the application and have it specified in paper.


This is especially true in companies following waterfall like processes, and sometimes it cannot be avoid, forcing the architects to produce such and such document/diagram.


Excessive initial architecture/design, aka Big design upfront (BDUF), is not only bad because is wasteful, its main risk is to let the development team believe that they cannot deviate from the original specifications, making it very difficult to be adaptive to future changes.


7.- Maximise feedback and transparency



Feedback and transparency guarantees no surprises for the customer, which in turn helps building a more trustworthy and productive relationship.


Maximising the feedback and transparency are one of the ultimate goals of the development process for any project, this allows for early and informed reaction when change is necessary, whether something is going wrong, or whether the customer wants to introduce a change in the specifications.

Friday

Cache Attibute

  
using System;
using System.Reflection;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using PostSharp.Aspects;

namespace Business.Shared.Attributes
{
[Serializable]
public sealed class CacheAttribute : OnMethodBoundaryAspect
{
// This field will be set by CompileTimeInitialize and serialized at build time,
// then deserialized at runtime.
private string _methodName;

// Method executed at build time.
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
_methodName = method.DeclaringType.FullName + "." + method.Name;
}

private string GetCacheKey(object instance, Arguments arguments)
{
// If we have no argument, return just the method name so we don't uselessly allocate memory.
if (instance == null && arguments.Count == 0)
return _methodName;

// Add all arguments to the cache key. Note that generic arguments are not part of the cache
// key, so method calls that differ only by generic arguments will have conflicting cache keys.
var stringBuilder = new StringBuilder(_methodName);
stringBuilder.Append('(');
if (instance != null)
{
stringBuilder.Append(instance);
stringBuilder.Append("; ");
}

for (int i = 0; i < arguments.Count; i++)
{
stringBuilder.Append(arguments.GetArgument(i) ?? "null");
stringBuilder.Append(", ");
}

return stringBuilder.ToString();
}

// This method is executed before the execution of target methods of this aspect.
public override void OnEntry(MethodExecutionArgs args)
{
// Compute the cache key.
var cacheKey = GetCacheKey(args.Instance, args.Arguments);

// Fetch the value from the cache.
var cacheMgr = CacheFactory.GetCacheManager();
var value = cacheMgr.GetData(cacheKey);

if (value != null)
{
// The value was found in cache. Don't execute the method. Return immediately.
args.ReturnValue = value;
args.FlowBehavior = FlowBehavior.Return;
}
else
{
// The value was NOT found in cache. Continue with method execution, but store
// the cache key so that we don't have to compute it in OnSuccess.
args.MethodExecutionTag = cacheKey;
}
}

// This method is executed upon successful completion of target methods of this aspect.
public override void OnSuccess(MethodExecutionArgs args)
{
var cacheKey = (string)args.MethodExecutionTag;

var cacheMgr = CacheFactory.GetCacheManager();
cacheMgr.Add(cacheKey, args.ReturnValue);
}
}
}

Monday

primer

ne moe :), vzjato otsjuda , prosto horoshij primer kak ljudi kalbasjat...est k 4emu stremico :)

4 дня висим в Top Paid iPhone Apps USA на третьем месте. Позиции в Top Grossing Apps (топ приложений по прибыльности) неопределенные. Были и на 22 месте. Были и на 15. Похоже, что в самые ближайшие дни из топов не уйдем, что, конечно, радует.


Удивляет некоторое количество камментов к игре, мол, это все поддельные review, типа «And the most annoying thing for me is an insane amount of fake reviews, I assume from the developer’s PR firm«. Подобное прислали и в блог: «Так это же накрученный рейтинг ведь, разве нет?» Жаль, что при зарождении новых жизней Где-то Там, мозги достаются не всем.


Однако, чего бы и не рассказать «секрет» такого взлета.


//*** вырезано цензурой ***\\


Итак, игра сейчас (еще раз повторю, не распространяйте эти результаты на птиц и катзеропы, на деле, если игра имеет больше топов, результаты ВЫШЕ), находясь в топе 5 дает от 9 до 12 тысяч загрузок в сутки. Вместе с продажами внутри игры, нам с издателем получается примерно в среднем 10 тысяч долларов в сутки. Всего со дня запуска продажи касок, нам с издателем она заработала 105 тысяч долларов. С момента попадания в топ-25 (14 августа) – 66 тысяч. Приведу еще одну цифру: с момента запуска продажи касок (со 2 августа по 20-е) игра заработала в общей сложности (нам с издателем и Эпплу, а именно эти цифры приводят другие издатели, когда хвастают доходами): 150 тысяч долларов. После того, как полная версия стала платной, продажи касок не упали, остались все на том же уровне: $2000-$2200 долларов в сутки нам с издателем. Со момента запуска каски принесли примерно 37 тысяч долларов (кстати, каким-то образом находятся люди, которые умудряются ВОЗВРАЩАТЬ деньги за каски тем же способом, что и возвращают деньги за «непонравившуюся» игру, как они это делают, мне нищебродскую душу не понять).



Вот так обстоят дела.


Сейчас «Too Addictive!« медленно спускается вниз, но третье место позволяет платной версии игры держаться на своем месте – топ делает свое дело, игра продает сама себя. К тому же, нужно отдать должное самой игре – она имеет очень хорошие отзывы и рейтинги (5 полных звезд), что также держит ее почти на вершине Олимпа.


Будет ли первое место? Скорее всего – нет, первые два, по моим расчетам, делают больше 30 тысяч загрузок в сутки каждая, сложно такого добиться. Оно и не нужно, сейчас неплохо бы остальным странам подтянуть игру в свои топы, тогда денег будет как минимум раза в два больше.


Работаем дальше, всем спасибо за поддержку!





floomby.ru

Да, нужно на базе имеющегося функционала выпустить доп фичу, с которой и монетизировать проект.
А вот то, как правильно выбрать эту фичу так, чтобы минимальными усилиями выжать максимальную пенку не навредив имеющемуся — это уже главный вопрос, требующий детального исследования темы.

Запартнёрится можно. Только не совсем понимаю, что вы имеете под этим ввиду. Впринципе, если есть желание развивать проект, то готов даже вложиться своими деньгами и знаниями.

Вот сейчас вы "спалили" тему. Вполне возможно, что конкуренты появятся очень быстро. Если вы начнёте монетизировать проект, то к моменту появления конкурентов надо быть готовым, ибо на монетизации это обязательно скажется. Вам необходимо так развивать проект, чтобы ценность вашего проекта в глазах пользователя была максимальна вне зависимости от того, сколько конкурентов повторят ваши фичи. Ваша фора в виде времени должна быть конвертирована в сетевой эффект. Чем скорее это будет сделано, тем больше будет прибыль в долгосрочной перспективе.
Однако, есть серьёзный риск здесь со стороны производителей ОС, если они встроят похожий функционал в систему. Это надо понимать.



Гражданин путает. Бывает разный траффик, хороший и плохой. Нагнать 15к уников задача несложная, вопрос только каких. У тебя аудитория со всего рунета, судя по галерее обычное интернетное хомячье, по географии и интересам не сегментированное. Такой траффик продается большими пачками и очереди на него не стоит. С этим можно побарахтаться но 20килобаксов тут нет даже если этот проект продать на корню.

По рекламе.

1. Для начала попробуй заменить AdSense на Бегун. Общий принцип, русский траффик лучше всего берут русские. Гугл у тебя даже дефолтные баннеры показывает, это никуда не годится.
2. Подключись к нормальной рекламной сети, лучше всего игровой. Бывают те, что платят за leads, а при твоем хомяковом траффике это уже интересно.
3. Попытайся запартнерится с игроделами. Они умеют извлекать из траффика деньги, а у тебя как раз есть траффик.
4. Сегментируй аудиторию. Реклама по сегментированной аудитории стоит дороже. Для этого можно, например, ввести теги.
5. Повышай лояльность пользователей. Сейчас у тебя в среднем два просмотра с пользователя. Прикрути комментарии и оценки, чтобы поднять хотя бы до 10.
6. Сейчас у тебя нет контекста, к которому может цепляться контекстная реклама. Это значит что контекст нужно либо добавить, либо отказаться от контекстной рекламы.
7. Займись SEO, там еще есть потенциал, тем более у тебя есть много потенциальных ссылок с внешних ресурсов.

Thursday

free to play

Аналитическая компания Flurry продолжает открывать для себя (и прочей изумленной публики) чудесный мир монетизации фритуплейных игр. Их новый инсайт, полученный после изучения 57 миллионов внутриигровых покупок на платформах iOS и Android, таков: основные деньги пользователи тратят на расходники, то есть такие предметы, которые тратятся и исчезают в процессе использования – это, например, наши любимые удобрения или какие-нибудь аптечки. На такие товары приходится 65% всех покупок. Еще 30% – это основательные предметы, типа например особо красивых домиков в Paradise Island, которые остаются с юзером надолго и дают ощущение прогресса. А меньше всего трат – 2% – приходится на всевозможную персонализацию, не влияющую на геймплей (то, на чем пытались зарабатывать социалки первой волны).



Напомним, что в одном из прошлых своих исследований компания Flurry выяснила, что средний платеж в бесплатных играх составляет 14 долларов, а до этого первой объявила недоверчивым мобильщикам, что фритуплей уже плотно поселился в их домах и перегнал по заработку традиционную модель оплаты премиум-игр.

Monday

sqlite merge table


C:\Development\Main\Common\SQLite>sqlite3 c:\test\a.db3

SQLite version 3.2.7

Enter ".help" for instructions

sqlite> attach 'c:\test\b.db3' as toMerge;

sqlite> insert into AuditRecords select * from toMerge.AuditRecords;

sqlite> detach database toMerge;

Sunday

Свожу в один пост инфу по продажам касок за три дня:


——-


4 августа скачали 190 тысяч раз.


- для айфона, 5 касок за $0.99 взяли 1108 раз,



- для айфона, 15 касок за $1.99 взяли 514 раз,


- для айпада, 5 касок за $0.99 взяли 35 раз,


- для айпада, 15 касок за $1.99 взяли 40 раз.


Итого, наши с издателем деньги – чуть меньше 1600 долларов.


——-


5 августа – 173 тысячи.



- для айфона, 5 касок за $0.99 взяли 1234 раз,


- для айфона, 15 касок за $1.99 взяли 561 раз,


- для айпада, 5 касок за $0.99 взяли 29 раз,


- для айпада, 15 касок за $1.99 взяли 47 раз.


Итого, наши с издателем деньги – чуть больше 1700 долларов.


——-



6 августа – 170 тысяч.


- для айфона, 5 касок за $0.99 взяли 1363 раз,


- для айфона, 15 касок за $1.99 взяли 651 раз,


- для айпада, 5 касок за $0.99 взяли 30 раз,


- для айпада, 15 касок за $1.99 взяли 30 раз.


Итого, наши с издателем деньги – чуть меньше 2000 долларов.



——-


Итого, с начала продаж (2 августа) по вчера (6 августа) заработано (с издательскими деньгами) почти 7 тысяч долларов.


При этом игра добралась до 333 места в Top Grossing в США.


Хорошо живут верхнии позиции этого топа. По слухам верхние позиции делают от 30 тысяч американских рублей в сутки играючи.


Так что есть куда стремиться.


Чего и всем желаю.

Friday

Pomodoro technique timer - this one with the RPG game

Pomodorium is a new pomodoro technique timer with embedded RPG game :)

In this game for completing pomodoro you are receiving 25-gold,

and you can spend it on buying weapons and armors and play from level 0 to 40 , travel through the map and free cities from monsters.


Software requires Adobe AIR.

here is link on Pomodorium website

Wednesday

linq subquery for in

for example following sql

select * from AccountTransactions a
where
a.TransactionId =19687 OR
a.TransactionId in (select ChildId from AccountTransactionRelations where InvoiceId=19687)


will have this equivalent in linq:

var records = from t in odc.AccountTransactions
join r in odc.AccountTransactionRelations on t.TransactionId equals r.InvoiceId into rel
where t.TransactionId == transactionId || rel.Select(o => o.ChildId).Contains(transactionId)
select t;



Friday

application monetization

Banners and ads :

Theres CPM banners, which pay per ad displayed:
Adbrite: www.adbrite.com
AdSense www.Google.com/AdSense < br>
Theres CPC banners, which pay per ad clicked:
Zohark: www.f
acebook.com/applications/Zohark_Ads/18584639088

Adchap: http://adchap.com/

Theres CPA
systems, which pay per action,
like surveys/offers:
Peanutlabs: www.peanutlabs.com
MillnicMedia: www.millnicmedia.com
$uperRewa
rds: http://www.facebook.com/apps/applicatio … 6131192103

Theres PPP
system, which pay per play of
audio advertisements:
Netaudioads: http://www.selling
ppp.com/a.cgi?ppp=1207763387


Some are easy to apply for..
like Google
AdSense Others are very difficult to apply for.. like peanut labs

Virtual currency:


make ubuntu business casual

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