drupal hit counter
Jerry Huang | apps and developing apps

Jerry Huang apps and developing apps

new feature in v1.4

6. April 2011 03:03 by Jerry in IP CAM

The new 1.4 version ships with a feature: upload / download your camera config files to/from server.

In the Setup screen, click the expand button at application bar (the "..." at right down corner), then click the "upload/download camera", enjoy! Laughing

My first app on Windows Marketplace now

17. March 2011 20:21 by Jerry in IP CAM

Finally, my first Windows Phone 7 application published!Laughing 

Search "ip cam control" in the Marketplace with your Windows Phone device!!

At the end of below page, I provided a windows version to test if my app compatible with your camera. Please have a try if you are interested.

more detail...

 

DbMoto comments and experience

3. September 2010 13:00 by Jerry in Product Experience

The previous blog I wrote last night is something about DbMoto. Today I found that my feeling is a bit more than that, so I list out the summary how I feel after using this product.

  1. It’s basically a good tool for syncalizing data from DB2 to SQL, in my case. Easy to setup and use comparing with some jumbo products. It provides a nice GUI tool to setup and manage replications.
  2. Not very good for real time change data capture, currently we set the interval to 30 minutes, i.e. data will sync from DB2 to SQL every 30 minutes. There was a time we set to 5 minute but it seems there were some problems. I am not sure about the detail (I'm not in the AS400 team), what I heard fromt my colleague is that the receiver in AS400 caused the CPU overran.
  3. The product and the company have a long history and the market share is growing. The support is ok; so far they solved all problems we hit, as I can remember.
  4. I believe the engine is base on .Net framework 2.0, so it needs to run on a Windows server. This is ok for us but some people insist the performance is better if a product is base on non-Microsoft server.
  5. Very good extensibility, we can write our own script into the replication. We are using VB.NET as script language, but I guess it also supports other .NET languages. The script will be compiled to .NET binary code so the efficiency will be better than those dynamically compile.
  6. Scripting is good but also brings the biggest problem – there is no way to debug the script in development. What we are doing now, is to write log for debugging. For development, ideally we hope the dbmoto engine somehow can call into Visual Studio so that we may set breakpoint, watch the value of local variables, etc. Due to this, we avoid to put something too complicated in the scripts.

Overall, I will say dbmoto is a light-weight to medium change data capture engine, to keep 2 different databases identical. If your requirement is not about some sort of comprehensive ETL solution, just to sync data from one place to another, DbMoto should be a good tool for that. However, it might not suit for you if require extremely low latency (i.e real time) syncalization. Hmmm, but real-time is a big challenge for all products.

The more stupid you assume the consumer is, the better implementation your framework would be

2. September 2010 23:29 by Jerry in Framework Design

DbMoto is a light-weight to medium change data capture product in my opinion. It basically sync data from one database to another, to keep 2 database identical, even target and source are not the same kind of database (from DB2 to SQL for example).

One of the strengths of DbMoto is that you can write your own script in a replication, so that it could satisfy some complicated business needs. In my case, we used VB.NET as the scripting language. Recently we found some error about deadlock in the log. Originally we thought the problem was from SQL database, but we couldn't find any log entry in SQL server. We fired a ticket for vendor support. Later on they told us to use SyncLock on the TargetConnection object. So I change the script to use Monitor (better than SyncLock) instead. The code goes like:

Code
1
2
3
4
5
6
7
8
9
10
11
 TrySystem.Threading.Monitor.Enter(TargetConnection)cmd = TargetConnection.CreateCommand...Catch e As Exception...FinallySystem.Threading.Monitor.Exit(TargetConnection)End Try

From this accident, I feel this should be a minor problem in the architecture of DbMoto, that's how the title came into my mind. In short, the object provided by Dbmoto is not thread-safe. From the point of view of framework design, when writing something will be used in multi-threads environment, it's better to make sure the objects that explosing to consumer are thread-safe. Rather than leaving the problem to sub-classes, why not just handle them internally?

scan barcode from TIFF

31. July 2010 09:25 by Jerry in Cool stuff

http://www.codeproject.com/KB/graphics/BarcodeImaging3.aspx

The ariticle above is really something awesome, you may easily scan barcode in an image, pure managed code. It supports Code39, Code39ex, Code128, EAN, EAN-2, EAN-5.

Together with below utility class, I used it in an application to scan barcode from tiff

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;using System.Collections;namespace AMA.Util
{/// <summary>/// Summary description for TiffManager./// </summary>public class TiffManager : IDisposable{private string _ImageFileName;private int _PageNumber;private Image image;private string _TempWorkingDir;public TiffManager(string imageFileName){this._ImageFileName=imageFileName;image=Image.FromFile(_ImageFileName);GetPageNumber();}public TiffManager(){}/// <summary>/// Read the image file for the page number./// </summary>private void GetPageNumber(){Guid objGuid=image.FrameDimensionsList[0];FrameDimension objDimension=new FrameDimension(objGuid);//Gets the total number of frames in the .tiff file_PageNumber=image.GetFrameCount(objDimension);return;}/// <summary>/// Read the image base string,/// Assert(GetFileNameStartString(@"c:\test\abc.tif"),"abc")/// </summary>/// <param name="strFullName"></param>/// <returns></returns>private string GetFileNameStartString(string strFullName){int posDot=_ImageFileName.LastIndexOf(".");int posSlash=_ImageFileName.LastIndexOf(@"\");return _ImageFileName.Substring(posSlash+1,posDot-posSlash-1);}/// <summary>/// This function will output the image to a TIFF file with specific compression format/// </summary>/// <param name="outPutDirectory">The splited images' directory</param>/// <param name="format">The codec for compressing</param>/// <returns>splited file name array list</returns>public ArrayList SplitTiffImage(string outPutDirectory,EncoderValue format){string fileStartString=outPutDirectory+"<a href="file://\\"+GetFileNameStartString(_ImageFileName">\\"+GetFileNameStartString(_ImageFileName</a>);ArrayList splitedFileNames=new ArrayList();try{Guid objGuid=image.FrameDimensionsList[0];FrameDimension objDimension=new FrameDimension(objGuid);//Saves every frame as a separate file.Encoder enc=Encoder.Compression;int curFrame=0;for (int i=0;i<_PageNumber;i++){image.SelectActiveFrame(objDimension,curFrame);EncoderParameters ep=new EncoderParameters(1);ep.Param[0]=new EncoderParameter(enc,(long)format);ImageCodecInfo info=GetEncoderInfo("image/tiff");//Save the master bitmapstring fileName=string.Format("{0}{1}.TIF",fileStartString,i.ToString());image.Save(fileName,info,ep);splitedFileNames.Add(fileName);curFrame++;} }catch (Exception){throw;}return splitedFileNames;}/// <summary>/// This function will join the TIFF file with a specific compression format/// </summary>/// <param name="imageFiles">string array with source image files</param>/// <param name="outFile">target TIFF file to be produced</param>/// <param name="compressEncoder">compression codec enum</param>public void JoinTiffImages(string[] imageFiles,string outFile,EncoderValue compressEncoder){try{//If only one page in the collection, copy it directly to the target file.if (imageFiles.Length==1){File.Copy(imageFiles[0],outFile,true);return;}//use the save encoderEncoder enc=Encoder.SaveFlag;EncoderParameters ep=new EncoderParameters(2);ep.Param[0]=new EncoderParameter(enc,(long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(Encoder.Compression,(long)compressEncoder);Bitmap pages=null;int frame=0;ImageCodecInfo info=GetEncoderInfo("image/tiff");foreach(string strImageFile in imageFiles){if(frame==0){pages=(Bitmap)Image.FromFile(strImageFile);//save the first framepages.Save(outFile,info,ep);}else{//save the intermediate framesep.Param[0]=new EncoderParameter(enc,(long)EncoderValue.FrameDimensionPage);Bitmap bm=(Bitmap)Image.FromFile(strImageFile);pages.SaveAdd(bm,ep);} if(frame==imageFiles.Length-1){//flush and close.ep.Param[0]=new EncoderParameter(enc,(long)EncoderValue.Flush);pages.SaveAdd(ep);}frame++;}}catch (Exception){throw;}return;}/// <summary>/// This function will join the TIFF file with a specific compression format/// </summary>/// <param name="imageFiles">array list with source image files</param>/// <param name="outFile">target TIFF file to be produced</param>/// <param name="compressEncoder">compression codec enum</param>public void JoinTiffImages(ArrayList imageFiles,string outFile,EncoderValue compressEncoder){try{//If only one page in the collection, copy it directly to the target file.if (imageFiles.Count==1){File.Copy((string)imageFiles[0],outFile,true);return;}//use the save encoderEncoder enc=Encoder.SaveFlag;EncoderParameters ep=new EncoderParameters(2);ep.Param[0]=new EncoderParameter(enc,(long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(Encoder.Compression,(long)compressEncoder);Bitmap pages=null;int frame=0;ImageCodecInfo info=GetEncoderInfo("image/tiff");foreach(string strImageFile in imageFiles){if(frame==0){pages=(Bitmap)Image.FromFile(strImageFile);//save the first framepages.Save(outFile,info,ep);}else{//save the intermediate framesep.Param[0]=new EncoderParameter(enc,(long)EncoderValue.FrameDimensionPage);Bitmap bm=(Bitmap)Image.FromFile(strImageFile);pages.SaveAdd(bm,ep);bm.Dispose();} if(frame==imageFiles.Count-1){//flush and close.ep.Param[0]=new EncoderParameter(enc,(long)EncoderValue.Flush);pages.SaveAdd(ep);}frame++;}}catch (Exception ex){
#if DEBUGConsole.WriteLine(ex.Message);
#endifthrow;}return;}/// <summary>/// Remove a specific page within the image object and save the result to an output image file./// </summary>/// <param name="pageNumber">page number to be removed</param>/// <param name="compressEncoder">compress encoder after operation</param>/// <param name="strFileName">filename to be outputed</param>/// <returns></</returns>public void RemoveAPage(int pageNumber,EncoderValue compressEncoder,string strFileName){try{//Split the image files to single pages.ArrayList arrSplited=SplitTiffImage(this._TempWorkingDir,compressEncoder);//Remove the specific page from the collectionstring strPageRemove=string.Format("{0}\\{1}{2}.TIF",_TempWorkingDir,GetFileNameStartString(this._ImageFileName),pageNumber);arrSplited.Remove(strPageRemove);JoinTiffImages(arrSplited,strFileName,compressEncoder);}catch(Exception){throw;}return;}/// <summary>/// Getting the supported codec info./// </summary>/// <param name="mimeType">description of mime type</param>/// <returns>image codec info</returns>private ImageCodecInfo GetEncoderInfo(string mimeType){ImageCodecInfo[] encoders=ImageCodecInfo.GetImageEncoders();for (int j=0;j<encoders.Length;j++){if (encoders[j].MimeType==mimeType)return encoders[j];}throw new Exception( mimeType + " mime type not found in ImageCodecInfo" );}/// <summary>/// Return the memory steam of a specific page/// </summary>/// <param name="pageNumber">page number to be extracted</param>/// <returns>image object</returns>public Image GetSpecificPage(int pageNumber){MemoryStream ms=null;Image retImage=null;try{ms=new MemoryStream();Guid objGuid=image.FrameDimensionsList[0];FrameDimension objDimension=new FrameDimension(objGuid);image.SelectActiveFrame(objDimension,pageNumber);image.Save(ms,ImageFormat.Bmp);retImage=Image.FromStream(ms);return retImage;}catch (Exception){ms.Close();retImage.Dispose();throw;}}/// <summary>/// Convert the existing TIFF to a different codec format/// </summary>/// <param name="compressEncoder"></param>/// <returns></returns>public void ConvertTiffFormat(string strNewImageFileName,EncoderValue compressEncoder){//Split the image files to single pages.ArrayList arrSplited=SplitTiffImage(this._TempWorkingDir,compressEncoder);JoinTiffImages(arrSplited,strNewImageFileName,compressEncoder);return;}/// <summary>/// Image file to operate/// </summary>public string ImageFileName{get{return _ImageFileName;}set{_ImageFileName=value;}}/// <summary>/// Buffering directory/// </summary>public string TempWorkingDir{get{return _TempWorkingDir;}set{_TempWorkingDir=value;}}/// <summary>/// Image page number/// </summary>public int PageNumber{get{return _PageNumber;}}#region IDisposable Memberspublic void Dispose(){image.Dispose();System.GC.SuppressFinalize(this);}#endregion}
}

PDF to Tiff

18. July 2010 22:33 by Jerry in Old blog posts

I don’t know why, it seems to be hard to find something to convert PDF to Tiff over the web. Maybe TIFF is not that popular than other formats. Few months ago, I had a task at work to find a new way to generate tiff files out of crystal report. Previously we have a batch job that print the crystal report to a virtual printer to produce a tiff file. It was working fine, but from now and then the job hit an IO error couple times in a month. I was pissed off by being called at night (the job was running overnight). So I decided to revamp this piece of sxxx process.

After some searching, I realized that I need to solve 2 problems:

  • PDF to TIFF by using 3rd party component. I chose Ghostscript API, because it’s free and simple (one dll).
    The only issue of Ghostscript API (or other components) in this case is that, if the PDF has multiple pages, it produces multiple tiff files which that each tiff representing one page in the PDF. So it brings us to the next step;
  • Group all single page tiff files into one multiple pages TIFF

The source code provide below is running quite stable as batch job for a few months.

References

Ghostscript: http://www.ghostscript.com/ you need to put the gsdll32.dll in the same folder of your dll/exe

for step 2, the related source code was convert from C# in this article:
http://www.codeproject.com/KB/GDI-plus/SaveMultipageTiff.aspx
However, the ConvertToBitonal function has a bug. You need to dispose the original bitmap object (original.Dispose();) before returning destination.

Usage

ConvertFile("c:\2.tiff", "C:\temp\pdf\PWBSample.pdf", "c:\temp\tiff", "-IC:\Program Files\gs\gs8.70\lib;C:\Program Files\gs\fonts;C:/Windows/fonts")
 

Source Code

 

' Copyright (c) 2002 Dan Mount and Ghostgum Software Pty Ltd
'
' Permission is hereby granted, free of charge, to any person obtaining
' a copy of this software and associated documentation files (the
' "Software"), to deal in the Software without restriction, including
' without limitation the rights to use, copy, modify, merge, publish,
' distribute, sublicense, and/or sell copies of the Software, and to
' permit persons to whom the Software is furnished to do so, subject to
' the following conditions:
'
' The above copyright notice and this permission notice shall be
' included in all copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
' EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
' MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
' NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
' BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
' ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
' CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.


' This is an example of how to call the Ghostscript DLL from
' Visual Basic.NET. There are two examples, one converts
' colorcir.ps to PDF, the other is like command line Ghostscript.
' The display device is not supported.
'
' This code is not compatible with VB6. There is another
' example which does work with VB6. Differences include:
' 1. VB.NET uses GCHandle to get pointer
' VB6 uses StrPtr/VarPtr
' 2. VB.NET Integer is 32bits, Long is 64bits
' VB6 Integer is 16bits, Long is 32bits
' 3. VB.NET uses IntPtr for pointers
' VB6 uses Long for pointers
' 4. VB.NET strings are always Unicode
' VB6 can create an ANSI string
' See the following URL for some VB6 / VB.NET details
' http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvb600/html/vb6tovbdotnet.asp

Option Explicit On

Imports System.Runtime.InteropServices
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Drawing

Module gsapi

Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal dest As IntPtr, ByVal source As IntPtr, ByVal bytes As Long)

