Abdulla AbdelHaq Blog


ForEach(Minute in MyLife)
MyExperience ++;
PEX - Let Me Fix Your Code [JorDev User Group]

 Hello .NET Heroes,

 This is my session on Microsoft PEX that I gave on JorDev User Group (Jordan .NET User Group), and for those who do not know What JorDev is? it is simply one of the biggest .NET User Group in Middle East.

Location : MIC (Microsoft Innovation Center)

 Time : 6:25PM Wednesday, October 28th 2009

I was wondered before if there a kind of tool that check my code in few clicks, just like the spell checker of our word documents! 

PEX is a Microsoft Research Project that help you to understand the behavior of .NET code, debugging issue and generating test cases for free.

You can view that playlist of the session from JorDev You Tube Channel 

 Or you can view it right away from the below videos.

The session was in Arabic, I am planing to translate it into English, but PEX team said that keep it in Arabic because it will target the Arabic speakers.

The session also posted on Microsoft Reseach - PEX home page  http://research.microsoft.com/en-us/projects/pex/

 You can download the presentation slides from here , or from the attachment link at the bottom of the article.

Note : Part1 is a brief introduction on Unit Testing, so if you want to see PEX directly, you can start from Part2

 

Part 1

 

Part 2

 

Part 3

 

Part 4

 

Part 5

 

I Hope Some One Will Find It Use Full.

 

~ Abdulla AbdelHaq
Jordan Remix the Technology.

Today, the IT  people in Jordan enjoyed in event called Jordan Remix !

Remix word comes from Remixing the technology together; .NET 2010, SharePoint 2010, Windows 7, Office 2010 and Windows Server 2008 R2. All these technologies were in one event, it really was a great day for me, remixing technology.

More than 400 people has attend the sessions at the hall, and more than 1500 people have watched it live on Jordan-Remix.com

All sessions were recorded, and I would like to share them with you.

http://www.jordan-remix.com


Enjoy :)

 

~ Abdulla AbdelHaq

How To Embedded StyleSheet File with Custom Control.

How to embedded StyleSheet file with custom control? Question has been opened many time on ASP.NET forum.

So in this article, I will try to demonstrate how to achieve this task.

In General

In general, if you want to embedded any thing with custom control, you need first to make its "Build Action" property to be "Embedded Resource", and then you need to add to the custom control assemblies using the <Assembly> attribute typically above class name, and finally you need to register in the page so it can be rendered.

I will illustrate all these things in details through the article.

 

Step One: make it as Embedded Resource

 After you added the StyleSheet file to your Custom Control Class Library project, first thing you need to do is to make build action property for the stylesheet file as embedded resource, otherwise your page will not be able to see the stylesheet file.

To do this, from the VS do a right click on the stylesheet file, and click on Properties,  and then change the "Build Action" property to be "Embedded Resource".

 

Step Two: Add it to the Custom Controls Assemblies

 Second thing you need to do is to register the Css file to the custom control assemblies by adding the below code typically above class name


[assembly: WebResource("YourProjectName.StyleSheetFileName.css", "text/css")]

namespace YourNameSpace

{

   public class MyCustomControl : CompositeControl

    {

       //Custom Control Rest Code

 

 Step Three: Register Css File on the Page

Finally, we have to tell the Page that our custom control has Css file needed to be registered when the final HTML is generated for that page. So we need to write a bit of code in the OnInit method.

 

protected override void OnInit(EventArgs e)

{

    base.OnInit(e);

   

    string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(this.GetType(),

    "YourProjectName.CssFileName.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";

   

               

    Page.ClientScript.RegisterClientScriptBlock(this.GetType, "cssFile", css, false);

}

 

And that's it, you can now use the CSS StyleSheet file within your Custom Control.

 

I hope some one will found this very helpful.

 

~ Abdulla AbdelHaq

 

How to fix this .. The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

 Sometimes when you write inline code inside Javascript tag or inside style sheet tag within the header of the page just like code 1, the yellow error page  will explode in your face telling you that The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Code 1

<%@ Page Language="VB" AutoEventWireup="false"

CodeFile="Default.aspx.vb" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head >

    <title>Inline Code inside JavaScript</title>

    <script type="text/javascript" language="javascript">

    function fnTest()

    {

        var txt = document.getElementById("<%= TextBox1.ClientID %>")

        alert(txt.value);

    }

   

   

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    </form>

</body>

</html>

 

The weird thing is that the error is not occurred each time! I mean if you tried to write the same code in another page it will work and the error will disappear !!

I searched on the Net to find an answer and to know more about this weird thing, and I found a nice blog that talked about this issue

http://www.west-wind.com/weblog/posts/5758.aspx

He posts a solution for the problem, but the funny thing is that he also did not know the main reason for the error. and I found no one know the main reason!

 I tried another solution and it worked for me. All I did is I moved the JavaScript tag to the bottom of the page, typically above the close form tag, and the error is gone!

Solution 1

 

<%@ Page Language="VB" AutoEventWireup="false"

CodeFile="Default.aspx.vb" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head >

    <title>Inline Code inside JavaScript</title>

</head>

<body>

    <form id="form1" runat="server">

 

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

 

    <script type="text/javascript" language="javascript">

    function fnTest()

    {

        var txt = document.getElementById("<%= TextBox1.ClientID %>")

        alert(txt.value);

    }

   

   

    </script>

 

 

    </form>

</body>

</html>

 

Or you can play around this by registering the  JavaScript code from code behind.

 Solution 2

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

 

        Dim strScript As New StringBuilder

 

        strScript.Append("function fnTest()")

        strScript.Append("{")

        strScript.Append("var txt = document.getElementById('")

        strScript.Append(Me.TextBox1.ClientID)

        strScript.Append("');")

        strScript.Append("alert(txt.value);")

        strScript.Append("}")

 

        Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "MyScript", strScript.ToString, True)

 

 

 

