Sunday 3 November 2013

Resolve problem of SimpleModal not being displayed when adding ScriptManager on the page

I came across the plug-in called "SimpleModal" that was developed by plasm in Mootools. You can read more and run the demo on http://simplemodal.plasm.it



This modal works great. However, SimpleModal doesn't work if there is ScriptManager on the page. I'm disappointed a bit because most of ASP.NET pages need ScriptManager to handle the Postback. After searching around for solutions but getting no luck. There seems to be no answers on Internet. I decided to investigate what the cause might be. Accidentally, I found a workaround. It's quite simple. I tried to do something with ScriptManager by going through all of its attributes. And here is the idea:

Workaround: Assign a value to ScriptPath. It could be any value, as long as it's not empty. See the highlighted section below:
<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptPath="MyCustomScriptPath">
</asp:ScriptManager>

Now please compare the source view before and after adding ScriptPath. Use the online tool (http://www.diffnow.com/) to see the difference.

In below screen (click to room in), the left half represents the source that causes SimpleModal problem and the right half represents the changes (ScriptPath):


Now. It works pretty good. At least, I can use SimpleModal for many ASP.NET pages in my projects. For complicated pages, I'm not sure if there are any other conflicts :-) Then, I'll go about resolving it once I encounter these.

You can download the modified demo code at: SimpleModal

That's it. I'm so relieved!
Please share with me on my blogs if you have any finding with this plug-in.


Saturday 24 August 2013

How to check JQuery existence and load JQuery from script

Usually, we load JQuery by including JQuery resource in <script src="..."></script>. What's happening if there is always a JQuery to be loaded in parent page or another control. To resolve this, we do 2 steps:
1) Check if JQuery has existed or not.
2) If not exist, load JQuery directly in script code as opposed to including resource. Here is the code:
document.writeln("<script type='text/javascript' src='scripts/jquery-1.4.1.js'><" + "/script>");

Remember that, document.writeln("...") doesn't run sequentially. That means all the codesnipet written after this code can be executed immediately without waiting for document.writeln() to end. If you write your own control and use more than 2 controls in the same Web page, you might run across a conflict when JQuery is loaded more than 2 times. To resolve this, we need the 3rd step:

3) Use the flag variable to make sure JQuery is loaded only once.
var setLoadOnce = false;

To sum up, it should look like:
<head runat="server">
    <script type="text/javascript">
        var setLoadOnce = false;
        function initJQuery() {
            if (typeof(jQuery) == 'undefined') {
               if (! setLoadOnce) {
                  //alert('init jquery');
                  //only output the script once..
                  setLoadOnce = true;
                  //Load JQuery from JS code
                  document.writeln("<script type='text/javascript' src='scripts/jquery-1.4.1.js'><" + "/script>");
               }
            }
        }
        initJQuery();
    </script>
</head>

Please note if you load JQuery in JS code as above, the handler of JQuery events ('ready' event for example) must be placed after <body> to avoid running in wrong sequences (jquery events run first, jquery load runs later). Even if JQuery load is set to be written first, JQuery events load does after, it doesn't work.

In the following example, try to put all the scripts in <head> tag. Run it to see if both message "init jquery" and 'jquery ready" is displayed alltogether?
<head runat="server">
    <script type="text/javascript">
        var setLoadOnce = false;
        function initJQuery() {
            if (typeof(jQuery) == 'undefined') {
               if (! setLoadOnce) {
                  alert('init jquery');
                  //only output the script once..
                  setLoadOnce = true;
                  //Load JQuery from JS code
                  document.writeln("<script type='text/javascript' src='scripts/jquery-1.4.1.js'><" + "/script>");
               }
            }
        }
 
   </script>
   <script type="text/javascript">
        $(document).ready(function () {
           alert('jquery ready');
        });
   </script>
</head>

Now, put the "ready" event after <body>, we can see that both messages are displayed alltogether. It indicates that JQuery is loaded and executed as normally:
<head runat="server">
    <script type="text/javascript">
        var setLoadOnce = false;
        function initJQuery() {
            if (typeof(jQuery) == 'undefined') {
               if (! setLoadOnce) {
                  alert('init jquery');
                  //only output the script once..
                  setLoadOnce = true;
                  //Load JQuery from JS code
                  document.writeln("<script type='text/javascript' src='scripts/jquery-1.4.1.js'><" + "/script>");
               }
            }
        }
    </script>
 