'------------------------------------------------
'UDTs Start
'------------------------------------------------
<StructLayout(LayoutKind.Sequential)> Public Structure GS_Revision
Public strProduct As IntPtr
Public strCopyright As IntPtr
Public intRevision As Integer
Public intRevisionDate As Integer
End Structure
'------------------------------------------------
'UDTs End
'------------------------------------------------

'------------------------------------------------
'Callback Functions Start
'------------------------------------------------
'These are only required if you use gsapi_set_stdio
Public Delegate Function StdioCallBack(ByVal handle As IntPtr, ByVal strptr As IntPtr, ByVal count As Integer) As Integer

Public Function gsdll_stdin(ByVal intGSInstanceHandle As IntPtr, ByVal strz As IntPtr, ByVal intBytes As Integer) As Integer
' This is dumb code that reads one byte at a time
' Ghostscript doesn't mind this, it is just very slow
If intBytes = 0 Then
gsdll_stdin = 0
Else
Dim ich As Integer = Console.Read()
If ich = -1 Then
gsdll_stdin = 0 ' EOF
Else
Dim bch As Byte = ich
Dim gcByte As GCHandle = GCHandle.Alloc(bch, GCHandleType.Pinned)
Dim ptrByte As IntPtr = gcByte.AddrOfPinnedObject()
CopyMemory(strz, ptrByte, 1)
ptrByte = IntPtr.Zero
gcByte.Free()
gsdll_stdin = 1
End If
End If
End Function

