Thursday, December 17, 2009

Windows Remote Desktop Web Connection ActiveX Reference

This articel help you understand how to use javascript create a customize windwos remote desktop web connection.
you can use this technic connect to your server desktop anywhere and the IE browser is all you need.
 
// Declare MsRdpClient object in the web page
    <OBJECT language="vbscript" ID="MsRdpClient" CLASSID="CLSID:7584c670-2274-4efb-b00b-d6aaba6d3850"
        onerror="OnControlLoadError"
        onreadystatechange="OnControlLoad"
        CODEBASE="msrdp.cab#version=5,2,3790,3959"
        WIDTH=<% resWidth = Request.QueryString("rW")
            if  resWidth < 200 or resWidth > 1600 then
               resWidth = 800
            end if
            Response.Write resWidth %>
        HEIGHT=<% resHeight = Request.QueryString("rH")
            if  resHeight < 200 or resHeight > 1200 then
               resHeight = 600
            end if
            Response.Write resHeight %>
    </OBJECT>
 
// Some Necessary input fields in web page
    Domain Name: <input type="text" name="Domain" id="editDomain">
    Screen Resolution:
    <select size="1" name="comboResolution" id=comboRes class="topspace">
        <option selected value="1"><ID id=option1>Full Screen</ID></option>
        <option value="2"><ID id=option2>640 x 480</ID></option>
        ....
        <option value="7"><ID id=option6>1600 x 1200</ID></option>
    </select>
   
    <input type="submit" id=connectbutton value="Connect" disabled="true" name="ButtonLogin" OnClick="RdpConnect">
 
// Validate MsRdpClient ActiveX is ready to load
    function onControlLoad
    {
       var control = document.getElementById("MsRdpClient");
       if(control == null)
       {
          if(control.readyState == 4)
          {
             document.getElementById("connectButton").disabled = false;
          }
       }
    }

// invok  connection to MsRdpClient object
function RdpConnect()
{
    MsRdpClient.Server="Server";
    MsRdpClient.Domain="Domain";
    MsRdpClient.UserName="user";
    MsRdpClient.AdvancedSettings2.ClearTextpassword="password";
    MsRdpClient.AdvancedSettings2.RDPPort = 3389;
    MsRdpClient.FullScreen=1;
    MsRdpClient.Width=1024;
    MsRdpClient.Height=768;
    MsRdpClient.DesktopWidth=1024;
    MsRdpClient.DesktopHeight=768;
    MsRdpClient.Connect();
}


MsRdpClient OCX Methods and controls reference:
    MsRdpClient.AdvancedSettings.PluginDlls
    MsRdpClient.AdvancedSettings2.AcceleratorPassthrough
    MsRdpClient.AdvancedSettings2.BitmapCacheSize
    MsRdpClient.AdvancedSettings2.BitmapPersistence
    MsRdpClient.AdvancedSettings2.BitmapVirtualCache16BppSize
    MsRdpClient.AdvancedSettings2.BitmapVirtualCache24BppSize
    MsRdpClient.AdvancedSettings2.BitmapVirtualCacheSize
    MsRdpClient.AdvancedSettings2.ClearTextPassword
    MsRdpClient.AdvancedSettings2.ConnectToServerConsole
    MsRdpClient.AdvancedSettings2.DedicatedTerminal
    MsRdpClient.AdvancedSettings2.DisableCtrlAltDel
    MsRdpClient.AdvancedSettings2.DisplayConnectionBar
    MsRdpClient.AdvancedSettings2.DoubleClickDetect
    MsRdpClient.AdvancedSettings2.EnableAutoReconnect
    MsRdpClient.AdvancedSettings2.EnableMouse
    MsRdpClient.AdvancedSettings2.EnableWindowsKey
    MsRdpClient.AdvancedSettings2.FullScreen
    MsRdpClient.AdvancedSettings2.GrabFocusOnConnect
    MsRdpClient.AdvancedSettings2.HotKeyAltEsc
    MsRdpClient.AdvancedSettings2.HotKeyAltShiftTab
    MsRdpClient.AdvancedSettings2.HotKeyAltSpace
    MsRdpClient.AdvancedSettings2.HotKeyAltTab
    MsRdpClient.AdvancedSettings2.HotKeyCtrlAltDel
    MsRdpClient.AdvancedSettings2.HotKeyCtrlEsc
    MsRdpClient.AdvancedSettings2.InputEventsAtOnce
    MsRdpClient.AdvancedSettings2.KeepAliveInterval
    MsRdpClient.AdvancedSettings2.KeyboardType
    MsRdpClient.AdvancedSettings2.MaxEventCount
    MsRdpClient.AdvancedSettings2.MaximizeShell
    MsRdpClient.AdvancedSettings2.MaxReconnectAttempts
    MsRdpClient.AdvancedSettings2.MinInputSendInterval
    MsRdpClient.AdvancedSettings2.MinutesToIdleTimeout
    MsRdpClient.AdvancedSettings2.NumBitmapCaches
    MsRdpClient.AdvancedSettings2.OrderDrawThreshold
    MsRdpClient.AdvancedSettings2.OverallConnectionTimeout
    MsRdpClient.AdvancedSettings2.PerformanceFlags
    MsRdpClient.AdvancedSettings2.PersistCacheDirectory
    MsRdpClient.AdvancedSettings2.PinConnectionBar
    MsRdpClient.AdvancedSettings2.RdpdrClipCleanTempDirString
    MsRdpClient.AdvancedSettings2.RdpdrClipPasteInfoString
    MsRdpClient.AdvancedSettings2.RdpdrLocalPrintingDocName
    MsRdpClient.AdvancedSettings2.RDPPort
    MsRdpClient.AdvancedSettings2.RedirectDrives
    MsRdpClient.AdvancedSettings2.RedirectPorts
    MsRdpClient.AdvancedSettings2.RedirectPrinters
    MsRdpClient.AdvancedSettings2.RedirectSmartCards
    MsRdpClient.AdvancedSettings2.ScaleBitmapCachesByBPP
    MsRdpClient.AdvancedSettings2.ShadowBitmap
    MsRdpClient.AdvancedSettings2.ShutdownTimeout
    MsRdpClient.AdvancedSettings2.SingleConnectionTimeout
    MsRdpClient.AdvancedSettings2.SmartSizing
    MsRdpClient.AdvancedSettings2.SmoothScroll
    MsRdpClient.AdvancedSettings3.ConnectionBarShowMinimizeButton
    MsRdpClient.AdvancedSettings3.ConnectionBarShowRestoreButton
    MsRdpClient.ColorDepth
    MsRdpClient.SecuredSettings.AudioRedirectionMode
    MsRdpClient.SecuredSettings.KeyboardHookMode
    MsRdpClient.SecuredSettings.StartProgram
    MsRdpClient.SecuredSettings.WorkDir


