Thursday

progstudios webcontrols dll

I had problem with legacy application, it has an old progstudios Combobox and it wasn't working propely.So in order to setup this it's required :

1.drop webctrl_client folder to your server root, it's requiresting it like /webctrl_client/progstudios/1_2/

2.Add add ProgStudios.HttpHandlers to IIS http handlers.

For some reason IIS under Win7 ignore this line from web.config

<httpHandlers>
<add verb="*" path="client_script.aspx" type="ProgStudios.HttpHandlers.ClientScriptHandler, ProgStudios.WebControls" />
</httpHandlers>

so I added it manually :

Wednesday

Законы Мерфи для программистов.

  • Любая работающая программа уже устарела.
  • Любая программа обходится дороже и требует больше времени, чем казалось в начале.
  • Если программа полезна, ее обязательно переделывают.
  • Если программа бесполезна, ее тщательно документируют.
  • Любая программа в конце концов занимает всю доступную память.   
  • Cложность программы обычно растет до тех пор, пока не превысит способности программиста, призванного ее поддерживать.
  • Если утилиты, испытанные при инсталяции, работают идеально, все остальные функции будут работать не верно.
  • Если входной редактор спроектирован так, чтобы исключить неверный ввод, найдется изобретательный идиот, который изыщет метод ввести разрушительную команду.
  • Невежество — единственный язык, которым владеют все программисты.
  • Увеличение численности программистов, работающих над проектом, увеличивает сроки его выполнения.
  • Небрежно спланированный проект требует в 3 раза больше времени, чем ожидалось, а тщательно спланированный — только в 2.
  • В программе всегда есть еще одна ошибка.
  • Невозможно создать программу с полной защитой от дураков, ибо дураки крайне изобретательны.
  • Если все идет хорошо, вас вскоре ждут серьезные осложнения.
  • Если дела идут хуже некуда, вскоре выяснится, что это не так.
  • Если кажется, что все в порядке, вы просто что-то просмотрели.   
  • Вы всегда найдете еще одну ошибку, если еще раз загляните в свою программу.
  • Терминал работает лучше, если его включить в сеть.
  • Если все не работает, читайте документацию.
  • Если вам не понятно какое-то слово в технической документации, игнорируйте его, смысл от этого не пострадает.
  • Не важно, много ли вы работаете, вы все равно работаете недостаточно.
  • То, чего вы не делаете, всегда важнее того, что вы делаете.
  • Всегда оставляйте место для объяснения того, почему ваша программа работает не так как планировалось.
  • Не существует ничего невозможного для человека, который не собирается ничего делать сам.
  • Если бы строители сооружали здания также, как программисты пишут свои программы, первый же дятел разрушил бы человеческую цивилизацию.
  • Программисты действуют рационально, лишь тогда, когда другие способы исчерпаны.
  • Friday

    sql convert date format

    CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

    --T-sql convert datetime function example usage code to format date mm-dd-yyyy

    SELECT CONVERT(nvarchar(30),getdate(),110)

    Sunday

    fibonacci sequence


    0  
    1  
    1  
    2  
    3  
    5  
    8  
    13  
    21  
    34  
    55  
    89  
    144  
    233  
    377  
    610  
    987  
    1597  
    2584  
    4181  
    6765  
    10946  
    17711  
    28657  
    46368  
    75025  
    121393  
    196418  
    317811  
    514229  
    832040  
    1346269  
    2178309  
    3524578  
    5702887  
    9227465  
    14930352  
    24157817  
    39088169  
    63245986  
    102334155  
    165580141  
    267914296  
    433494437  
    701408733  
    1134903170  
    1836311903  
    2971215073  
    4807526976  
    7778742049  

    golden ratio in gui version









































    basewidthheigh
    00.00.0
    500309.0186.0
    1000618.0372.0
    1500927.0558.0
    20001236.0744.0
    25001545.0930.0
    30001854.01116.0
    35002163.01302.0
    40002472.01488.0
    45002781.01674.0
    50003090.01860.0
    55003399.02046.0
    60003708.02232.0
    65004017.02418.0
    70004326.02604.0
    75004635.02790.0
    80004944.02976.0
    85005253.03162.0
    90005562.03348.0
    95005871.03534.0
    100006180.03720.0
    105006489.03906.0
    110006798.04092.0
    115007107.04278.0
    120007416.04464.0
    125007725.04650.0
    130008034.04836.0
    135008343.05022.0
    140008652.05208.0
    145008961.05394.0
    150009270.05580.0
    155009579.05766.0
    160009888.05952.0
    1650010197.06138.0
    1700010506.06324.0
    1750010815.06510.0

    Friday

    robokill stats

    Оргазационные моменты сьели кучу времени - делали втроем(code,art,designer) все РедШторм игры. Первую часть, как я уже говорил - сделали за 20 дней, и это был почти-клон Робокилла. Над остальными работали кое-как кое-когда - от 2 до 4 месяцев в сумме. Сегодня выпустили 4ую часть - 'Red Storm Defense', которая наконец-то не клон ничего! =) своя, собственная игра, в моем любимом сеттинге - Геройском Товер Дефенсе.




    а теперь самое вкусное - факты и статистика:

    9m+ gameplays.


    Реклама принесла 5k$+, Микротранзакции - 4k$+, Лицензии- 9k$, iPhone - 1k$, итого около 20k$. Самый играемый домен - ВКОНТАКТЕ! на нем даже заработалось несколько тысяч голосов.



    Немного о Микротранзакциях- большинство продаж было на NinjaKiwi, Mochiads, Elite-Games.Net и это примерно 50% от всех продаж. География - 55% из US+Germany+UK+Canada. Если кто в танке - это English+French+German языковые группы.



    Об iPhone - все тяжко здесь - особенно с первой игрой, не хитовой. iPad версия ждет аппрува, Дефенс в разработке, кстати он выйдет с шейдерами=)

    Wednesday

    UnicodeDecodeError: 'ascii' codec can't decode byte in position

    possible solution will be to eliminate non-ascii characters, here is function in python

    import string
    def n(self,myStr):
    return filter(lambda x: x in string.printable, myStr)

    sqlite3.OperationalError: Could not decode to UTF-8 column

    to get rid of this error add following line after opening connection:


    db_connection = sqlite.connect('my.db')
    db_connection.text_factory = str


    more about connections objects

    Thursday

    The certificate for omega.contacts.msn.com could not be validated. The certificate chain presented is invalid.


    2010-11-24 Update: Please download latest version of Pidgin, that has this problem fixed , no additional steps required.


    Here are 3 ways to fix this error:
    sorted from easier to harder,solution #1 works in most cases .
    If it doesn't you can try solution #2 or solution #3 , this will fix problem for sure.

    solution #1(easiest, try it first )

    remove file :
    c:\Documents and Settings\[your-username]\Application Data\.purple\certificates\x509\tls_peers\contacts.msn.com

    In Win 7 the path is: C:\Users\[UserID]\AppData\Roaming\.purple\certificates\x509\tls_peers

    or for linux :
    ~.purple/certificates/x509/tls_peers/contacts.msn.com
    and Pidgin will load latest certificate.

    Update: it also can be fixed by deleting certificate from Pidgin menu Tools/Certificate.


    Solution #2: (if #1 is not working)

    a.Download this file,

    b. delete the .txt extension, so that you end up with omega.contacts.msn.com only,

    c. copy the file to your c:\Documents and Settings\[your-
    username]\Application Data\.purple\certificates\x509\tls_peers
    folder


    Solution #3: (similar to solution #2 but importing certificate directly from omega.contacts.msn.com)

    a. open https://omega.contacts.msn.com/

    b. On the URL bar, click on the security lock (usually just in front of the URL). Click on the certificate information.

    c. Go to the Detail tab and click the “Export” button. Save the file as “omega.contacts.msn.com” (without the quotes).




    d. Copy and paste this file to
    “/home/your-username/.purple/certificates/x509/tls_peers/omega.contacts.msn.com”. When prompted, select “Replace” to replace the existing file.That’s it. Open your Pidgin and the SSL certificate error will be gone.

    Friday

    The element has invalid child element. List of possible elements expected: .

    Error:The element 'Schedule' has invalid child element 'RecurrenceRule'. List of possible elements expected: 'Occurring'.

    To fix this XSD problem:
    Theory:

    XSD gives 3 indicators: <xs:all>, <xs:sequence>, and <xs:choice>.

    xs:all allows the specified child elements to appear (or not) in any order in the containing element... except they can only appear once.

    xs:sequence requires the specified child elements to appear in the order they are given

    and xs:choice requires that only one of the specified child elements appears, but it can appear any number of times.


    so I just changed tag from <xs:sequence> to <xs:all> and it fixed problem.

    orginal code

       
    <xs:element name="Requirement" minOccurs="0">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="Name" type="xs:string" minOccurs="0" />
    <xs:element name="Duration" type="xs:int" minOccurs="0" />
    <xs:element name="Occurring" type="xs:int" minOccurs="0" />
    </xs:sequence>
    </xs:complexType>
    </xs:element>


    changed code

       
    <xs:element name="Schedule" minOccurs="0">
    <xs:complexType>
    <xs:all>
    <xs:element name="Name" type="xs:string" minOccurs="0" />
    <xs:element name="Duration" type="xs:int" minOccurs="0" />
    <xs:element name="Occurring" type="xs:int" minOccurs="0" />
    </xs:all>
    </xs:complexType>
    </xs:element>

    Monday

    how to keep ssh tunnel alive

    To keep ssh session alive Create ssh_config file in your home folder with this line:
            
    ServerAliveInterval 5

    This will keep ssh alive and open.

    remote logoff user windows

    1.Use quser command to load list of sessions

      
    C:>quser
    USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
    johndoe ica-tcp#966 10 Active 7 7/31/2008 3:04 PM
    averagejoe ica-tcp#969 1 Active 9 7/31/2008 3:30 PM


    2.Logoff session you need:
      
    C:>logooff 2


    focus popup window

    it can be done by this line : if (window.focus) { newwindow.focus() }
    Here is an example:
      
    <script type="text/javascript">
    function OpenNote(noteid,t) {
    var w1 = 550;
    var h1 = 500;

    var left = window.screenLeft + (screen.width / 2) - w1; //
    var top = window.screenTop + (screen.height / 2) - h1; //

    var newwindow = window.open('TransactionsNotes.aspx?i=<%=AccountTransactionId%>&u=<%=UserId%>&n=' + noteid + "&t=" + t, '_note_', 'top=' + top + ',left=' + left + ',width=' + w1 + ',height=' + h1 + ',location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no');
    if (window.focus) { newwindow.focus() }
    }
    </script>


    Thursday

    Wednesday

    msbuild release configuration

    to build release from command line:
     msbuild  buildsrc\Test\Test.sln   /p:Configuration=Release 

    Wednesday

    C# bind dropdown to enum

    For example we have enumeration Enum1 and want to bind ddEnum1.
    here is how to do it in directly into html page , when GetEnum1 is function in codebehing , that will be getting SelectedValue for every record object (passign by parameter)
         
    <asp:TemplateField HeaderText="Type" ItemStyle-Width="5%" ItemStyle-Wrap=False HeaderStyle-HorizontalAlign=Center HeaderStyle-Wrap=False ItemStyle-HorizontalAlign=Center>
    <ItemTemplate>
    <asp:DropDownList id="typeDropDown" runat="server" Width='150'
    DataSource="<%# Enum.GetNames(typeof(myEnum1)) %>"
    SelectedValue='<%# GetEnum1(Container.DataItem) %>'
    OnInit="InitDropDown" />

    </ItemTemplate>
    </asp:TemplateField>


    here is how to do it in codebehind
           
    private void Page_Load(object sender, System.EventArgs e)
    {
    if(!IsPostBack)
    {
    ddEnum1.DataSource = Enum.GetNames(typeof(Enum1));
    ddEnum1.DataBind();
    }
    }

    private void ddEnum1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    Enum1 selectedEnum1 = (Enum1)Enum.Parse(ddEnum1.SelectedValue);
    }



    Monday

    This application has failed to start because vcl60.bpl was not found.


    Easiest way for C++ Builder 6.0:
    Project/Options:
    Compiler tab: Click 'Release'

    Packages tab:
    Un-check 'Bulid with runtime packages'

    Linker tab:
    Uncheck the first 3 items under 'Linking'

    more...

    Tuesday

    linq "in" exisits


    var itemQuery = from cartItems in db.SalesOrderDetails
    where cartItems.SalesOrderID == 75144
    select cartItems.ProductID;


    var myProducts = from p in db.Products
    where itemQuery.Contains(p.ProductID)
    select p;

    details

    mercurial source control visual studio

    HgSccPackage - Mercurial Source Control Plugin for Microsoft Visual Studio 2008/2010

    VisualHG - Mercurial Source Control Plugin for Microsoft Visual Studio 2005, 2008 and 2010

    more...

    Tuesday

    C# shuffle list


    public void Shuffle<T>(List<T> list)
    {
    Random rng = new Random();
    int n = list.Count;
    while (n > 1)
    {
    n--;
    int k = rng.Next(n + 1);
    T value = list[k];
    list[k] = list[n];
    list[n] = value;
    }
    }

    more...

    Manage Stored User Names and Passwords

    To manage stored user names and passwords, follow these steps:
  • Log on to the computer as the user whose account you want to change.
  • Click Start, and then click Control Panel.
  • In Control Panel, click User Accounts under Pick a category to open the User Accounts dialog box.
  • Open the Stored User Names and Passwords dialog box; to do so, use the appropriate method:
    • If you log on with a limited account:
      1. Under Related Tasks, click Manage my network passwords.
    • If you log on with an account with administrative privileges:
      1. Under or pick an account to change, click your user account to open the What do you want to change about your account? dialog box.
      2. Under Related Tasks, click the Manage my network passwords.


    A list of stored user names and passwords similar to the following example is displayed:


    more...
  • Friday

    ASP.NET Editable grid

    aspx page:
     
    <div style="overflow:auto;height:150px;border-width:1px;">
    <asp:DataGrid ID="ScheduledPaymentAdjustmentDataGrid" CssClass="TableWithGrayBorders" Runat="server"
    AutoGenerateColumns="False"
    Width="200" BorderStyle="None"
    HeaderStyle-CssClass="TableWithGrayBordersHeader" ShowFooter=true
    HeaderStyle-HorizontalAlign="Center" DataKeyField="sID"
    OnItemCommand="ItemsGrid_Command"
    >

    <Columns>
    <asp:TemplateColumn HeaderText="Profile" ItemStyle-Width="5%" ItemStyle-Wrap=False
    HeaderStyle-HorizontalAlign=Center HeaderStyle-Wrap=False ItemStyle-HorizontalAlign=Center>
    <ItemTemplate>
    <img src="../images/spacer.gif" width=2>
    <asp:DropDownList id="ProfileDropDown" runat="server" Width='150'
    DataSource="<%# GetProfiles() %>"
    DataValueField="id" DataTextField="name"
    SelectedValue='<%# GetProFileId(DataBinder.Eval(Container.DataItem, "sID")) %>'
    />
    <img src="../images/spacer.gif" width=2>
    </ItemTemplate>

    <FooterTemplate>

    <img src="../images/spacer.gif" width=2>
    <asp:DropDownList id="ProfileDropDown" runat="server" Width='150' BackColor="LightGreen"
    DataSource="<%# GetProfiles() %>"
    DataValueField="id" DataTextField="name"
    SelectedValue='<%# GetProFileId(DataBinder.Eval(Container.DataItem, "sID")) %>'
    />
    <img src="../images/spacer.gif" width=2>
    </FooterTemplate>
    </asp:TemplateColumn>


    <asp:TemplateColumn HeaderText="Amount" ItemStyle-Width="5%" ItemStyle-Wrap=False
    HeaderStyle-HorizontalAlign=Center HeaderStyle-Wrap=False ItemStyle-HorizontalAlign=Center>
    <ItemTemplate>
    <img src="../images/spacer.gif" width=2>
    <asp:TextBox ID="AmountTextBox" runat="server" Text='<%# string.Format("{0:0.00}",DataBinder.Eval(Container.DataItem, "dAmount")) %>' Width='70' MaxLength="8" />
    <img src="../images/spacer.gif" width=2>
    </ItemTemplate>

    <FooterTemplate>
    <img src="../images/spacer.gif" width=2>
    <asp:TextBox ID="AmountTextBox" runat="server" BackColor="LightGreen" Text='<%# string.Format("{0:0.00}",DataBinder.Eval(Container.DataItem, "dAmount")) %>' Width='70' MaxLength="8" />
    <img src="../images/spacer.gif" width=2>
    </FooterTemplate>

    </asp:TemplateColumn>


    <asp:TemplateColumn HeaderText="" ItemStyle-Width="1%" ItemStyle-Wrap=False
    HeaderStyle-HorizontalAlign=Center HeaderStyle-Wrap=False ItemStyle-HorizontalAlign=Center>
    <ItemTemplate>

    <asp:ImageButton ID="ImageButton1" Runat="server" CommandName="Delete" ImageUrl ='../images/delete_icon.gif' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>' />

    </ItemTemplate>

    <FooterTemplate>
    <asp:ImageButton ID="ImageButton2" Runat="server" ImageUrl='../images/bullet_add.png' CommandName="new" />
    </FooterTemplate>

    </asp:TemplateColumn>
    </Columns>

    </asp:DataGrid>



    Code behind:
      
    public void SaveScheduledPaymentAdjustmentDataGridChanges()
    {
    List<InvoiceDetailsRowView> lst = ((List<InvoiceDetailsRowView>)ScheduledPaymentAdjustmentDataGridSource);
    Hashtable H = new Hashtable(lst.Count);

    bool changed = false;
    foreach (InvoiceDetailsRowView i in lst)
    {
    H.Add(i.sID,i);

    }


    foreach (DataGridItem dataGridItem in ScheduledPaymentAdjustmentDataGrid.Items)
    {
    string key =(string) ScheduledPaymentAdjustmentDataGrid.DataKeys[dataGridItem.ItemIndex];
    UpdateInvoiceDetailsRowViewWithCells((InvoiceDetailsRowView)H[key], dataGridItem.Cells);
    }

    ScheduledPaymentAdjustmentDataGridSource = lst;
    }



    public void UpdateInvoiceDetailsRowViewWithCells(InvoiceDetailsRowView i,TableCellCollection Cells )
    {
    TextBox date = (TextBox)Cells[2].FindControl("DateTextBox");
    TextBox Note = (TextBox)Cells[3].FindControl("NoteTextBox");
    TextBox amount = (TextBox)Cells[1].FindControl("AmountTextBox");
    DropDownList dd = (DropDownList)Cells[0].FindControl("ProfileDropDown");

    decimal am;
    assert.IsTrue(decimal.TryParse(amount.Text, out am), iam+" " +amount.Text);
    assert.IsTrue(am > 0, iam + " " + amount.Text);
    i.NoteText = Note.Text;
    i.dAmount = am;
    i.TXNDate = date.Text;
    i.ProfileID = int.Parse(dd.SelectedValue);

    }



    public void ItemsGrid_Command(Object sender, DataGridCommandEventArgs e)
    {

    RunSafe(Process_Command,new object[]{e});
    }

    public void Process_Command(params object[] p)
    {
    DataGridCommandEventArgs e =(DataGridCommandEventArgs) p[0];

    switch (e.CommandName)
    {
    case "Delete":
    SaveScheduledPaymentAdjustmentDataGridChanges();
    DeleteSP((string)ScheduledPaymentAdjustmentDataGrid.DataKeys[e.Item.ItemIndex]);
    break;

    case "new":
    SaveScheduledPaymentAdjustmentDataGridChanges();

    InvoiceDetailsRowView i= new InvoiceDetailsRowView();
    UpdateInvoiceDetailsRowViewWithCells(i, ((System.Web.UI.WebControls.TableRow) (e.Item)).Cells);
    i.status = EnumRecordStatus.added;
    i.sID = Guid.NewGuid().ToString();
    List<InvoiceDetailsRowView> lst = ((List<InvoiceDetailsRowView>)ScheduledPaymentAdjustmentDataGridSource);
    lst.Add(i);
    ScheduledPaymentAdjustmentDataGridSource = lst;
    ScheduledPaymentAdjustmentDataGridBind();
    break;
    }
    GetTotalInBills();
    }


    more...

    Wednesday

    sql:select one row on join

            

    SELECT *
    FROM AccountTransactions AS inv
    INNER JOIN [Accounts basic] a2 ON inv.AccountId = a2.ID
    JOIN ( SELECT *
    FROM ( SELECT *,
    ROW_NUMBER() OVER ( PARTITION BY AccountTransactionId ORDER BY ProcessDate ) AS RowId
    FROM dbo.BillingTransactions
    ) Tmp
    WHERE RowId = 1
    ) b ON inv.TransactionId = b.AccountTransactionId

    more...

    Tuesday

    Select into another table update from another table

    insert into table from select.

    SELECT *
    INTO new_table_name [IN externaldatabase]
    FROM old_tablename


    Update from one table into another

    UPDATE
    Sales_Import
    SET
    AccountNumber = RAN.AccountNumber
    FROM
    Sales_Import SI
    INNER JOIN
    RetrieveAccountNumber RAN
    ON
    SI.LeadID = RAN.LeadID

    more...

    Friday

    asp.net dropdownlist selectedvalue


    <script language='javascript'>
    function getDropdownSelectedValue()
    {
    var e = document.getElementById("<%=MyDropDown.ClientID%>");
    var chain= e.options[e.selectedIndex].value;

    return chain;
    }
    </script>

    more...

    sql today

    to get today's records from table :

    select * from mytable where
    CONVERT(varchar(8), mydatefield, 112)=CONVERT(varchar(8), GETDATE(), 112)

    more...

    Monday

    outlook keyboard shortcuts







































    Switch to Inbox. CTRL+SHIFT+I
    Switch to Outbox. CTRL+SHIFT+O
    Choose the account from which to send a message. CTRL+TAB (with focus on the To box) and then TAB to the Accounts button
    Check names. CTRL+K
    Send. ALT+S
    Reply to a message. CTRL+R
    Reply all to a message. CTRL+SHIFT+R
    Forward a message. CTRL+F
    Mark a message as not junk. CTRL+ ALT+J
    Display blocked external content (in a message). CTRL+SHIFT+I
    Post to a folder. CTRL+ SHIFT+S
    Apply Normal style. CTRL+SHIFT+N
    Check for new messages. CTRL+M or F9
    Go to the previous message. UP ARROW
    Go to the next message. DOWN ARROW
    Create a new message (when in Mail). CTRL+N
    Create a new message (from any Outlook view). CTRL+SHIFT+M
    Open a received message. CTRL+O
    Open the Address Book. CTRL+SHIFT+B
    Convert an HTML or RTF message to plain text. CTRL+SHIFT+O
    Add a Quick Flag to an unopened message. INSERT
    Display the Flag for Follow Up dialog box. CTRL+SHIFT+G
    Mark as read. CTRL+Q
    Mark as unread. CTRL+U
    Show the menu to download pictures, change automatic download settings, or add a sender to the Safe Senders List. CTRL+SHIFT+W
    Find or replace. F4
    Find next. SHIFT+F4
    Send. CTRL+ENTER
    Print. CTRL+P
    Forward. CTRL+F
    Forward as attachment. CTRL+ALT+F
    Show the properties for the selected item. ALT+ENTER
    Mark for Download. CTRL+ALT+M
    Clear Mark for Download. CTRL+ALT+U
    Display Send/Receive progress. CTRL+B (when a Send/Receive is in progress)

    Tuesday

    sql connection string port

    If you want to connect to specific instance sometimes you have to specify port on which this instance running.
    Port is specifying by comma in connection string like this(1362):


    <add key="ConnectionString" value="server=sql-server1\qa,1362;database=db1;user id=u1;password=MyPassword;Trusted_Connection=no"/>

    Wednesday

    base page asp.net error handling

    basepage class:
     
    public delegate void UnSafeProcedure();
    public class BasePage : System.Web.UI.Page
    {
    public CAssertions assert= new CAssertions(); // my own assertor, produce AssertionException
    public void RunSafe(UnSafeProcedure s)
    {
    try
    {
    s();
    }
    catch (Exception e1)
    {
    if (e1.GetType().FullName == "AssertionException")
    {

    ShowMessage(e1.Message);

    }
    else
    {
    ShowMessage("Unhandled Exception");
    Debug.Write(e1.ToString());
    }
    }

    }
    // will be overwrited on actual page:
    public virtual void ShowMessage(string s) { Debug.Write(s); }
    }



    This is how actual page would look like:
      
    public partial class NewEft : BasePage {
    protected void SubmitButtonClick(object sender, EventArgs e) {
    RunSafe(Submit);
    }

    private void Submit() {

    AUtyl butyl = new AUtyl();
    assert.IsTrue(butyl.CheckRoutingNumberByRouting(txtRoutingNumber.Text), "Routing Number is invalid");
    }

    public override void ShowMessage (string s ) { lblMessage.Text = s; }
    }




    more...

    get source from github (windows)

    1.download and install git from
    googlecode

    Bash installation is good enough
    2.click on "Git Bash" on desktop, you can change folder
    with "cd" command like cd c:\temp\


    3.run git clone command to get sources:
    git clone [link from github]

    for example:
    git clone http://github.com/twilio/stashboard.git
    more...

    Tuesday

    c# parse string into enum


    public enum enmode
    {
    fee , scheduledpayment , adjustment , new1 , del , cancel , freeze
    }


    Propery convering string from Request["mode"] into enum:

    public enmode Mode
    {
    get { return (enmode) Enum.Parse(typeof (enmode), Request["m"].ToLower()); }
    }

    more...

    open popup in center of screen ( popup window javascript )

          
    function openPopUpInCenter() {
    var w1 = 400;
    var h1 = 450;
    var left = (screen.width / 2) - (w1 / 2);
    var top = (screen.height / 2) - (h1 / 2);
    window.open('AddPopup.aspx', 'add', 'top=' + top + ',left=' + left + ',width=' + w1 + ',height=' + h1 + ',location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no');
    }

    more...

    Thursday

    iis7 enable asp and asp.net


    You need to install ASP/ASP.NET through the Windows setup interface available from the Control Panel \ Programs applet:

    Tuesday

    close popup window c#


    string clientScript = @"<script language='javascript'>
    window.opener.location.reload();
    window.close();
    </script>";

    this.Page.ClientScript.RegisterStartupScript(clientScript.GetType(),"_reload",clientScript);


    more...

    opener reload javascript

    to close popup and reload main window:

    <script language='javascript'>
    window.opener.location.reload();
    window.close();
    </script>

    register javascript asp.net c#

         
    string clientScript = @"<script language='javascript'>
    alert("hello");
    </script>";


    this.Page.ClientScript.RegisterStartupScript(clientScript.GetType(),"hello",clientScript);

    remove space above table in Blogger.com

    when you publishing table on Blogger.com you will have a bunch of space above table.
    Because Blogger.com adds a
    <br />

    tag for each new line
    To avoid this, add this before HTML for your table:

    <style type="text/css">.nobrtable br { display: none }</style>
    <div class="nobrtable">

    credit card type based on number

    first numbers identifying card issuer:





























    IssuerIdentifierCard Number Length
    Diner's Club/Carte Blanche300xxx-305xxx,
    36xxxx, 38xxxx
    14
    American Express34xxxx, 37xxxx15
    VISA4xxxxx13, 16
    MasterCard51xxxx-55xxxx16
    Discover6011xx16















    first digitIssuer Category
    0ISO/TC 68 and other industry assignments
    1Airlines
    2Airlines and other industry assignments
    3Travel and entertainment
    4Banking and financial
    5Banking and financial
    6Merchandizing and banking
    7Petroleum
    8Telecommunications and other industry assignments
    9National assignment


    jquery iframe contents

    JQuery allows to open regular popup in nice dialog window by using iframe,
    here is code how to do that:
            
    <html>
    <head>
    <link rel="stylesheet" href="./styles/smoothness/jquery-ui-1.7.2.custom.css" type="text/css" media="screen" />
    <script type="text/javascript" src="./scripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="./scripts/jquery-ui-1.7.2.custom.min.js"></script>
    <script type="text/javascript">
    $(function() {
    $(' .diag').click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var horizontalPadding = 30;
    var verticalPadding = 30;
    $('<iframe id="externalSite" class="externalSite" src="' + this.href + '" />').dialog({
    title: ($this.attr('title')) ? $this.attr('title') : 'External Site',
    autoOpen: true,
    width: 800,
    height: 500,
    modal: true,
    resizable: true,
    autoResize: true,
    overlay: {
    opacity: 0.5,
    background: "black"
    }
    }).width(800 - horizontalPadding).height(500 - verticalPadding);
    });
    });
    </script>
    </head>
    <body>
    <ul>
    <li><a href="http://www.google.com" class ='diag' title="Google Dialog">Google</a></li>
    </ul>
    </body>
    </html>

    more...

    Sunday

    show hide javascript

    Here is sample how to show hide, control in asp.net/javascript
    let say we have ddBerechnung control and we have to hide controls when this dropdown has value 'identisch'

    server side will have this :
             
    protected override void OnPreRender(EventArgs e)
    {
    ddBerechnung.Attributes.Add("onChange", "ShowHidePercentField(this)");
    }


    and aspx will have this javascript:
             
    function ShowHidePercentField(cb){
    var selIdx = cb.selectedIndex;
    var newSel = cb.options[selIdx].text;
    var textBox=document.getElementById('<%=txtBerechnung.ClientID%>');
    var Runden= document.getElementById('<%=ddRunden.ClientID%>');
    var RundenSpan= document.getElementById('RundenSpan');


    if (trim(newSel)=='identisch'){ ///
    textBox.style.display="none";
    Runden.style.display="none";
    RundenSpan.style.display="none";

    }else{
    textBox.style.display="";
    Runden.style.display="";
    RundenSpan.style.display="";

    }

    }

    ///.... at the end of control
    <script language='javascript'>
    var elem=document.getElementById('<%=ddBerechnung.ClientID%>')
    ShowHidePercentField(elem);
    </script>

    more...

    tsql ceiling round not working for percent calculation because

    it's required to put additional zero after 100.0, check this out:

    select CEILING(50/100.0) , CEILING(50/100)
    ----
    1,0





    more...

    Saturday

    Controls.add c#/asp.net adding controls table/rows/labels

    ASPX page must have placeholder

    <asp:PlaceHolder ID="DynamicPlaceHolder" runat="server"></asp:PlaceHolder>


    codebehind

    protected override void OnPreRender(EventArgs e)
    {
    HtmlTable mainHtmlTable = new HtmlTable();
    HtmlTableRow helpTableRow = AddLabelRow(mainHtmlTableRow.Cells.Count, "Hello World",true);
    mainHtmlTable.Rows.Add(helpTableRow);
    DynamicPlaceHolder.Controls.Add(mainHtmlTable);
    }

    public HtmlTableRow AddLabelRow(int cellCount, string text,bool applySkin)
    {
    HtmlTableRow helpTableRow = new HtmlTableRow();
    HtmlTableCell helpTableCell = new HtmlTableCell();
    //helpTableCell.Attributes.Add("style", "border: solid 2px; border-color: Blue;");
    helpTableCell.ColSpan = cellCount;

    Label helpLabel = new Label();
    if (applySkin) helpLabel.SkinID = "labelBoldSkin";
    helpLabel.Text = "<br>"+text;

    helpTableCell.Controls.Add(helpLabel);
    helpTableRow.Cells.Add(helpTableCell);
    return helpTableRow;
    }

    more...

    Attributes.Add style


    change font weight:
             
    helpLabel.Attributes.Add("style", "font-weight:bold");


    change color
             
    helpTableRow.Attributes.Add("style", "color:red;");


    more...

    Thursday

    start of the week C#

         
    public static class DateTimeExtensions
    {
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
    int diff = dt.DayOfWeek - startOfWeek;
    if (diff < 0)
    {
    diff += 7;
    }

    return dt.AddDays(-1 * diff).Date;
    }
    }

    Usage:
         
    dateFrom.Value = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

    what day is the start of the week

    Sunday :)
    more...

    datatable copy c#

    here is procedure for copying data b/w different fields in two tables
             
    public DataTable CopyData(DataTable indata, Hashtable fields)
    {
    DataTable ret = new DataTable();
    foreach (string k in fields.Keys)
    {
    ret.Columns.Add((string)fields[k], indata.Columns[k].DataType);
    }
    foreach (DataRow row in indata.Rows)
    {
    DataRow dr = ret.NewRow();
    foreach (string k in fields.Keys)
    {
    dr[(string)fields[k]] = String.Format("{0}", row[k]);
    }
    ret.Rows.Add(dr);
    }
    return ret;
    }

    create mapping b/w fields in original table and result table and call procedure
             
    Hashtable fieldsMap= new Hashtable()
    {
    {"[Measures].[Week]","Week"},
    {"[Measures].[Month]","Month"},
    {"[Measures].[Quarter]","Quarter"},
    {"[Measures].[Year]","Year"},
    };

    // call copy data procedure
    DataTable result = CopyData(OriginaldataTable, fieldsMap);



    more...

    datatable.columns.add

             
    DataTable table = new DataTable("MyTable");
    Type str = System.Type.GetType("System.String");
    table.Columns.Add("Checbox", System.Type.GetType("System.Boolean"));
    table.Columns.Add("String1", str);
    table.Columns.Add("String2",str);
    table.Columns.Add("Decimal", 0.0.GetType());

    create datatable on the fly

    // here is procedure for creating table on the fly
       
    private DataTable CreateTable()
    {
    DataTable table = new DataTable("Report");
    Type str = System.Type.GetType("System.String");
    table.Columns.Add("chk1", System.Type.GetType("System.Boolean"));
    table.Columns.Add("From", str);
    table.Columns.Add("To",str);
    table.Columns.Add("Hours", 0.0.GetType());
    table.Columns.Add("Desc", str);
    return table;
    }

    // below is procedure for filling table with data
    private void ProcessReport()
    {
    xreport = XDocument.Load(ReportFile.Text);
    var header = (from head in xreport.Elements("Journal").Elements("Header")
    select head).First();

    Rate.Text= header.Attribute("Rate").Value;

    var entries = from entri in xreport.Elements("Journal").Elements("Entry")
    select entri;
    DataTable dataTable = CreateTable();
    foreach (var element in entries)
    {
    DataRow dr = dataTable.NewRow();
    dr["From"] = element.Attribute("StartTimeStamp").Value;
    dr["To"] = element.Attribute("EndTimeStamp").Value;
    dataTable.Rows.Add(dr);
    }
    Grid.DataSource = dataTable;
    }

    more...

    Friday

    C# csharp read from file write into file


    public static string ReadFile(string f){
    System.IO.StreamReader file = new System.IO.StreamReader(f);
    string testxmldata = file.ReadToEnd(); file.Close();
    return testxmldata;
    }
    public void WriteIntoFile(string path,string m) {
    if (!File.Exists(path)) {
    // Create a file to write to.
    using (StreamWriter sw = File.CreateText(path)) {
    sw.WriteLine(m);
    }
    }
    else {
    // This text is always added, making the file longer over time
    // if it is not deleted.
    using (StreamWriter sw = File.AppendText(path)) {
    sw.WriteLine(m);
    }
    }
    }

    more...

    Thursday

    remove bing from internet explorer

    Go to this page and setup different provider (google for example):
    http://www.ieaddons.com/en/searchproviders

    In internet explorer menu open Tools/Manage addons /Search providers
    Right click on Bing, then select remove from popup menu.

    more...

    Tuesday

    Passing NULL values to SqlCommand.Parameters.AddWithValue

    this code might help
           
    SqlCommand sqlCmd = new SqlCommand(sqlStatment, dbConn);
    sqlCmd.Parameters.AddWithValue("@Name", name);
    sqlCmd.Parameters.AddWithValue("@Surname", surname);
    foreach (SqlParameter Parameter in sqlCmd.Parameters)
    {
    if (Parameter.Value == null)
    {
    Parameter.Value = DBNull.Value;
    }
    }

    more...

    Friday

    The wave header is corrupt fix Or how to play wav file with System.Media.SoundPlayer in dot.Net C#

    1.add this MediaPlayer class
    class MediaPlayer
    {
    System.Media.SoundPlayer soundPlayer;
    public MediaPlayer(byte[] buffer)
    {
    MemoryStream memoryStream = new MemoryStream(buffer, true);
    soundPlayer = new System.Media.SoundPlayer(memoryStream);
    }
    public void Play() {soundPlayer.Play();}
    public void Play(byte[] buffer)
    {
    soundPlayer.Stream.Seek(0, SeekOrigin.Begin);
    soundPlayer.Stream.Write(buffer, 0, buffer.Length);
    soundPlayer.Play();
    }
    }

    2. Then file playing procedure will be looking like this:
    private void PlayMyFile()
    {
    string file1 = @"c:\sample.wav";
    List<byte> soundBytes = new List<byte>(File.ReadAllBytes(file1));
    //create media player loading the first half of the sound file
    MediaPlayer mPlayer = new MediaPlayer(soundBytes.ToArray());
    //begin playing the file
    mPlayer.Play();
    }

    more...

    Thursday

    C# generic list copy with constructor

         
    using System;
    using System.Collections;
    using System.Collections.Generic;
    namespace Business.Web.Models {
    public class DtoMapper {
    // this is generic method replacing non-generic metod
    // InvoiceDto_OLD provided in source below
    public List<T2> Transform<T1,T2>(List<T1> i, Func<T1,T2> del)
    {
    List<T2> ret = new List<T2>();

    foreach (T1 val in i) {
    ret.Add(del(val));
    }
    return ret;
    }

    // generic method can be called as follows:
    public List<InvoiceDto> InvoiceDto(List<Invoice> i) {
    return Transform<Invoice,InvoiceDto> (i.ToList(),l=>new InvoiceDto(l));
    }

    // this is sample of old non-generic method
    public List<InvoiceDto> InvoiceDto_OLD(List<Invoice> i) {
    List<InvoiceDto> ret = new List<InvoiceDto>();

    foreach (Invoice invoice in i) {
    ret.Add(new InvoiceDto(invoice) );
    }
    return ret;
    }
    }
    }

    more...

    Tuesday

    view GAC, add dll to GAC


    to view registred dlls in GAC open this folder in explorer:
    C:\WINDOWS\assembly

    To Register GAC , use following command:
    c:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe /i [mydll]
    more...

    Saturday

    To analyze website with FxCop

    Open FxCop click newProject/AddTargets and find your website compiled here:
    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\[yourwebsitename]
    Press Ctrl+A and add all dlls.

    more...

    open web page in android application:

    don't forget to set permission


    package com.test2;
    import android.app.Activity;
    import android.os.Bundle;
    public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }
    @Override
    protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    android.webkit.WebView wv =
    (android.webkit.WebView)this.findViewById(R.id.WebView01);
    wv.loadUrl("http://sourcefield.blogspot.com");
    }
    }

    Could not load file or assembly Microsoft.ReportViewer.WebForms:

    usually it's located into c:\Program Files\Microsoft Visual Studio 9.0\ReportViewer\

    For visual Studio 2005 run this installer to add this to GAC:
    C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\ReportViewer\ReportViewer.exe
    more...

    Thursday

    fix:android.webkit.WebView

    In order to allow WebView to display pages,android.permission.INTERNET permission has to be added :

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>


    Can also be edited graphically in Eclipse plugin through permissions tab.

    Monday

    AutoHotkey autoplayer for Online games

    Here is auto-click script for 'point and click' games , you will need AutoHotkey and save this as .ahk file .

    SetKeyDelay, 75, 75
    ;Exits AutoHotKey application.
    $^CapsLock::
    ExitApp
    return
    ;Pauses AutoHotKey Script.
    F6::Pause, Toggle, 1
    $x::
    Loop {
    MouseClick
    sleep 10
    }

    more...

    C# source to find XML tag recursively


     [TestFixture]
    public class test
    {
    [Test]
    public void XPathTest()
    XmlDocument doc = new XmlDocument();
    doc.Load(@"c:\LinqObjects.xsd");

    foreach (XmlNode node in doc.DocumentElement.ChildNodes)
    {
    ProcesNode(node, doc.DocumentElement.Name);
    }
    }



    private void ProcesNode(XmlNode node, string parentPath)
    {
    if (!node.HasChildNodes || ((node.ChildNodes.Count == 1) && (node.FirstChild is System.Xml.XmlText)))
    {
    if (node.Name == "Parameter")
    {
    //System.Diagnostics.Debug.WriteLine(parentPath + "/" + node.Name);
    }
    }
    else
    {
    foreach (XmlNode child in node.ChildNodes)
    {
    ProcesNode(child, parentPath + "/" + node.Name);
    }
    }
    }
    }

    more...

    make ubuntu business casual

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