Public Function gsdll_stdout(ByVal intGSInstanceHandle As IntPtr, ByVal strz As IntPtr, ByVal intBytes As Integer) As Integer
' If you can think of a more efficient method, please tell me!
' We need to convert from a byte buffer to a string
' First we create a byte array of the appropriate size
Dim aByte(intBytes) As Byte
' Then we get the address of the byte array
Dim gcByte As GCHandle = GCHandle.Alloc(aByte, GCHandleType.Pinned)
Dim ptrByte As IntPtr = gcByte.AddrOfPinnedObject()
' Then we copy the buffer to the byte array
CopyMemory(ptrByte, strz, intBytes)
' Release the address locking
ptrByte = IntPtr.Zero
gcByte.Free()
' Then we copy the byte array to a string, character by character
Dim str As String = ""

For i As Integer = 0 To intBytes - 1
str = str + Chr(aByte(i))
Next
' Finally we output the message
Console.Write(str)
gsdll_stdout = intBytes
End Function

Public Function gsdll_stderr(ByVal intGSInstanceHandle As IntPtr, ByVal strz As IntPtr, ByVal intBytes As Integer) As Integer
gsdll_stderr = gsdll_stdout(intGSInstanceHandle, strz, intBytes)
End Function
'------------------------------------------------
'Callback Functions End
'------------------------------------------------

