Friday

WINService in python sample



import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "SmallestPythonService"
_svc_display_name_ = "The smallest possible Python Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# And set my event.
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
# We do nothing other than wait to be stopped!
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)



more...

Thursday

port forwarding RDP;cannot connect to localhost


symptoms:
"The client could not connect. You
are already connected to the console of this computer. A new console
session cannot be established".

Procedure:
1. Create a folder (For example c:\TSclient) on your XP box
2. Copy mstsc.exe and mstscax.dll from your XP's %systemroot%\system32
to this folder.
3. Right click mstsc.exe and go to the properties of it.
4. Select the Compatibility tab
5. Check "Run this program in compatibility mode for"
6. Select "Windows 98/ Windows Me"
7. Click on OK
8. Connect your SSH to the remote network or machine
9. Forward another port than 3389, for example 3390
10. Use the newly copied mstsc.exe to connect to 127.0.0.1:3390

more...

run RDP from localhost

mstsc.exe /v:127.0.0.1:3390
more...

Monday

Photoshop online tutorials:


PS Hero - [link]

1.jpg


PSD tuts - [link]


2.jpg


Tutorial 9 - [link]

3.jpg


PSD Learning - [link]

4.jpg


Photoshop Tutorials - [link]


5.jpg


Photoshop Contest - [link]

6.jpg


Luxa - [link]

7.jpg


Tutorial Sphere - [link]
8.jpg


Good Tutorials - [link]
9.jpg


Photoshop Talent - [link]
10.jpg



more...

Wednesday

simple python unit test sample,TDD rule


import unittest
class TestTank(unittest.TestCase):
def testImage(self):
tank="boo"
assert tank != "boo", "tank image is None"
def test1(self):
tank ="moo"
assert tank != "moo", "test1 tank image is None"


if __name__=="__main__":
unittest.main()

more...

Generate XSD from XML with DataSet (VB.NET)


<Test()> _
Public Sub generateXsd()
Try

Dim d As DataSet = New DataSet()
d.ReadXml("C:\projects\LeadInformation.xml")
d.WriteXmlSchema("C:\projects\LeadInformation.xsd")
Catch ex As Exception
End Try

End Sub
more...

SQL server 2005-create indexes for temporary tables t-sql



1 SELECT
2 ad.[DealerId]
3 ,ad.[APSDealerId]
4 ,cu.CustomerID
5 ,cu.[FirstName]
6 ,cu.[LastName]
7 ,cu.[DOB]
8 ,cu.OwnerID
9 ,cu.referencefield1
10 ,cu.referencefield2
11 into #tmain
12 FROM [Customers] cu
13 INNER JOIN [AdvanceCustomer] ac ON ac.[CustomerID] = cu.[CustomerID]
14 INNER JOIN [ApsUbillDealer] ad ON ad.[DealerId] = ac.[DealerID]
15 WHERE cu.[DateCreated] > @XmlData.value('(/args/FromDate)[1]','varchar(10)')
16 AND cu.[DateCreated] < @XmlData.value('(/args/ToDate)[1]','varchar(10)')
17
18 CREATE UNIQUE CLUSTERED INDEX IX_1 on #tmain (CustomerID, OwnerID)
19 CREATE INDEX IX_2 on #temp_employee_v1 (APSDealerId)
20
21


more...

Thursday

To Add gVIM to External Tools to Visual Studio or SQL Management Studio

Title:vim&-
Command:C:\vim\vim71\gvim.exe
Arguments: -p -o --remote-silent +$(CurLine) $(ItemPath)
now vim can be called by : <Alt-T> -
more...

Monday

Create SQL INSERT from Excel file (ruby script)

import excel file into SQL.
first row is column names.


