.net, Ajax, C#, Code, Microsoft, Technical

‘Sys’ is undefined – ASP.Net Ajax error

I was using ASP.NET 2.0 along with Ajax Extensions 1.0. I received this error ‘Sys’ is undefined error message every time I used an Ajax control. I was pulling my hair out on it and decided to give the Control Toolkit’s web.config a glance. The following lines were not available in my web.config, so i copied them over:

<httpHandlers>
            <remove verb=”*” path=”*.asmx”/>
            <add verb=”*” path=”*.asmx” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
            <add verb=”*” path=”*_AppService.axd” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
            <add verb=”GET,HEAD” path=”ScriptResource.axd” type=”System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ validate=”false”/>
</httpHandlers>
<httpModules>
            <add name=”ScriptModule” type=”System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
</httpModules>

P.S: These lines go inside the System.Web section of your web.config file

Bingo.. the error vanished and all my controls started to function as they should 🙂

 

Technorati Tags: ,,
Advertisements
.net, C#, Code, Microsoft, WPF

Hide a window instead of closing it in WPF

I wanted to give WPF a try and was creating a timer application which will pop up a window once a while. But what I wanted was for the application to keep running in the tray even when its closed. The following code does NOT work in WPF for some reason:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            Window.Visibility = !Window.Visibility;
        }

 

In order to hide a closing window in WPF, this is what needs to be done:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

            //Do some stuff here 

            //Hide Window
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback)delegate(object o)
            {
                Hide();
                return null;
            }, null);

            //Do not close application
            e.Cancel = true;

        }

.net, C#, Code, Microsoft, Technical

Using StreamReader without locking the file in C#

I was using the StreamReader class to read the contents of a text file. I was under the assumption (well I know its a bad

thing)  that because I am only reading the contents of the file, the file would be available for other applications to read or write. Guess what, i was wrong. The StreamReader class does maintain a lock on the file until you call the Close() method. So to not have the lock, we have to explicitly set up the sharing mode.

FileStream fs = new FileStream(@”c:\test.txt”, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
txtContents.Text = sr.ReadToEnd();
sr.Close();

Technorati Tags: ,,
Code, Microsoft, Performance, SQL, SQL Server, T-SQL, Technical

Computed Columns in SQL Server 2005

“Computed Columns” as the name suggests allows you to set the value of a column based on other columns data. Here’s how you could specify the formula in T-SQL:

--Create Table
CREATE TABLE T1 (
    a INT, 
    b INT, 
    operator CHAR,
    c AS CASE operator
        WHEN '+' THEN a+b
        WHEN '-' THEN a-b
        ELSE a*b
    END
    PERSISTED
) ;

--Insert dummy data into it
INSERT INTO T1 VALUES(1,2,'+')
INSERT INTO T1 VALUES(5,3,'-')
INSERT INTO T1 VALUES(4,4,'')

--View the results
SELECT * FROM T1

Notice the keyword PERSISTED. This will enable the computed column value to be stored physically on to the disk so that it need not be created every time you ask for it. Creating an index on this computed column will improve performance by doing a seek rather than a table scan.

If you want to specify the above computed column in SQL Server management studio directly you can do this:

Modify the table. Go to the computed column specification for the specific column. Expand it and type the following in the “Formula” field:

(CASE [operator] WHEN '+' THEN [a]+[b] WHEN '-' THEN [a]-[b]

ELSE [a]*[b] END)

Enter without line breaks. If you want the column values to be persisted in the storage medium, just change the value of “Is Persisted” to “Yes”

.net, C#, Code, Microsoft, Standards, Technical, XML

Strip Illegal XML Characters based on W3C standard

W3C has defined a set of illegal characters for use in XML . You can find info about the same here:

XML 1.0 | XML 1.1

Here is a function to remove these characters from a specified XML file:

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace XMLUtils
{
    class Standards
    {
        /// <summary>
        /// Strips non-printable ascii characters 
        /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
        /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
        /// </summary>
        /// <param name="filePath">Full path to the File</param>
        /// <param name="XMLVersion">XML Specification to use. Can be 1.0 or 1.1</param>
        private void StripIllegalXMLChars(string filePath, string XMLVersion)
        {
            //Remove illegal character sequences
            string tmpContents = File.ReadAllText(filePath, Encoding.UTF8);

            string pattern = String.Empty;
            switch (XMLVersion)
            {
                case "1.0":
                    pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
                    break;
                case "1.1":
                    pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
                    break;
                default:
                    throw new Exception("Error: Invalid XML Version!");
            }

            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            if (regex.IsMatch(tmpContents))
            {
                tmpContents = regex.Replace(tmpContents, String.Empty);
                File.WriteAllText(filePath, tmpContents, Encoding.UTF8);
            }
            tmpContents = string.Empty;
        }
    }
}
.net, C#, Code, Microsoft, Security, Technical

Quickly calculate and compare MD5 or SHA2 values

There might be situations when you might want to quickly calculate the MD5 or SHA2  values of any file or a set of files. The solution depends on what is your requirement: 1) Its a one time work and you would just want the results in a text / html file 2) You want the hash inside your .Net program

Scenario 1: The best bet is to download a program called HashMyFiles by nirsoft.net
This nifty little program can generate an HTML report containing the hashes of all the files in the specified file/folder.

Scenario 2: Here is the C# version of creating the hashes using the build in Cryptography classes.

using System.Security.Cryptography;
using System.Text;

public string GetMD5(string filePath)
{
            StringBuilder sb = new StringBuilder();
            FileStream fs = new FileStream(file, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(fs);
            fs.Close();
            fs.Dispose();
            foreach (byte hex in hash)
            {
                //Returns hash in lower case.
                //To return upper case change “x2” to “X2”
                sb.Append(hex.ToString(“x2”));
            }
            return sb.ToString();
}

public string GetSHA2(string filePath)
{
            StringBuilder sb = new StringBuilder();
            FileStream fs = new FileStream(file, FileMode.Open);
            SHA256 s2 = new SHA256CryptoServiceProvider();
            byte[] hash = s2.ComputeHash(fs);
            fs.Close();
            fs.Dispose();
            foreach (byte hex in hash)
            {
                //Returns hash in lower case.
                //To return upper case change “x2” to “X2”
                sb.Append(hex.ToString(“x2”));
            }
            return sb.ToString();
}

.net, Code, Microsoft, Technical, Visual Studio

LIFO and FIFO (Stack and Queue)

Well, I was working on one of the projects which required the use of the FIFO and LIFO data structures. Since the project was based on .NET, I had no trouble at all implementing the same.

The System.Collections namespace provides us with the classes required to implement FIFO and LIFO.

Declare the queue:
Queue myQ = new Queue(5);
To add an item:
myQ.Enqueue(“myItem”);
To remove an item:
myQ.Dequeue();

For LIFO:
Declare the Stack:
Stack myStack = new Stack(5);
To add an item:
myStack.Push(“myItem”);
To remove an item:
myStack.Pop();

Gone are the days where one has to write the entire code to implement these oft used operations.