'------------------------------------------------
'API Calls Start
'------------------------------------------------
'Win32 API
'GhostScript API
' Public Declare Function gsapi_revision Lib "gsdll32.dll" (ByVal pGSRevisionInfo As IntPtr, ByVal intLen As Integer) As Integer
Public Declare Function gsapi_revision Lib "gsdll32.dll" (ByRef pGSRevisionInfo As GS_Revision, ByVal intLen As Integer) As Integer
Public Declare Function gsapi_new_instance Lib "gsdll32.dll" (ByRef lngGSInstance As IntPtr, ByVal lngCallerHandle As IntPtr) As Integer
Public Declare Function gsapi_set_stdio Lib "gsdll32.dll" (ByVal lngGSInstance As IntPtr, ByVal gsdll_stdin As StdioCallBack, ByVal gsdll_stdout As StdioCallBack, ByVal gsdll_stderr As StdioCallBack) As Integer
Public Declare Sub gsapi_delete_instance Lib "gsdll32.dll" (ByVal lngGSInstance As IntPtr)
Public Declare Function gsapi_init_with_args Lib "gsdll32.dll" (ByVal lngGSInstance As IntPtr, ByVal lngArgumentCount As Integer, ByVal lngArguments As IntPtr) As Integer
Public Declare Function gsapi_run_file Lib "gsdll32.dll" (ByVal lngGSInstance As IntPtr, ByVal strFileName As String, ByVal intErrors As Integer, ByVal intExitCode As Integer) As Integer
Public Declare Function gsapi_exit Lib "gsdll32.dll" (ByVal lngGSInstance As IntPtr) As Integer
'------------------------------------------------
'API Calls End
'------------------------------------------------

'------------------------------------------------
'User Defined Functions Start
'------------------------------------------------
Public Function StringToAnsiZ(ByVal str As String) As Byte()
' Convert a Unicode string to a null terminated Ansi string for Ghostscript.
' The result is stored in a byte array. Later you will need to convert
' this byte array to a pointer with GCHandle.Alloc(XXXX, GCHandleType.Pinned)
' and GSHandle.AddrOfPinnedObject()
Dim intElementCount As Integer
Dim intCounter As Integer
Dim aAnsi() As Byte
Dim bChar As Byte
intElementCount = Len(str)
ReDim aAnsi(intElementCount + 1)
For intCounter = 0 To intElementCount - 1
bChar = Asc(Mid(str, intCounter + 1, 1))
aAnsi(intCounter) = bChar
Next intCounter
aAnsi(intElementCount) = 0
StringToAnsiZ = aAnsi
End Function

Public Function AnsiZtoString(ByVal strz As IntPtr) As String
' We need to convert from a byte buffer to a string
Dim byteCh(1) As Byte
Dim bOK As Boolean = True
Dim gcbyteCh As GCHandle = GCHandle.Alloc(byteCh, GCHandleType.Pinned)
Dim ptrByte As IntPtr = gcbyteCh.AddrOfPinnedObject()
Dim j As Integer = 0
Dim str As String = ""
While bOK
' This is how to do pointer arithmetic!
Dim sPtr As New IntPtr(strz.ToInt64() + j)
CopyMemory(ptrByte, sPtr, 1)
If byteCh(0) = 0 Then
bOK = False
Else
str = str + Chr(byteCh(0))
End If
j = j + 1
End While
AnsiZtoString = str
End Function