Related Links:
Installing Remote Desktop Web Connection in Windows XP
 
 

Sunday, November 29, 2009

ASP.NET WebService Samples

// Calling WebService Function for javascript
WebServiceObj.GetYourFunctionName(param1, param2, ..., onSucceeded, onFailed, userContext);

/**
* WebService onSuccess Callback function for AJAX.
* @param {Object} result               Can be any types return from WebService Function.
* @param {String} userContext      String can be pass into OnSucceeded or OnFailed Callback Function.
* @param {String} methodName    The WebService Name you called.
*/

function OnSucceeded(result, userContext, methodName)
{
    if (methodName == "GetSessionValue")
    {
        displayElement.innerHTML = "Current session state value: " + result;
    }
}
 
/**
* WebService onFailed Callback function for AJAX.
* @param {Object} result              The value retrun from WebService Function.
* @param {String} userContext     Any String you want pass into callback functions.
* @param {String} methodName   The WebService Function name you calling.
*/

function OnFailed(error, userContext, methodName)
{
    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();
    ...
    ...
}
 
 
Related Links:


SQL Server Collation Name

COLLATE  SQL_SortRules[_Pref]_CPCodepage_<ComparisonStyle>
Sample
COLLATE Chinese_Taiwan_Stroke
COLLATE Chinese_Taiwan_Stroke_BIN
COLLATE Chinese_Taiwan_Stroke_CI_AS
COLLATE Chinese_Taiwan_Bopomofo_CS_AI

SortRules
A string identifying the alphabet or language whose sorting rules are applied when dictionary sorting is specified.
Examples are Latin1_General, Polish or
Chinese_Taiwan.
Pref
Specifies uppercase preference.

Codepage
Specifies a one- to four-digit number that identifies the code page used by the collation. CP1 specifies code page 1252, for all other code pages the complete code page number is specified. For example, CP1251 specifies code page 1251 and CP850 specifies code page 850.

CaseSensitivityCI specifies case-insensitive, CS specifies case-sensitive.
AccentSensitivity
AI specifies accent-insensitive, AS specifies accent-sensitive.

BIN
Specifies the binary sort order to be used.

SQL Server Collation Name (Transact-SQL)
SQL Server 2005 Books Online (September 2007) - Collation Settings in Setup

Monday, November 9, 2009

Retrieve Last Inserted Identity of Record

SQL SERVER

March 25, 2007 by pinaldave

