REGEX: Replace all characters A-Z and a-z in a variable.

This is a regex expression you can use to filter a variable (let’s say a number), from all unwanted chars and sybols. Below is an example of how to use it with the Regex.Replace method:

[A-Za-z;'%^!@#$%&*()_+-]
result = Regex.Replace(value,"[A-Za-z;'%^!@#$%&*()_+-]", String.Empty)
Posted in Uncategorized | 1 Comment

Add an event handler to a control programmatically.

First we declare a Button named myButton:

Dim myButton As Button = New Button()
 myButton.ID = "btnMyButton"
 myButton.Text = "Just Do It!"

Here is how we add a handler to its click event:

 AddHandler myButton.Click, AddressOf myButton_Click

And last thing to do is write the actual method that handles the click event:

Protected Sub myButton_Click(ByVal sender As Object, ByVal e As EventArgs)

 'Your code goes here.

 End Sub

Here is how you can create an event in C#. I will briefly describe how the event is being created, how we raise the event and how add an eventhandler to it.

// we declare the delegate for the event; this is just the signature of
// a method, that will handle the event.
public delegate void Del(object sender, EventArgs e);
// then we declare the event object which holds the type of Del
//(the delegate we declared earlier) 
public event Del ev;
// We now add an EventHandler to the event being raised.
ev += new Del(SomeMethodName);
// And this is the method that will handle our event
void SomeMethodName(object sender, EventArgs e){
throw new NotImplementedException();}

// We trigger the event like this:
ev(sender, e);

 

Posted in Uncategorized | Leave a comment

Javascript: How To Set Cursor to Textbox End

< script language="javascript">
function func()
{
    var t2 = document.getElementById("t2");
    t2.focus();
    t2.value = t2.value;
}
< /script>

The trick is to reset the value of the textbox like that:

t2.value = t2.value;

Don’t put a focus() method after that line, as it won’t work. If you want to focus the control do it before you reset the value.

Posted in Uncategorized | Leave a comment

Set a MSSQL Database as read-only

EXEC sp_dboption “HereGoesYourDBName”, “read only”, “True/False”;

Posted in Uncategorized | Leave a comment

Disable script debbuging in Visual Stuio 2008 and IE8

 

You may have noticed the huge tree of constantly appearing script documents in Visual Studio 2008. Script debugging is a great feature of Visual Studio, but it can as well slow down dramatically project execution. There are several ways you can turn that off.

The first method requires that you have Silverlight 2 Tools for Visual Studio 2008 SP1. You can get them here:

http://www.microsoft.com/downloads/details.aspx?familyid=C22D6A7B-546F-4407-8EF6-D60C8EE221ED&displaylang=en

In project properties go to Start Options and click ‘Silverlight’ at the bottom of the screen. The debugger can’t simultaneously debug Silverlight and Scripts and this will shut down script debugging. This method would allow you to turn on and off debugging of scripts.

The other method:

* Start command prompt (start->run, cmd.exe). On a 64 bit Windows run (start->run, c:\windows\syswow64\cmd.exe)
* reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {4FF9DEF4-8922-4D02-9379-3FFA64D1D639} /f

If you use Visual Web Developer Express, change ‘VisualStudio’ with ‘VWDExpress’:

* reg add HKLM\SOFTWARE\Microsoft\VWDExpress\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {4FF9DEF4-8922-4D02-9379-3FFA64D1D639} /f

If you would like to turn on script debugging again:

* reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {170EC3FC-4E80-40AB-A85A-55900C7C70DE} /f

Ако искате да изключите само генерирането на ‘anonymous code’ нодове, вместо да изключите изцяло дебъгването на скриптове:
(трябва да имате инсталиран Visual Studio 2008 SP1)

If you just want to disable the ‘anonymous code’ nodes generation (you’ll need Visual Studio 2008 SP1):

* reg add HKCU\Software\Microsoft\VisualStudio\9.0\Debugger /v HideAnonymousScriptCodeNodes /t REG_DWORD /d 1 /f

 

Posted in Uncategorized | Leave a comment

ASP inline tags explained

There are a couple of inline tags and here they are quickly explained:
<% … %>

This is the basic asp tag, which is used to execute normal code in the aspx page:

<% if (User.IsInRole(“admin”)) { %>
You can see this
<% } else { %>
You are no admin fool!
<%} %>

http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx

<%= … %>

This tag is used to get the value of a variable or display a property of a control (i.e. TextBox1.Text)

The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>

http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx

*Note: <%= is equivalent to Response.Write()

<%# .. %>

This is one is used for so called binding expressions (Bind and Eval). Like in a GridView template column, when you want to set the text property of a label to the value of the column in the datasource:

It’s used in GridView, Repeater, DetailsView и т.н.

<asp:Repeater ID=”rptMeetings” DataSourceID=”meetings” runat=”server”>
<ItemTemplate>
<%# Eval(“MeetingName”) %>
</ItemTemplate>
</asp:Repeater>

http://msdn2.microsoft.com/en-us/library/ms178366.aspx

<%$ … %>
Used for expressions, not code; often seen with DataSources:

<asp:SqlDataSource ID=”party” runat=”server” ConnectionString=”<%$ ConnectionStrings:letsParty %>” SelectCommand=”SELECT * FROM [table]” />

http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx

<%@ … %>

This one is used for descriptions or directives, or simply said the things you see on top of each of your aspx pages.

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” Title=”Untitled Page” %>
<%@ Register TagPrefix=”wp” Namespace=”CustomWebParts” %>

http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx

<%– … –%>

This is a server side comment.

<asp:Label ID=”lblAwesome” runat=”server” />
<%– sometimes end users make me angry –%>
<asp:LinkButton ID=”lbEdit” Text=”Edit” OnClick=”Edit_Click” runat=”server” />

http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx

Posted in Uncategorized | Leave a comment

A Simple C# Labyrinth/Maze Solving Application

This is a simple application where by clicking you can create a maze using a GridView control. Cells have either true or false values. The ones with false ones represent the passable areas and the true-valued ones are so to say the walls. Most importantly, of course, the maze gets solved. Background I have accidentally landed once on an article regarding maze solving algorithms. I decided to try and find a solution myself. Using the Code As I have explained earlier in the introduction, the maze is represented by a GridView control, false-valued cells being the passable areas. You create your own paths and crossroads by clicking each individual cell. The movement is represented by changing the style of the current cell and changing the x, y coordinates according to the passable areas. The rules that the “algorithm” follow are:

 1.It stores all the visited coordinates (KeyValuePair of integers)

2.It marks the crossroads (KeyValuePair of integers) it goes by and when a blockage is recognized, it goes back to the last crossroad and continues “moving” if possible.

3.It has one main method which is being called recursively to perform the movement. We also have 4 supporting methods called: LookLeft(), LookRight(), LookUp(), LookDown() which return boolean and perform a move by changing x, y int variables corresponding to the coordinates of cell and row indices and depending on the result, call each other in this GoMove() main method.

4.To recognize a blockage on the path taken, the program uses CanLookRight(), CanLookLeft(), etc. methods which also return boolean values. The only difference they have to the previously mentioned methods is that they don’t change the x,y variables and perform no actual “movement” on the GridView. This is the main GoMove method which uses the supporting LookLeft, etc. supporting methods and calls itself recursively to perform movement on the passable areas:

// we run this method on a separate thread to avoid "hanging" in the form
void GoMove0()
{
    CheckForIllegalCrossThreadCalls = false;
    if (x == 0 && y == 0)
    {
        return;
    }

    if (hasPassed)
    {
        if (z < crossroads.Count)
        {
#region [ checks if it has stucked up ]
            if (!CanLookUp()) // checks if it can go up
            {
                if (!CanLookRight()) // checks if it can go right
                {
                    if (!CanLookLeft()) // checks if it can go left
                    {
                        if (!LookDown()) // checks if it can go down;
// if true goes all the way
                        { // sets the current coordinates to those of the
// last visited crossroad and calls the method again.
                            y = crossroads[z].Key;
                            x = crossroads[z].Value;
                            z++;

                            GoMove0();
                        }
                    }
                }
            }
#endregion
#region [ checks if it has stucked down ]
            if (!CanLookDown())
            {
                if (!CanLookRight())
                {
                    if (!CanLookLeft())
                    {
                        if (!LookUp())
                        {
                            y = crossroads[z].Key;
                            x = crossroads[z].Value;
                            z++;

                            GoMove0();
                        }
                    }
                }
            }
#endregion
#region [ checks if it has stucked left ]
            if (!CanLookLeft())
            {
                if (!CanLookUp())
                {
                    if (!CanLookDown())
                    {
                        if (!LookRight())
                        {
                            y = crossroads[z].Key;
                            x = crossroads[z].Value;
                            z++;

                            GoMove0();
                        }
                    }
                }
            }
#endregion
#region [ checks if it has stucked right ]
            if (!CanLookRight())
            {
                if (!CanLookUp())
                {
                    if (!CanLookDown())
                    {
                        if (!LookLeft())
                        {
                            y = crossroads[z].Key;
                            x = crossroads[z].Value;
                            z++;

                            GoMove0();
                        }
                    }
                }
            }
#endregion
        }
    }
    hasPassed = true;
    if (LookUp()) // goes all the way up
    {
        if (!LookLeft())
 // it went all the way up tries left,
// if not goes right if possible
        {
            LookRight();
        }

        GoMove0(); // recursive call to continue movement
        return;
    }
    if (LookDown())
    {
        if (!LookLeft())
        {
            LookRight();
        }
        GoMove0();
        return;
    }
    if (LookRight())
    {
        if (!LookDown())
        {
            LookUp();
        }
        GoMove0();
        return;
    }
    if (LookLeft())
    {
        if (!LookDown())
        {
            LookUp();
        }
        GoMove0();
        return;
    }
}

bool LookLeft()
{
bool hasMoved = false; 

try
{
// checks if the following cell is a passable area
//(if the cell is false-valued)
while (!checkIfVisited(x-1,y) &&
    Convert.ToBoolean(dataGridView1.Rows[y].Cells[x - 1].Value) == false)
{
// if it hasn't visited the current coordinates, performs a 'move'
// and then sets the hasMoved flag to true;
hasMoved = true;

visitedCoordinates.Add(new KeyValuePair<int, int>(x, y));
// performs a 'move'
x = x - 1;
listBox1.Items.Add("x = " + x.ToString() + "\t\ty = " + y.ToString());

// sets a distinguished style for the visited cell
dataGridView1.Rows[y].Cells[x].Style = style2;
// set it's value to true
dataGridView1.Rows[y].Cells[x].Value = true;
// puts the thread to sleep to get that sleek move feel
System.Threading.Thread.Sleep(Convert.ToInt16(textBoxSpeed.Text)); 

#endregion
// checks for crosssroads on the way
if ((bool)dataGridView1.Rows[y].Cells[x - 1].Value == false)
{
// if a passing on the upper side cell has false value we then have
// a 'T' shaped crossroad and add its coordinates to the list
if ((bool)dataGridView1.Rows[y + 1].Cells[x].Value == false)
{
dataGridView1.Rows[y + 1].Cells[x].Style = style3;
crossroads.Add(new KeyValuePair<int, int>(y + 1, x));
listBox2.Items.Add("x = " + x.ToString() + " y = " +
(y + 1).ToString());
}
// if an underlying cell has false value we then have
// a 'T' shaped crossroad and add its coordinates to the list
if ((bool)dataGridView1.Rows[y - 1].Cells[x].Value == false)
{
dataGridView1.Rows[y - 1].Cells[x].Style = style3;
crossroads.Add(new KeyValuePair<int, int>(y - 1, x));
listBox2.Items.Add("x = " + x.ToString() + " y = " +
(y - 1).ToString());
}
}
}
if (hasMoved)
{
return true;
}
else
return false;
}
catch
{
if (hasMoved)
{
return true;
}
else
return false;
}
}

You can also save the mazes you create as *.txt files and then load them into the application. Here are 2 sample mazes I have created which you can load and test right away after downloading the VS 2008 solution. You can also adjust the speed (cell per millisecond) the maze is being solved.

Download the complete source here:

http://www.myhomebills.info/mazesolver.rar

Read my article at CodeProject here:

http://www.codeproject.com/KB/grid/Labyrinth-Solver.aspx

Posted in Uncategorized | Leave a comment

Edit event not firing when we set the DataSource of a GridView programmatically

If you set the DataSource of a GridView programmatically like this: 

GridView1.DataSource = someDataTable
GridView1.DataBind()

And if we put, let’s say a template field insite a GridView and a LinkButton, which has its CommanName property set to “Edit”. So far so good, but if you click on your edit LinkButton the GridView won’t go in EditMode. 

You have to do two things: 

put a RowEditing EventHandler: 

Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing

and put the following line it, which would set the EditIndex of our GridView and put it in EditMode: 

GridViewListItems.EditIndex = e.NewEditIndex

And then rebind the GridView. 

If you the want to exit EditMode just set GridViewListItems.EditIndex = -1 

Posted in Uncategorized | Leave a comment

is not a valid Win32 application. (Exception from HRESULT: 0x800700C1) Exception Details: System.BadImageFormatException: is not a valid Win32 application

Have you come accross this error? If  you perhaps have a 64 bit machine and use IIS 7+ and/or have migrated an application from 1.1 to 2.0 then this should be your case:

1. In Windows 7 в IIS (7) open Application Pools.
2. Locate the Application Pool-а which your application uses
3. Click on Advanced Settings on the right.
4. Set Enable 32-Bit Applications to true.

Posted in Uncategorized | Leave a comment

Visual Studio crashes and hangs after Office 2010 installation

Sometimes Visual Studio 2008 happens to crash, after you have installed ot upgraded to Office 2010. This happens when you try to view the design of an apsx page.

This is due to some changes the installer makes to the “Microsoft Visual Studio Web Authoring Component”, which is part of Office 2007. A simple solution is to repair its installation. Just go to:

Windows 64bit
C:\Program Files (x86)\Common Files\microsoft shared\OFFICE12\Office Setup Controller\Setup.exe
Windows 32bit
C:\Program Files\Common Files\microsoft shared\OFFICE12\Office Setup Controller\Setup.exe

and do a repair.

Posted in Uncategorized | 1 Comment