    End Sub

 

I really still do not know the error main reason, if anybody know about this then please write it as comment.

 I hope someone will found this very helpful.

 

~ Abdulla AbdelHaq

RadioButton inside GridView, How to get it work as normal.

As we all know, RadioButton control used in a situation when you want end-users to select only one option at a time from group of options.

Did you tried before to drag a RadioButton control inside a Gridivew templatefield, and then you attempt to select these RadioButtons , you will notice that the behavior of RadioButton control will be changed and it will work just like the behavior of checkbox control! the user will be able to select more than one radiobutton in the grid!

O.k you can use html radiobutton element instead of server radiobutton control in the templatefield, this will do the trick and the behavior will get back again, but what if you want to do some event in codebeind and collect the selected Radiobutton?! this time you need to add the run at server attribute to the html element to be able to see it in the codebehind, in that case, the behavoir will be changed again and the user can select more than one option from the radio buttons.

So what is the solution for that ?

In simplest scenario, when the situation is only radio button and text beside it, you can use the RadioButtonList control instead, but if the form gets to be more complex and you need to display other controls beside the radiobutton, then (gridview,repeater,datalist) should be your choice.

the below code will help you to accomplish that.

<script type="text/javascript" language="javascript"> 

     

 function fnCheckUnCheck(objId) 

   {

  var grd = document.getElementById("<%= GridView1.ClientID %>"); 

      

   //Collect A

   var rdoArray = grd.getElementsByTagName("input"); 

       

   for(i=0;i<=rdoArray.length-1;i++) 

    { 

     if(rdoArray[i].type == 'radio')

      {

       if(rdoArray[i].id != objId) 

        { 

           rdoArray[i].checked = false; 

        } 

     }

   } 

} 

</script>

<asp:GridView ID="GridView1" runat="server"

 AutoGenerateColumns="false" >

<Columns>

 

<asp:TemplateField HeaderText="Select/UnSelect"> 

<ItemTemplate > 

<input id="grdRdo" name="grdRdo" type="radio" runat="server"

  onclick="fnCheckUnCheck(this.id);" /> 

 </ItemTemplate>

 </asp:TemplateField>

 

<asp:BoundField DataField="User_Name" HeaderText="Name" />

<asp:BoundField DataField="User_Department" HeaderText="Dep" />

   

</Columns>

</asp:GridView>

 

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

 

  For Each grdRow As GridViewRow In GridView1.Rows

    Dim htmlRdo As New HtmlInputRadioButton

   htmlRdo = DirectCast(grdRow.FindControl("grdRdo"), HtmlInputRadioButton)

 

     If htmlRdo.Checked Then

         ' Do Something

     Else

         'Do something else

      End If

 

   Next

 

End Sub

I hope someone will found this very helpful :)

~ Abdulla AbdelHaq

Displaying Arabic Number.

 Well, most applications that I worked with was multilingual that supports English UI and Arabic UI.

 And one of the major issue that we have faced is displaying Arabic numbers without the need of changing the regional settings of the PC.

So the code below will help you to display Arabic number without  changing any regional settings.


Code 1: the HTML code:

 

<form id="form1" runat="server">

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<br />

<asp:Label ID="Label1" runat="server"></asp:Label>

<br />

<asp:Button ID="Button1" runat="server" Text="Convert to Arabic" />

</form>

 

Code 2: Code Behind

 

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

 

        'Call Function

        Me.Label1.Text = "Arabic Number : <b>" & TranslateNumerals(Me.TextBox1.Text.Trim) & "</b>"

    End Sub

 

 