SELECT @@IDENTITY
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
SELECT IDENT_CURRENT(’tablename’)
It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.
Source: Pinal Dave (http://www.SQLAuthority.com)

MySQL

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function or by executing a SELECT LAST_INSERT_ID() statement with mysql_query() and retrieving the value from the result set returned by the statement. .
If you want to use the ID that was generated for one table and insert it into a second table, you can use SQL statements like this:
INSERT INTO foo (auto,text)
    VALUES(NULL,'text');         # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table


You can check from your C applications whether a value was stored in an AUTO_INCREMENT column by executing the following code (which assumes that you've checked that the statement succeeded). It determines whether the query was an INSERT with an AUTO_INCREMENT index:
if ((result = mysql_store_result(&mysql)) == 0 &&
    mysql_field_count(&mysql) == 0 &&
    mysql_insert_id(&mysql) != 0)
{
    used_id = mysql_insert_id(&mysql);
}
Source: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
 
 

Sunday, October 25, 2009

retrieve the horizontal resolution for a video display, or printer

Device-Independent Bitmaps
A device-independent bitmap (DIB) contains a color table. A color table describes how pixel values correspond to RGB color values, which describe colors that are produced by emitting light. Thus, a DIB can achieve the proper color scheme on any device. A DIB contains the following color and dimension information:
  • The color format of the device on which the rectangular image was created.
  • The resolution of the device on which the rectangular image was created.
  • The palette for the device on which the image was created.
  • An array of bits that maps red, green, blue (RGB) triplets to pixels in the rectangular image.
  • A data-compression identifier that indicates the data compression scheme (if any) used to reduce the size of the array of bits.
The color and dimension information is stored in a BITMAPINFO structure, which consists of a BITMAPINFOHEADER structure followed by two or more RGBQUAD structures. The BITMAPINFOHEADER structure specifies the dimensions of the pixel rectangle, describes the device's color technology, and identifies the compression schemes used to reduce the size of the bitmap. The RGBQUAD structures identify the colors that appear in the pixel rectangle.
There are two varieties of DIBs:
  • A bottom-up DIB, in which the origin lies at the lower-left corner.
  • A top-down DIB, in which the origin lies at the upper-left corner.
If the height of a DIB, as indicated by the Height member of the bitmap information header structure, is a positive value, it is a bottom-up DIB; if the height is a negative value, it is a top-down DIB. Top-down DIBs cannot be compressed.
The color format is specified in terms of a count of color planes and color bits. The count of color planes is always 1; the count of color bits is 1 for monochrome bitmaps, 4 for VGA bitmaps, and 8, 16, 24, or 32 for bitmaps on other color devices. An application retrieves the number of color bits that a particular display (or printer) uses by calling the GetDeviceCaps function, specifying BITSPIXEL as the second argument.
The resolution of a display device is specified in pixels-per-meter. An application can retrieve the horizontal resolution for a video display, or printer, by following this three-step process.
  1. Call the GetDeviceCaps function, specifying HORZRES as the second argument.
  2. Call GetDeviceCaps a second time, specifying HORZSIZE as the second argument.
  3. Divide the first return value by the second return value.
The application can retrieve the vertical resolution by using the same three-step process with different parameters: VERTRES in place of HORZRES, and VERTSIZE in place of HORZSIZE.
The palette is represented by an array of RGBQUAD structures that specify the red, green, and blue intensity components for each color in a display device's color palette. Each color index in the palette array maps to a specific pixel in the rectangular region associated with the bitmap. The size of this array, in bits, is equivalent to the width of the rectangle, in pixels, multiplied by the height of the rectangle, in pixels, multiplied by the count of color bits for the device. An application can retrieve the size of the device's palette by calling the GetDeviceCaps function, specifying NUMCOLORS as the second argument.
Windows supports the compression of the palette array for 8-bpp and 4-bpp bottom-up DIBs. These arrays can be compressed by using the run-length encoding (RLE) scheme. The RLE scheme uses 2-byte values, the first byte specifying the number of consecutive pixels that use a color index and the second byte specifying the index. For more information about bitmap compression, see the description of the BITMAPINFOHEADER, BITMAPFILEHEADER, BITMAPV4HEADER, and BITMAPV5HEADER structures.
An application can create a DIB from a DDB by initializing the required structures and calling the GetDIBits function. To determine whether a device supports this function, call the GetDeviceCaps function, specifying RC_DI_BITMAP as the RASTERCAPS flag.
An application that needs to copy a bitmap can use TransparentBlt to copy all pixels in a source bitmap to a destination bitmap except those pixels that match the transparent color.
An application can use a DIB to set pixels on the display device by calling the SetDIBitsToDevice or the StretchDIBits function. To determine whether a device supports the SetDIBitsToDevice function, call the GetDeviceCaps function, specifying RC_DIBTODEV as the RASTERCAPS flag. Specify RC_STRETCHDIB as the RASTERCAPS flag to determine if the device supports StretchDIBits.
An application that simply needs to display a pre-existing DIB can use the SetDIBitsToDevice function. For example, a spreadsheet application can open existing charts and display them in a window by using the SetDIBitsToDevice function. To repeatedly redraw a bitmap in a window, however, the application should use the BitBlt function. For example, a multimedia application that combines animated graphics with sound would benefit from calling the BitBlt function because it executes faster than SetDIBitsToDevice.

Wednesday, October 21, 2009

How to make auto line break in HTML table td element

CSS can imperfectly solved this issue asa below

.table
{
    table-layout: fixed;
}
.td
{
    word-break: break-all;
    word-wrap:break-word;
}

Friday, October 9, 2009

How to pass parameters to UserControl

  1. Define a constructor method in your UserControl class
    public partial class MyUserControl : System.Web.UI.UserControl
    {
        public MyUserControl()
        {
        }
        public MyUserControl(string param1, int param2, bool param3)
        {
            // Do anything you whant for your parameters here
            textbox1.Text = param1;
            .....

        }
    }
  2. Define our customize LoadControl() method so that the parameters can be pass into the UserControl
    private UserControl LoadUserControl(string controlPath, params object[] parameters)
    {
        List<Type> paramTypes = new List<Type>();
        foreach(object param in parameters)
        {
            paramTypes.Add(param.GetType());
        }
        Page page = new Page();
        UserControl uc = page.LoadControl(controlPath) as UserControl;
        ConstructorInfo ci = uc.GetType().BaseType.GetConstructor(paramTypes.ToArray());
        if(ci == null)
        {
            throw new MemberAccessException(
                "The requested constructor was not found on : "
               
    + uc.GetType().BaseType.ToString());
        }
        else
        {
            ci.Invoke(uc, parameters);
        }
        return uc;
    }
  3. Now you can use the LoadControl as below to pass the parameters to the UserControl
    // Initiallize the UserControl with it parameters .....UserControl myControl = LoadControl(
                                        "MyUserControl.ascx"
                                      , "This is value of param1"
                                      ,  1234, true);
 
 
 
 
 

Friday, September 25, 2009

身份證字號說明

身份證字號 共有十碼, 以下是位置說明,僅供各位參考

N1 N2 N3 N4 N5 N6 N7 N8 N9 N10
戶籍 性別 ~流~~~~~~~~水~~~~~~~~~~~碼~

代表說明

戶籍代表字母
A台北市 B台中市 C基隆市 D台南市 E高雄市 F台北縣
G宜蘭縣 H桃園縣 I嘉義市 J新竹縣 K苗栗縣 L台中縣
M南投縣 N彰化縣 O新竹市 P雲林縣 Q嘉義縣 R台南縣
S高雄縣 T屏東縣 U花蓮縣 V台東縣 W金門縣 X澎湖縣
Y陽明山 Z連江縣

英文字母代表的數字
A=10 B=11 C=12 D=13 E=14 F=15 G=16 H=17 I=34 J=18 K=19 L=20
M=21 N=22 O=35 P=23 Q=24 R=25 S=26 T=27 U=28 V=29 W=32 X=30
Y=31 Z=33

性別代表數字
1:男性
2:女性

步驟

1. 查出英文字所代表的數字

再將所查出的數字 "十位數+個位數x9"
例: 台北市=10
1 + 0x9 =1
台中市=11
1 + 1x9 =10

2. N2x8+N3x7+N4x6+N5x5+N6x4+N7x3+N8x2+N9+N10

將流水碼依序乘8765432
一個個乘.乘完要加起來. (別忘了先乘除後加減)
例: 123456789
1x8+2x7+3x6+4x5+5x4+6x3+7x2+8+9


3.將步驟1 和步驟2 的兩個數加起來除以10.

例:步驟1 台北計算結果 =1
步驟2 1x8+2x7+3x6+4x5+5x4+6x3+7x2+8+9 =129 (1+129)/10

除10後看看是否可以整除.如可以整除即為正確的
身份證字號. 如無法整除即是錯誤的身份證字號

(1+129)/10 = 13 => 可以整除.正確

Wednesday, September 16, 2009

Clear Drop Down List of Recent Connection From SQL Server Management Studio


SQL Server Management Studio 2017 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\14.0\SqlStudio.bin
SQL Server Management Studio 2016 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin
SQL Server Management Studio 2014 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin
SQL Server Management Studio 2012 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin
SQL Server Management Studio 2008 delete the fileC:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
SQL Server Management Studio 2005 delete the file – same as above answer but the Vista path. C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat


In fact there's a way to delete all the history info in the dialog fields.
For SQL Server 2005:
C:\Documents and Settings\<user>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
If you can not find mru.dat at above location look for mru.dat in following folder.
C:\Documents and Settings\[user]\Application Data\Microsoft\Microsoft SQL Server\90\Tools\ShellSEM\mru.dat
For SQL Server 2008:
C:\Documents and Settings\<user>\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
If you can not find mru.dat at above location look for mru.dat in following folder.
C:\Documents and Settings\[user]\Application Data\Microsoft\Microsoft SQL Server\100\Tools\ShellSEM\mru.dat
If you are using VISTA OS instead of XP OS. Replace C:\Documents and Settings\[user]\Application Data\Microsoft\ with
C:\Users\\AppData\Roaming\Microsoft\ and it should work.
Make sure to take note down any IP address of SQL Server you may need in future.
Reference : Pinal Dave (http://www.SQLAuthority.com)

Saturday, September 5, 2009

How to reset MS SQL Server IDENTITY

If the table is new create you can use this to reset the identity
DBCC CHECKIDENT (yourtable, reseed, seed_value)

If you delete that data in the table u can use
DBCC CHECKIDENT (yourtable, reseed, 0)

Thursday, August 27, 2009

How to Install/UnInstall COM Componets

If the COM file is a executive .exe file.Excute the file with a argument as below:
 -Service            // Install .exe COM file as a windows service.
 -UnregServer    // Uninstall .exe COM componet.
 -RegServer       // Install .exe COM file as a windows COM componet.


If the COM file is a DLL file, suppose the file name is mycom.dll.
regsvr32 mycom.dll              // To install dll COM
regsvr32 /u mycom.dll          // Run regsvr32 with argument /u to uninstall the dll COM

dcomcnfg    // This tool can see the all DCOM componets has installed in the system.


The Installutil.exe is a tool for .NET componets registration
Here some argument options
Option Description
/h[elp] Displays command syntax and options for the tool.
/help assemblypath Displays any additional options recognized by individual installers within the specified assembly.
/logFile=[filename] Specifies the name of the log file where install progress is recorded. The default is assemblyname.InstallLog.
/logToConsole={true|false} If true, displays output to the console. If false (the default), suppresses output to the console.
/showCallStack Prints the call stack to the log if an exception occurs at any point during installation.
/u[ninstall] Uninstalls an assembly. Unlike other options, /u applies to all assemblies regardless of where it appears on the command line.
/? assemblypath Displays any additional options recognized by individual installers within the specified assembly.
/? Displays command syntax and options for the tool.

The SC.exe is a Windows SDK tool
The SC.exe can be used to Query, Install, Uninstall and Setting Windows Service and Windows Hardware Drivers.

How to use it go ask google!


Friday, July 17, 2009

How to config network in Solaris 10

Changes Static IP Address and Host Name
    The sample below shows how to uses ipconfig change static IP address to 192.168.0.10 with netmask 255.255.255.0
  1. ifconfig vfe0 unplumb
  2. ifconfig vfe0 plumb 192.168.0.10 netmask 255.255.255.0 up
Config host name for ethernet card
    /etc/hostname.vfe0
     solaris10
Config network mapping for IP address and host name (hostname of Ethernet card)
    the hosts file format of each line is:
        IP-address    official-host-name    nicknames....
    the nicknames can be optional.
    /etc/hosts
     127.0.0.1         localhost            loghost
     192.168.0.xxx  solaris10
    /etc/netmasks
     192.168.0.xxx 255.255.255.0
Config Gateway
    /etc/defaultrouter
     192.168.0.1
Config DNS
    1. Specify DNS Server
        /etc/resolv.conf
         nameserver 168.95.192.1
         nameserver 168.95.192.2
    2. In order to enable DNS resolve, change the line in nsswitch.conf as below
        /etc/nsswitch.conf
         hosts: files dns
         inodes: files dns

Tuesday, July 7, 2009

How to uses callback function for C++

 
// This is a callback function sample without parameter.
void callbackProc1()
{
    printf("this is a call back 1..\r\n");
}
 
// This is a callback function sample with 2 parameters
bool callbackProc2(int nSize, char* pszName) {
    printf("this is a call back 2..\r\nSize is:%d  pszName is:%s \r\n", nSize, pszName);
    return true;
}
 
// This function invoke callback function as a parameter to it
void test1(void(*p)(void))
{
    p();
}
// This function invoke a callback function with 2 parameters
void test2(bool(*p)(int, char*), int param1, char* param2)
{
    if(p(param1, param2))
    {
        printf("the callback func return TRUE.......\r\n");
    }
}

void main()
{
    // this is a sample to demonstrate how to invoke a callback function without parameter
    // the callback function name is a memory address reference to callback function.
    test1(callbackProc1);
   
    // this is a sample shows how to invoke a callback functions with two parameters
    test2(callbackProc2, 999, "johnrock");
 
 

How to create a process to run a dos command with dos dialog window

CreateProcess(NULL, "cmd /c copy file1 file2", ....),

Create Sequence Numbers for Oracle

Full Create Sequence Syntax
CREATE SEQUENCE <sequence_name> INCREMENT BY <integer> START WITH <integer> MAXVALUE <integer> / NOMAXVALUEMINVALUE <integer> / NOMINVALUECYCLE / NOCYCLECACHE <#> / NOCACHEORDER / NOORDER;

Create Sequence Simplest Form
CREATE SEQUENCE seq_campus_site_id;
SELECT seq_campus_site_id.NEXTVAL FROM dual;

Simple Autonumber With Sequence
INSERT INTO <table_name>(<column_name>)VALUES(<sequence_name>.NEXTVAL);
INSERT INTO campus_site(site_id, organization_name, campus_name)VALUES(seq_campus_site_id.NEXTVAL, 'Univ. of Washington', 'Main Seattle');
SELECT * FROM campus_site;
INSERT INTO campus_site(site_id, organization_name, campus_name)VALUES(seq_campus_site_id.NEXTVAL, 'Univ. of Washington', 'Bothell');
SELECT * FROM campus_site;

Simple Autonumber With Sequence Into Two Tables
INSERT INTO <table_name>(<column_name>)VALUES(<sequence_name>.CURRVAL);
CREATE SEQUENCE seq_division_id;
INSERT INTO campus_site(site_id, organization_name, campus_name)VALUES(seq_campus_site_id.NEXTVAL, 'Univ. of Washington', 'Tacoma');
INSERT INTO division (division_id, site_id, division_name) VALUES(seq_division_id.NEXTVAL, seq_campus_site_id.CURRVAL, 'Engineering');
SELECT * FROM campus_site;
SELECT * FROM division;

Windows Smart Card Utilities

Connect to network by smart card
net use /smartcard
Specifies the network connection is to use the credentials on a smart card. If multiple smart cards are available, you are asked to specify the credential. This parameter cannot be used with /savecred.
 
Query all available samrt card and reader in the system
certutil -scinfo
 
 
Smart card PIN tool
pintool
 
 

Monday, June 22, 2009

How to dynamic manage upload files name in web server

This topic is help to understand how to manage file name uses SQL Server and dynamic specific the client upload file name store in the server file system.
the purpose is save the file to the server file system without having the file name replicated problems. if client download the files from the server, the server can specify the file name depend which the real file name store in the server file system and a popup dialog on user browser  with a file name specify from SQL server but not the physical file name store in the server file system.
 
 
Over write MIME protocol
When Internet Explorer receives the header, it raises a File Download dialog box whose file name box is automatically populated with the file name that is specified in the header.
 
For ASP .NET
Response.AddHeader("content-disposition","attachment; filename=fname.ext");
 
For JSP
response.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );
 
Note:
  1. You may have to specify the Content Type resp.setContentType( "application/x-download" );
  2. Another Content-Type can instate of the content-disposition but it bahaves is differently
    resp.setHeader( "Content-Type", "attachment; filename=" + downloadFileName );
References:
    For more information about content-disposition, see Request for Comments (RFC) 1806
    http://support.microsoft.com/kb/260519

JSP Example
<%@ page  language="java" contentType="text/html"%>
<%@ page import="java.io.*, java.util.*, javax.servlet.*"%>
<%
    if (request.getParameter("filename").equals("") == false)
    {
        String path = request.getParameter("path");
        String filename = request.getParameter("filename");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + request.getParameter("filename"));
        int iRead;
        FileInputStream stream = null;
        try
        {
            File f = new File(path + filename);
            stream = new FileInputStream(f);
            int ilength = 0;
            while ((iRead = stream.read()) != -1)
            {
                out.write(iRead);
            }
            out.flush();
        }
        finally
        {
            if (stream != null)
            {
                stream.close();
            }
        }
    }
%>

Tuesday, June 16, 2009

How to Load ResourceBundle

 
Load Resource from different location
// Load resource from specific file object
File f = new File("d:\\\\props\\res.jar");
URL url = f.toURI().toURL();
URL[] urls = new URL[]{url};
ResourceBundle lang = ResourceBundle.getBundle("tw.com.mycomp.res.properties", new Locale("en", "US"), new URLClassLoader(urls));
 
// Load resource from specific URL
URL[] urls = new URL[]{ new URL("file:///d:/props/errmsg.properties") };
ResourceBundle lang = ResourceBundle.getBundle("tw.com.mycomp.res.properties", new Locale("en","US"), new URLClassLoader(urls));
 
 

Wednesday, June 10, 2009

How to declare and initial array in java

Declares and initial an array in Java
 
int [] anArray;                         // can also be written as :  int anArray [];
 
int [] anArray = null;
int [] anArray = new int[10];    // can also be written as :  int anArray [] = new int[10];
 
String [] array = {"A", "B", "C"};
String [][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}};
 
