Wednesday

how to show hide div in asp.net

1.add this javascript function:


<script type="text/javascript">
function showHideExcel(){
thisElement=document.getElementById('overlayExcel')
if (!thisElement) return;
if(thisElement.style.visibility == "visible"){
thisElement.style.visibility = "hidden";
}else {
thisElement.style.visibility = "visible";
}
}
</script>



2.add this div to asp.net code


<div id="overlayExcel" name="overlayExcel" style="visibility:hidden;position:absolute; top: 120px; left: 900px;background-color:white;display:block;">
<div style="padding: 3px; background-color: #CCCCCC; border: 1px solid #666666;">
<table border="0" border="0" cellspacing="0" cellpadding="0" >
<tr><td height="30">Start Date:&nbsp;</td> <td><asp:TextBox ID="txtExcelStartDate" runat="server" /></td></tr>
<tr><td height="30">End Date:&nbsp;</td> <td><asp:TextBox ID="txtExcelEndDate" runat="server" /><br></td></tr>
<tr><td height="30" colspan="2"><asp:Button ID="btnExcelMe" runat="server" Text="Open Excel Report" OnClick="OpenExcelReport" />
<input type=button value="Cancel" onclick="showHideExcel();"></td>
</tr>
</table>
</div>
</div>



that's it.
more...

Friday

very nice and free music for running or training on eclipse

I gave up on running for several times , recently discovered very good music for running.
Actually this music is free and keep me running all time.
It sorted by bits per secod,for.ex. 153BPM just right for me.

check this out http://djsteveboy.com/podrunner.html

more...

Tuesday

sql split string


DECLARE @t VARCHAR(50)
SET @t = '3333-4'
SELECT LEFT(@t, CHARINDEX('-', @t) - 1), RIGHT(@t, LEN(@t) - CHARINDEX('-', @t))

more...

how to configure VB6 works with TFS:

Read
download


more...

copy odbc from one computer to another


1.if this i user odbc run regedit.exe and export this folder into .reg file.
HKEY_CURRENT_USER\Software\ODBC
2.copy .reg file on target machine and double click on .reg file to add all keys to registry.

If they are System DSN odbc you have to do the same operations for
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
registry folder.

more...

Wednesday

Derive Collection class:Override Add,Insert,Remove methods

These methods are not overridable,
will be more correctly to override InsertItem,RemoveItem methods, they will be called from other methods Add,Insert,Remove , etc

using System.Collections.ObjectModel;
using System.Diagnostics;
using System;
namespace CollectionTest
{
class Program
{
static void Main(string[] args)
{
Debug.Write("MAIN");
LimitedCollection<String> col = new LimitedCollection<String>();
col.Add("hello");
col.Insert(0,"hello");

}
}
public class LimitedCollection<T> : Collection<T>
{
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
Debug.Write("InsertItem called");
}
}
}

more...

Tuesday

How to create Setup project for Windows Service

How to create a Setup project for a Windows Service in Visual Basic .NET or in Visual Basic 2005
Create a Setup project for a Windows Service
This section describes how to create a Windows Service project and how to use a compiled Setup project to install the Windows Service.
Create a Windows Service project

1. Click Start, point to Programs, point to Microsoft Visual Studio .NET or Microsoft Visual Studio 2005, and then click Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
2. On the File menu, point to New, and then click Project.
3. In the New Project dialog box, follow these steps:
1. Under Project Types, click Visual Basic Projects or click Windows under Visual Basic.
2. Under Templates, click Windows Service.
3. In the Name box, type LogWriterService.
4. In the Location box, type C:\, and then click OK.
4. In Solution Explorer, right-click Service1.vb, and then click View Code.
5. In the OnStart event handler, replace the comments with the following code.

EventLog.WriteEntry("My simple service started.")

6. In Solution Explorer, double-click Service1.vb.
7. In the Properties dialog box, click Add Installer.
8. In the Properties dialog box for ServiceInstaller1, change the ServiceName property to LogWriterService.
9. In Design view, click ServiceProcessInstaller1 in the Code Editor.
10. In the Properties dialog box, change the Account property to LocalSystem. The LocalService value and the NetworkService value are only available in Microsoft Windows XP and later operating systems.

Use a compiled Setup project to install the Windows Service
After you complete the steps in the "Create a Windows Service project" section to configure the Windows Service project, you can add a deployment project that packages the service application so that the service application can be installed. To do this, follow these steps:

1. Add a new project to your LogWriterService project.
1. In Solution Explorer, right-click Solution 'LogWriterService', point to Add, and then click New Project.
2. Under Project Types, click Setup and Deployment Projects or Setup and Deployment.
3. Under Templates, click Setup Project.
4. In the Name box, type ServiceSetup.
5. In the Location box, type C:\, and then click OK.
2. Tell the deployment project what the deployment project will package.
1. In Solution Explorer, right-click ServiceSetup, point to Add, and then click Project Output.
2. In the Add Project Output Group dialog box, click LogWriterService in the Project box.
3. Click Primary Output, and then click OK.
3. For correct installation, you have to add only primary output. To add the custom actions, follow these steps:
1. In Solution Explorer, right-click ServiceSetup, point to View, and then click Custom Actions.
2. Right-click Custom Actions, and then click Add Custom Action.
3. Click Application Folder, and then click OK.
4. Click Primary output from LogWriterService (Active), and then click OK. Notice that Primary output appears under Install, Commit, Rollback and Uninstall.
4. By default, Setup projects are not included in the build configuration. To build the solution, follow these steps:
1. Use one of the following methods:
* Right-click LogWriterService, and then click Build. Then, right-click ServiceSetup, and then click Build.
* To build the whole solution at the same time, click Configuration Manager on the Build menu, and then click to select the Build check box for ServiceSetup.
2. Press CTRL+SHIFT+B to build the whole solution. When the solution is built, you have a complete Setup package for the service.
5. To install the service, right-click ServiceSetup, and then click Install.
6. In the ServiceSetup dialog box, click Next three times. Notice that a progress bar appears while the Setup program is installing the service.
7. When the service is installed, click Close.