require 'win32ole'
xl = WIN32OLE.connect('Excel.Application')
wb = xl.ActiveWorkbook
wb.Worksheets.each do |ws|
data = ws.UsedRange.Value
if data!=nil
field_names = data.shift
flds=field_names.join(',')
data.each do |row|
row.collect! { |f| f = "'" + f.to_s + "'" }
puts ("INSERT INTO [#{ws.Name}] (#{flds}) VALUES \
( #{row.join(',')} );")

end
end
end

As alternative there is app that can convert Excel into SQL witn CREATE TABLE and INSERT statements

Handling custom error messages from sql in VB.NET (System.SslClient , SQL Server 2005)

Imports System.Data.SqlClient
Imports CSharp.Core

Public Class DBProvider

Public Sub LogSQLMessages(ByVal sender As Object, ByVal e As SqlInfoMessageEventArgs)
Logger.prn("SQLMessage:" & e.ToString)
End Sub

Private Shared youBillConn As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString

Public Function ExecuteScalar(ByVal spname As String, ByVal ParamArray sparams() As Object) As Object
Dim sqlc As New SqlConnection(youBillConn)
Try
AddHandler sqlc.InfoMessage, AddressOf LogSQLMessages
'sqlc.FireInfoMessageEventOnUserErrors = True
sqlc.Open()
Return SqlHelper.ExecuteScalar(sqlc, spname, sparams)

Catch ex As SqlClient.SqlException

Dim erix As Integer = ex.Message.IndexOf("MSIEX:[[")
Dim eree As Integer = ex.Message.IndexOf("]]")

If erix >= 0 And eree > 0 And eree > erix Then
Assertions.Throw(ex.Message.Substring(erix + 8, (eree - erix) - 8))
Else
Logger.prn(ex)
Throw ex
End If

Return Nothing

Catch allex As Exception
Logger.prn(allex)
Throw allex

Finally
sqlc.Close()
End Try

End Function

End Class

more...

Friday

TRY..CATCH in T-SQL (sqlserver 2005)



SELECT * FROM sys.messages
ALTER Procedure usp_sp1
@XMLData XML
AS
BEGIN
DECLARE
...declarations...
SET XACT_ABORT ON
BEGIN TRY
BEGIN TRANSACTION usp_sp1_tran
...transactions...
COMMIT TRANSACTION usp_sp1_tran
END TRY
BEGIN CATCH
ROLLBACK TRAN usp_sp1_tran

DECLARE @ErrorMessage NVARCHAR(4000)
,@ErrorNumber INT
,@ErrorSeverity INT
,@ErrorState INT
,@ErrorLine INT
,@ErrorProcedure NVARCHAR(200) ;

SELECT @ErrorNumber = ERROR_NUMBER()
,@ErrorSeverity = ERROR_SEVERITY()
,@ErrorState = ERROR_STATE()
,@ErrorLine = ERROR_LINE()
,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-') ;


SELECT @ErrorMessage = 'Procedure:' + @ErrorProcedure + '; Line:'
+ CAST(@ErrorLine AS VARCHAR(10)) + '; ' + ERROR_MESSAGE() ;

--EXEC usp_Email @ErrorMessage, 'mymail@host.com'
RAISERROR ( @ErrorMessage, 16, 1 )
END CATCH
END


more...

Custom RAISERROR in SQL Server 2005 (T-SQL)

how to add custom message %s is place holder for argument:
 exec sp_addmessage @msgnum = 60555, @severity = 16,
@msgtext = 'MSIEX:[[%s]]',
@lang = 'us_english';
go

to see your message in messages table:

SELECT * FROM sys.messages

Assert procedure in TSQL :

ALTER PROC usl_AssertionsThrow
@msg VARCHAR(MAX)
AS
BEGIN
RAISERROR ( 60555, 20, 1,@msg) WITH LOG
END

this setting terminate stored procedure after RAISERROR

SET XACT_ABORT ON




more...

Tuesday

Custom Error in MS-SQL server by RAISERROR (TSQL)


