Posts

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

Unix Debugging Cheat Sheet

pmap To check the memory address mapping of the core dumped process. e.g. 036AA000 2592k [heap] So, it means 036AA000 and above is heap address. FFB3A000 [stack] And likewise. Also can be used to check shared memory, shared libraries used and etc. truss -d -o -p System API trace. gcore - o Force core dump Use dbx later to investigate the core file. pstack call stack. ps -ef getting running process PID. Monitor system log file. tail -f /var/adm/SYSLOG tail -f /var/adm/messages tail -f /var/log/syslog ls -l /proc/ /as ps -p -o pmem,vsz,osz,rss,pid To check memory usage. pldd check dependencies pargs check all arguments passed to process. Note: arg[0] is always the process execution path like even Win32. Useful also if the ls -l return truncated path.

Excel VBA for conditional formatting.

Sub CreateConditionalFormatting() Dim column As String column = "C" Dim NoOfRowNeeded As Integer NoOfRowNeeded = 3000 Dim j As Integer Dim cellSelect As String For j = 1 To NoOfRowNeeded cellSelect = column & CStr(j) Range(cellSelect).Select Selection.FormatConditions.Delete If (j - 1) < 1 Then Range(cellSelect).Interior.ColorIndex = 4 Else 'maximum 3 formula allowed. Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=INT(" & column & CStr(j - 1) & ") Selection.FormatConditions(1).Interior.ColorIndex = 3 Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=INT(" & column & CStr(j - 1) & ")>INT(" & column & CStr(j) & ")" Selection.FormatConditions(2).Interior.ColorIndex = 6 Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=INT(" & column & CStr...

.NET 2.0 modifying content of app.config file (C#)

Before you start, make sure you have added reference to System.Configuration.dll for .NET 2.0. I think the default the Visual Studio C# Express referenced to is from .NET 1.1 which will not compile. using System.Configuration; using System.Collections.Specialized; //to write System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings.Remove("myKey"); config.AppSettings.Settings.Add("myKey", "123"); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); //to read NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings; string strRead = (string)appSettings["myKey"]; Content of app.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="myKey" value = "123"/> </appSettings...

Clearcase check in/uncheck out all the checked out files script

I am so used to source safe recursive check in and found troublesome in clearcase having to do it manually one by one. This is the Unix script that I have come out with //for undo check out all the checked out files cleartool lsco -cview -avobs | cleartool unco -rm `awk '{ print $(5) }' | sed -e 's/^\"*//' -e 's/ *\"$//'` //for check in all the checked out files cleartool lsco -cview -avobs | cleartool ci -nc `awk '{ print $(5) }' | sed -e 's/^\"*//' -e 's/ *\"$//'` //Using xargs cleartool lsco -cview -avobs -short | xargs cleartool ci