Public Function CheckRevision(ByVal intRevision As Integer) As Boolean
' Check revision number of Ghostscript
Dim intReturn As Integer
Dim udtGSRevInfo As GS_Revision
Dim gcRevision As GCHandle
gcRevision = GCHandle.Alloc(udtGSRevInfo, GCHandleType.Pinned)
intReturn = gsapi_revision(udtGSRevInfo, 16)
Console.WriteLine("Revision = " & udtGSRevInfo.intRevision)
Console.WriteLine("RevisionDate = " & udtGSRevInfo.intRevisionDate)
Console.WriteLine("Product = " & AnsiZtoString(udtGSRevInfo.strProduct))
Console.WriteLine("Copyright = " & AnsiZtoString(udtGSRevInfo.strCopyright))

If udtGSRevInfo.intRevision = intRevision Then
CheckRevision = True
Else
CheckRevision = False
End If
gcRevision.Free()
End Function

Public Function CallGS(ByVal astrGSArgs() As String) As Boolean
Dim intReturn As Integer
Dim intGSInstanceHandle As IntPtr
Dim aAnsiArgs() As Object
Dim aPtrArgs() As IntPtr
Dim aGCHandle() As GCHandle
Dim intCounter As Integer
Dim intElementCount As Integer
'Dim iTemp As Integer
Dim callerHandle As IntPtr
Dim gchandleArgs As GCHandle
Dim intptrArgs As IntPtr

' Print out the revision details.
' If we want to insist on a particular version of Ghostscript
' we should check the return value of CheckRevision().
CheckRevision(704)

' Load Ghostscript and get the instance handle
intReturn = gsapi_new_instance(intGSInstanceHandle, callerHandle)
If (intReturn < 0) Then
Return (False)
End If

' Capture stdio
Dim stdinCallback As StdioCallBack
stdinCallback = AddressOf gsdll_stdin
Dim stdoutCallback As StdioCallBack
stdoutCallback = AddressOf gsdll_stdout
Dim stderrCallback As StdioCallBack
stderrCallback = AddressOf gsdll_stderr
intReturn = gsapi_set_stdio(intGSInstanceHandle, stdinCallback, stdoutCallback, stderrCallback)

If (intReturn >= 0) Then
' Convert the Unicode strings to null terminated ANSI byte arrays
' then get pointers to the byte arrays.
intElementCount = UBound(astrGSArgs)
ReDim aAnsiArgs(intElementCount)
ReDim aPtrArgs(intElementCount)
ReDim aGCHandle(intElementCount)
For intCounter = 0 To intElementCount
aAnsiArgs(intCounter) = StringToAnsiZ(astrGSArgs(intCounter))
aGCHandle(intCounter) = GCHandle.Alloc(aAnsiArgs(intCounter), GCHandleType.Pinned)
aPtrArgs(intCounter) = aGCHandle(intCounter).AddrOfPinnedObject()
Next
gchandleArgs = GCHandle.Alloc(aPtrArgs, GCHandleType.Pinned)
intptrArgs = gchandleArgs.AddrOfPinnedObject()
callerHandle = IntPtr.Zero

intReturn = gsapi_init_with_args(intGSInstanceHandle, intElementCount + 1, intptrArgs)

' Release the pinned memory
For intCounter = 0 To intElementCount
aGCHandle(intCounter).Free()
Next
gchandleArgs.Free()

' Stop the Ghostscript interpreter
gsapi_exit(intGSInstanceHandle)
End If

' release the Ghostscript instance handle
gsapi_delete_instance(intGSInstanceHandle)

If (intReturn >= 0) Then
CallGS = True
Else
CallGS = False
End If

End Function

Private Sub ClearTempFolder(ByVal path As String)
Dim folder As New DirectoryInfo(path)
Dim files() As FileInfo = folder.GetFiles()
For Each fi As FileInfo In files
fi.Delete()
Next
End Sub

Public Sub OutputToTiff(ByVal tifPath As String)
Dim folder As New DirectoryInfo(tmpFolder)
Dim files() As FileInfo = folder.GetFiles("*.tiff")
If files.Length > 0 Then
Dim imgs(files.Length - 1) As Image
SortByName(files)

For i As Integer = 0 To files.Length - 1
imgs(i) = Image.FromFile(files(i).FullName)
Next
saveMultipage(imgs, tifPath, "TIFF")
For Each img As Image In imgs
img.Dispose()
Next

'ClearTempFolder(tmpFolder)
End If
Directory.Delete(tmpFolder, True)
End Sub

Private tmpFolder As String

