Wednesday

T-SQL (Microsoft SQL Server): How to find table by column name:

Run this to find table with column name:

SELECT o.name AS TableName, c.name AS ColumName
FROM syscolumns c JOIN sysobjects o
ON c.id = o.id
WHERE c.name like '%account%'
ORDER BY o.name, c.name

more...

serializable abstract class, can be used for inheritance , C# .net

can be used for serialize object to xml


abstract public class AbstractXMLObject
{
public string XML
{
get
{
XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
StringWriter stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter,this);
return stringWriter.ToString();
}
set
{
XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
StringReader stringReader = new StringReader(value);
this = xmlSerializer.Deserialize(stringReader);
}
}
}


more...

Tuesday

.net Threading:Passing parameters to the thread for ParameterizedThreadStart in C# (csharp / dot.net)


0.Create MultiThreadArgument class and add all parameters for thread starting 
public class MultiThreadArgument {
public MerchantBase merchant;
public TransactionCollection transactionCollection;
public string email;
}

1.Thread starter in main thread class (thread class):
private void ThreadStarter(MerchantBase m, TransactionCollection c,string email){
if (c.Count > 0) {
Thread th = new Thread(new ParameterizedThreadStart(ThreadWorker));
// create class parameters :
MultiThreadArgument ma = new MultiThreadArgument();
ma.merchant = m;
ma.transactionCollection = c;
ma.email = email;
th.IsBackground = true;
th.Start(ma);
}
}

2.Thread worker in main class:
private void ThreadWorker(Object o) {
MultiThreadArgument ma = (MultiThreadArgument)o;
DateTime st = DateTime.Now;
string mid = ma.merchant.ID.ToString();
Logger.prn("*** Processing started for merchant #", mid , "transactions - ", ma.transactionCollection.Count.ToString());
ma.merchant.ProcessRequest(ma.transactionCollection, this);
.....
}

more...

Friday

appent new element to string[] array

to add:

string[] newarr = new string[oldarr.Length + 1];
oldarr.CopyTo(newarr, 0);
newarr[newarr.Length-1] = "new element";
return newarr;

more...

casting Array into string[]


return Array.ConvertAll<object, string>(ls, delegate(object obj) { return (string) obj; });

more...

Thursday

how to get file name and file extentions [ C# / CSarp]

by System.IO.Path class in dot.net framework:

string
file_extention;
string file_name;
file_name=Path.GetFileName(this.mffFileName);
file_extention = Path.GetExtension(this.mffFileName);

more...

TimeSpan parse method (part of the info from msdn)

Here is format of input string :

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]


Items in square brackets ([ and ]) are optional; one selection from the list of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required; colons and periods (: and .) are literal characters and required; other items are as follows.

Item

Description

ws

optional white space

"-"

optional minus sign indicating a negative TimeSpan

d

days, ranging from 0 to 10675199

hh

hours, ranging from 0 to 23

mm

minutes, ranging from 0 to 59

ss

optional seconds, ranging from 0 to 59

ff

optional fractional seconds, consisting of 1 to 7 decimal digits

The components of s must collectively specify a time interval greater than or equal to MinValue and less than or equal to MaxValue.



days , hours , minutes , but what if it's required to have timespan in a weeks, month , years ?
more...

Wednesday

operator overloading example c#

Samples of string and bool operator overloading in C-Sharp, this code inside of class Result:
 1   public static implicit operator bool(Result p){
2 return p.Status == enResultStatus.OK;
3 }
4
5 private const string of = "\nResult:\n\tstatus:{0}\n\tdesc:{1}\n\tMsg:{2}\n\tException:{3}\n\tval:{4}\n\tSuggested:{5}";
6 public static implicit operator string(Result p) {
7 return String.Format(of, p.Status , p.Description, p.UserFriendlyErrorMsg,p.ExeptionHappend,p.Value,p.SuggestedValue);
8 }