</head>
<body>
   <script type="text/javascript">
        $(document).ready(function () {
           alert('jquery ready');
        });
   </script>
</body>

Side-effect of loading JQuery dynamically:
Loading JQuery on demand is great, but should not abuse it. The truth is, with JQuery loaded dynamically, you cannot create HTML elements on the fly using JQuery! There are always certain problems with dynamic script loading, no matter what. So please be careful! You should only use this technical if really needed.

Happy coding,


Monday 18 March 2013

What is the difference between GetPostBackEventReference and GetPostBackClientHyperlink?

GetPostBackEventReference is used to raise postback from a control which has OnClick event associated with it. Meanwhile, GetPostBackClientHyperlink is used to raise post back from a  control without OnClick event associated with it, such as HyperLink...

The following code example demonstrates the difference between GetPostBackEventReference and  GetPostBackClientHyperlink method.

<%@ Page Language="C#"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  public class MyControl : Label, IPostBackEventHandler
  {

    // Use the constructor to defined default label text.
    public MyControl()
    {
      base.Text = "No postback raised.";
    }

    // Implement the RaisePostBackEvent method from the
    // IPostBackEventHandler interface. 
    public void RaisePostBackEvent(string eventArgument)
    {
      base.Text = "Postback handled by " + this.ID.ToString() + ". <br/>" +
                  "Postback caused by " + eventArgument.ToString() + ".";

    }
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Create an instance of the custom label control and 
    // add it to the page.
    MyControl mycontrol = new MyControl();
    mycontrol.ID = "mycontrol1";
    PlaceHolder1.Controls.Add(mycontrol);
    PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));

    // Create a button element with its onClick attribute defined
    // to create a postback event reference to the custom label control.
    HtmlInputButton b = new HtmlInputButton();
    b.ID = "mybutton1";
    b.Value = "Click";
    b.Attributes.Add("onclick", cs.GetPostBackEventReference(mycontrol, b.ID.ToString()));
    PlaceHolder1.Controls.Add(b);
    PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));

    // Create a link element with its href attribute defined
    // to create a postback event reference to the custom label control.
    HtmlAnchor a = new HtmlAnchor();
    a.ID = "myanchor1";
    a.InnerText = "link";
    a.HRef = cs.GetPostBackClientHyperlink(mycontrol, a.ID.ToString());
    PlaceHolder1.Controls.Add(a);
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ClientScriptManager Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:PlaceHolder id="PlaceHolder1" 
                       runat="server">
      </asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

What is the exact definition of "Software Specification"?


A software requirements specification (SRS) is a comprehensive description of the intended purpose and environment for software under development. The SRS fully describes what the software will do and how it will be expected to perform.

- A specification describes WHAT a program does, a design describes HOW the program does it, and documentation describes WHY it does it
- A specification is a document which forms a contract between the customer and the designer.
- A specification is a document by which we can judge the correctness of an implementation.


An SRS minimizes the time and effort required by developers to achieve desired goals and also minimizes the development cost. A good SRS defines how an application will interact with system hardware, other programs and human users in a wide variety of real-world situations. Parameters such as operating speed, response time, availability, portability, maintainability, footprint, security and speed of recovery from adverse events are evaluated. Methods of defining an SRS are described by the IEEE (Institute of Electrical and Electronics Engineers) specification 830-1998.


A specification is a precise, unambiguous and complete statement of the requirements of a system (or program or process), written in such a way that it can be used to predict how the system will behave.

Wednesday 16 January 2013

Nhân sự kiện lỗi máy đánh bạc hiển thị 55,5 triệu đô la và bàn về chất lượng phần mềm