    Public Shared Function TranslateNumerals(ByVal sIn As String) As String

 

        Dim enc As New System.Text.UTF8Encoding

 

        Dim utf8Decoder As System.Text.Decoder

 

        utf8Decoder = enc.GetDecoder

 

        Dim sTranslated = New System.Text.StringBuilder

 

        Dim cTransChar(1) As Char

 

        Dim bytes() As Byte = {217, 160}

 

        ' Start Converting characters into Arabic mode.

 

        Dim aChars() As Char = sIn.ToCharArray

 

        For Each c As Char In aChars

 

            If Char.IsDigit(c) Then

 

                bytes(1) = 160 + CInt(Char.GetNumericValue(c))

 

                utf8Decoder.GetChars(bytes, 0, 2, cTransChar, 0)

 

                sTranslated.Append(cTransChar(0))

 

            Else

 

                sTranslated.Append(c)

 

            End If

 

        Next

 

        TranslateNumerals = sTranslated.ToString

 

    End Function

 

 

After you run the page, enter some English number and then click "Convert to Arabic" button to display the entered number in Arabic number mode.

Figure 1: Convert English Number into Arabic Number

 

 

I hope some one will find this very helpful

 ~ Abdulla AbdelHaq

Adding ToolTip for each List Item.

In Some cases, you have a restricted design that forces you to place a DropDownList control inside a "td" or "div" element, which has a fixed width. if that DropDownList contains long pieces of text then the user will not be able to read the whole  text  as you can see in Figure1.

Figure 1

 

The best solution to overcome this problem is to add a ToolTip for the item to display the whole text. As we know the regular DropDownList does not support that which is the main goal of this post.

Lest us say that we have a DropDownList that contains three list items.

Code 1


<asp:DropDownList ID="DropDownList1" runat="server" Width="119px">
  
<asp:ListItem Value="1">Technical Department</asp:ListItem>
  
<asp:ListItem Value="2">Production Department</asp:ListItem>
  
<asp:ListItem Value="3">HR Department</asp:ListItem>
</asp:DropDownList>

 

As I said, the regular DropDownList does not support a ToolTip for each list item, so we will add a new attribute for each list item which is the "title" attribute.

Code 2


foreach (ListItem _listItem in this.DropDownList1.Items)



  _listItem.Attributes.Add(
"title", _listItem.Text);

}

As you can see in the above code, we wrote a foreach loop to walk through the DropDownList item-by-item to add the title attribtue.

You can enter any text to represent the ToolTip for the item as description; here in our example I am using the list item text to be its ToolTip.

We need to add a title attribute for the selected item too, as shown in below code.

Code 3

DropDownList1.Attributes.Add("onmouseover", _ 
 "this.title=this.options[this.selectedIndex].title");

if you view your code in a browser, right click on the page and choose view source, take a look at the HTML generated element for our DropDownList, in Code 4, note that a new title attribute is added for each item in the list.

Code 4

<select name="DropDownList1" id="DropDownList1"
onmouseover="this.title=this.options[this.selectedIndex].title"
    style="width:119px;">
  <option value="1" title="Technical Department">Technical Department</option>
  <option value="2" title="Production Department">Production Department</option>
  <option value="3" title="HR Department">HR Department</option>
</select>

Figure 2

 

The above figure shows you how our new tooltip works when the mouse goes over the list item.

Conclusion

in this article, we have added a new tooltip attribute for each item in the DropDownList which will help the users to read the whole text. I hope you found this useful and informative. If you have any questions, please write your comments below.

 ~ Abdulla AbdelHaq

 

VS Debug Problem with IE8

 

Since this is my first post on Weblogs, I decide to write about a problem that has been opened frequently on ASP.NET official forum which is VS debugger crashes with IE8.

 

  I had answered the same problem 4 times, so I hope that some one will found this post very helpful if he is facing the same problem.

 

 

How VS debugger could be crashed with IE8?

 

If you opened multiple instances of IE8 and you attempt to debug your project, you mostly will have the issue where VS debugger just stops and ignores your break points!

 

 

Why was that?

 

Well, IE 8 has a feature called Loosely-Coupled Internet Explorer (LCIE) which results in IE running across multiple processes.
http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie

Older versions of the Visual Studio Debugger get confused by this and cannot figure out how to attach to the correct process. 

 

To overcome this issue, you need to disable the process growth feature of LCIE by follow the below steps:

1)  Open RegEdit
2)  Browse to HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
3)  Add a dword under this key called TabProcGrowth
4)  Set TabProcGrowth to 0

 If you run into the same problem on Vista or newer, you will also need to turn off protected mode.

And then go a head and start debugging your code :)

 

 

~ Abdulla AbdelHaq

More Posts