Create an new Array object as a parameter in function
getNames( new String [] {"Smith", "Jones", "Oehler"} );
 
 

Monday, June 8, 2009

Query Statement for Test Connection

Oracle
SELECT 1 FROM DUAL
 
MSSQL
SELECT 1
 

Sunday, June 7, 2009

Create Schema in Oracle

Purpose
Create multiple tables and views and perform multiple grants in your own schema in a single transaction. If all statements execute successfully, then the database commits them as a single transaction. If any statement results in an error, then the database rolls back all of the statements.
 
conn / as sysdba

CREATE USER uwclass
IDENTIFIED BY uwclass
DEFAULT TABLESPACE uwdata
TEMPORARY TABLESPACE temp
QUOTA 10M ON uwdata;

GRANT create session TO uwclass;
GRANT create table TO uwclass;
GRANT create view TO uwclass;

conn uwclass/uwclass

-- first one that doesn't work (t3 does not exist)
CREATE SCHEMA AUTHORIZATION uwclass
CREATE TABLE t1
(tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20))
CREATE TABLE t2
(tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20))
CREATE VIEW t1t2_view AS
SELECT t1.tid, t2.last_name FROM t1, t3 WHERE t1.tid = t2.tid
GRANT select ON t1t2_view TO system;

-- then one that does
CREATE SCHEMA AUTHORIZATION uwclass
CREATE TABLE t1
(tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20))
CREATE TABLE t2
(tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20))
CREATE VIEW t1t2_view AS
SELECT t1.tid, t2.last_name FROM t1, t2 WHERE t1.tid = t2.tid
GRANT select ON t1t2_view TO system;
 