Private Function GetTempFolder() As String
Dim g As Guid = Guid.NewGuid()
While Directory.Exists(tmpFolder & "\" & g.ToString())
g = New Guid()
End While
Return tmpFolder & "\" & g.ToString()
End Function


Public Function ConvertFile(ByVal tifPath As String, ByVal pdfSource As String, ByVal tempFolder As String, ByVal startUpStr As String) As Boolean
tmpFolder = tempFolder

tmpFolder = GetTempFolder()
Directory.CreateDirectory(tmpFolder)
'ClearTempFolder("c:\temp\tiff")
Dim astrArgs(16) As String
astrArgs(0) = "accfax" 'The First Parameter is Ignored
astrArgs(1) = startUpStr
astrArgs(2) = "-dNOPAUSE"
astrArgs(3) = "-dBATCH"
astrArgs(4) = "-dSAFER"
astrArgs(5) = "-sDEVICE=tiffg4"
astrArgs(6) = "-r300"
astrArgs(7) = "-sOutputFile=" & tmpFolder & "\%03d.tiff"
astrArgs(8) = "-dDEVICEXRESOLUTION=204"
astrArgs(9) = "-dDEVICEYRESOLUTION=196"
astrArgs(10) = "-dDEVICEWIDTH=1686"
astrArgs(11) = "-dDEVICEHEIGHT=2292"
astrArgs(12) = "-dNOPLATFONTS"
astrArgs(13) = "-sFONTPATH=""c:\psfonts\"""
astrArgs(14) = "-c ""<< /Policies << /PageSize 5 >> /PageSize [595 842]/InputAttributes currentpagedevice /InputAttributes get mark exch {1index /Priority eq not {pop << /PageSize [595 842] >>} if } forall >>setpagedevice"" -f"""
astrArgs(15) = "-f"
astrArgs(16) = pdfSource
If CallGS(astrArgs) Then
OutputToTiff(tifPath)
End If

End Function

Private Function InteractiveGS() As Boolean
Dim astrArgs(2) As String
astrArgs(0) = "gs" 'The First Parameter is Ignored
astrArgs(1) = "-c"
astrArgs(2) = "systemdict /start get exec"
Return CallGS(astrArgs)
End Function


'------------------------------------------------
'User Defined Functions End
'------------------------------------------------

'Sub Main()
' ConvertFile()
' 'InteractiveGS()
' MsgBox("Done")
'End Sub

#Region "multi-pages tiff generation"
Private Function saveMultipage(ByVal bmp() As Image, ByVal location As String, ByVal type As String) As Boolean
If Not bmp Is Nothing Then
Try
Dim codecInfo As ImageCodecInfo = getCodecForstring(type)


For i As Integer = 0 To bmp.Length - 1
If bmp(i) Is Nothing Then
Exit For
End If
bmp(i) = CType(ConvertToBitonal(CType(bmp(i), Bitmap)), Image)
Next

If bmp.Length = 1 Then

Dim iparams As EncoderParameters = New EncoderParameters(1)
Dim iparam As Encoder = Encoder.Compression
Dim iparamPara As EncoderParameter = New EncoderParameter(iparam, CType((EncoderValue.CompressionCCITT4), Long))
iparams.Param(0) = iparamPara
bmp(0).Save(location, codecInfo, iparams)


ElseIf bmp.Length > 1 Then

Dim saveEncoder As Encoder
Dim compressionEncoder As Encoder
Dim SaveEncodeParam As EncoderParameter
Dim CompressionEncodeParam As EncoderParameter
Dim EncoderParams As EncoderParameters = New EncoderParameters(2)

saveEncoder = Encoder.SaveFlag
compressionEncoder = Encoder.Compression

' Save the first page (frame).
SaveEncodeParam = New EncoderParameter(saveEncoder, CType(EncoderValue.MultiFrame, Long))
CompressionEncodeParam = New EncoderParameter(compressionEncoder, CType(EncoderValue.CompressionCCITT4, Long))
EncoderParams.Param(0) = CompressionEncodeParam
EncoderParams.Param(1) = SaveEncodeParam

File.Delete(location)
bmp(0).Save(location, codecInfo, EncoderParams)



For i As Integer = 1 To bmp.Length - 1
If bmp(i) Is Nothing Then
Exit For
End If

SaveEncodeParam = New EncoderParameter(saveEncoder, CType(EncoderValue.FrameDimensionPage, Long))
CompressionEncodeParam = New EncoderParameter(compressionEncoder, CType(EncoderValue.CompressionCCITT4, Long))
EncoderParams.Param(0) = CompressionEncodeParam
EncoderParams.Param(1) = SaveEncodeParam
bmp(0).SaveAdd(bmp(i), EncoderParams)
bmp(i).Dispose()
Next

SaveEncodeParam = New EncoderParameter(saveEncoder, CType(EncoderValue.Flush, Long))
EncoderParams.Param(0) = SaveEncodeParam
bmp(0).SaveAdd(EncoderParams)
bmp(0).Dispose()
End If
Return True


Catch ee As System.Exception
Throw New Exception(ee.Message + " Error in saving as multipage ")
End Try
Else
Return False
End If

End Function

Private Function getCodecForstring(ByVal type As String) As ImageCodecInfo
Dim info() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()

Dim i As Integer
For i = 0 To info.Length - 1 Step i + 1
Dim EnumName As String = type.ToString()
If info(i).FormatDescription.Equals(EnumName) Then
Return info(i)
End If
Next

Return Nothing

End Function

Private Function ConvertToBitonal(ByVal original As Bitmap) As Bitmap
Dim source As Bitmap = Nothing

' If original bitmap is not already in 32 BPP, ARGB format, then convert
If original.PixelFormat <> PixelFormat.Format32bppArgb Then
source = New Bitmap(original.Width, original.Height, PixelFormat.Format32bppArgb)
source.SetResolution(original.HorizontalResolution, original.VerticalResolution)
Using g As Graphics = Graphics.FromImage(source)
g.DrawImageUnscaled(original, 0, 0)
End Using
Else
source = original
End If

' Lock source bitmap in memory
Dim sourceData As Imaging.BitmapData = source.LockBits(New Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)

' Copy image data to binary array
Dim imageSize As Integer = sourceData.Stride * sourceData.Height
Dim sourceBuffer(imageSize) As Byte
Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize)

' Unlock source bitmap
source.UnlockBits(sourceData)

' Create destination bitmap
Dim destination As Bitmap = New Bitmap(source.Width, source.Height, PixelFormat.Format1bppIndexed)

' Lock destination bitmap in memory
Dim destinationData As BitmapData = destination.LockBits(New Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed)

