Saturday, February 28, 2009

Using EXEC() AT with Oracle DB

My previous blog was about using OPENQUERY() method with an Oracle DB. The advantage of using this method call is to pass through a query to a linked server such as Oracle server and to leverage the Oracle server to do the job. The great benefit of this strategy is to obtain much fast performance compared to using a T-SQL query directly against an Oracle database object locally at SQL server.

However, when I tried OPENQUERY next day. I was so disappointed. What I found is that the query passed to OPENQUERY() must be a literal string, no variable or expression is supported. That means I cannot build a query string dynamically with different constrains. This greatly limits the usage of OPENQUERY. I just cannot use it in my projects.

Fortunately, I found another pass-through way to leverage Oracle's power to query data, and it is possible to pass result back. I spent about one and half day to figure it out. I posted several questions to StackOverflow web site but I did not get any answer there. Eventually I got the solution through Google searching. I posed my answer to StackOverflow as well.

The method is to use "EXEC (...) AT ..." to the job:

EXEC (@sql) AT linedOracleServer;

Actually, there are some good examples of using this method. However, all those examples are using either Microsoft SQL server or Express SQL server. By using pass-through query, the syntax of the query is very different from Microsoft SQL server and Oracle SQL server. That's why it took me a while to figure it out.

I can build an Oracle SQL query to combine all the inputs into a query string. That's an easy part. The most challenge issue is to pass results as output parameters. For example, I need to get total count of rows in an Oracle table with WHERE clause, and pass the result out to my SQL server.

Here is what I did:

DECLARE @sql NVARCHAR(MAX);
DECLARE @myCount INT;
-- Initialize setting
SET @myCount = NULL;
-- Build sql query
SET @sql = N'
BEGIN
SELECT COUNT(*) INTO :myCount
FROM owner.myTable
WHERE id = '
+ CAST(@id AS VARCHAR) + N';
END;'
;
EXEC (@sql, @myCount OUTPUT) AT linedOracleServer;
IF (@myCount IS NOT NULL)
BEGIN
PRINT
'I get the count from my Oracle table: ' +
CAST(@myCount AS VARCHAR);
END
ELSE
BEGIN
PRINT
'It must be an query syntax error';
END

The key points to build an Oracle query with an output parameter is to follow these steps:
  • making sure the query being a valid Oracle PL/SQL query such as SELECT ... INTO ... to assign result to a variable or parameter;
  • using ":" before a parameter name;
  • using an anonymous block (BEGIN...END) to wrap the query; and
  • Appending ";" at the "END" block.


One lesson I learned from this practice is that exceptions raised by "EXE () AT" may provide misleading error messages. For example, when I used "@" for parameter or missed ";" after END. I got somethink like "illegal characters in expression". You have to open your view in all different angles.

Read More...

Wednesday, February 25, 2009

Using OPENQUERY for Oracle DB

Today I googled an alternative solution to run an Oracle PL/SQL query or stored procedure from Microsoft SQL server 2005. I am very impressed by the result of this alternative way.

What I mean by an alternative way is that I have been using T-SQL queries directly against linked servers defined in Microsoft SQL server. A linked server is a server added to Server Objects->Linked Servers by using Microsoft SQL Sever Management Studio tool.



The linked server that Microsoft SQL server supports covers a variety of database servers, including Oracle server. By using T-SQL queries, you can easily query data from to any database object such as a table or view on this server in the same way as querying data from a local table or view, as in the following example:

SELECT COUNT(*) AS MyCount 
FROM myOracleServer..owner.tableName
WHERE ...;

where myOracleServer could be a linked server to an Oracle server.

One problem I troubles me is that when a table on Oracle side is very big(with millions of rows of data), the query may take a while to execute, sometimes more than 1 minute just for a query call. I had many cases to take more than 10 hours to update data from my Microsoft SQL server to an Oracle server with thousands of T-SQL calls(checking, updating and inserting data).

The alternative way I found today is to use OPENQUERY call like this:

SELECT MyCount 
FROM OPENQUERY(myOracleServer,
N'SELECT COUNT(*) AS MyCount FROM owner.tableName WHERE ...');

The execution time is 00:00:00 comparing 00:01:09 with the similar direct T-SQL query as above. It was a stunning when I saw the result back right away.

The information I found is from a discussion on Bytes web forum, where one person responded a recommendation by using OPENQUERY in a Google Groups' discussion. Then I figured out the solution that I need to improve my current T-SQLs.

The reason for such a big difference, I think o as my understanding, is that the SQL server may create a temporary table or allocate a cache for the database object referenced by a linked server in a T-SQL' query, while OPENQUERY is just a OLE DB connection call to the linked server with a SQL query by which the server or Oracle does its job with its full power.

Read More...

Sunday, February 22, 2009

T-SQL Tip: Combine Column Names as a String

I found following T-SQL query to build a string of selected column names together separated by command for a table. This string can be used then for another SQL query as a column list.

The first thing what I did is to use Coaslesce function to combine a list of row values into a string, separated by ',' if a value is not null or '' if null.

The second trick is to use information_schema.colums to get column names by column_name. Notice that table_name and column_name are a special key words here for table and column names.

1    DECLARE @v_FiledList NVARCHAR(MAX);
2 -- Use Coalesce to combine rows to a string
3 SELECT @v_FieldList = COALESCE(@v_FieldList + ',','') + column_name
4 FROM (
5 -- Use information_schema to get table's column names
6 SELECT column_name FROM information_schema.columns
7 WHERE table_name = 'myTable' AND
8 column_name NOT LIKE 'keyCol' -- filter col 'keyCol' out
9 ) AS A;
10 PRINT 'Field list: ' + @v_FieldList;

You can get more detail information such as data type, length, and so on from information_schema.columns:
SELECT column_name, * 
FROM information_schema.columns
WHERE table_name = 'myTable'

Read More...

Tuesday, February 17, 2009

jQuery Tutorial Videos

Today Ajaxian posted a group of tutorial videos on jQuery. I just finished the first one by John Resig, the designer and developer of jQuery. I saw a number of his training videos. The first one by Ajaxian's blog is for entry level:



Not sure what link is used for this embedded video, Adobe flash? The quality of the video is quite good, comparing to similar ones on YouTube.com.

By the way, the editor John used for the video is SubEthaEdit, an interesting editor with multi-user to work on one text file.

Read More...

Thursday, February 12, 2009

Vimperator Tip of the Day: xall Command

Tip of the DayIn my Firefox Preference, I have set up my tab settings to save all the tab as a session when it is closed and reopen the session when it starts.

However, sometimes this feature does not work. I get a blank tab occasionally and lost my previous tabs. I don't know why.

Today I found a Vimperator command to resolve the issue: xall command. Just type :x and then tab, this command is available for use. The description for this command is:

    Save the session and quit
or a snap-short:



Just remember to use this command close my Firefox from now on. I have add this key to My favorite Vimperator Keys.

The Power of Muscle Memory with Vimperator!

Read More...

Tuesday, February 10, 2009

Command Line Tool: curl

toolsToday I watched a video on Atom Publishing Protocol at YouTube.com GoogleDevelopers. Further reading on this topic, I found an article on this by IBM: Getting to know the Atom Publishing Protocol Part 1.

One thing that got my attention is the command line tool: curl. In my Mac terminal, I found this one is available. That's Unix world benefit. According to the manual information of curl(man curl):

curl is a tool to transfer data from or to server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, SCP, SETP, TFTP, DICT, TELNET, LDAP, or FILE). The command is designed to work without user interaction.

That's a great tool. I like this one so that I can interact with a web server in command line. For example I tried this command to get a feed from a server:

curl -s -X GET http://heeds.beedburner.com/Macblogz?format=xml