Thursday, June 4, 2009

The Properties of Tomcat Server

Tomcat System Properties
 
System.getProperty("catalina.base");
System.getProperty("catalina.home");
System.getProperty("catalina.config");
System.getProperty("user.dir");
 
ServletContext.getRealPath("/WEB-INF/");
 
 

How to compair two objects in java

 
// exact match for a class.
if (object.getClass() == MyClass.class)
{
    ...
}
 
// Determines if the specified Object is assignment-compatible 
// with the object represented by this Class. This method is the 
// dynamic equivalent of the Java language instanceof operator. 
// The method returns true if the specified Object argument is 
// non-null and can be cast to the reference type represented by 
// this Class object without raising a ClassCastException. 
// It returns false otherwise.
if (MyClass.isInstance(obj))
{
...
}

Wednesday, May 6, 2009

Build Windows Service with Setup Project using VS2008

To create a windows service with a setup project for a service can easy way to install and start up the service after the service is installed.
here both windows service and  setup project are more works have to do.
first of all we have to create a windows service project and add some code for setup program so that
it capable installation the windows service and then to start it up.

Create a Windows Service Project


  1. In the Add new projcet dialog select Windows Service Template to create new service project.
  2. Right click service1.cs and click View Code
  3. In the OnStart event handler, replace the comments with anything code you want the service to run.
  4. In the OnStop event handler, replace the comments with the code if you need to free the resources.
  5. For the service installation, double click service1.cs to open Design View, In the Design View Right click and select Add Installer in this step a new class ProjectInstaller.cs will add to the project, two elements serviceProcessInstaller1 and serviceInstaller1 you can see in the ProjectInstaller.cs Design View.
  6. In the Properties of serviceInstaller1, change the ServiceName, DisplayName and Description properties for you need.
  7. In the Properties of serviceProcessInstaller1, change the Account to LocalSystem.
    Note: If you want override OnShutdown Event in the Service, you have to use LocalService Account, Otherwise like LocalSystem the OnShutdown Event will never be invoke.
    (LocalService and NetworkService values are available only in Microsoft Windows XP)
  8. If you want the service start up automatical at every tiems system start, you have to change the property StartType to Automatic.

    If you want the service startup when the service end of it installation, there more steps start from step 9 below you have to do.
  9. Add new class as a Install class into the project, open it in code view, Override the Comit Method as below:
        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Commit(System.Collections.IDictionary savedState)
        {
            base.Commit(savedState);
            ServiceController[] scServices = ServiceController.GetServices();
            foreach(ServiceController sc in scServices)
            {
                if(sc.ServiceName == "yourServiceName")
                {
                    if(sc.Status == ServiceControllerStatus.Stopped)
                    {
                        sc.Start();
                        break;
                    }
                }
            }
        }