Thursday

tinyget call samples

Invoking the page for 4000 times.

tinyget -srv:localhost -uri:/BuggyBits/Links.aspx -loop:4000

Invoking the page on 30 threads, 50 times each.

tinyget -srv:localhost -uri:/BuggyBits/FeaturedProducts.aspx -threads:30 -loop:50

Wednesday

To try find out asp.net performance leak/locks or why my .net app is slow on multiple requests :) ?


1.take memory dump and load it in windbg with "sos" as described here.
Then you can load sos commands .cmdtree c:\debuggers\cmdtree.txt
3.Evaluate clr stacks for all threads by ~* e !clrstack
or by selecting Stacs/All managed Stacks from Sos Commands menu window.
as result you will see call stack lists,similar stacks like for memory dump.
4.Look for System.Threading.Monitor.Enter or System.Threading.Monitor.Exit in page load stacks , that might indicate that static object is using
that might cause slow performance for multiple requests.

5.to monitor sysncBlock use !syncblk commad
it will show who owns the lock and how many people waiting for it in "MonitorHeld" column.

"Info" column will - contains thread number [thr] that locking, use this commands:
~[thr]s
!clrstack
to display locking stack and which give you a chance to locate which procedure holding it.

also debugging and preview of dump files will be available in Visual studio 2010.

more...

How to find memory leak in .net application:


1.Create dump file of application process in windows , you can use this tool

DebugDiag (free tool from Microsoft)
Open it, go to "process" tab and select "create dump file"
2. Download and install
windbg
Start windbg and drag dump file there.
3.if it's dot.net you have to load sos extension , in windbg command line , type:
.loadby sos mscorwks
4.then !dumpheap -stat you will get list of all .Net objects in memory/dump
if you want to get specific instances , you can hit:
!dumpheap -mt [addr] - where [addr] is addr from left column in windbg
you will receive list of objects loaded into memory , by dump out do objects:
!do [addr] you will dump specific objects with it's properties.
when you do !do [addr] when [addr] of specific property you will get particular value of that property.
5.if you dumped web-application and see aspx pages this is not good.
you can get static objects by this command (it will show links on cache objects as well):
!gcroot [addr] where [addr] -- address of page in memory

As alternative you can use different analysis from [Analysis] tab in DebugDiag.
Memory Analysis gives a nice report.

Friday

micosoft sql server SHRINKFILE command:

first find file_name by:
select * from sys.database_files
then:
DBCC SHRINKFILE (mydb_log, 1000) WITH NO_INFOMSGS

Thursday

C#:ActiveDirectory : Check User cannot change password

in project add COM reference to "Active DS Type Library" COM library v1.0
usually located in C:\WINDOWS\system32\activeds.tlb.


using ActiveDs;
public void CheckUserCanChangePasswordsProperty()
{
DirectoryEntry de = GetDirectoryObject(UserName);
string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
string[] trustees = { "NT AUTHORITY\\SELF", "EVERYONE" };


ActiveDs.IADsSecurityDescriptor sd =
(ActiveDs.IADsSecurityDescriptor)de.Properties["ntSecurityDescriptor"].Value;
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
ActiveDs.AccessControlEntry ace = new ActiveDs.AccessControlEntry();


double denied = (double)ActiveDs.ADS_ACETYPE_ENUM.ADS_ACETYPE_ACCESS_DENIED_OBJECT;
double objectType = (double)ActiveDs.ADS_FLAGTYPE_ENUM.ADS_FLAG_OBJECT_TYPE_PRESENT;
double dsControl = (double)ActiveDs.ADS_RIGHTS_ENUM.ADS_RIGHT_DS_CONTROL_ACCESS;

foreach (string trustee in trustees)
{
ace.Trustee = trustee;
ace.AceFlags = 0;
ace.AceType = Convert.ToInt32(Math.Floor(denied));
ace.Flags = Convert.ToInt32(Math.Floor(objectType));
ace.ObjectType = PASSWORD_GUID;
ace.AccessMask = Convert.ToInt32(Math.Floor(dsControl));

acl.AddAce(ace);
}
sd.DiscretionaryAcl = acl;
de.Properties["ntSecurityDescriptor"].Value = sd;

de.CommitChanges();
}

more...

C#:Active Directory:Uncheck User cannot change password


public void SetUserCanChangePasswordsPropertyUncheck()
{
DirectoryEntry de = GetDirectoryObject(UserName);
string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
ActiveDs.IADsSecurityDescriptor sd =
(ActiveDs.IADsSecurityDescriptor)de.Properties["ntSecurityDescriptor"].Value;
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
//ActiveDs.AccessControlEntry ace = new ActiveDs.AccessControlEntry();
ActiveDs.ADS_ACETYPE_ENUM aceType;

//look for existing ace and get rid of
foreach (ActiveDs.AccessControlEntry ace in acl)
{
if (!(ace.ObjectType == null) && ace.ObjectType.ToLower() == PASSWORD_GUID)
{
if (ace.Trustee == "Everyone")
{
acl.RemoveAce(ace);
de.CommitChanges();
}
else if (ace.Trustee == "NT AUTHORITY\\SELF")
{
acl.RemoveAce(ace);
de.CommitChanges();
}
}
}

//now put in the one we want
sd.DiscretionaryAcl = acl;
de.Properties["ntSecurityDescriptor"].Value = sd;
de.CommitChanges();
}