Immediately I got returned strings back in the terminal. I tried to use Fixfox to open the feed but I could not GET result back in browser. Firefox prompted me to add it to my bookmark. By using curl tool, I can get the result back for analysis. It's a great tool to test and verify Atom Publishing Server or any web servers.

I don't think Windows cmd terminal has this one available. It might be something similar in PowerShell.

Read More...

Saturday, February 07, 2009

Caching Data and IFactory

Recently I have been working a project to extract data from a huge database server for a daily reporting service. The process generates data in a required format based a complicated business logic.

The structure of this project contains a Repository service as a gateway to provide interfaces to get domain objects by Domain classes. To retrieve data, I use IFactory pattern to get data:

interface IFactory<T> 
{
T CreateObject(IDBService);
}

where IDBService is an interface to provide methods to get data from database by using SQL.

The only problem with this strategy is that the process is too slow. It constantly makes SQL queries from the database, more than thousands SQL query calls.

I need a way to cache data to reduce those SQL calls at Repository. Since the data amount is none-predictable, I have to limit the cache. I use a maximum cache counter in the application configuration, 10000 as example. If the count of required data is less than this limit, then the Repository will cache all the data for later use. Otherwise, I have to get one data at a time.

The more I get into this caching feature, the better the process performs. With a maximum caching number, I reduced the SQL calls down to 8, and reduced the time from hours to minutes or less than 1 minute! That's great improvement.

For example, I created two factory classes for retrieving data:

public class SpectInfoListFac<List;<SpectInfo>> :
IFactory
{
...
List<SpectInfo> CreateObject(IDBSerivce db) {...}
...
}

public class SpectInfoFac<SpectInfo> :
IFactory
{
...
SpectInfo CreateObject(IDBSerivce db) {...}
...
}

For caching data, I used the first factory to get a list of data back if not too much data. The constructor of the factory provides information about the data and date range, as well as the maximum count number. If too much data or over the limit, the factory will return a null and I'll use the second factory class to get a specific data.

However,how about different levels of caching? Taking another finding people as example, if I want to find people with the name like "David Chu" and male from Canada, I may get too many. I could try with one more condition province = "AB", then city = "Calgary", then district area in "NW"... This will result in too many factory classes. Can I combine all these into one?

Here I changed the IFactory interface to a more generic way:

interface IFactory<T> 
{
IEnumerable<T> CreateObject(IDBService);
}

public class SpectInfoFac<SpectInfo> :
IFactory
{
...
IEnumerable<SpectInfo> CreateObject(IDBSerivce db, int level) {...}
...
}

There is only one method to create or retrieve objects. The level parameter is used for the granularity of data range. It will be up to the implementation Factory class to decide the level. For example, 0 for all, 1 for AB, 2 for Calgary...

The result is an enumerable collection. It could be a collection more than one, one for specified data item, or null for nothing being found.

Still I can have options with various implementations of IFactory class or one implementation to cover all the cases. My simplified factory pattern provides a caching option.

I love to re-factory of my codes!

Read More...

Sunday, February 01, 2009

Vimperator Tip of the Day: Show Sidebar Window


If you have not set your wideoptions to auto in your .vimperatorrc(for Mac) or _vimperatorrc(Windows), you may type the command to enable command auto-completion. Read details in my WordPress blog ....

Read More...

Saturday, January 31, 2009

Use Dropbox to Share Audios in Blog

I tried to update some audio files in my blog but I could not do it in Blogger. There is one option to add videos. When I tried this to update a mp3 file(about 3-4mb), it took me long time to upload. I had to give it up.

I have to use other web tools to load my mp3 files: Dropbox. This is a tool to share your files on web. If you install the application in your local computer either Mac or Windows, you can specify a folder to sync files between the computer and your Dropbox web server. One additional feature of this tool is that you can put files in public folder. Today I tried this one. It works perfect!

Here in my Mac, Control+click on a file in the public folder, you will see:



Copy the URL of public link, you can paste it to your blog like:

<img src="http://http://dl.getdropbox.com/u/268733/ChineseAudios/CCLesson.mp3" alt="dee" />

I verified that this feature is also available in Windows in a similar way.

The URL link is created when you upload a file to your public folder. It looks like a dynamically generated which does not have link to your Dropbox account. Anyway, it is a good way to put some files which you need to link to your blog to share.

Read More...

Monday, January 26, 2009

WordPress vs Blogger

I have tried WordPress for several days and posted several blogs there. It is good in terms of UI and some features such as rich templates and wedges like tag cloud. However, after digging several days, I find out there so many things are required with updates, such as spaces with medias and CSS styles.

I cannot add my own CSS styles to my templates so that my blog page cannot have default style classes for my code coloring. That's really bad. For images I had really hard time to find out a way to add to my posts, not as easy as Blogger. The only thing I was thinking to switch to WordPress is its UI, better than Blogger. For example, in the Compose mode I cannot add < char directly. I have to use &lt; instead. If I have a block of codes in clipboard, it will take me hard time to replace them.

However, I can still use the WordPress as well. I may use its Visual mode to convert these chars easily for me and then switch back to html mode to get the html source codes. I did the same thing by using ASP.Net forum's code generation piece to get color coded html source codes. By using WordPress I may reach to other people with the same interest. Just remember to post the same thing to two places, one with source and another is the link.

Read More...

Sunday, January 25, 2009

Vimperator Tip of the Day: Using Keys for Tabs

I have added a blog entry on my WordPress blog site: Vimerator Tip of the Day: Keys for Tabs.

Read More...

Tuesday, January 20, 2009

Live Mesh Devices Beta Available

Yesterday I learned from .Net Rocks audio talk on this new release from Microsoft. It is a tool to sync almost anything based on Web services or Cloud. I just tried this from iMac machine; unfortunately, it does not support Mac yet.

I have been used Dropbox to sync files between computers including Mac. Dropbox is only for file sharing with 2GB space for free. This tool is similar as Foxmarks, which is used to sync Firefox bookmarks.

Based on the information from the .Net Rocks talk, the Live Mesh is even bigger than those. It provides a framework for .Net developers to write services for various usages.

From my Mac, what I can do is to create folders on my Live Mesh Desktop. I think I can update or sync files with my local PC folders just like Dropbox.

Here is the picture of my Live Mesh:



I had my Firefox crashed when I browsing Live Mesh on my iMac.

Then I connected to my Windows though Remote Desktop Connection. I can view Live Mesh there and install Application Live Mesh, which is similar as Dropbox to sync files if I have files defined for sync. There is no more other features like services right now.

Read More...

Image Zoomer and Croppter

I read a new blog entry from Ajaxan on Dojo's demo on image zoomer. It is really cool. All the codes are based on Dojo and JavaScript.

There is one comment on this which provides another demo on image cropper UI. I know Prototype but never got chance to learn it. I only spent some time on Dojo at my iMac.

Read More...

Saturday, January 17, 2009

Vimerator Settings

Another feature of Vimperator is the settings. You can either set them dynamically or set in the configuration file, just like the way in Vim.

Here are two settings I think are very useful:


# enable hints for command mode
:set wildoptions=auto
# enable hints for links in command open mode. l or one.
:set cpt=l


Give these a try and see the difference. If you like them, you can add them to your Vimperator configuration setting file. In Windows, the file is _vimperatorrc in your %userprofile% directory; while .vimperator in your home for Mac.

When you open a link or type an Vimperator command with hint mode, you may see a list of hints available. Use Tab key to make a selection.

Updated: actually I found the same function of hints can be achieved without the settings. For example, press o to open a link with any word, link or blank. Press Tab key, then you will see a list of hints available. Same thing for any commands. For example, press :set then Tab, you will see a list of set commands available. Very cool, right? In addition to that, if you want to make a selection, just press tab key to make a selection.

Read More...

VIM + Firefox = Vimperator

I have used Vimperator for very long time. I can't believe that I don't have a blog on this issue. I think I started to use this after I read the blog by Jean Paul.