Create a Setup Project for Windows Service
1. In the Add new projcet dialog select Setup Project Template to create new setup project.
2. Open the properties panel of the project, in the properties panle change the Manufacturer, ProductName to your fit, through the
    installation all the files will copy to the default folder which is composite from Program file/[Manufacturer]/[ProductName].
    but you can change the default install location setting in Properties of File System->Application Folder.
    the RemovePreciousVersions is false by default, indicate when you reinstall the program, the old version won't be uninstall.
    there are some more properties have to concern like Version, Author, Description, Subject etc.
2. In the Solution Explorer, Right click the projcet name and select View->File System, right click in the Application Folder
    and select Add->File or Add->Folder to add anything files you want to add to the folder where you service installed. you also
    can select Add->Project Output to specific any other projects output file into this setup project.
3. This step can install mySev.exe to windows system as a service. In the Solution Explorer, Right click the projcet name and select
    View->Custom Actions, Now a Select item dialog will show up to you, in the Look In Dropdown list select the file of
    window service mySev.exe in the Application Folder and then select ok. the file must been add by step 2.
4. In the Solution Explorer right click Project Name and select Properties to open the Project Properties Page, Click the buttom
    Prerequister, checked all .NET Framework version you need and uncheck the all you don't.
    If any version you select in the prerequist is missing in the installation computer, the install program will popup dialog to installing
    user to request install the properly version of .NET Framework.