more...

C#:Active Directory:Check/Uncheck Password never expires


public void SetPasswordNeverExpiresProperty(bool PasswordNeverExpires)
{
DirectoryEntry de = GetDirectoryObject(UserName);
if (PasswordNeverExpires)
{
ActiveDirectoryHelper.SetProperty(de, "userAccountControl",
(int)de.Properties["userAccountControl"].Value | 0x10000);
}
else
{
ActiveDirectoryHelper.SetProperty(de, "userAccountControl",
(int)de.Properties["userAccountControl"].Value ^ 0x10000);
}
de.CommitChanges();
}

more...

C#:Active Directory:Check/Uncheck User must change password at next logon



public void SetuserHasToChangePasswordsInTheNextLoginProperty(bool userHasToChangePasswordsInTheNextLogin)
{
DirectoryEntry de = GetDirectoryObject(UserName);
if (userHasToChangePasswordsInTheNextLogin)
{
ActiveDirectoryHelper.SetProperty(de, "pwdLastSet", 0);
}
else
{
ActiveDirectoryHelper.SetProperty(de, "pwdLastSet", -1);
}
de.CommitChanges();
}

more...

treeview .net control style



<table> <tr> <td style="border: solid 1px;">
<div style="overflow:scroll;height:200px">
<asp:TreeView PopulateNodesFromClient = "true" EnableClientScript = "true"
ID="WebTreeView1" runat="server" ShowCheckBoxes="Leaf" Width="100%"
NodeStyle-ForeColor="DarkBlue"
NodeStyle-Font-Names="Verdana"
NodeStyle-Font-Size="8pt"
NodeStyle-HorizontalPadding="5"
NodeStyle-VerticalPadding="0"
NodeStyle-BorderColor="#FFFFFF"
NodeStyle-BorderStyle="solid"
NodeStyle-BorderWidth="0px"
RootNodeStyle-Font-Bold="true"
SelectedNodeStyle-BackColor="#cccccc"
SelectedNodeStyle-BorderColor="#888888"
SelectedNodeStyle-BorderStyle="solid"
SelectedNodeStyle-BorderWidth="0px"
ShowLines="True"
NodeIndent="15"
ExpandDepth="1"
PathSeparator="|"
>
</asp:TreeView>
</div>
</td></tr></table>

more...

asp.net treeview load expanded and keep selection

 

TreeNode newNode = new TreeNode();
string title=string.Format("{0};{1};{2};{3}", row["Field1"], row["Field2"], row["Field3"], row["Field4"]);
newNode.Text=string.Format("<input type='hidden' value='{0}'><span title='{0}' onclick='return false;'>{1}</span>;",title,Bezeichnung);
string val=string.Format("{0}",row["NameGroupID"]);
newNode.Value =val;
newNode.Checked=stored.Contains(val);
newNode.Expand();
ProduktbereichNode.ChildNodes.Add(newNode);

more...

asp.net treeview javascript search

Backward search:
 

function SearchBack(tv_id,str)
{
var tree = document.getElementById(tv_id);
var treeLinks = tree.getElementsByTagName('A');
eval(' var sel_name = '+tv_id+'_Data.selectedNodeID.value;');
var elem;
var sel_passed=0;
for(var element in treeLinks )
{
var sub1=treeLinks[element].firstChild;

if (sel_name && treeLinks[element].id==sel_name) {
sel_passed =1;
if (!sel_name || sel_passed==1) break;
}
if (sub1 && (''+sub1.value).indexOf(str) >=0)
{
//log("found"+treeLinks[element].id);
elem=treeLinks[element];
}
}

if (elem) {
eval('TreeView_SelectNode('+tv_id+'_Data,elem,"'+elem.id+'");');
elem.focus();
}else{
alert('Not found');
}
}


Forward search:
 

function SearchForward(tv_id,str)
{
var tree = document.getElementById(tv_id);
var treeLinks = tree.getElementsByTagName('A');
eval(' var sel_name = '+tv_id+'_Data.selectedNodeID.value;');
var elem;
var sel_passed=0;
for(var element in treeLinks)
{
var sub1=treeLinks[element].firstChild;
if (sub1 && (''+sub1.value).indexOf(str) >=0)
{
//log("found"+treeLinks[element].id);
elem=treeLinks[element];
if (!sel_name || sel_passed==1) break;
}

if (sel_name && treeLinks[element].id==sel_name) {
sel_passed =1;
}
}
if (elem) {
eval('TreeView_SelectNode('+tv_id+'_Data,elem,"'+elem.id+'");');
elem.focus();
} else{
alert('Not found');
}


}

Saturday

Add Winmerge to TortoiseHg as default merge tool

1.Right mouse click on repository, select TortoiseHg >> Global setting
2.in Open Dialog select "User Global Setting" and Click "Edit"
3.Add these two lines at end of file :

[extdiff]
cmd.winmerge = C:\Program Files\WinMerge\WinMerge.exe
opts.winmerge = /e /x /ub /wl

4.Now run the Global Settings tool. On the TortoiseHg tab, you should see winmerge available
in the drop-down list for Visual Diff Command. Select winmerge, apply, then close.