Usage:
15  Result res;
16 if (res) {
17 Debug.WriteLine("Dump of result object :"+res )
18 }


more...

Monday

sample of sorting algoritm for collection of Invoice objects by date-time

Collection is type of System.Collections.Generic.List

// sorting class 
public class InvoiceSorterbyDueDate : System.Collections.Generic.IComparer<BaseObject>
{
#region IComparer<Invoice> Members
public int Compare(BaseObject x, BaseObject y){
return ((Invoice)x).DueDate.CompareTo(((Invoice)y).DueDate);
}
#endregion
}


//call
IComparer<BaseObject> ins = new InvoiceSorterbyDueDate();
p.InvoiceCollectionToCheck.Sort(ins);

//


more...

python time or datetime format and function

1 import time
2 timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
more...

Wednesday

to debug javascript (errors :) ) in internet explorer

you can use debugger; directive to step into default javascript debugger (visual studio 2005)
or you can create debugger window and paste variables there:
var dbgwin;
dbgwin=window.open("", "Debug", "left=0,top=0,width=300,height=700,scrollbars=yes," +"status=yes,resizable=yes");
function log(msg){
dbgwin.document.write("<br>"+msg);
}

log('Started');


more...

Read userprofile environment variable containing userprofile path in dot.NET

Environment.GetEnvironmentVariable("USERPROFILE")
more...

.etl file extension is used by standart windows performance monitoring

It's binary file
Run :tracerpt.exe your.etl from command line and your file will be processed to readable csv file and text summary.
or tracert.exe /? to view help information:


>tracerpt /?
Microsoft TraceRpt.Exe (5.1.2600.2180)
Microsoft Corporation. All rights reserved.

Tracerpt processes binary Event Trace Session log files or real-time streams from instrumented Event Trace providers and creates a report or
a text (CSV) file describing the events generated.

Usage:
tracerpt { <filename [filename ...]> | -rt <session_name [session_name ...]> } [options]

Parameters:
<filename [filename ...]> Event Trace log file to process.

Options:
-? Displays context sensitive help.
-o [filename] Text (CSV) output file. Default is dumpfile.csv.
-summary [filename] Summary report text file (CSV) file. Default is summary.txt.
-report [filename] Text output report file. Default is workload.txt.
-rt <session_name [session_name ...]> Real-time Event Trace Session data source.
-config <filename> Settings file containing command options.
-y Answer yes to all questions without prompting.

Examples:
tracerpt logfile1.etl logfile2.etl -o -report
tracerpt logfile.etl -o logdmp.csv -summary logdmp.txt -report logrpt.txt
tracerpt -rt EVENT_SESSION_1 EVENT_SESSION_2 -o logfile.csv



more...

Monday

C# Query string .net Parsing.

Instead for splitting string with & and = you can use HttpUtility class to split query string into NameValueCollection:
Private responseHash As NameValueCollection = New NameValueCollection()
responseHash = HttpUtility.ParseQueryString(ServerRersponse)
'than use it as usual
responseHash("MErrMsg")

Read query string parameters from javascript

Read query string parameters from javascript.
Here is script demonstrating it:
var qsParm = new Array();
function qs() {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0) {
var key = parms[i].substring(0,pos);
var val = parms[i].substring(pos+1);
qsParm[key] = val;
}
}
}

Sunday

Post to your blog at blogger.com from gVIM.

Tested on windows only.
Requirements:
1.python installed.
2. Google Data APIs - gdata-python-client
can be downloaded from here : http://gdata-python-client.googlecode.com/files/gdata.py-1.0.10.latest.zip

Installation :
1.Install python
2.Download gdata-python-client unpack and run "setup.py install"
3.download bg01.zip unpack bg.py and place in any folder mentioned in %PATH%
4. add this line to your _vmrc file :
nnoremap <Leader>blog :! bg.py --f %:p --u my@email.com --p inline<cr>
where my@email.com is your email registered on blogger.com