For debug or some reason you can use Installutil.exe to install or uninstall the windows service by manual
Installutil.exe is only for .net, can not be uses in earlier windows service develop by C or C++.

Monday, May 4, 2009

Date Format in SQL

MS SQL
-- in this sample Dateadd() function retrieve that day befor 7 days by getdate() , then format it to varchar
-- the format as a date of japan yy/mm/dd
-- convert() function format date to 111 as japan date format , like this yyyy/mm/dd
select convert(varchar(20), DATEADD(day, -7, getdate()) ,111)

-- This sample casting date to float and floor the times part to 00:00:00.000
-- so that return the result same as 2008-10-22 00:00:00.000
-- If you trying to compare two datetime, this probably is best choice
SELECT CAST(FLOOR( CAST( GETDATE() AS FLOAT ) )AS DATETIME)


MySQL
-- Format a DATETIME or TIMESTAM to VARCHAR
-- for sample 2009-06-19 13:30:21

DATE_FORMAT(update_date,'%Y-%m-%d %T')

The formats that can be used are:

Format Description
%a Abbreviated weekday name
%b Abbreviated month name
%c Month, numeric
%D Day of month with English suffix
%d Day of month, numeric (00-31)
%e Day of month, numeric (0-31)
%f Microseconds
%H Hour (00-23)
%h Hour (01-12)
%I Hour (01-12)
%i Minutes, numeric (00-59)
%j Day of year (001-366)
%k Hour (0-23)
%l Hour (1-12)
%M Month name
%m Month, numeric (00-12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss AM or PM)
%S Seconds (00-59)
%s Seconds (00-59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00-53) where Sunday is the first day of week
%u Week (00-53) where Monday is the first day of week
%V Week (01-53) where Sunday is the first day of week, used with %X
%v Week (01-53) where Monday is the first day of week, used with %x
%W Weekday name
%w Day of the week (0=Sunday, 6=Saturday)
%X Year of the week where Sunday is the first day of week, four digits, used with %V
%x Year of the week where Monday is the first day of week, four digits, used with %v
%Y Year, four digits
%y Year, two digits