more...

display DDR type memory (RAM) installed free utility

to find out which type of memory installed you can use this free utility:
1.download CPUZ from >here
2.Run and open memory tab :

listen podcast audio book faster (timesaving tip) with mplayer

First download mplayer player from http://www.mplayerhq.hu/design7/dload.html


mplayer.exe -cache 1024 -speed 1.77 %1\*.*


Other Mplayer command line samples

play shuffle-music from directory


mplayer.exe -cache 1024 -shuffle %1\*.*


Play shuffle winamp/text file list


mplayer.exe -cache 1024 -shuffle -playlist %1

more...

Tuesday

DateTime to string with milliseconds


string resTime = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff");
Console.WriteLine(resTime);

more...

Wednesday

C# linq transfer data between linq object and business layer object sample

public class myClass
{
public int RecordID { get; set; }
public string Field1 { get; set; }
}

public void GetDataAndCallBusinessMethod()
{
using (DBDataContext db = new DBDataContext)
{
IEnumerable<myClass> Recs =
from tab in db.table
select new myClass
{
RecordID = tab.RecordID,
Field1 = tab.Field1
};
BusinessLayer.Businessmethod(Recs);
}
}

Monday

c# initialize new hashtable

Hashtable ht = new Hashtable() {
{"key1", "value1"},
{"key2", "value2"}
};

Thursday

C# example:how to get version/created time of assembly

1, We need function like this :
  public string GetServerInfo(Assembly _assembly)
{
StringBuilder r = new StringBuilder();
try
{
r.AppendLine("Version:" + _assembly.GetName().Version.ToString());
r.Append("Build: " + System.IO.File.GetLastWriteTime(_assembly.Location).ToString("dd/MM/yyyy HH:mm"));
}
catch (Exception ex)
{
Logger.prn(ex);
}
return r.ToString();
}


Then we can call it like this :

Assembly _assembly = Assembly.GetExecutingAssembly();
string info= GetServerInfo(_assembly);

Sunday

mysql how to select records with unicode characters

following select returning these records:
SELECT * FROM candidate WHERE CHAR_LENGTH(first_name)<>LENGTH(first_name);


mysql and php to fix character encoding

*  call mb_internal_encoding("UTF-8") at the head of my PHP scripts
*  MySQL tables all have DEFAULT CHARSET=utf8  > COLLATE=utf8_unicode_ci
*  call mysql_set_charset('utf8') immediately after I connect to the  DB with mysql_connect().
*  call header('Content-Type: text/html; charset=utf-8') before  outputting anything to the browser.
*  specify <meta http-equiv="Content-Type" content="text/html;  charset=utf-8"/> in the HEAD of my HTML.
*  FORM tags all have accept-charset="UTF-8".



Friday

vim commands

:g/search-string/norm @h  
runs a macro recorded in h for every match of search-string

Vim-style movement:
'h' 'j' 'k' 'l' for movement (Up, Down, Left, Right)
'gg' End
'G' Home
'0' Beginning of line
'$' End of Line
'H' Top of the Screen
'M' Middle of the screen
'L' Bottom of the screen

windows using
:split command or the ^w commands:

^wn - new window

^ws - horizontal split

^wv - vertical split

^wr - rotate windows

^ww/^wW - move to the next/previous window

^w= - make all windows equal size

^wc - close the active window




Tuesday

Load controls in asp.net dynamically

1.Add placeholder to .aspx
<asp:Panel ID="PlaceHolderPanel" runat="server">
</asp:Panel>

2. add control loading code to codebehind :
string AlreadyLoaded=null;
private void loadControl(string ctr){
if (!string.IsNullOrEmpty(ctr) && AlreadyLoaded!=ctr ) {
Control ctrl = LoadControl(ctr);
ctrl.ID="ctr1";
PlaceHolderPanel.Controls.Clear();
PlaceHolderPanel.Controls.Add(ctrl);
ControlName = ctr;
AlreadyLoaded=ctr;
}

}

protected void Page_Load(object sender, EventArgs e){
loadControl("~/Controls/mycontrol.ascx");
}


There are limitations for loaded controls , one of them using onPreRender rather then Page_load:

// 1.call all functions in prerender only
protected override void OnPreRender(EventArgs e){
SetFilterValues();
Bind();
base.OnPreRender(e);
}

Saturday

C# how to use iterator


// create iterator method