--p inline - means that password will be asked on every posting to blog , you can specify it in this line if you want.
Than script will not be asking every time.
nnoremap <Leader>blog :! bg.py --f %:p --u my@email.com --p mypassword<cr>

Using:
When you want to post current file to blog : just hit '\blog' enter password and new blog entry will be created.
I added post here how to create blog with syntax-highlighted source code.
Please leave a word or bug :) or questions,concerns,comments,jockes here

more...

Wednesday

How to blog source code from gVim

you have to :
1.add
let html_use_css = 1
to your _vimrc

2.add these style (depends on your current color scheme) to blog template


<style type="text/css">
<!--
.Statement { color: #a0ffa0; }
.Comment { color: #507080; }
.StorageClass { color: #a0a0ff; background-color: #103040; }
.Type { color: #a0a0ff; }
.Conditional { color: #a0ffa0; background-color: #103040; }
.Constant { color: #00cdcd; background-color: #103040; }
.pre { font-family: monospace; color: #e0eee0; background-color: #103040; }
.code { font-family: monospace; color: #e0eee0; background-color: #103040; }
-->
</style>



3.Use :TOhtml command for create html file from selected part of source code.
4.Install script from here and Use \blog command calling python script to post file on your blog.

How to create custom event in System.Web.UI.UserControl (C#):

How to create custom event in System.Web.UI.UserControl (C#):


//0.define delegate:
public delegate void ToolBarClick(string command);

//1. in control declare instance:
public ToolBarClick Click;

//and raiser:
protected void rpt_ToolBarAction_ItemCommand(object source, RepeaterCommandEventArgs e){
if (Click!=null){
Click(e.CommandArgument.ToString());
}
}

//2. On page add handler:
protected void Page_Load(object sender, EventArgs e)
{
ToolBar1.Click = new ToolBarClick(ToolBar_Click);

//and event function:
protected void ToolBar_Click(string s)
{

Tuesday

C# Anonymous methods , "generic" exception handling

this is why C# Anonymous methods are cool :
Below is one of top classes of winservice/remote rule application server.
Methods of this top class must handle exception and be rock-stable.
Instead of handling exception in every overloaded method "Rule"
I can pass anonymous method into one/major and handle exception there.
Here's sample :


using System;

using System.Collections.Generic;

using System.Text;



namespace BusinessRules.Reactor

{

    /// <summary>

    /// Control panel is central dispatcher and  Rules-Runner

    /// </summary>

   public class ControlPanel

    {

       public Result Rule(int EnityType, string ReferenceID, int ruleid)

       {

           BasicProperties p = new BasicProperties();

           p.ReferenceID = ReferenceID;

           Result res = Rule(p, delegate() {return Storage.getRule(Storage.GetEntityID(EnityType, ReferenceID), ruleid); });          

           return res;

       }

      

       public Result Rule(RuleProperties RuleProperties ,int EnityType, string ReferenceID,int ruleid){            

           return Rule(RuleProperties, delegate() {

                                                      return

                                                          Storage.getRule(Storage.GetEntityID(EnityType, ReferenceID),

                                                                          ruleid);});

       }

      

       public Result Rule(RuleProperties RuleProperties, int ruleid) {

           return Rule(RuleProperties, delegate() { return Storage.getRule(ruleid); });

       }



      

       public delegate ConcreteRule GetRule();

       public Result Rule(RuleProperties RuleProperties, GetRule rule_get){

            Result res= new Result();

            try

            {

                ConcreteRule rule = rule_get();

                rule.Init((BasicProperties)RuleProperties);

                rule.ApplyRule();

                res = rule.Result;



            }catch (AssertionException aex){                

                                

                res.ExeptionHappend = aex.ToString();

                res.Status = enResultStatus.Collision;

                res.Description = aex.Message;

            } catch ( Exception ex) {



                res.ExeptionHappend = ex.ToString();

                res.Status = enResultStatus.UnhandledException;

                res.Description = ex.Message;

            }

            return res;

        }





    }

}


Sample of code evolution from C#1.1 into C#3.0

Sample of code evolution from C#1.1 into C#3.0
C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ): "From code name “cool” to C# 3.0, it’s been a long journey for this amazing language with .NET Runtime. Here I am going to show you the evaluation step by step."

you might feel a bit like Alice falling into Rabbit hole :)

to fix this exception System.Runtime.Serialization.SerializationException

to fix this exception : System.Runtime.Serialization.SerializationException: The constructor to deserialize an object of type was not found.
Add empty/default constructor and if error still appear add specific constructor like in class below:

 [Serializable]

 public class AssertionException : ApplicationException {

 public AssertionException(SerializationInfo info, StreamingContext context) : base(info, context) {}

 public AssertionException() : base() { }

Blogging from VIM with source code snipplets

1.In Visual or Normal mode use :TOHtml command to get html representation of source code you have selected .
2.in opened buffer surround text with this div:
<div style="background-color:#103040; overflow:scroll;height:200px"> <font color="#e0eee0">
-- created html code here --
</font></div>
3.root font tag has specific color for my vim-color it's "#e0eee0"
and you will have post with source like that :


using System;

using System.Collections.Generic;

using System.Text;



    public abstract class CustomAttribute : Attribute { }



    public class ExcludeFromToXml : CustomAttribute { }

    public class FoldStorage : CustomAttribute{}

    public class FoldableClass : CustomAttribute { }

    public class Folded : CustomAttribute

    {

        public string IntoProperty;

        public Folded(string intoProperty){

            IntoProperty = intoProperty;

        }

    }



    public class CollectionProperty : CustomAttribute { }



    public class EnumeratedProperty : CustomAttribute

    {

        private Type m_enumType;

        public virtual Type EnumType

        {

            get { return m_enumType; }

        }



        public EnumeratedProperty(Type inEnumType)

        {

            m_enumType = inEnumType;

        }

    }







Read how to post from vim into blogger.com over python API in my next post.

Monday

Writing Attributess for extending business classes and found interesting doc on msdn : Attributes Tutorial (C#)

I'm writing custom attributess for extending business classes and found interesting doc on msdn :
Attributes Tutorial (C#): "This tutorial shows how to create custom attribute classes, use them in code, and query them through reflection."

Saturday

How to create abstract object with serialization methods.

C#,CSharp : it will be easy to serialize/deserialize inherited object into xml string
   23     abstract public class AbstractXMLObject
   24     {
   25         public string XML
   26         {
   27             get
   28             {
   29                 XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
   30                 StringWriter stringWriter = new StringWriter();
   31                 xmlSerializer.Serialize(stringWriter, this);
   32                 return stringWriter.ToString();
   33             }
   34             set
   35             {
   36                 XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
   37                 StringReader stringReader = new StringReader(value);
   38                 this = xmlSerializer.Deserialize(stringReader);
   39             }
   40         }
   41     }

C# threading , msdn examples/explanations :

C# threading , msdn examples/explanations :

How to: Use a Thread Pool (C# Programming Guide):
How to: Create and Terminate Threads (C# Programming Guide)
How to: Synchronize a Producer and a Consumer Thread (C# Programming Guide)

Good unit-tests have ... : A-TRIP rule (quote from one book about unit testing ,don't remember the title)

Good unit-tests have ... : A-TRIP rule (quote from one book about unit testing ,don't remember the title)
Good unit-tests have the following properties, which makes them
A-TRIP:
• Automatic
• Thorough
• Repeatable
• Independent
• Professional

C#(CSharp/dot.net 2.0/Micsrosoft Visual Studio 2005)How to read string xml into dataset:

C#(CSharp/dot.net 2.0/Micsrosoft Visual Studio 2005)How to read string xml into dataset:

   24 string ready= (String.Format("{0}", str));
   25 Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(ready));
   26 DataSet ds = new DataSet();
   27 ds.ReadXml(s);

make ubuntu business casual

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