Posts

Resumeable Windows File Copying

Recently having need to copy huge files or a whole set of files more often over the network. Thinking of finding a tool like getright. So, this is the tool I found really useful. Robocopy - http://en.wikipedia.org/wiki/Robocopy How it fit my usage is with command like below. robocopy \\source\dir \\destination\dir /W:15 /R:30 /E /Z W = 15 seconds pause should it failed R = Retry of 30 times Z = Restartable mode E = Copying content recursively (including subfolders content) (use /MIR if want to mirror both side of content instead of /E. /MIR would remove the destination file if not found in source)

Adding notepad, command prompt, powershell run here context menu

Create a text file, name it temp.reg. Then, for each application you want to add it context menu. Copy and paste to the temp.reg. Then, just execute the temp.reg by double clicking it. For Powershell -------------- Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\Directory\shell\powershell]@="PowerShell Here"[HKEY_CLASSES_ROOT\Directory\shell\powershell\command]@="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%L'" Command Prompt ----------------- Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Directory\shell\CommandPrompt] @="Command Prompt Here" [HKEY_CLASSES_ROOT\Directory\shell\CommandPrompt\command] @="C:\\Windows\\system32\\cmd.exe /k pushd %1" Notepad ---------- Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\Edit in Notepad] [HKEY_CLASSES_ROOT\*\shell\Edit in Notepad\command] @="notepad.exe \"%l\""

Searching word/phrase in a very large text file in windows

1. Firstly, you need to have a grep tool (like Unix). For windows, you can try http://www.wingrep.com/ 2. Then, you just search a word/phrase in the text file with simple query or advanced regular expression query in the wingrep. 3. You should be getting the line number in the grep search result. 4. Then, start dos prompt. 5. Type command - "more +123 YourHugeFile.txt" where 123 for example is the line number you wish to see starting from. 6. Then, you should see some content in "more" dos screen. 7. If you wish to scroll line by line in "more", key in "enter/ret". if you wish to go page by page, key in "space" 9 Once you are done, type "CTRL + C" to exit.

Virtual PC setting - resetting MAC address.

In the case where you would want to change the IP address by forcing the DHCP to re-assign a new IP to you Virtual PC. (or in the case you are using the same *.vmc file and you don’t bother to recreate a new one) Stop your virtual machine. Then, in your *.vmc, look for <ethernet_card_address type="bytes">0003FFxxxxxx</ethernet_card_address> Remove the number so the line appears as follows: <ethernet_card_address type="bytes"></ethernet_card_address> After you remove the number, Virtual PC will create a new MAC address the next time you start the virtual machine. And in turn, DHCP will assign u a new IP address for your virtual machine.

SQL server IDENTITY and seed