public IEnumerable<decimal?> BucketIterator(Accounts_basic a ) {
int cycle = 0;
for (int i=7 ; i > 0 ; i--){

switch (i) {
case 1:yield return a.dd_15;break;

case 2 :yield return a.dd_30; break;

case 3:yield return a.dd_60; break;

case 4:yield return a.dd_90; break;

case 5 :yield return a.dd_120; break;

case 6:yield return a.dd_150; break;

case 7:yield return a.dd_180; break;

default : yield break;

}

}



// use iterator method as follows
foreach (decimal? amount in BucketIterator(accounts_basic)) {
// use amount here
}

Stored User Names and Passwords

to retrieve a list of Stored User Names and Passwords do:
C:>rundll32.exe keymgr.dll, KRShowKeyMgr

Windows can store your logon information for network locations and Web sites. To add an entry, click Add. To edit an existing entry, select it, and then click Properties.


is already mapped in workspace or removing other's working space

The path C:\Projects is already mapped in workspace PC123;DOMAIN\USER

tf workspaces /computer:PC123 /owner:* /format:detailed

And – sure enough, it looks like there’s another workspace for a different user profile – with the same PC name (PC123).
tf workspaces /computer:PC123 /owner:* /format:detailed /server:http://tfs:8080
================================
Workspace: PC123
Owner : *ME*
Computer : PC123
Comment :
Server : tfs.domain
Working folders:
====================================
Workspace: PC123
Owner : *SOMEONE-ELSE*
Computer : PC123
Comment :
Server : tfs.domain

Working folders:
$/AAA: C:\Projects
$/AAA/BBB/CCC: C:\Projects\AAA\BBB\CCC
Not sure how/why this has happened – perhaps a duplicate PC-NAME ?

Anyway – here’s the command to REMOVE the baaad workspace – clear it out all and start again.

tf workspace /delete PC123;other-user /server:http://tfs:8080
A deleted workspace cannot be recovered.
Workspace ‘PC123′ on server ‘http://tfs.8080′ has 0 pending change(s).
Are you sure you want to delete the workspace? (Yes/No) Y



Friday

vim commands

:e . Открыть встроенный файл-менеджер
:Sex Разбить окно и открыть встроенный файл менеджер
:browse e Графический файл-менеджер
:ls Список буферов
:cd .. Перейти в родительскую директорию
:args Список открытых файлов

Tuesday

Web Service set amount of Concurrent Connections

add this to web.config file:

<system.net>
<connectionManagement>
<addaddress="*"maxconnection="40"/>
</connectionManagement>
</system.net>

Friday

locked file, how to release file in use

To find out which application is using a file in Windows and to release/delete/remove/overwrite file do following:
use processexplorer and search the handles (Menu/Find/Find Handle (Crtls+F))for the file you want.
This way you can easily find which process is having a handle to your file.
Then do right click + 'Close Handle' to release locked file.

Wednesday

try catch python: error handling in python

simple error handling in python:

try:
.... your code here ....
except Exception, e:
print "Error",i,e

Sunday

List sorting by SQL ASC/DESC Extender



using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Linq.Expressions;

public static class Extenders
{
public static List<T> Sort<T>(this List<T> source, string sortExpression)
{
string[] sortParts = sortExpression.Split(' ');
var param = Expression.Parameter(typeof(T), string.Empty);
try
{
var property = Expression.Property(param, sortParts[0]);
var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);

if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
{
return source.AsQueryable<T>().OrderByDescending<T, object>(sortLambda).ToList<T>();
}
return source.AsQueryable<T>().OrderBy<T, object>(sortLambda).ToList<T>();
}
catch (ArgumentException)
{
return source;
}
}
}

linq select into class list

let's say we have following class:

public class GridCell {
public string page_name{get;set;}
public string link_code { get; set; }
public int page_state { get; set; }
public int landing_pages_id { get; set; }

}

and want to create list of these classes , to bind them to grid for example :
LandingPagesDataContext lpdc = new LandingPagesDataContext();
var query = from p in lpdc.landing_pages
select new { p.page_name, p.link_code, p.page_state, p.landing_pages_id };
bind(query.Select(p=>new GridCell{page_name = p.page_name, link_code = p.link_code, page_state = p.page_state, landing_pages_id = p.landing_pages_id }).ToList<GridCell>());

Wednesday

find lines from one file into another

How to find lines from one file into another ?
here is sample script showing lines from "find.txt" file those are into "findinto.txt"

common.py find.txt findinto.txt


import os
import re
import sys

fileHandle = open (sys.argv[1])
linesToPatch = fileHandle.readlines()
f = open(sys.argv[2])

for aline in f:
for rline in linesToPatch:
p=re.compile(rline.strip())
if p.search(aline.strip()):
print aline

Monday

SQL Next business Day Function


-- get next business day
-- assumption: first day of the week is Sunday
CREATE FUNCTION NextBusinessDay
(@date DATETIME)
RETURNS VARCHAR(12)
AS
BEGIN
DECLARE @date1 DATETIME,
@m INT
SELECT @date1 = @date, @m = 0
WHILE @m < 1
BEGIN
SET @date1 = DATEADD(DD,1,@date1)

/* ** the following line checks for non-business days (1 and 7)
** IF your business days are different, change the following line to
** comply with your schedule
*/
IF DATEPART(DW,@date1) NOT IN (1,7)
BEGIN
SET @m = @m + 1
END
END

RETURN CAST(@date1 AS VARCHAR(12))
END

JQuery Autocomplete plugin , nice and easy to implement


nice and easy to implement JQuery Autocomplete plugin

javascript:unescape/escape: decode/encode URL characters


<script type="text/javascript">
alert (unescape('Hello%20World'));
alert (escape('Hello World'));
</script>

Tuesday

Microsoft.AnalysisServices.AdomdClient.AdomdErrorResponseException

When trying to connect to Analysis Services 2005 I was getting this error:

Microsoft.AnalysisServices.AdomdClient.AdomdErrorResponseException: Either the user, NT
AUTHORITY\NETWORK SERVICE, does not have access to ...

I have solved this problem by :
1.logging with "Microsoft SQL Server Management Studion" to Analysis Server
2.expanded "Roles"
3.created new "admin" role with Administration priveleges
4.added "Network Service" as Member of this role.

Monday

return table from stored procedure

To return table from stored procedure:
declare value as table in sql and fill it from stored procedure by insert..execute like in this code below:

DECLARE @Accounts1 AS TABLE
(
customer NUMERIC(9, 0),
sub TINYINT,
tp1 VARCHAR(100)
)


insert into @Accounts1
execute usp_AccountDifferentialReportSelector @Did,@CycID

to get data from datasource declared in aspx