--Add message
exec sp_addmessage @msgnum = 60000, @severity = 16,
@msgtext = 'The record has been modified already by other process',
@lang = 'us_english';
go
-- sample of usafe
if @CurrCheckSum <> @xmlCheckSum
RAISERROR (60000, 16, 1)
ELSE

more...

Sunday

ASP.NET/VB.NET Embed pdf into html page



Public Shared Sub EmbToPdf(ByVal objViewcreator As ViewCreatorGeneral, ByVal dtFromDatabase As DataTable, ByVal inColumnArrList As ArrayList, ByVal report_header As String, ByVal originalSort As String)
If Not System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("./ViewControlExport/")) Then
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("./ViewControlExport"))
End If
dim pid as string =Guid.NewGuid.ToString & ".pdf"
Dim filePath As String = System.Web.HttpContext.Current.Server.MapPath("./ViewControlExport/") & pid

Try


Dim inDataSet As DataSet = New DataSet
GeneralHelper.GetDataSetForDiffFormats(dtFromDatabase, inDataSet, inColumnArrList)

'this code convert dataset into pdf document , itext is using
' see post belo for more info
inDataSet.Tables(0).DefaultView.Sort = originalSort
objViewcreator.BindingDataView = inDataSet.Tables(0).DefaultView
objViewcreator.ConvertDataViewToPdf(filePath,report_header,"",new Rectangle(1190,842 )) 'PagesSize.A3 = 1190,842


System.Web.HttpContext.Current.Response.Write("<embed src='" & "./ViewControlExport/" & pid & "#toolbar=1&navpanes=1&scrollbar=1' width='960' height='760'>")

System.Web.HttpContext.Current.Response.End()
Catch ex As Exception
Ubill.Logger.prn(filePath, ex.ToString)
End Try
End Sub


more...

IE7 opening excel files.

may not be working , check out : http://blogs.msdn.com/excel/archive/2006/09/26/771221.aspx



Public Shared Sub ExportToExcel(ByVal objViewcreator As ViewCreatorGeneral, ByVal dtFromDatabase As DataTable, ByVal inColumnArrList As ArrayList, ByVal report_header As String, ByVal originalSort As String)

System.Web.HttpContext.Current.Response.ClearContent()
System.Web.HttpContext.Current.Response.ClearHeaders()
System.Web.HttpContext.Current.Response.Charset = ""
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=report.xls")
System.Web.HttpContext.Current.Response.AddHeader("Pragma", " private")
System.Web.HttpContext.Current.Response.AddHeader("Cache-control", " private, must-revalidate")

'writing tab separated stuff here
Dim tabFile As String = "my tab separted cols crlf separeted rows"
System.Web.HttpContext.Current.Response.BinaryWrite(Encoding.GetBytes(tabFile))

System.Web.HttpContext.Current.Response.End()
End Sub


more...

Monday

read data from SQL sevrer with Ruby/WIN32OLE way



def read_sp(sp_text,sr,db,pwd)
conn = WIN32OLE.new('ADODB.Connection')
conn.Open("driver={SQL Server};Uid=sa;server=#{sr};pwd=#{pwd};database=#{db};")
rset = WIN32OLE.new('ADODB.Recordset')
rset.ActiveConnection = conn
rset.Open(sp_text)
s = ""
while not rset.EOF do
for i in (0..rset.Fields.Count - 1) do
s += rset.Fields.Item(i).Value.to_s.strip
end
rset.MoveNext
end
return s;

end



more...

Using @@Rowcount to Determine the Number of Rows Affected by a SQL


The @@Rowcount function will be set after any statement that changes or returns rows. In the following statement, the RowsReturned column will display the number of rows selected by the previous select statement:

SELECT * FROM AUTHORS
WHERE state = 'CA'
SELECT @@rowcount AS 'RowsReturned'

While this example could obviously be rewritten to use a SELECT COUNT... type of syntax, the @@Rowcount function is useful in that it is also set after any statement that changes rows. As such it is useful in determining how many rows were affected by an INSERT or an UPDATE statement. For example, the following SQL statement changes the city column in the authors table of the pubs database from Salt Lake City to Oakland:

UPDATE authors SET city = 'Oakland' WHERE city = 'Salt Lake City'
SELECT @@rowcount AS 'RowsChanged'

The statement will return the number of rows changed as the RowsChanged column.

more...

Thursday

hanging-up asp web application on IIS 7, solved .server 2003

When web application has asp server debugging option available it creates vsjitdebubber.exe process on server 2003.
and asp page is not responding until this vsjitdebugger.exe killed.

So by switching debugging options to off I eliminated this asp application hang ups.
server responses with error immediately.

more...

Tuesday

ASP:how to show all session variables

<!--
<% =Session.Contents.Count %>
<%
ON Error resume NEXT
Dim item, itemloop
For Each item in Session.Contents
If IsArray(Session(item)) then
For itemloop = LBound(Session(item)) to UBound(Session(item))
%>
<% =item %> <% =itemloop %> = <% =Session(item)(itemloop) %>
<%
Next
Else
%>
<% =item %> = <% =Session.Contents(item) %>
;
<%
End If
Next
%>
-->

more...

Sunday

.rm to .mp3 free converter (no installation needed)

1.download and unpack [mplayer] and [lame].
2.create two bat files :

--enc.bat --
mplayer.exe -v -ao pcm -cache 2048 %1
lame audiodump.wav %1.mp3
rm audiodump.wav
---

-- endir.bat--
for %%f in (%1\*.rm) do (enc.bat "%%f")
--

to encode folder with .rm files just run

endir [target-dir]

more...

Wednesday

To change xml namespace definition you can try this xsl,see input



<?xml version="1.0" encoding="iso-8859-1"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:NAME="old_namespace">

<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>

<xsl:template match="NAME:*">
<xsl:element name="{name()}">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>

<xsl:template match="ROOT">
<xsl:element name="ROOT">
<xsl:attribute name="xmlns:NAME">http://tempuri.org/mynew</xsl:attribute>
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>

</xsl:stylesheet>


If you put in input an XML like this:

<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<ROOT xmlns:NAME='old_namespace'>
<NAME:element attr1="xxx" >
<NAME:subElement attr2="yyy">abcdefghi</NAME:subElement>
</NAME:element>
<NAME:element attr1="xxx" >
<NAME:subElement attr2="yyy">abcdefghi</NAME:subElement>
</NAME:element>
</ROOT>

The output message will be:


<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT xmlns:NAME="http://example.org/new">
<NAME:element attr1="xxx">
<NAME:subElement attr2="yyy">abcdefghi</NAME:subElement>
</NAME:element>
<NAME:element attr1="xxx">
<NAME:subElement attr2="yyy">abcdefghi</NAME:subElement>
</NAME:element>
</ROOT>



more...

Friday

OpenSSHd + Cygwin on Windows XP

Found a good HOWTO-style article on how to set up OpenSSH to run as a daemon under Cygwin for Windows
http://pigtail.net/LRP/printsrv/cygwin-sshd.html
The quick outline is:
Install Cygwin, make sure you include the OpenSSH package since it's not included in the default install
Run '# mkdir -p /home/$username' and then edit /etc/passwd accordingly to create a sane home directory structure
Run '# ssh-host-config' to generate host keys, add an 'sshd' privsep user, and install sshd as a service
Run '# sc query sshd' to verify that the service is running
Run '# ssh-user-config' as necessary to generate private/public SSH keys for users if desired

more...

C#(csharp):remove (replace with whitespace) not allowed (non printable) characters from XML


rt = Regex.Replace(rt,"[\x01-\x1F]", "");


more...

Fortmatting in python :


def CheckKey(self,k3y):
return "select count (*) as cnt from %s where k3y='%s'" % (self.cfg.get('dbset','waTable') , k3y)


more...

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 ...