' Create destination buffer
imageSize = destinationData.Stride * destinationData.Height
Dim destinationBuffer(imageSize) As Byte

Dim sourceIndex As Integer = 0
Dim destinationIndex As Integer = 0
Dim pixelTotal As Integer = 0
Dim destinationValue As Byte = 0
Dim pixelValue As Integer = 128
Dim height As Integer = source.Height
Dim width As Integer = source.Width
Dim threshold As Integer = 500

' Iterate lines

For y As Integer = 0 To height - 1
sourceIndex = y * sourceData.Stride
destinationIndex = y * destinationData.Stride
destinationValue = 0
pixelValue = 128

' Iterate pixels
For x As Integer = 0 To width - 1
' Compute pixel brightness (i.e. total of Red, Green, and Blue values)
pixelTotal = CType(sourceBuffer(sourceIndex + 1), Integer) + CType(sourceBuffer(sourceIndex + 2), Integer) + CType(sourceBuffer(sourceIndex + 3), Integer)
If pixelTotal > threshold Then
destinationValue += CType(pixelValue, Byte)
End If
If pixelValue = 1 Then
destinationBuffer(destinationIndex) = destinationValue
destinationIndex = destinationIndex + 1
destinationValue = 0
pixelValue = 128
Else
pixelValue = pixelValue >> 1
End If
sourceIndex += 4
Next
If pixelValue <> 128 Then
destinationBuffer(destinationIndex) = destinationValue
End If
Next

' Copy binary image data to destination bitmap
Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize)

' Unlock destination bitmap
destination.UnlockBits(destinationData)
original.Dispose()
' Return
Return destination
End Function

Private Function Compare(ByVal d1 As FileInfo, ByVal d2 As FileInfo) As Integer
Return d1.Name.CompareTo(d2.Name)
End Function

Private Sub SortByName(ByVal files As FileInfo())
Array.Sort(Of FileInfo)(files, New Comparison(Of FileInfo)(AddressOf Compare))

End Sub

#End Region

End Module

SqlCommand to Sql statement

18. July 2010 22:31 by Jerry in Old blog posts

Recently I have a requirement that log down the message when an error occurs on the server. If the error was caused by execution of SQL statement, log that as well.

It came to a problem that when the SQL is carried by a SqlCommand object, there is no any built-in function to get back the SQL statement in a string format. I wrote a small VB module to do the job.