Sunday, April 5, 2009

How To Compile Java Code To Eariler Version

For example if you want to compile java code to eariler version 1.4 is..
javac -target 1.4 -bootclasspath \jdk1.4.19\lib\rt.zip Hello.java
How to distinguish the compile version of the class file 
Every java class file had a version stamp two unsigned short integers starting at byte offset 4 right after the 0xCAFEBABE magic number

Java 1.2 platform: 0xCAFEBABE 0x00002E 0x00AF0100
Java 1.3 platform: 0xCAFEBABE 0x00002F
Java 1.4 platform: 0xCAFEBABE 0x000030
Java 1.5 platform: 0xCAFEBABE 0x000031
Java 1.6 platform: 0xCAFEBABE 0x000032

Relate Article: What version is your Java code?
 

Saturday, February 21, 2009

SQL Syntax Reference

MS SQL
-- Creating a UNIQUE Constraint to exist table
 ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> UNIQUE(<column_name>)

--Add a Column into table
ALTER TABLE <table_name> ADD <column_name> CHAR(1) NOT NULL DEFAULT '0'
--Change Column
ALTER TABLE <table_name> ALTER COLUMN <column_name> CHAR(1) NOT NULL DEFAULT '0'

-- Rename column
SP_RENAME '<table_name>.<original_column_name>' , '<new_column_name>', 'COLUMN'
GO
-- Rename table name
SP_RENAME '<original_table_name>' , 'new_table_name';
GO

-- Check if column exist (available for SQL Server 2000)
IF NOT EXISTS (SELECT column_name FROM INFORMATION_SCHEMA.columns
                WHERE table_name = 'MyTable' AND column_name='my_column_name')
    ... do anything you do here.
GO

-- Check if table exist (available for SQL Server 2000)
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'myTable')
    DROP TABLE myTable;
GO


-- Insert data into IDENTITY  INCREMENT column
SET IDENTITY_INSERT [TableName1] ON;
INSERT INTO [TableName1](...)VALUES(...);
SET IDENTITY_INSERT [TableName1] OFF;


MySQL
-- Add a column to table
ALTER TABLE table_1 ADD COLUMN column_1 INT(10) NOT NULL;