public bool OrderExists(int order_index) {
DataView dv1 = (DataView)CategoriesDataSource.Select(new DataSourceSelectArguments());
foreach( DataRow d in dv1.Table.Rows){
if ((int)d["order_index"] == order_index) {
gvMerchantCategoriesLabel.Text = "Update Not Successful, Order Index Already exists";
gvMerchantCategoriesLabel.Style.Add("color", "#FF0000");
return true;
}

}
return false;
}

C# find text in .net grid Rows


public bool OrderExists(int order_index)
{
foreach (GridViewRow r in gvMerchantCategories.Rows)
{
int ord1 = 0;
if (int.TryParse(r.Cells[2].Text, out ord1) && ord1 == order_index)
{
gvMerchantCategoriesLabel.Text = "Update Not Successful, Order Index Already exists";
gvMerchantCategoriesLabel.Style.Add("color", "#FF0000");
return true;
}
}

}

Thursday

replacing non-english symbols with equivalent (removing Diacritics)

namespace Remove {
using System;
using System.Text;
using System.Globalization;
  class Remove {
    [STAThread]
    static void Main(string[] args) {
      foreach(string st in args) {
        Console.WriteLine(RemoveDiacritics(st));
      }
    }

    static string RemoveDiacritics(string stIn) {
      string stFormD = stIn.Normalize(NormalizationForm.FormD);
      StringBuilder sb = new StringBuilder();

      for(int ich = 0; ich < stFormD.Length; ich++) {
        UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
        if(uc != UnicodeCategory.NonSpacingMark) {
          sb.Append(stFormD[ich]);
        }
      }

      return(sb.ToString().Normalize(NormalizationForm.FormC));
    }
  }
}

Tuesday

sql select comma delimited field as one row


SELECT TOP 10
hphone + ', ' as [text()]
from
person
for
xml path('')

vb6 command line options


vb6 command line options