It is an add-on for Firefox. After the installation, all the menu, toolbar and address bar are invisible with maximum window of browser page. The only input place is on the bottom like this:



To use it, you have to use your keyboard to input command to control browsing, almost without mouse! just like using VIM or VI.

It took me about one week to taste the power of Vimperator. Now I cannot use my browser without it. Actually, I use just a few of keys only. Whenever I need a key for a feature normally used by mouse, I just search or read from the Vimperator help by F1 key in Windows or :help on Mac. Here is a list of keys I used commonly:


  • Esc key: escape from any mode. If you find out keys not working, you may in some mode such as search, Insert or other modes; Press Esc to escape;
  • [num]gt or C-n: go to next or nth (if num is provided) tab;
  • gT or C-p: go to the previous tab;
  • gf or :view: view the source in the current tab;
  • g0 or g^: go to the first tab;
  • g$: go to the last tab;
  • gh or gH: go to home page or new tab with home page;
  • gu or gU: go up parent link or root;
  • gi: focus the last used input field;
  • S-h or C-o: go to the previous history link;
  • S-l or C-i: go to the next history link;
  • f or F: hint mode to display links by number. F for open link in a new tab;
  • ;{keys}: hint mode by command keys:
    • a or s: save a link (prompt dialog or no dialog);
    • o or t: open a link in current tab or new tab;
    • O or T: open a link in current tab or new tab with its command in the command area(bottom);
    • v: view source code in the current tab;
    • y: yank the link;
    • Y: yank the link's text;
  • o or t: open a link in the current or new tab. You can type in a link in the command area then press enter key;
  • O or T: similar as above with the current link displayed;
  • y: yank the current link;
  • a or A: add or added the current link to bookmark;
  • [num]h,j,k, or l: move left, down, up or right by number if num is provided or by one as default;
  • gg: move to top;
  • G: move to button;
  • C-d, C-u, C-b or C-f: scroll down or up with half or full page;
  • z{keys}: zooming
    • i: zoom in;
    • o: zoom out;
    • z: back to 100%;
  • :sav[eas]>: save the current link to disk;
  • /: start search in Vimperator command area;
  • n or N: search forward or backward;
  • :st[op] or C-c: stop current loading;
  • r or R: fore to reload the current page(R for skipping the cache);
  • d or :quita[ll]: close the current tab or all tabs;
  • u or :undoa[ll]: undo closing one or all tabs;
  • :restart: restart Firefox;
  • :ZQ: quit and don't save current session;
  • :ZZ: quit and save the current session;
  • :ver: displaying versions of Vimperator and Fixfox;

That's just a small portion of keys in Vimperator! You can see there are not too many keys to be remembered. Actually, it is a muscle memory game. The more you use, the more they will be hard-burned to your brain. The keys will be naturally typed by your hands without thinking or looking. The result is fast browsing with easy!

Update: I posted the similar entry in my WordPress blog.

Read More...

Wednesday, January 07, 2009

DNRTV Traning Shows

During the time while I am in Wuhan, China, I have some time to browse web and get several DNRTV training shows viewed. DNRTV is my favourite web site for the new technology for .Net.

Shows 117 & 118 on The Entity Framework (part 1 and 2) is about the entity framework for data source connection and data mapping APIs. The cool part is that the data are retrieved only at the point the query is called and only the required data are retrieved instead of cache a lots of data on client side. The only thing I concerned is that the back end may use Ad hoc SQL query to get data.

Show 119 on XML Literals by Beth Massi is really cool. She demonstrated a way to use LINQ to do various things which normally needs a lots of codes. It makes the codes much easy to understand and maintain.

Scott Cate on EasyDB.com, show 121, demonstrate a very interesting cloud DB. This provides a way to get and manage data on web.

I like "Miguel Castro: Extreme WCF" (show 122) very much. This Miguel showed a new and well-structured way to build WCF applications. It reveals the logic and underneath parts of WCF and make applications much each to maintain. I like his way very much.

I just finished the show 124, Brian Noyes on Prism. The show demonstrates Prism, which is based on P&P's CAB or MVP. I used P&P CAB pattern before. The Prism makes the structure much clean and simpler than the previous version. It provides a framework for WPF applications. I am looking forward for the next part this show: commands and events in Prism.

Read More...

Tuesday, December 30, 2008

Const Class

I call it as const class since the class is used mainly for constants. I learned this this strategy when I used MVP for desktop applications. Concept is very simple, use this class to manage all the constants used in your application so that all the related constants are organized in a better structure.

For example, all the table name field names for a SQL table are defined in a class. Instead of hard-coded strings in your application, you can use this class to manage the table and fields names. I also added some query in the class to get some query SQLs. This makes the maintenance of my application much easier. Whenever I want to change the table or field or query strings, I know where to find them to make changes. No more need to search for the hard-code strings in my application.

Read More...

Parameterized SQL Query Over Ad Hoc SQL

I have been using Ad Hoc SQL query for very long time in various .Net projects, including ASP.Net. I realized the danger of SQL injection attacks, however, in most cases, I don't provide UI for client or hacker to enter any parks of SQL query. As most people mentioned that the reason of Ad Hoc SQL queries are used in most cases is based on the fact that most of examples codes are using Ad Hoc SQL queries.

Parameterized SQL query is better than Ad Hoc SQL query not only because it could prevent SQL injection attacks. It is better than Ad Hoc one in terms of performance. SQL server has ability to cache parameterized SQL query as stored procedure so that they could be compiled and executed in less time.

Based on the second reason, I have been convert most of SQL queries into parametrized SQL query. The conversion is actually very simple in most cases. I think this should be a rule for any applications with SQL related queies.

Read More...

Wednesday, December 17, 2008

WordPress

I have heard WordPress.Com many times and tried to browse its information. I think it is an open source based blogging tool. Anyway, today, I registered an account at WordPress with my new blog account here: chudq.wordpress.com. After I install the software, I may start blogging from the new site. A new experience for me!

Read More...

Network Drive Mapping in SQL Database Project

Today I tried to add a feature to map to a network drive in a .Net SQL database projjavascript:void(0)ect. The codes is based Windows API functions to map to a network drive. It works fine as a windows application. However, when I tried the same codes in my SQL database project, it fails to map to a network drive. I got an windows exception about something like a log on session failure (I need to use a user and password to make a map drive). The source codes is based on aejw.com's codes.

That's too sad. Maybe there are some other ways to get around this. One way is to run an external process to make a mapping by starting a process from SQL server. Another way may be something like described in this discussion on topic of C# Mapping a network drive, running a process of net.exe directly in C#.

Read More...

Remote Twitter Widget From My Blog

I have to remove the widget of Twitter from my blogger since I cannot access to my blog at work. The company I work does not allow me to access most web emails such as yahoo mail, hot mail and gmail. Recently Twitter is banned as well. No choice to do it.

Read More...

Tuesday, December 02, 2008

More on SproutCore

Just read an article on Cocoa for Windows + Flash Killer = SproutCore. The article provides in depth of SproutCore and its background stories. I really enjoying reading it. It looks like that SproutCore has strong support by Apple and has great potential to rock the web development and application development. Very exiting!

There is also another article on this at AppleInside: Apple's open secret: SproutCore is Cocoa for the Web.

Read More...

Saturday, November 29, 2008

SQL Send Email (3)

This is the continuing part of my previous two posts:

As I mentioned in the previous post, what I need is to save the content to an html file. The main reasona are: I need to get the size of the html content, and I have optiont to send the html content by attachment file. I could do the first one easily by calculating the length of variables which hold html strings and xml content. However, when I come to the point how to send the html content, I have to decide to sent it in the body of email or by a file attachment.

If the file size is too big, more than 10mb in some cases, it will cause mail application (outlook) hanging for a long time when the email is opened. In this case, it is better to send html as an attachment file. In addition to that, I could save the html file to a reporting server site so that a light notifiation email with a link to the html file could be sent.