The primary idea is going through the CommandText, record every place (replace index) that need to replace the parameter name (starts with “@"), and then replace them.

 

The code is written in VB.NET, but it should not be difficult to convert to C# by using http://www.developerfusion.com/tools/convert/vb-to-csharp/

Usage:

smply call SqlCommandToSql and pass in a SqlCommand object.

Dim cmd As New SqlClient.SqlCommand()
cmd.CommandText = "update abcd set a=@a,b=@ab, c=@abc where cd=@a"
cmd.Parameters.Add("@a", SqlDbType.VarChar).Value = "a@aa"
cmd.Parameters.Add("@ab", SqlDbType.Bit).Value = False
cmd.Parameters.Add("@abc", SqlDbType.DateTime).Value = Now
MsgBox(SqlCommandToSql(cmd)) 

 

source code:

Imports System.Data.SqlClient

Friend Module Module1
Private Class ReplaceIndex
Implements IComparable

Public Index As Integer
Public ParaName As String
Public Sub New(ByVal idx As Integer, ByVal para As String)
Index = idx
ParaName = para
End Sub

Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
Dim r As ReplaceIndex = DirectCast(obj, ReplaceIndex)
Return Me.Index - r.Index
End Function
End Class

Private Function GetParaValue(ByVal para As SqlParameter) As String
Dim value As String = ""
If para.Value Is Nothing Then
'it should throw an error if an parameter had not set value
'but here just make it through
value = "Nothing"
End If
If para.Value Is DBNull.Value Then
value = "NULL"
End If
value = para.Value.ToString()
'special handle for some types
Select Case para.SqlDbType
Case SqlDbType.VarChar, SqlDbType.Char, SqlDbType.Text, SqlDbType.NChar, SqlDbType.NText, SqlDbType.NVarChar
value = "'" & value.Replace("'", "''") & "'"
Case SqlDbType.Date, SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.Time
value = "'" & value & "'"
Case SqlDbType.Binary, SqlDbType.Image, SqlDbType.VarBinary, SqlDbType.Timestamp
value = "0x" & BitConverter.ToString(TryCast(para.Value, Byte())).Replace("-", "")
Case SqlDbType.Bit
If TypeOf para.Value Is Boolean Then
value = IIf(para.Value, "1", "0")
End If
End Select
Return value
End Function

Private Sub Replace(ByRef source As String, ByVal startIdx As Integer, ByVal paraName As String, ByVal paraType As SqlDbType, ByVal value As String)
Dim len As Integer = paraName.Length
source = source.Remove(startIdx, len)
source = source.Insert(startIdx, value)

End Sub




Public Function SqlCommandToSql(ByVal cmd As SqlCommand) As String
'loop through the parameters
'record the start index where need to replace every para name
'loop the index array, replace para name one by one
'when replace one, need to adjust the rest indexs, since the string length might be changed
Dim index As New Hashtable()

Dim sql As String = cmd.CommandText

For Each p As SqlParameter In cmd.Parameters
FindIndex(index, sql, 0, p)
'index.Add(p, idx)
Next

Dim keyCollection As ICollection = index.Keys
Dim keys As ReplaceIndex() = New ReplaceIndex(keyCollection.Count - 1) {}
keyCollection.CopyTo(keys, 0)
'sort the index first
Array.Sort(keys)

Dim offset As Integer = 0
'loop through each replace point(index)
For i As Integer = 0 To keys.Length - 1
Dim r As ReplaceIndex = DirectCast(keys(i), ReplaceIndex)
Dim p As SqlParameter = DirectCast(index(r), SqlParameter)
Dim value As String = GetParaValue(p)
r.Index += offset
Replace(sql, r.Index, p.ParameterName, p.SqlDbType, value)
'calc the total offset
offset += value.Length - p.ParameterName.Length
Next

Return sql
End Function

Private Sub FindIndex(ByVal ht As Hashtable, ByVal source As String, ByVal startIdx As Integer, ByVal para As SqlParameter)
Dim idx As Integer = source.IndexOf(para.ParameterName, startIdx)
If idx < 0 Then
'no more match is found
Exit Sub
End If
Dim idx2 As Integer = source.LastIndexOf(para.ParameterName)
If idx = idx2 Then
'only one match in the remaining string
idx2 += para.ParameterName.Length
If idx2 >= source.Length Then
Dim r As New ReplaceIndex(idx, para.ParameterName)
ht.Add(r, para)
Else
Dim nextChar As String = source.Substring(idx2, 1)
'if the next char is special charater, this is the match we are looking for
If " ~!@#$%^&*()+-={}[]\|;:,./?'""".Contains(nextChar) Then
Dim r As New ReplaceIndex(idx, para.ParameterName)
ht.Add(r, para)

End If
End If

Exit Sub
End If

'more than once match the parameter name
'e.g. @a will match @a, @ab and @abc, etc.
'store each start index
Dim index As New List(Of Integer)
index.Add(idx)
'index.Add(idx2)
idx = source.IndexOf(para.ParameterName, idx + para.ParameterName.Length)
While idx <> idx2
index.Add(idx)
idx = source.IndexOf(para.ParameterName, idx + para.ParameterName.Length)
End While
'find the actual match index
For Each i As Integer In index
idx2 = i + para.ParameterName.Length
startIdx = idx2
If idx2 = source.Length Then
'this match is the last one (reach the end of source string)
Dim r As New ReplaceIndex(i, para.ParameterName)
ht.Add(r, para)
Exit Sub
Else
Dim nextChar As String = source.Substring(idx2, 1)
'if the next char is special charater, this is the match we are looking for
If " ~!@#$%^&*()+-={}[]\|;:,./?'""".Contains(nextChar) Then
Dim r As New ReplaceIndex(i, para.ParameterName)
ht.Add(r, para)

FindIndex(ht, source, startIdx, para)
Exit Sub
End If
End If
Next
FindIndex(ht, source, startIdx, para)
End Sub
End Module

How to be compatible with UpdatePanel or ASP.NET AJAX

18. July 2010 22:26 by Jerry in Old blog posts

Suppose you have following function in your project:

C# Code:

    

Code
1
2
3
4
5
6
7
8
9
10
public void MessageBox(string msgText){string scriptKey = "Message";if (!ClientScript.IsStartupScriptRegistered(scriptKey)){ClientScript.RegisterStartupScript(this.GetType(), scriptKey, "<script>alert('" + msgText + "')</script>");}}

VB Code:

   

Code
1
2
3
4
5
6
7
8
9
10
11
 Protected Sub MessageBox(ByVal strMsg As String)Dim key As String = "Message"If Not ClientScript.IsStartupScriptRegistered(key) ThenClientScript.RegisterStartupScript(Me.GetType(), key, "<script>alert('" + strMsg + "');</script>")End IfEnd IfEnd Sub 

This function is to show a client-side message box by using javascript. You might utilize this function like this:

C# Code:

       

Code
1
2
3
4
5
6
7
8
9
protected void btnSearch_Click(object sender, EventArgs e){......code omitted MessageBox("Search completed!");}

VB Code:

  

Code
1
2
3
4
5
6
7
8
9
10
Protected Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click......code omittedMessageBox("Search completed!")End Sub

The code above has no problem at all if not using AJAX. With Ajax extension however, the button "btnSearch" will be placed inside an UpdatePanel control to avoid the page being post-back.  The MessageBox will not work as normal any more afterward. In such case, you might need to do some extra work on the MessageBox method.

C# Code:

       

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 public void MessageBox(string msgText){string scriptKey = "Message";if (ScriptManager.GetCurrent(this.Page)!=null && ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack {ScriptManager.RegisterStartupScript(this, this.GetType(), scriptKey , "alert('" + msgText+ "');", true);}else {if (!ClientScript.IsStartupScriptRegistered(scriptKey)){ClientScript.RegisterStartupScript(this.GetType(), scriptKey, "<script>alert('" + msgText + "')</script>");}}}

VB Code:

   

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Protected Sub MessageBox(ByVal strMsg As String)Dim key As String = "Message"If ScriptManager.GetCurrent(Me.Page) IsNot Nothing AndAlso ScriptManager.GetCurrent(Me.Page).IsInAsyncPostBack Then'to support ajax post back ScriptManager.RegisterStartupScript(Me, Me.GetType(), key, "alert('" + strMsg + "');", True)Else'normal callIf Not ClientScript.IsStartupScriptRegistered(key) ThenClientScript.RegisterStartupScript(Me.GetType(), key, "<script>alert('" + strMsg + "');</script>")End IfEnd IfEnd Sub

Simply use RegisterStartupScript from ScriptManager (System.Web.Extension.dll) to generate javascript code instead of that from Page object.

Hope you enjoy with ASP.NET AJAX again!