dot net resources

  • IoC: Ruby Unity Castle Spring.net Autofac NInject StructureMap


  • Mock-фреймворки: Typemock Isolator Rhino Mocks NMock Moq

  • VS расширения: ReSharper BooLangStudio Nemerle IronPython Studio SPVisualDev


  • Цвет: Schemes Vibrant Ink

  • Разбор: Reflector NDepend

  • TDD: Gallio (MbUnit) NUnit TestDriven.net NBehave


  • Source control: Google Code Codeplex GitHub SourceForge

  • секция .Net на Хабрахабр блоги на GotDotNet ITCommunity


  • CodeBetter CodeProject StackOverflow
  • NT AUTHORITY\NETWORK SERVICE does not have write access

    When you have created virtual directory of your application created in .Net2.0 and application is not running.
    Even everything is fine in web.config, still it is giving error in web.config file.

    Error :- The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'.

    Solution is :
    goto command prompt then navigate to directory
    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

    Now run this command

    aspnet_regiis -ga "NT AUTHORITY\NETWORK SERVICE"


    Friday

    call webservice from sql function

    here is function allowing you to do so:
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[Call_WebService] (@inId AS VARCHAR(50))
    RETURNS XML
    AS BEGIN

    DECLARE @Object AS INT ;
    DECLARE @ResponseText AS VARCHAR(8000) ;
    DECLARE @Url AS VARCHAR(MAX) ;

    SELECT @Url = 'http://myserver/CCRequestProxy.aspx?RequestID=' + @inId

    EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT ;
    EXEC sp_OAMethod @Object, 'open', NULL, 'get', @Url, 'false'
    EXEC sp_OAMethod @Object, 'send'
    EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
    EXEC sp_OADestroy @Object
    EXEC sp_OAStop ;


    --load into Xml
    DECLARE @XmlResponse AS XML ;
    SELECT @XmlResponse = CAST(@ResponseText AS XML)
    RETURN @XmlResponse

    END

    disable cache on asp page

    add following instruction on top of the page
    <%@ OutputCache Location="None" VaryByParam="None" %>

    Thursday

    Relevance in Fulltext Search

    Create Fulltext index first:
    CREATE FULLTEXT INDEX indx_text
    ON attachment (text)

    Add relevance field for select:
    SELECT MATCH('text') AGAINST ('financial') as Relevance FROM attachment WHERE MATCH
    ('text ') AGAINST('+financial +bank' IN
    BOOLEAN MODE) HAVING Relevance > 0.2 ORDER
    BY Relevance DESC

    full search documentation

    SQL update with join : update table with count from another table

    let's say we have two tables connected like this:
    SELECT a.saved_list_id, COUNT(b.saved_list_entry_id)
    FROM saved_list a
    LEFT OUTER JOIN saved_list_entry b ON (a.saved_list_id = b.saved_list_id)
    GROUP BY a.saved_list_id;

    so update will be looking like follows:
    update saved_list p JOIN saved_list_entry c ON p.saved_list_id = c.saved_list_id
    SET p.`number_entries` = (SELECT count(saved_list_entry_id) as number_entries
    FROM saved_list_entry c where c.saved_list_id = p.saved_list_id)

    Monday

    Team Foundation Server (TFS) - How to see history of whole project or see last changed files

    How to see history of whole project in Team Foundation Server (TFS) or see last changed files:
    -Locate Team Foundation Server Client -tf.exe file, usually located into
    "c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\TF.exe"
    -Run this from console inside project:
    "c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\TF.exe" history /recursive *
    it will return list of changesets,click on changeset to view list of files

    Tuesday

    alter table with check constraint


    SET ANSI_PADDING OFF
    GO
    ALTER TABLE [dbo].[web_contracts] WITH NOCHECK ADD CONSTRAINT [CK_web_contracts] CHECK NOT FOR REPLICATION (([payment_source]=(3) AND len(isnull([eft_routing_number],''))=(9)))
    GO
    ALTER TABLE [dbo].[web_contracts] CHECK CONSTRAINT [CK_web_contracts]
    GO
    EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Routing number is not specified' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'web_contracts', @level2type=N'CONSTRAINT',@level2name=N'CK_web_contracts'

    ASP.NET/csharp:FileUpload inside AJAX Update panel

    To make it working it's required :
    1.Created interface:

    public interface ITriggerable {
    void RegisterPostbackTrigger(Control parent,Control trigger);
    }


    2.implement this interface on page containing ajax update panel:

    public void RegisterPostbackTrigger(Control parent,Control button){
    PostBackTrigger trigger = new PostBackTrigger();
    trigger.ControlID =((Button) button).UniqueID;
    UpdatePanel1.Triggers.Add(trigger);
    }


    3.Add button inside of control as trigger:

    protected override void OnInit(EventArgs e){
    base.OnInit(e);
    ((ITriggerable)this.Page).RegisterPostbackTrigger(this, btnRename);
    }

    WebRequest Exception 401: The remote server returned an error: (401) Unauthorized.

    it's required to add default credentials:
    request.Credentials = CredentialCache.DefaultCredentials;
    See this post for complete source.

    Charp (C#):validate http links



    public bool ImageExists(string url) {
    Uri urlCheck = new Uri(url);

    WebRequest request = WebRequest.Create(urlCheck);
    request.Credentials = CredentialCache.DefaultCredentials;

    request.Timeout = 15000;

    WebResponse response;
    try {
    //get URL web response
    response = request.GetResponse();
    return true;
    }
    catch (Exception){
    return false; //url does not exist
    }
    }

    JQuery working inside UpdatePanel

    To make jquery works inside Update panel you have to add handler to updatepanel reload with restorig jquery bindings :

    1. create jquery binding function , to specific links for example:

    function re_init(p1,p2){
    $('a[name=modal]').click(function(e) {
    // Add your jquery bindings here
    // ...
    //
    }
    }


    2 on document ready add handling UpdatePanel reload

    $(document).ready(function() {
    re_init(null,null);
    // add re-initialisation after update panel reloading
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(re_init);
    });

    Friday

    authentication in active directory


    using System.Security;
    public User Login(string login_name, string password){
    ICredValidator cv = new LdapCredValidator(); //LanCredValidator();
    User u = new User(conn);
    if (cv.ValidateCred("MY-DOM", login_name, password))
    {
    // validation sucess
    }else Throw("Login failed for {0}",login_name);
    return u;
    }

    active directory - get computer lists



    public void AD_ComputerList()
    {
    DirectoryEntry entry = new DirectoryEntry("LDAP://my-dom");
    DirectorySearcher mySearcher = new DirectorySearcher(entry);
    mySearcher.Filter = ("(objectClass=computer)");
    Console.WriteLine("Listing of computers in the Active Directory");
    Console.WriteLine("============================================");
    foreach(SearchResult resEnt in mySearcher.FindAll())
    {
    Console.WriteLine("Name: {0}", resEnt.GetDirectoryEntry().Name.ToString());
    }
    Console.WriteLine("=========== End of Listing =============");

    }

    C# how to get current windows login


    public void WinIdentity() {
    System.Security.Principal.WindowsIdentity i = System.Security.Principal.WindowsIdentity.GetCurrent();
    Console.WriteLine("name: {0}, token: {1}", i.Name, i.Groups[0].ToString());
    Assert.IsNotNull(i);
    }

    webservice logging incoming/outgoing data

    add following to web.config under system.web

    <httpModules>
    <add name="RequestResponseLogger" type="LoggingFilter, LoggingFilter"/>
    </httpModules>
    <customErrors mode="Off"/>
    </system.web>
    <microsoft.web.services2>
    <diagnostics>
    <trace enabled="true" input="D:\Logs\in.txt" output="D:\Logs\out.txt"/>
    </diagnostics>
    </microsoft.web.services2>
    </configuration>

    php function for dot.net webservice submission




    <?
    function web_service($serv,$plain_data){
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, "https://myserver.com/myService.asmx/".$serv);
    curl_setopt($curl_handle, CURLOPT_HEADER, 1);
    curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl_handle, CURLOPT_POST, 1);
    curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $plain_data);
    $response = curl_exec ($curl_handle) or die ( "There has been an error connecting");
    #echo $response;
    curl_close ($curl_handle);
    $response= strstr($response, '<?xml version="1.0" encoding="utf-8"?>');
    $re = str_replace('&gt;','>',str_replace('&lt;','<',$response));
    $re1= str_replace('<string xmlns="http://tempuri.org/">',"<string>",$re);

    return $re1;
    }


    function web_method($f,$u){

    $data="Subscriber=".$f['studid']."&Affiliate=".$u['referral']
    $re1= msi_service("MyMethodName1",$data);
    $xml = simplexml_load_string($re1);
    $result = $xml->xpath("/string"); // <- parsing result
    foreach($result as $result_code) {
    return $result_code;
    }
    return $re1;
    }
    ?>



    here is post how to configure web service to allow remote post/get submission

    rework dynamic sql into stored procedure with optional parameters


    CREATE PROCEDURE TestProc
    (
    @Param1 varchar(50) = NULL,
    @Param2 varchar(50) = NULL,
    @Param3 varchar(50) = NULL
    )
    AS
    SELECT
    *

    FROM
    TestTable

    WHERE
    ((@Param1 IS NULL) OR (col1 = @Param1)) AND
    ((@Param2 IS NULL) OR (col2 = @Param2)) AND
    ((@Param3 IS NULL) OR (col3 = @Param3))


    Monday

    c# property with using cache (expiration added)



    public static int CacheDyration = 10;
    /// <summary>
    /// Cached Merchant table
    /// </summary>
    public static Hashtable MerchantHash
    {
    get
    {
    Hashtable retValue = null;
    // Check if cache has Merchant saved
    if (HttpContext.Current.Cache["MerchantHash"] != null)
    { // Return cached version
    retValue = (Hashtable)HttpContext.Current.Cache["MerchantHash"];
    }
    else
    {
    // initializing new instance, you can change this initialization with using BLL classes
    MerchantTableAdapter da = new MerchantTableAdapter();
    retValue = Hashmaker.Hash(da.GetData(), "merchant_id", "merchantname");
    if (retValue.Count > 0)
    {
    HttpContext.Current.Cache.Insert("MerchantHash", retValue, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, CacheDyration, 0));
    }

    }
    return retValue;
    }

    set
    { // Check if item is already in there
    if (HttpContext.Current.Cache["MerchantHash"] != null)
    {
    // Remove old item
    HttpContext.Current.Cache.Remove("MerchantHash");
    } // Place a new one
    HttpContext.Current.Cache.Insert("MerchantHash", value, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, CacheDyration, 0));
    }
    }

    clear cache in ASP.NET VB.NET


    Private Sub ClearCache()
    For Each CacheKey As DictionaryEntry In Cache
    If CacheKey.Key.GetType.Equals(GetType(System.String)) Then
    Dim MyKey As String = CacheKey.Key
    Cache.Remove(CacheKey.Key)
    End If
    Next
    End Sub

    more...

    Tuesday

    Duplicate filename:7z:creating archive files from list

    you have list of files from differen folders in text file.

    To create zip archive use this command:
    "c:\Program Files\7-Zip\7z.exe" a  -tzip archive.zip  @c:\listfile.txt

    when you get error Duplicate filename:  because of file with the same name in different folders, remove drive name  from list file.


    Sunday

    System.Data.StrongTypingException

    to fix this exception in strong-type dataset use method IsNull method before reading value to avoid this exception.

    in C# it will be like :
    if (!logins[0].Isincorrect_attempt_dateNull())
    {
     incor_pass_hours_ago = DateTime.Now.Subtract((DateTime)logins[0].incorrect_attempt_date).TotalHours;
    }


    fix "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."

    Use System.Data.SqlTypes.SqlDateTime.MinValue.Value  insted DateTime.MinValue and System.Data.SqlTypes.SqlDateTime.MaxValue.Value instead DateTime.MinValue.


    Saturday

    to transfer file by pscp (putty scp) to sftp (secured ftp) server:

    source file: source1.txt
    server ip : 61.155.5.15
    server shh port : 2222
    destination file:d\target1.txt

    command line: 
    pscp  -l al -P 2222 source1.txt user@67.155.5.15:d\target1.txt

    pscp help:

    PuTTY Secure Copy client
    Release 0.57
    Usage: pscp [options] [user@]host:source target
           pscp [options] source [source...] [user@]host:target
           pscp [options] -ls [user@]host:filespec
    Options:
      -p        preserve file attributes
      -q        quiet, don't show statistics
      -r        copy directories recursively
      -v        show verbose messages
      -load sessname  Load settings from saved session
      -P port   connect to specified port
      -l user   connect with specified username
      -pw passw login with specified password
      -1 -2     force use of particular SSH protocol version
      -C        enable compression
      -i key    private key file for authentication
      -batch    disable all interactive prompts
      -unsafe   allow server-side wildcards (DANGEROUS)
      -V        print version information
      -sftp     force use of SFTP protocol
      -scp      force use of SCP protocol


    Wednesday

    python post example



    from httplib2 import Http
    from urllib import urlencode

    url = 'http://de.gigajob.com/req.ax'
    #body = {'USERNAME': 'foo', 'PASSWORD': 'bar'}
    #headers = {'Content-type': 'application/x-www-form-urlencoded'}
    body={'xajax':'ajax_get_sgd_html_display' ,'xajaxargs':'<xjxobj><e><k>searchword</k><v>C%23</v></e><e><k>zip</k><v></v></e><e><k>adtype</k><v>offer</v></e><e> <k>distance</k><v>25</v></e><e><k>country</k><v>all</v></e><e><k>language</k><v>de</v></e><e><k>page</k><v>1</v></e><e><k>sort</k><v>age</v></e><e><k>location</k><v></v></e><e><k>age</k><v>999</v></e></xjxobj>' ,'xajaxargs':'1' ,'xajaxargs':'1' ,'xajaxr':'1234400546535'}
    h = Http()
    response, content = h.request(url,'POST',urlencode(body))
    print response
    print content


    more...

    Friday

    easy_install.exe for Python 2.6 on Windows

    get ez_setup.py and setuptools-0.6c9-py2.6.egg.
    type: python ez_setup.py setuptools-0.6c9-py2.6.egg and that should get setuptools installed.
    2. Now that you have setuptools installed, in your Python 2.6 directory there is a directory called Scripts. If you go to that directory (C:\Python26\Scripts on the systems I worked on) you’ll see easy_install.exe.

    make ubuntu business casual

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