I have posted several blogs on SQL Server Porjects. It is very easy to create a .Net project to save string to a file. Therefore, I created a SQL procedure .Net project to do the job. The store procedure is very simple:
public partial class StoreProcedures
{
[Microsoft.SqlServer.Server.SqlProdure]
public static void SaveToFile(
string content,
int overwrite0OrAppend1,
string fileName)
{
...
}
...
}

In the same way, I have created another .Net based SP to get file size. With these SPs,
here are some SQLs to save content vars to a file:
EXEC SaveToFile @htmlBefore, 0, @fileName;
EXEC SaveToFile @xml, 1, @fileName;

Finally, I use the following SQLs to send the HTML content by email:
IF @fileSize < @fileSizeLimit
BEGIN
EXEC
msdb.dbo.sp_send_dbmail -- SQL SP to send email
@receipients = @p_recipents, -- recipients passed by parameter
@subject = @v_subject,
@body = @v_content,
@body_format = 'HTML'; -- set content as HTML
END
ELSE
BEGIN
EXEC
msdb.dbo.sp_send_dbmail -- SQL SP to send email
@receipients = @p_recipents, -- recipients passed by parameter
@subject = @v_subject,
@file_attachments = @fileName, -- set attachment file
@body = @v_msg,
@body_format = 'HTML'; -- set content as HTML
END

Read More...

SproutCore Presentation

I just finished watching a show on SproutCore by Charles Jolley. Note: the real show starts after 20 minutes (the first part is on Google App Engine). It is very inspiration and a fresh view. I really like the SproutCore infrastructure.

His view on the current web applications is true. There are too much loads on the server side, data, html presentation, and business logic. Click and wait is a pain process for most web applications, and you rely on server availability to see web application content.

I have started to learn jQuey and Dojo recently. This is my evening part time exploring. All these tools are very good ones to move html presentation part to client side so that data can be retrieved and updated by using Ajax on cient's requests. SproutCore framework jumps one more further step, moving the server side business logic to client side. As a result, the server is very thin!

I think this is a new way to develop web applications and we will see more smooth and desktop like web applications on web. Enjoying the exploration!


Skip 20 minutes to start SproutCore presentation.

Read More...

Wednesday, November 26, 2008

Value2 in Excel VBA

I did a lots of VB programs long time ago. Actually, I started to develop Windows applications by using VB3.0 to VB6.0. Then since the .Net, I switched to .Net C# and VB.Net. However, VB6.0 still has its market. During this year my contract job, I have done a lots VBA applications for Excel, Word and some legacy applications which provides VB6.0 code scripts.

Anyway, I encountered one interesting issue today. I tried to use Value2 in Excel VBA codes to compare two date date types. I know that I put the same date from one worksheet to another worksheet. However, when I tried to search for the same date in another worksheet, the cells with dates are not matched:

v1 = sheet1.Cells(row, col).Value2
v2 = sheet2.Cells(col, row).Value2
If v1 = v2 Then
...
End If


When I changed Value2 to Value, these cells with the same dates are found.

I googled the Value2 and found out that Value2 does not use Currency and Date data types (ref MSDN Office developer center). These values are converted to double type. This conversion caused a very insignificant difference 0.###E-11. This difference makes them different!

By the way, I know that when float values saved in variables, the actual value is very close the "float value" such as 1.2 as 1.199999999, and the value might be dependent on CPUs or OS. That means a float values in one machine may not the exactly same as the value in another machine. For safe gard, when I compare two floating values, I always use absolute the difference to epsilon, same if less then epsilon, not same others.

However, when I looked at C#'s floating data types, I see Equal() operator or == for these data types. Not sure why they are there.

Read More...

Sunday, November 23, 2008

Thin Server Archetecture Using Dojo

Just watched a tech show on Youtube.com on Practical Thin Server Architecture Using Dojo:



This well explained the server oriented web development and thin server web development by using client side JavaScript. I have done many ASP.NET web applications. It is true that the server side dominates everything including client side UI's by sending HTML & XML streams from server side. It is very heavy coupled between server and client.

Actually, the most important part between server and client is the data to fill for the client side UI, or passing data with request to server to data source such as DB.

Dojo provides a very good way to provide client side JavaScript codes in Dojo API form so that UI can be easily build and quickly respond by utilizing client side CPU and resources. The Widget I just learned is very clean one, Rating widget. It encapsulates all the UI codes to display icons and events to update icons. The testing HTML page is very clean.

Then web service is another great tool to use: sending request to get and put data between client side and server side. The server could be different web servers. In this way, the web application is very scalable and can be done by components. I can see that many parts are all reusable. Compared to the current way to build web applications, I am getting better picture of those new tools I am interested: REST, Dojo, jQuery, GWT, and YUI.

Read More...

Saturday, November 22, 2008

A Dojo Widget: Rating

The title is a tutorial article on how to create a Dojo Widget: Rating by mindtrove' blog. I spent some evenings on this new adventure: Dojo Widget programming. I made some changes and tests to undertand how the Dojo's API working. It is a rewarding process.

Not All Browsers Support Dojo Widget Events

I tried it on Mac and Windows, Firefox, IE and Safari. The widget works fine in Firefox and IE. For Firefox, there was only one minor issue. When I have to Vimperaotr enabled, some keys are not working such as Left, Right, Home and End keys. What I found out is that those key events are trapped by Vimperator and never passed to the widget. After I set pass-through mode(Control-Z), the keys are working fine.

However, Safari is tough. It is a UI mouse driven based browser. It does not let key events to passed to the widget. Only a few HTML DOM controls such as button and text can receive focus but not for others like span. Not sure if there is any way to change Safari's blocking.

Separate Dojo Library from Widget Project

Mindtrove' structure is to put his widget in the folder of Dojo. I don't like this. I prefer to put my customer projects outside of Dojo. Therefore, I tried to put my files like in this structure:

-html (all the test hmtl files)
-images (all the image files)
-scripts
-dojo-release-1.2.0
-[dojo folders]
-mindtrove (customer widget)


The customer widget codes are in a separate folder mindtrove, in the same level of other Dojo API library folders.

Here is the codes to load Dojo library files:
<script type="text/javascript"
src="../scripts/dojo-release-1.2.0/dojo/dojo.js"
</script>

And JavaScripts codes to load the widget:

<script type="text/javascript">
dojo.registerModulePath("info.mindtrove",
"../../../scripts/dojo-release-1.2.0/mindtrove"
);
dojo.require("dojo.parser");
dojo.require("info.mindtrove.Rating");
...
</script>

I tried to move my widget up one level, but the localization files could be not loaded by i18n.js. It looks like that i18n.js does not support cross domain scripts (widget codes outside of Dojo library folder could be treated as cross domain loading).

Add Debug and Double Click Event

When I learn something like this Dojo widget, I always like to add something at the same time. This helps me a lot to better understand structure, logic and codes. As I mentioned above to move my testing html page and Dojo library files not at the root like original codes did.