Gần đây có một sự kiện khá nóng trên truyền thông liên quan đến sự cố lỗi máy đánh bạc của công ty Đại Dương khi một khách hàng không tin vào mắt mình đã thắng 55,5 triệu đô la (http://vnexpress.net/gl/ban-doc-viet/phap-luat/2013/01/vu-thang-bac-55-5-trieu-usd-phap-luat-viet-co-lo-hong). Không cần biết Tòa án sẽ xử thua bên nào nhưng rõ ràng đây là một lỗi phần mềm nghiêm trọng. Qủa là một sự kiện hi hữu! Tôi có thắc mắc liệu đó có phải là lỗi phần cứng hay lỗi phần mềm. Cho dù phần cứng có như thế nào đi nữa thì phần mềm vẫn là đầu ra cuối cùng để hiển thị con số khủng. Rõ ràng lớp bảo vệ cuối cùng là phần mềm đã không thể ngăn chặn được hậu quả khủng khiếp đó. Tôi cho rằng các nhà sản xuất phần mềm phải chịu trách nhiệm về lỗi đó chứ không phải lỗi từ các nhà sản xuất phần cứng.

Nguyên nhân là gì? Phần mềm đã không có cơ chế bảo vệ dữ liệu một cách thông minh. Công tác đánh giá chất lượng dữ liệu trong phần mềm đó hoàn toàn có vấn đề. Đây là một phần của chuyên ngành học về dữ  liệu có tên là “Data Profiling”

Data Profiling hay "Khảo cố học dữ liệu":
Theo định nghĩa trên Wikipedia (http://en.wikipedia.org/wiki/Data_profiling) thì Data Profiling được định nghĩa như sau:
Data profiling is the process of examining the data available in an existing data source (e.g. a database or a file) and collecting statistics and information about that data. The purpose of these statistics may be to:
1. Find out whether existing data can easily be used for other purposes
2. Improve the ability to search the data by tagging it with keywords, descriptions, or assigning it to a category
3. Give metrics on data quality, including whether the data conforms to particular standards or patterns
4. Assess the risk involved in integrating data for new applications, including the challenges of joins
5. Assess whether metadata accurately describes the actual values in the source database
6. Understanding data challenges early in any data intensive project, so that late project surprises are avoided. Finding data problems late in the project can lead to delays and cost overruns.
7. Have an enterprise view of all data, for uses such as master data management where key data is needed, or data governance for improving data quality.

Theo định nghĩa trên http://searchdatamanagement.techtarget.com thì Data Profiling được định nghĩa như sau:

Data profiling, also called data archeology, is the statistical analysis and assessment of the quality of data values within a data set for consistency, uniqueness and logic.  

Profiling tools evaluate the actual content, structure and quality of the data by exploring relationships that exist between value collections both within and across data sets. For example, by examining the frequency distribution of different values for each column in a table, an analyst can gain insight into the type and use of each column. 

Quay lại bài toán máy đánh bạc. Nếu phần mềm có cơ chế đánh giá chất lượng dữ liệu cả đầu vào và đầu ra thì hậu quả đã có thể được giảm bớt. Phần mềm không thể tùy tiện hiển thị một con số lớn bao nhiêu cũng được. Nó cần phải có khả năng phát hiện lỗi ở khâu nào trong quá trình xử lý dữ liệu.

Trong ứng dụng thương mại cũng vậy, để đề phòng gian lận, các đơn hàng có số tiền khủng cần phải có cảnh báo từ xa ở các mức khác nhau tùy vào thiết lập đằng sau ứng dụng (back-end). Những đơn hàng như vậy cần phải được thông báo cho các lãnh đạo có thẩm quyền trước khi xuất hàng nhằm giảm thiểu gian lận từ phía khách hàng hay nhân viên, hoặc thậm chí có thể là lỗi gõ máy.

5 năm trước đây tôi đã từng tham gia thiết kế một hệ thống nhập đơn hàng với rất nhiều điểm nhập dữ liệu (input). Đặc điểm của hệ thống này là người dùng sẽ sử dụng thao tác nhập bằng tay và dùng Tab thường xuyên thay vì dùng chuột để tang tốc hiệu suất công việc. Khi đó có một người dùng gõ nhầm năm “2008” thành năm “2108” thành thử một loạt các báo cáo bị sai hàng loạt. Lỗi nghiêm trọng đó được gửi về cho nhóm phát triển của chúng tôi. Chúng tôi mất 1 ngày để dò nguyên nhân và phát hiện sự cố nghiêm trọng này. Sau khi thông báo nguyên nhân lỗi, chúng tôi cũng chủ động lên kế hoạch xây dựng một non-functional requirement nhằm cảnh báo những dữ liệu lạ đi vào hệ thống, thí dụ dữ liệu ngày tháng năm cách quá xa thời gian hiện tại, số tiền nhập quá lớn một cách bất thường… Tất cả các dấu hiệu bất thường đều được gán các mức cảnh báo từ xa một cách tương ứng nhằm giúp người nhập dữ liệu phát hiện sự cố sớm ngay trước khi dữ liệu được gửi lên.