One can make a column to be auto increment by setting it as identity. CREATE TABLE dbo.MyTable ( MyID int identity(1,1), MyName nvarchar(20) ) One can make it start from certain number by setting the seed identity(1000, 1) So, the first row would have id 1001 One can also increase the seed even with some data in the table say already the record run up to 102. If set seed to 200, the next record id would be 201. (one catch is if seed is 1, it will start with 1. But if seed as 11, it will start at 12.) Also one note is that the seed can not be smaller than the existing one as it would not make any changes. (the existing seed number can be check in the property of the column) For reseting the identity seed. The DBCC command is needed like DBCC CHECKIDENT('MyTable', RESEED, 1) It will attempt to start over from 1 and if found some ID with the same number exist, it will skip that ID and use next number. (This is done by the MSSQL in best effort mode. It is not predictable and guaran...

Getting started powershell

After installing powershell 1.0. The $profile will not be added. The $profile is equivalent to .profile in ksh where it initialized when it started. So, to add it. You need to specify permission first (like below), then, create the $profile. (you can echo $profile to see where the file resides in the windows) Set-ExecutionPolicy RemoteSigned new-item -path $profile -itemtype file -force

Fix login of restored DB (SQL server 2005)

After when restored Database from *.bak file. The associated login will not be restored into the MSSQL. And when trying to create the same login in the security tab in managemement studio. It will prompt Error 15023: User already exists in current database. The off hand workaround that normally one would do would be drop the user in the database user login and recreate again. like USE YourDB GO EXEC sp_dropuser 'YourRestoredDBLogin' GO The better way would be run command below to check the orphan logins. USE YourDB GO EXEC sp_change_users_login 'Report' GO then below to restored the login with command below. It will retain the settings that you have. USE YourDB GO EXEC sp_change_users_login 'Auto_Fix', 'YourRestoredDBLogin', NULL, 'YourRestoredDBLoginPassword' GO Reference: http://blog.sqlauthority.com/2007/02/15/sql-server-fix-error-15023-user-already-exists-in-current-database/

Winmerge - To be able to see non English characters in compare windows

Firstly, Change your windows Language for non-unicode program to the language you want.(In Regional and Language Option in control. refer Windows Help file) Then, In winmerge – Edit – Options – Codepage (tab) Tick ‘According to WinMerge User Interface’ Then, In View – Select Font – choose the font which has needed font script. E.g. CHINESE_GB2312 for simplified chinese Then In winmerge – Edit - Refresh Selected (if you are already viewing something.) and no restart required to see the changes.

Win32 SendMessage equivalent in Javascript

Problem Statement: Custom control written in Javascript can't immediate trigger the onchange event if the textbox control are updated using the code. e.g. ctrl.value = "123"; It will only trigger the onchange when move focus to another control. Solution: Win32 SendMessage equivalent in Javascript IE: element.fireEvent('onchange'); And via DOM2 Events (for Gecko): var evt = document.createEvent('HTMLEvents'); evt.initEvent('change', true, true); element.dispatchEvent(evt);

Eclipse CVS Repository Integration Watch Out

Eclipse has CVS version control integrated. It is nifty but some watch out to be careful of. 1. Always Refresh your project/ whole thing in the project view before performing Team - Synchronize With Repository or else you would not see your changes during synchronization and causing your changes GONE if you choose to update the files thinking your side have no changes!!! 2. Always use synchronize to check the changes. NEVER use the update (to overwrite local file with changes from server) or commit (to overwrite server/remote files with local file changes) to a folder directly. You would cause either server version get overwritten by your version if there are additional changes by others or your version get overwritten by server copy without doing the conflict checking and merge. 3. If you have already merged the changes (by comparing remote file and local file and use move change facility), your side with the server. Select ‘mark as merge’ and then commit.

MSSQL GROUP_CONCAT

This is using XML feature of the SQL server. (nothing new here) select Type, RestaurantNames from Restaurant AS A CROSS APPLY (SELECT RestaurantName + ',' FROM Restaurant AS B WHERE A.Type = B.Type FOR XML PATH('')) D (RestaurantNames) GROUP BY Type, RestaurantNames This is to get something like below (similar to MYSQL GROUP_CONCAT) Type |RestaurantNames ----- --------------- Chinese Food | Ah Yat Abalone, Liang Yah Yong Tau Foo, Indian Food | Kanna Curry House, Western Fast Food | Burger King, McDonald instead of multiple rows. like Type |RestaurantName ----- --------------- Chinese Food |Ah Yat Abalone Chinese Food |Liang Yah Yong Tau Foo Indian Food |Kanna Curry House

ASP.NET i18n setting.

web.config <globalization requestencoding="utf-8" responseencoding="utf-8" fileencoding="utf-8"></globalization> If UTF-8 does not solve the problem for some reasons or feeling it is too consuming bytes since it standardize to 2 bytes. use each language codec (multibyte mode) by specify. <globalization requestencoding="euc-jp" responseencoding="euc-jp" enablebestfitresponseencoding="true"></globalization> Note: the language codec must be installed of course in the first place.

Truncate String in XSL call-template

The purpose is to just prune the string and add ... at the end when certain size of the string in xsl output exceeded. This method do not burden CPU much. (as some using recursive ways do) <!-- include this into XSL stylesheet --> <xsl:template name="fixed-string"> <xsl:param name="targetVar"> <xsl:param name="allowable-length"> <xsl:value-of select="substring($targetVar, 1, $allowable-length)"> <xsl:if test="string-length($targetVar) & gt ; $allowable-length"> <xsl:text>...</xsl:text> </xsl:if> </xsl:value-of></xsl:param></xsl:param></xsl:template> To use it, just <xsl:call-template name="fixed-string"> <xsl:with-param name="targetVar">'<xsl:value-of select="MyContent">'</xsl:value-of> <xsl:with-param name="allowable-length" select="15"> <!-- say, limited to 15 char...

Press anykey to continue

Taken from http://www.codeproject.com/useritems/PressAnyKeyToContinue.asp private void FlushConsole() { while( Console.In.Peek() != -1 ) { Console.In.Read(); } } Console.WriteLine("Press any key to continue..."); FlushConsole(); Console.Read();

Crystal Report Formula - ToWords - Remove 'xx/100' the trailing string.

Left(ToWords(Sum ({YourTable.Field})), InStr(ToWords(Sum ({YourTable.Field})), " and ")) & " and " & ToWords(ToNumber (Right(ToText(Sum ({YourTable.Field})), 2 )), 0) & " cents."

LPAD in T-SQL and Crystal Report Formula

I am sure there should have some neater ways to do this but if all you need are just working version, here it goes. T-SQL REPLICATE('0', 8 - LEN(LTRIM(STR(YourTableField)))) + LTRIM(STR(YourTableField)) Crystal Report Formula StringVar Message := ""; StringVar Num := {YourCrystalReportTable.Field}; Num := Trim (Num); NumberVar Counter := 8 - Length(Num) ; While (Counter > 0) do ( Message := Message & "0"; Counter := Counter - 1; ); Message := Message & Num

Workflow in ASP.NET

Same codes except placing static variable static WorkflowRuntime wr = new WorkflowRuntime(); in Application_Start of global.asax then (quoted from MSLearning) If you use the WorkflowWebRequestContext object to access the workflow runtime, you cannot add services such as persistence or scheduling services because the workflow is already started. If you try to add services to the runtime when it has already started it will generate an error. Instead, to configure the runtime with services, use the <workflowRuntime> section in the Web.config file: [Web.config] <configuration> <configSections> <section name="WorkflowRuntime" type="WorkflowRuntimeSection, System.Workflow.Runtime" /> </configSections> </configuration>

Host Workflow in .NET WinForm

Add reference to - System.Workflow.Activities - System.Workflow.Runtime - System.Workflow.ComponentModel - <the MyWorkflow assembly> in the WinForm codes, add member variable WorkflowRuntime myWorkflowRuntime = new WorkflowRuntime() Then, in the constructor of the winform. //setup event handler myWorkflowRuntime.WorkflowCompleted += new EventHandler<WorkflowCompletedEventArg>(wr_WFCompleted); myWorkflowRuntime.WorkflowTerminated += new EventHandler<WorkflowTerminatedEventArg>(wr_WFTerminated); //handler for the workflow thread. void wr_WFCompleted(object sender, WorkflowCompletedEventArg e) { MessageBox.Show("Workflow output" + e.OutputParameters["Field"].ToString()); } //to kick start the work flow thread. Type type = typeof(MyNamespace.MyWorkflow); //to pass parameter to the workflow thread. Dictionary<string, object> param = Dictionary<string, object>; param.Add("Field", System.Convert.ToInt32(123)); WorkflowInst...

WPF sample

(Nothing new, codes taken from MSLearning) <Application x:Class="MyApp" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="Window1.xaml"> Startup="MyApp_Startup" Activated="MyApp_Activated" Deactivated="MyApp_Deactivated" SessionEnding="MyApp_SessionEnding" Exit="MyApp_Exit" </Application> C# public class MyApp : Application { StackPanel rootPanel; Window win; protected override void OnStartup(StartupEventArgs e) { win = new System.Windows.Window(); rootPanel = new StackPanel(); win.Content = rootPanel; win.Show(); } void MyApp_Startup (object sender, StartupEventArgs e) { //singleton model and where sharing information pages uses Properties. MyApp.Current.Properties["TextFromPage1"] = txtBox.Text; // Retrieve the...

Hosting WPF (Avalon Control) in WinForm quick info

Though this code snippet already available in the Win SDK sample. //the host should be a private member variable. ElementHost host = new ElementHosy(); host.Dock = DockStyle.Fill; myPanel.Controls.Add(host); //adding the control the panel control in the winform. //the variable datatype available after added reference //to the WPF/Avalon control and WPF namespace) avControl = new MyNamespace.MyAVControl(); avControl.InitializeComponent(); host.Child = avControl; //control has been linked to the winform //The RoutedEventHandler is used because the WPF in this case is a //child control. There are 3 type of event routing namely direct, tunnel and bubble. //refer http://msdn2.microsoft.com/en-us/library/ms742806.aspx#why_use //for more info on the event on WPF. avControl.Loaded += new RoutedEventHandler(avCtrl_Loaded); //To use Avalon control in Win32 which wrap the Avalon control into HwndSource //refer http://blogs.msdn.com/nickkramer/archive/2005/07/17/439659.aspx