In addition to that, I have added one more attribute or property called debugKeyCode in the widget. This property is a bool(true or false) data type. I use this property to display keyCode value in the span's Title or tooltip. The keyCode value is saved in the local var preKeyCode when onkeypress event is fired on span object. In this way, I'll be able to see the key codes. Here are some codes I added to Rating.js(under mintrove folder):
dojo.declare('info.mindtrove.Rating', [dijit._Widget, dijit._Templated], {
...
// After currentValue property I added two vars.
// initial value
currentValue: 0,
// Add a property for deug key code, see Rating.html template as well.
debugKeyCode: false,
// this is a related property value to hold previous key code
preKeyCode: "",
...
postCreate: function() {
...
this.connect(span, 'onclick',
dojo.hitch(this, this._onClick, i+1));
// listern for mouse doubleclick on the span with the value it
// represents in the index of star
this.connect(span, 'ondblclick',
dojo.hitch(this, this._onDoublClick, i+1));
...
},
...
/*
* Called when the user doubleclick a star.
*/
_onDoublClick: function(value, event) {
if ( this.currentValue >= value )
this.currentValue -= 1
this.currentValue = Math.max(this.currentValue, this.minimumValue);
this._update();
},
...
_getDescription: function() {
...
var str = dojo.string.substitute(template, [this.currentValue]);
if ( this.debugKeyCode &&
this.preKeyCode )
{
str = str + ' previous key code: ' + this.preKeyCode;
}
return str;
},
...
_onKeyDown: function(event) {
...
this.preKeyCode = event.keyCode;
...
}
});

In above codes I also added codes to handle double click event. Since Safari does allow span object to get focused and to get onkeypress event, I added this feature so that by using mouse, rating can be added and removed.

Using Firebug Addon
Firebug add-on is a great tool for developers. No only it saves you a lots of time and effort to debug JavaScript codes, but it also provides some information normally you cannot get from the browser.

For example, Dojo supports Firebug by using some attributes when Dojo library is loaded. If you enable two attributes in djConfig like in following codes, you will see the Get Dojo library files in Firebug's console tab. That great to see what is downloaded and what are failed if you set them in wrong location:
<script type="text/javascript">
var djConfig={
...
parseOnLoad:true,
isDebug:false
};
</script>



Another great feature of Firefbug is that you can view the dynamically created DOM elements. By using Dojo and jQuery, you can create DOM elements, change style class, do animations on fly. Normally, I would like to see those elements in html but they are not available from browser's View Page Source or View Selection Source. Firebug does reveal the dynamic changes. That's great help.

For example, if you view the HTML tab in Firebug for this Rating widget, you will see the spans dynamically created and hidden text as well. By learning this Widget tutorial, I discovered a lots of new things, both in Dojo and Firebug.

Read More...

Wednesday, November 19, 2008

JavaScript and Ajax for Web Applications

Just read an article about Fixing Web, Part 1 referred by Ajaxian blog. It mentioned leading three tools used by developers: jQuery, Dojo and YUI. I know the first two already, actually in the learning progress and very impressed by them, the last one is new.

YUI is Yahoo! User Interface Library with set of utilities and controls based on JavaScript. I went to Yahoo! developer site for YUI and watched the overview vedio. It is another very impressive tool I am going to learn.

As the article says, "We've made major progress on the web since 2005 and the rise of Ajax. JavaScript toolkits like JQuery, Dojo, and YUI have expanded what we can do with web browsers and increased our productivity...", I really like to sharp my skills with these great tools.

Read More...

Monday, November 10, 2008

Dojo Does Raise Exceptions

Dojo does raise exceptions in some cases. As I tried out some example codes from Dojo Quick Start Guide: Events, I got exceptions.

The following codes explains the case:

var mineObj = {
aMethod: function() {
console.log("Running mineObj method A");
},
bMethod: function() {
console.log("Running mineObj method B");
}
};
dojo.addOnLoad(function() {
// run bMethod() whenever aMthod gets run
dojo.connect(mineObj, "aMethod", mineObj, "bMethod");
//dojo.connect(mineObj, "aMethod", mineObj, "bMethod1"); // exception!
//dojo.connect(mineObj, "aMethod1", mineObj, "bMethod"); // OK
// start chain of events
mineObj.aMethod();
//mineObj.aMethod1(); // JavaScript error!
});

The second connect(commented out) will throw an exception in FireBug:
uncaught exception: dojo.hitch: scope["bMethod1"] is null (scope="[object Object]")

The connect fails to invoke method bMethod1 as it is not defined. However, the third connect call is OK.

The last commented out code is a JavaScript error in FireBug:
mineObj.aMethod1 is not a function

Read More...

No Exception On Dojo Chain Calls

I spend about 1 or 2 days a week on learning and exploring Dojo. I really like this JavaScript based API framework. I found one very nice feature of Dojo. Not only you can call Dojo methods by using Dojo chain calls, and you don't need to worry about if any middle part of the chain returns undefined or not.

For example, I added the following codes to the head's script section:

dojo.addOnLoad(function() {
console.log("OnLoad ready to add events");
dojo.query("#testHeadingEvent")
.style("cursor", "pointer")
.connect("onclick", function() {
this.innerHTML="I've been clicked";
});
console.log("Onload fires adding event on headEvent");
});
the query() function returns a DOM node by id. If the node is not found, it's still OK. No exception is thrown. I can still see the messages print out on the console(by using FireBug add-on). Isn't that nice?

Read More...

Saturday, November 08, 2008

SQL Send Email (2)

Microsoft SQL Sever 2005 supports xml data type. This data type provides a very convenient way to hold data from SQL SELECT statement. Continue from the previous blog, the following codes set xml with data from MyData table(id, name and value three columns):

DECLARE @xml xml;
DECLARE @htmlAfter NVARCHAR(MAX);
..
SET @xml =
-- Checks if count is 0 or not. Avoid NULL value in the result.
CASE
-- @count is a var to get the count from MyData table.
WHEN @count is null OR @count = 0 THEN null
ELSE
-- Get data from MyData table
-- Note: the three columns should match the previous
-- table header column definition (3 cols)

(SELECT
td = CAST(t.ID AS VARCHAR), '',
td = t.NAME, '',
td = t.VALUE, ''
FROM MyData t
FOR XML PATH('tr'), TYPE -- As XML output
)
END;

SET @htmlAfter = N'</table></div>'

The comments should well explain how to set xml in this example case. The reason I use xml data type is that it can hold large amount of data. I tried to use NVARVAR(MAX) before. In one case, the data retrieved by SELECT are millions rows of data and my var was overflowed with some data missing. When this happened, there was not any errors or indications. It took me a day to figure it out. With xml data type, The problem is gone.

The next article will continue to discuss how to use a SQL Database Project to save results to a file and get back text size information before sending out email.

Read More...

SQL Send Email (1)

I have created a stored procedure to send an email notification of some data. This is quite convenient to get notifications about database status, reports and any related business needs.

Basically, this is done by using Microsoft SQL 2005's build-in msdb.dbo.sp_send_dbmail. It looks like that some of email related SPs have been faded out since the SQL Reporting Service launched. The reporting services provides much versatile features and allow developers to design more ad-hoc web based reports. However, email notification still has its uniqueness and useful applications.

Since my SP is used for specific notification about data status, therefore, only one parameter is defined, as recipients of emails separated by comma.

The content of the email is HTML text. Depending on the length of text, if it less than the size of email limit(see my previous SQL Server Database Mail setting), then the data are formatted as HTML; otherwise, the file will be saved as a file and it will be attached to the email out.

The following codes set HTML header part:

DECLARE @headerHTML  NVARCHAR(MAX);
...
SET @headerHTML =
N'<html>
<head>
<script type=''text/javascript''>
function toggleIt(id) {
var post = document.getElementById(id);
if (post.style.display != ''none'') {
post.style.display = ''none'';
}
else {
post.style.display = '''';
}
}
</script>
</head>';

Here I added some JavaScript to hide and display detail views of data by function toggleIt(id). For example, the following codes define a title node with a link referenced to the function:
DECLARE @htmlTitle1 NVARCHAR(MAX);
...
SET @htmlBefore =
N'<a href=''javascript:void(0)''
onclick=''javascript:toggleIt("1")'';
style=''text-decoration:none'' title=''Expand/collapse this item''>
<H2>[+/-]My Data</H2></a>
<div class=''post-body''
id="1" style="display:none">
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Value</th>
</tr>'
;

After the link tag(a), the above codes add a table tag with a row of headers defined for the next data retrieved from SQL.

The next blog will continue on the topic on how to use xml type to hold SQL retrieved data.

Read More...

Tuesday, November 04, 2008

Enabling PHP for Apache Server in Leopard

While I was doing coding to learn Dojo, I reached one point that I needed PHP module enabled for my Mac Apache server. By default, it is not enabled.

I found information about enabling PHP for Apache Server. The steps are very simple, however, I did not have the right to edit the file httpd.config in /private/etc/apache2. The file is owned by root user. Soon, I found a way to edit the file: logging as root user, see my Mac blog entry.

After all these settings, I made my Dojo page working with php page. Basically, Dojo web page calls the server side php page to pass information back. It is very cool. This is also my first experience with PHP web page development. One lesson I learned is that for a php page, you have to indicate it by <?php and no space between ? and php.

Read More...

Monday, November 03, 2008

Doio: JavaScript Tool for Web Page Development

Today, I just started to learn Dojo. It is something very similar to jQuery. However, it provides core and APIs directly for Web Page development. It is very cool!

Just tried the Hello World example to display a button, to run Dojo script, to Get and Post back to server. I used my Mac with PHP to test it. It is very interest! The tool provides universal JavaScript APIs and you don't need to worry about brower syntax for DOM elements. I like it very much. This is another area I would like to invest my energy into it.

One neat thing about Dojo is that you don't need to install Dojo package or core APIs into your server. You can define <script ... src="http//..." /script> to either AOL developer's site or Google's developer's site. You will always have the updated engine for your Dojo scripts.

Read More...

Sunday, November 02, 2008

VIM, Initial Configuration and PlugIns

I have been used VIM for about weeks and started to fall in love with it. I am still in learning stage and found many some settings very neat.

The first thing is to configure VIM initial settings. This is done through the configuration file ~/.vimrc for Mac OS and C:\_rimrc for Windows. You can find many sites with good .vimrc file and use it as start. If you don't like some settings, you can change it.

Based on vimrc in the article of VIM Introduction and Tutorial, I made some changes. For example, I prefer the background color as white and tab as 2:

  "Tabs are 2 spaces:
set tabstop=2
"We use a white background, don't we?
set bg=white

I found some settings and added them in .vimrc:
  "Set characters shown for special cases such as:
"wrap lines, trail spaces, tab key, and end of line.
"(must be turned on whith set list)
set listchars=extends:»,trail:°,tab:>¤,eol:¶
"Set moving around at the end of line back to previous line by
" key and coursor keys, and normal movememt h and l keys
set whichwrap=b,s,<,>,h,l

"Enable C style indention
set cindent

I love special char setting, which displays tab, trial spaces, and end of line as special characters. I have to use command ":set list" to enable the setting. The move around setting enables backspace, arrow keys, and move keys h and l to move back previous lines.

There are many VIM plugins available. This is quite new for me. I found only one is working for me so far: Align. To use it, just type in the command ":Aligh =" when you in visual mode with several lines selected. Then the text will be aligned by = sign to separate left part and right part aligned by = sign.



After aligning, the text are aligned by =:



To install it, find the folder where the file "Align.vba.gz" located in Terminal. Type in the command:
  vim Align.vba.gz

The file is opened by VIM. Then typing the command to read scripts and then quit:
  :so %
:q

Reopen VIm again. The command :Align is available!

Read More...

Saturday, November 01, 2008

Scaling SVG Graphics with Javascript (3)

Here I would like to summarize my experience and tips about scaling svg with JavaScript.

Change Only Red Marked Scripts

First, I have shown two ways to scale svg graphics. The first way is to add scripts to both html and svg files. Even the scripts are quite long, actually you need to do is just copy-and-paste scripts. As I explained in demo, the blue area of scripts are ones you do not need to make change. The only scripts are marked as red or marked by '!!!...'.

I tried to make the scripts as generic as possible so that you do not need to touch. The only scripts are variables you have to set. As in the first way to call functions from html to svg, you need to set the object tag id in html being consistent with a var in svg. This will enable the svg to attach functions to object element in html.

I would recommend you to set the var in svg first as unique as possible. For example, you can name the var as first 10 char of svg plus a time stamp as the var name like 'ClipArtDog200810281259'. If you do this, it most likely there will be no other svg in your htlm file have the same svg with this name. This may reduce your touch svg file. What you need is to verify svg's top g id name.

The second way to scale svg is done by using JavaScript only in svg file. Normally, you don't need to change the scripts. I have defined some 'constant' vars in the top part of JavaScript for the size of circle and colors for the scale down and up. You may change them at your preference. I'll add one more method to enable and disable in-svg-scaling-scripts. So you will have control from html or in svg to disable the behavior.

SVG Grphics

As you know, svg graphics are defined as in xml files. It offers great control for art designer and programmers to create vector graphics with animation effect and unlimited potentials.

I used the InkScape tool to create svg with scripts(actually vim for adding scripts). When you create svg files, you may see the scaling scripts not working well. There are many reasons that may cause the problem. You should examine the svg xml file by a text editor. One issue is the transform function or tag used in the top g tag. This is not necessary because you could place the graphics in the right position by setting other position and size tag attributes. If you find it, you can remove it and use InkScape to make proper adjustment, selection and save.

Another issue is that you should not try to use scripts to create graphics dynamically since some hard-coded size values may not be scaled. As you can see my small circle with size of 5 px as radium is small enough but they are not scaled. These circles are created by script for scaling UI.

Not Working for SVG on Different Sites


As I discussed in the past two blogs, if you place your svg on different sites other than the size where your html file is hosted, the JavaScripts will not work! This is JavaScript security issue. I think there is nothing we can do. Just image if you would refer to another site to execute JavaScript codes, that would open a door for hackers to pull valuable information about the client sites and you have not place to trace down.

JavaScript has is security concern for adding scripts on html file. The browser will not allow you to execute scripts on a mysterious site.

Therefore, in order to make it to work, you have to have the total control of your html file and svg file on one site.

I am so sorry that I could not show you the demo on my blog since I cannot place svg to my blog site.

That's great experience for me to explore svg and JavaScript. I may add some more features like mirror-flip and transform to svg. I'll blog those and update my demo on my blog. Enjoy programming!

Read More...

Friday, October 31, 2008

Scaling SVG Graphics with Javascript (2)

In the previous posting, I have provided a demo example how to add scripts to scale svg grphics. I was going to add svg graphics in my blog and to show the scaling feature. However, I struggled for two days to make it working but without luck.

I can add script functions to my blog through Blogger's layout settings. In this sense, I have control of my HTML page. Here I mean by having control of HTML page is that you can edit and update the HTML page to web sever. However, I cannot find a way to submit svg graphics to my Blogger server. What I tried was to upload my svg to another site, Open Clip Art Library. I added my scripts to a svg xml graphic.

This brings a problem: my Blogger and my svg are in two different sites. What I found out is that the scripts in my blog does not have access to the scripts in my svg file. JavaScript has security reason to prevent calling scripts on other sites. What have been working in my local computer as shown in the demo would not work any more when I changed the svg reference to a different site!

In order to make this working, you have to put svg in your site.

Anyway, the instructions in my demo still work well if you follow this rule: you have the control of both html and svg files on one site.

The demo shows you a way to attach script functions defined in svg to the object in your html file. In JavaScript world, anything is object. A tag <object> is a DOM element. It also can be obtained by DOM documention object's getElementById() method. The unique feature of JavaScript is that you can attach or detach a function as a method to a object dynamically! That's basic technique I used in the demo. In this way, you can control the scale of svg from your html page.

That is one way to do it. I further investigated an alternative way to scale svg: adding scripts to a svg xml file. This provides some UIs in the svg: two small circles on the top-left corner the svg graphic with some mouse events(mouseover, mouseout and mouseup for click). By clicking on the left circle, it will scale down the svg; while clicking on the right circle, scaling up the svg.

I thought there is no attachment from my html and svg. The scripts in svg should be able to work. Nop! Since the svg is referenced by another site, any function or DOM method calls stop working.

Here is my svg with scripts at Open Clip Art Library. I put it here but the scripts in the svg do not work:

This browser does not support svg. You may need to download FireFox or get Adobe's plugin if you use IE

Open the dog graphic in another tab or browser window. Try it out and enjoy it!

NOTE: don't zoom in or scale the svg too big. It will slow down your browser for minutes. I event got crash once! If you scale too small or too big, refresh the page to restore to its original size.

Read More...

Monday, October 27, 2008

Scaling SVG Graphics with Javascript (1)

This blog, as well as coming ones, contains information about how to scale svg graphics by using JavaScript. It is based on the article of svg scaling with JavaScript. You need to have the control of the source codes of both the html page and svg so that you can add JavaScripts codes.

I discovered svg just recently, and like it very much. Inread of using jpg or png like bitmap graphics, svg is totally based xml. It is a standard way to display graphics at much more control by programmers. However, the first problem I encountered is to scale svg, or change the size of svg graphics. Soon I found the above article. It provides a very simple way to scale svg. It has limitations. The biggest problem is that it can only scale one svg graphic since it linked the graphics set dimension and scale methods to top window object. There is only one top window object.

Then I spent some week's evening time to figure out alternative ways to do it. Finally, I got a better way to scale svg. You can scale as many svg graphics as you like and the scales for each one are different. I am very satisfied with the current solution. Here I put them summarized in this and coming blogs, as well as some examples.

Here is the link to get the demo of HTML and SVG graphics files.

Enjoy it.

Read More...

Thursday, October 23, 2008

Stack OverFlow: Developers' Q&A Social Site

I found a very good web site: StackOverFlow. It is basically a developers' Q&A social group. You can post any questions there. All the questions are categorized by tags. I added some tags I am interested in and some questions. Actually, I posted some answers first.

I got this web site information while I was walking outside downtown Calgary during my lunch break, listening a podcast by Scott Hanselman. The topic is all about StackOverFlow web site for almost one hour. That's great talk.

Today I google the site, found it, and joined the site. One interesting thing is that you don't need to create a new account. I used my Blogger account(googl's actually) to join the site. That saves me time and brain for another new account. Just for a few hours, I earned 1 point for my reputation. It is an encouragement to spend sometime to share programming experience and learn something as well. I always get valuable knowledge and solutions from web, forums, and discussion groups. This one is the right one for me! I think I'll use it more than other ones. One shop for almost all my skill areas.

Read More...

Sunday, October 19, 2008

SVG and DropBox Web Share Space Tool

SVG is a xml file for defining graphics and it is a World Wild Web Consortium (W3c) recommendation. It is very cool graphics. With SVG, it opens a door to create interactive and dynamics graphics with scripts so that web page content is more dynamic.

One interesting about SVG graphics is that you cannot copy the image by right click. The image is defined by xml source codes in a SVG tag. What you can do is to open the source codes and copy the SVG tag section and save it as a SVG file. You can either use a browser or Adobe SVG Viewer. There are many SVG editor tools available as well.

The graphics is defined as SVG tag in an xml file. However, one problem is that you cannot directly place the xml graphics section in a html web page. It has to be placed in the same way as other graphics, ie, referenced by a link. Therefore I could directly place a SVG graphics in my Blogger, when I first learned about SVG. Blogger does allow me to place a graphics like jpg or png files, but does not support SVG. Blogger does not provide any space for me to directly put my files.

Today, I found a web tool called as DropBox. It is a web tool to share your files between you computer and your account there. With DropBox public shared space available. I can place my svg files there so I can reference to it by using embed tag.

Here is one svg file I saved in my public space and make a short name to it:



medium

Or click Feather Pan. I got this SVG graphics from Open Clip Art Library by wsnaccad.

I created a short name by MetaMark for the long name link. The only problem is that both tools are only active if your file and link active at least something like 90 days. I am not sure how long they are available. Anyway, for a blog entry, as long as it is working for the time being, it is OK. I can change the link later on if they are not working. There always some other options available.

Read More...

Saturday, October 18, 2008

Add Categories or Labels to My Blog

I have added Blogger's new gadget Labels to my blog. To add a gadget is very simple. Just go to your blogger's Layout tab in Customize link on the top right corner. There should a link as Add a Gadget in the layout page:


To add a label to your posts, just type a label text in Blogger's editor's lower right input box ("Labels for this post"). If you have already defined some labels for your posts, you may see some labels displayed as Label Sense Completion.



To remove a label, you have to remove that label from all your posts.

It is really nice to be able to display Categories in my blog so that I can easily jump to the posts I did before. In addition to that, I'll have a picture what I have posted. For other browsers, I think this provides valuable information about my blogs.

Read More...

Friday, October 17, 2008

JavaScript Class-less Objects

Nice article on JavaScript Class-less Objects. Enjoy reading the article!

Read More...

Thursday, October 16, 2008

Blogger Layout and Gadget

I have not touched my layout for a long time. Today I tried to add a twitter to my blog my new twitter account. I realized that I can also add a twitter gadget from Blogger's layout. Actually, there a tons of gadgets available. That's really great! I like some of them.

One of gadgets is Label, something like tags you can define for your blog. While you create a new blog, you can add labels on your blog. This is a very convenient way to group blogs. With Label gadget, you will provide a way for you and other browsers or follows to get interested topics. I'll try to add my own labels to my blog. Hopefully, the Label gadget will be able to provide some visual information about those labels.

Read More...

Saturday, October 11, 2008

Web Tool: Short URL

I read an article about web tool to make URL short long time ago (last year?). That is ShortURL. However, the site may not free soon as I recall a warning in the article. Now I think that I do need a tool to redirect long urls such as my blog entries to a short one. By gooling web, I found MetaMark.

The short URL generated by this site is not a user friendly one, but it works. According to the information of this site, if the url has not been used for more than two years, it may expire. For short term use, this web tool is great. For example, my previous post is at http://xrl.us/otgzf, comparing to http://davidchuprogramming.blogspot.com/2008/10/web-tools-firebug-and-smushit.html.

Here is the form I copied from the site to do the job:



Enter a long URL to make shorter





I did several tests. If you use it to generate one and try the same long URL again, the one first time generated is returned back. Therefore, you just cannot change it. It does not check if the URL exists or not. I gave a none-existing one, and it still generated a new short name, which is not not-found-url. May be this is a way to change it (by making the previous existing one invalid). The web server just generates an alternative short URL, no matter the URL you provide is valid or none-short one. I tried to get a short URL for "http://google.ca". The new one is "http://xrl.us/bemw2" (it may exist or I just generate one for it):).

A related technique about URL is to implement ASP.Net's MVC framework. Its URL is based on controller, action and router. You can construct your own user-friendly URLs. The URLs based on ASP.Net MVC does not contain .aspx or .html suffix and not url parameters like ¶1=value1... You will see more short and user friendly URLs on web. The Metamark page mentioned that it is using MVC pattern. Maybe this server just use the pattern to build a very simple, random and short URL mapped to a long URL.

You can do the same thing for your company's web pages. Most of them are not-user-friendly URLs and hard to remember. By using ASP.Net and MVC framework, you can define a structure of URL and mapping user-friendly URLs to a existing ones without any change to the old ones. It should be very simple project.

Update: One of the great feature of Metamark web tool server is that you can provide a nickname and secret. The nickname must be unique one, not taken by others. Then the generated URL is [server_home]\[nickname]-[secret]. You could create a user-friendly URL! This blog is at http://xrl.us/shortURL1-WebTool. "shortURL" has been taken. I had to add "1" to it.

The generated short URL does not take any suffix like ".aspx" or ".html", which is not needed actually!

Read More...

Web Tools: FireBug and Smushit

Two great tools for Web developers: FireBug and Smush.it.

FireBug provides a view panel on the bottom with a lots of options to view such as Console, HTML, CSS, Script, DOM and more. If you click on Inspect to toggle it on, then you can hover your web page to see selections with updates on FireBug panel. I think it will save a lots of time for Web-developers to debug their web-pages. You may find out more about what actually in your client side web page codes when you debug your ASP.Net applications.

Smush.it is a great tool by some Google developers. You simply upload your image and to see how much it can smush. For example, I posted a blog on my Mac log with png image. After smush.it, it reduces 37%. The logic is very simple. It tries to turn off some image bits which will not make much difference in view. I'll use this tool to reduce my images on web. It for-sure will make your web page much faster for your clients!

Read More...

Thursday, October 09, 2008

Apple Programming: User Defaults

Just started to look at some Apple Xcode application examples. That's a whole new huge framework for OS X. One application is about user defaults. In Windows there are many ways to store application defaults or values such as Registry, XML file, Ini file or Active Directory.

In Mac OS X, Apple provides a plist and bundle for user preferences and in Objective-C, there are some classes can be used to get user default values, NSUserDefaults for example:

NSUserDefaults *defaults;
// Get all the defautls for the current app
defaults = [NSUserDefaults standardUserDefaults];
// Register 2 defaults in case they are not available in user defaults
// Note, the registerDefaults does not change defaults.
[defaults registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
@"Joe", @"first_name",
@"NO", @"is_married",
nil]];
//...

NSString firstName;
BOOL married;

// the following two calls will return the user's individual preferences,
// if they are available. Otherwise, it will just return the values we
// registered previously. Saves us some hassle!
firstName = [defaults stringForKey:@"first_name"];
married = [defaults boolForKey:@"is_married"];


That's quit difference way to do in Mac. Very interesting! Some good links about User Preference Defaults:

Read More...

Friday, October 03, 2008

SQL Server Database Mail

I use msdb.dbo.sp_send_dbmail to send email notification in SQL Server. Recently I migrated our DB to a new server. The problem I encountered is my SQL SP does not working any more.

Finally, I find out this is the SQL server configuration issues. There are some configuration settings to be done on SQL server level.

First, I have to turn the mail feature on by using the command:

  sp_configure 'Database Mail XPs', 1
reconfigure

Next, I have to configure the Database Mail. Here is the picture to access the configuration:



where you have to create a Database Mail account and profile. Basically, the configuration contains information about mail server, SMTP Authentication. The profile will be created for you after you add a new account.

One thing you have to do in the Database Mail configuration is that to set the default profile as you will use in sp_send_dbmail so that you would not need to specify a profile.

For my case, I use this sending mail feature to send file attachment in some cases. My notification report mail contains information from DB in html format. The content may be very big. If the content is very big, it will take time to open the mail. In case of very large size content, I'll send the report as an attachment file.

By default, the file size for Database Mail configuration is 1,000,000 bytes. It is very small in most cases. I have to change it to 10,000,000 or about 10MB. This can be done in Database Mail configuration.



After all these settings, my email notification runs with success.

Read More...

Thursday, October 02, 2008

ASP.Net MVC

Just watched a training video Creating Task List on ASP.Net MVC. It is very impressive. MVC design pattern has been used for Windows application and now the framework for ASP.Net is available.

I have used this or MVP in several desktop applications before and I have not touched this type of design for several month. I'm very glad to see the new package available.

MVC pattern provides very good design infrastructure with separations of UI, Controller and Model. In addition to this model, I prefer to add a Repository level to separate data base and classes. The Repository model is responsible to provide data as objects and interface for updating objects back to DB.

Any good design pattern does not resolve all the issues. Still you have to keep good practice to use them. I understand that the tutorial video is just an instruction to MVC. My comments on the practice in this video is that there are too many client to server calls. To create a new task you have to make a call to server side to add a new task. However, to mark a task as completed, I don't think that the Complete action call to server for each edit is necessary. It could be done on client side to mark one or more tasks as completed. Add a Save button to save changes. This will avoid frequent calls to server.

In order to do that, I think client side script may be needed to handle these changes. In addition to that, you have to handle redirect change by client to another page. That means a warning message to indicate changes.

New design patterns would provide a gateway to design a better applications. You should remember that that does not resolve all the problems or make your application in a good structure. It'll take time to master skills to develop good applications.

Read More...

Add Scripts to Client Side Page 3

In my first post on this topic, I mentioned that there some cases that prompts may not be desired. You can avoid prompt display for a control's click event by calling the base class's method BypassModifiedMethod().

This method actually disables the prompt display by setting the client side page level script var on click event:

  m_needToConfirm = false;

However, in case of saving failure, such as exception raised from back-end DB, a postback call may be called back to the client side with some error message being displayed. This would cause a problem: if the user redirects to another page, the prompt would not be displayed and the changes may not be lost.

To resolve the problem, I added a method ResetOnSubmit() in the base class. You should call this method on Page_Load event for postback case if you want to reset the flag variable back.

protected void Page_Load(object sender, EventArgs e)
{
...
if (!IsPostBack)
{
base.ResetOnSubmit();
...
}
...
}

Another handy method I added to the client side base class is DebugChanges():

protected void DebugChanges(
WebControl wc,
string wcEventAttribute,
string clientIDForDisplay)
{
string script = string.Format("javascript: displayChanges('{0}')",
clientIDForDisplay);
wc.Attributes[wcEventAttribute] = script;
}

where displayChanges() is a client side javascript function registered on the client side page level. This function will display the current monitored changes and original values on a WebControl specified by control's event. You call this method in Page_Load event to add this debug feature. You can decide when the control is visible. I used a URL request parameter to enable the visibility of a control in one case. See my previous post on Using Query String Parameters in ASP.Net Page.

As I promised in my previous post, here is the source codes of ClientSidePage class.

Read More...

Wednesday, October 01, 2008

SQL Server Project (5)

I have written several blogs on SQL Server Projects. Here is the list of links of previous posts:


Recently we moved our SQL server from one virtual machine to a real PC SQL server. DBAs created the new server and installed a blank SQL server. After that, we had to move our DBs to the new user.

Generally, DBAs don't give us sa password. What they did is to created an appsupport user with almost as same as settings as sa for us. We use this user to back up the existing DBs and copied to the new PC for restoring.

The restoring process went very well. Almost every thing has been set up as same as the existing DBs. However, for SQL database project, as I mentioned in previous articles, some Asymetric Keks for assembly keys and Log Permissions have to be set up in master db. Fortunately, I logged the steps to do that (as I wrote in my previous articles) and restored the keys and permissions in master DB.

One thing I realized that the master DB as created by sa and our other DBs with SQL database projects were restored by appsupport. The owners of these DBs are different. As a result, I could not deploy my project to DBs. The error messages say that the owners are different and they could be changed by ALTER... I used this command to change the DB(MyDB for example) owner:

  ALERT AUTHORIZATION DATBASE::MyDB TO sa

I think that if DBs' owners are different, you cannot deploy your project from Visual Studio 2005. You have to make change to keep them in sync.

The second thing I had to do is to set DB TRUSTWORTH on:

  ALTER DATABASE MyDB SET TRUSTWORTHY ON

since I referenced System.Web.dll framework assembly in my SQL database project. Otherwise an exception would be thrown out when Ssytem.Web.dll classes are called.

The last thing is to give permissions to Windows' users since I have to use VS to deploy my project remotely to the SQL server with Windows authentication. Instead of give permissions(alter and create assembly) to one user, I created a Role on SQL server DB called as db_developers and adding my user name as a member of the role. Then I set related permissions to the role.

After all these settings, I can deply my project remotely to the SQL server DB and run the deployed assembly based ST with success.

Read More...