Saturday, August 27, 2011

Burn audio CDs using iTunes for Windows

iTunes Version 10
Although audio CDs seem to be obsolete, there are some cases that CDs are still relevant. In this post, I will explain how to create an audio CD using iTune. Unfortunately, the procedure is not that intuitive which can be attributed to the fact that CDs are not being used anymore.
  1. Create a playlist as follows:
    1. From menu choose File>New Playlist. A new entry will be created under playlists (left pane).
    2. Name your new playlist; I’ll name it MyCD.
    3. On the left pane select Music under LIBRARY.
    4. Highlight the songs you’d like to burn to the CD (hold Ctrl + Click).
    5. Right click and select Add to playlist>MyCD. If you didn’t name the playlist MyCD which I’m sure you didn’t, replace MyCD with the name you chose for your playlist.
  2. Now that the playlist is ready we can easily burn it to CD by right-clicking on it and selecting Burn playlist to Disc.
  3. On Burn Setting windows, select Audio CD and click Burn. Obviously you need a blank CD in your driver.
I hope this post helps the few that proudly still use audio CDs.

Sunday, June 12, 2011

Using other search engines with Google Chrome

Google Chrome Version 12

Chrome address bar (Omnibox) allows users to directly search the internet. Users can set a search engine as their default engine and at any time they can use the address bar to perform their searches. That’s a very helpful feature of Chrome however we sometimes require to use multiple search engines or even search content of certain sites.

To accommodate this need, Chrome allows you to define search engines and quickly and easily access them.

The following shows you how you can add Wikipedia as a search engine to Chrome.

  • Open Chrome and click on the wrench button.
  • Click on Options
  • From the left pane choose Basics
  • Click on Manage search engines…
  • At this point a page opens up containing two section namely Default search options and Other search engines. Under Other search engines, you can define your own search engine. At the bottom of the section, you’ll see Add a new search engine. That is where you specify the name you would call your new search engine with. I’ll call it Wikipedia; you may choose any name you’d like. In the second column or Keyword, you need to specify a shorthand for your search engine; this can be anything however you need to remember it when you want to search. I will use _wiki. The reason for starting with underscore is so Chrome doesn’t confuse it with other things it cached such as you previous search queries.In the third column or URL, specify the URL of the search engine. It is not always URL of the website that the search is provided within. This is very crucial to find the correct URL since if you specify an incorrect URL, you will not be able to search at all.To find the correct URL, you need to lookup a word using your search engine and take the URL that you land on and replace the word you searched with %s.

Here is how it should be done for Wikipedia.

  • 1. Go to http://www.wikipedia.com
  • 2. In the search box type in MySearch and push enter
  • 3. You will land on a page with the following URL http://en.wikipedia.org/wiki/Mysearch
  • 4. Replace MySearch with %s as follows http://en.wikipedia.org/wiki/%s

That’s it.

Now here is how you use the new search engine:

  • 1. Open a new tab
  • 2. type _wiki
  • 3. Push Tab and notice that Chrome address bar at the left-side showing Search Wikipedia.
  • 4. Type your query and push enter

Note that Chrome allows you to change the default search engine. If you set your entry in Search Engines page to default, you can type your query directly in the address bar and push enter to search; You can skip steps 2 and 3.

Thursday, October 1, 2009

Software Version Disclaimer

Please note that the point made in the post might not apply to next or previous versions of the software.

Saturday, June 6, 2009

Ensure web application security by correct web.config configuration

In his article Bryan Sullivan explains about the most common mistakes in web.config file that leads to web site vulnerabilities.

It's easy to overlook these mistakes in web.config. Moving the application from one stage to another without modifying web.config is one of the common mistakes.

The following is the list of vulnerabilities; It can be used as a checklist for ensuring that the deployed product is protected from the most common web.config security flaws. For more details about each entry in the list, please read the complete article linked to at the bottom of the page.

  1. Custom Errors Disabled.
  2. Leaving Tracing Enabled in Web-Based Applications.
  3. Debugging Enabled.
  4. Cookieless Session State Enabled.
  5. Cookieless Authentication Enabled.
  6. Failure to Require SSL for Authentication Cookies.
  7. Sliding Expiration Used.
  8. Non-Unique Authentication Cookie Used.
  9. Hardcoded Credentials Used.

 

Read the complete article at:

Application Security Vulnerabilities in Web.config Files Part One and Part Two by Bryan Sullivan.

Sunday, January 18, 2009

Disabling "See this location in bird's eye view" message

To disable the message, add the following to your style sheet:

 

#MSVE obliquenotification

{ visibility:hidden}

 

Source:

http://blogs.msdn.com/virtualearth/archive/2008/09/22/disabling-the-bird-s-eye-view-indicator.aspx

Thursday, October 2, 2008

Error connecting to undo manager of source file

Issue

Above error message appears when user tries to debug a web application in Visual Studio 2005.

Solution

This error message can be fixed by simply deleting the designer file (aspx.designer.cs/aspx.designer.vb) of the page that is causing the error; you can get the page name from the complete error message you are receiving.

To recreate the designer file, right click on the page ASPX file and click on Convert to Web Application.

That will fix the problem.

User control properties do not show up on IDE property window

Issue

When you place a user control (.ascx) on a page, public properties of the user control do not appear on the IDE's property window.

Solution

In order for the properties to show in property window, it must be a public property and also have definition for both get and set accessors.

If the above conditions are met and still the property is not accessible by property window, just close and reopen the page on which you placed the user control.

Thursday, September 11, 2008

Internet Explorer Loads Slowly (First Tab)

To fix the problem follow these steps:

  1. Open Internet Explorer.
  2. Point to Tools> Internet Options.
  3. Select Connections tab.
  4. Click on LAN settings.
  5. Uncheck Automatically detect settings.

Thursday, August 21, 2008

Generics

In framework 2 Microsoft introduced support for generic types. Generic can take on any type; it might sound familiar to you; objects can do exactly the same. Generics are to replace objects when possible, since they firstly improve the performance by eliminating the need to boxing and unboxing, secondly decrease the number of run-time errors caused by incorrect casting.

Here is an example of incorrect casting:

object MyObj=new object();

MyObj="Not an integer";

int MyNumber=(int)MyObj;//CAUSES RUN-TIME ERROR

The above mistake won't be caught by the compiler and as a result will generate a run-time error.

The class definition does not provide the exact variable types and when the class is used, the exact types are passed to the class.

The following is the definition of a class that uses generic concept:

class MyGenericClass<MyGenericTypeOne,MyGenericTypeTwo>
    {
        private MyGenericTypeOne MyFieldOne;
        private MyGenericTypeTwo MyFieldTwo;
        public MyGenericTypeOne MyPropertyOne
        {
            get
            {
                return MyFieldOne;
            }
            set
            {
                MyFieldOne = value;
            }
        }

        public MyGenericTypeTwo MyPropertyTwo
        {
            get
            {
                return MyFieldTwo;
            }
            set
            {
                MyFieldTwo = value;
            }
        }
    }

 

MyGenericTypeOne and MyGenericTypeTwo are two generic types that the above class uses.

The following code consumes the above class:

 

MyGenericClass<string,int> NewInstanceOne=new MyGenericClass<string,int>();
NewInstanceOne.MyPropertyOne = "Some text";
NewInstanceOne.MyPropertyTwo = 10;

MyGenericClass<double, Uri> NewInstanceTwo = new MyGenericClass<double, Uri>();
NewInstanceTwo.MyPropertyOne = 2.2;
NewInstanceTwo.MyPropertyTwo = new Uri("http://mycomputerknowhow.blogspot.com");

 

As you can see, when, in this case, instantiating the class, the exact type of the generic type is specified.

If MyGenericClass were a static class including all static members, you would pass the exact types as follows:

MyGenericClass<string, int>.MyPropertyOne = "string";
MyGenericClass<int, int>.MyPropertyOne = 10;

Debug.WriteLine(MyGenericClass<int, int>.MyPropertyOne);
Debug.WriteLine(MyGenericClass<string, int>.MyPropertyOne);

In the above code, classes MyGenericClass<string, int> and MyGenericClass<int, int> are in fact completely isolated from each other and can hold different values.

Though we have one class definition, since the actual types are different, MyGenericClass<string, int> and MyGenericClass<int, int> are two separate classes with different types.

Saturday, August 16, 2008

Disabling Ajax JavaScript error message

By default, if an exception is thrown in the asynchronized code, ScriptManager shows the exception in a JavaScript Alert window. Although this behavior is required some times, mostly for security purposes programmer wants to hide the run-time errors from the end users even if it does not make any clear sense to them. This is especially important for public web sites which can be exposed to all types of threats.

ScriptManager exposes an event called AsyncPostBackError that is fired every time there is an exception thrown during the execution of partial postback code. We can use this event in order to stop the exception from reaching the client script by re-throwing it; therefore, it can be captured by general web site error capturing mechanism.

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
    {
        throw (e.Exception);
    }

How to create a global error capturing mechanism for your web site

All web sites should include a general error handling code in case anything unexpected happens.

Creating this mechanism is really simple. Add Global Application Class (Global.asax) to your project if it doesn't already include one. Create the following method in the class if there isn't one.

 

void Application_Error(object sender, EventArgs e)
    {  

       Exception LastException=Server.GetLastError();
        //Your error handling code here.
        Server.ClearError();

    }

 

If the exception is not handled in the application, the above method gets called. You can call Server.GetLastError() method in order to get the last exception. After your error handling code, you should make a call to Server.ClearError() method to clear the exception.

Sunday, August 10, 2008

Boxing and Unboxing

Boxing simply means converting a value type to a reference type. Unboxing, on other hand, means converting a reference type to a value type.

For more information about reference types and value types, see this post.

The following is an example of boxing and unboxing:

object MyObject= 2.2; //boxing

double MyNumber=(double)MyObject;//unboxing

 

To improve the performance and maintain type safety, it is recommended to use boxing/unboxing in your code as little as possible .

Reference types and value types

Value types are the variables that store the actual values as opposed to reference types that keep a reference to memory where the data is stored.

Note: strings are reference types.

Example:

int MyValueType=123;//Value type

object MyReferenceType=new object();// reference type

Sunday, August 3, 2008

Choosing the right .Net Framework data collection

The .Net Framework includes several useful data collection classes; choosing the right one for the task at hand is greatly crucial. In the following, I will explain about some of the most useful collections available in Framework. So, you can easily decide which one to use in different situations.

These classes which are part of System.Collections namespace and System.Collections.Specialized are ArrayList, SortedList, Queue, Stack, Hashtable, BitArray, StringCollection, StringDictionary, ListDictionary, HybirdDictionary, and NameValueCollection.

ArrayList

ArrayList stores the data items of any object type in an unordered manner. Add method is used to add new data items to the collection as the last item. To add new items at a specific location, the class provides users with Insert method. You can use ArrayList numeric indexer to access each item in the collection or iterate over items. Also, you can use foreach for iteration of type object or a particular type in the case all the items are of that type (see the example for more details). Removing items from the collection is done by Remove and RemoveAt methods.

Other useful methods of ArrayList are:

Clear (empties the collection), IndexOf (specifies index of an item in the collection), Sort (sorts items in the collection), and Contains (verifies existence of an item in the collection).

Example:

Note: the example below requires System.Collections and System.Diagnostics namespaces.

ArrayList MyArrayList=new ArrayList();

MyArrayList.Add("New Item");

MyArrayList.Insert(0,"This is placed as the first item");

if (MyArrayList.Contains("New Item"))

{
    Debug.Write(MyArrayList.IndexO("New Item"))//Writes to output window. Run in debug mode.
    MyArrayList.Remove("New Item");
}

foreach (string EachItem in MyArrayList)
    System.Diagnostics.Debug.Write(EachItem )//Writes to output window. Run in debug mode.

MyArrayList.RemoveAt(0);
MyArrayList.Clear();

StringCollection

StringCollection is built to store only string items and not any other types of object. Working with StringCollection is similar to ArrayList.

Queue

The Queue stores objects in a first-in first-out manner. It means that the fist item added to the collection is the first item that is retrieved from it. Working with Queue is very simple; you can use Enqueue method to add new items, Dequeue method to retrieve items which removes the object from the collection as well, Peek method to extract the object without removing it from the collection, and Count property which returns the number of objects in the collection.

Example:

Note: the example below requires System.Collections and System.Diagnostics namespaces.

Queue MyQueue = new Queue();
MyQueue.Enqueue(2000);
MyQueue.Enqueue(new object());
MyQueue.Enqueue("Last Item");
Debug.WriteLine(MyQueue.Count);
if (MyQueue.Peek() is int)
    Debug.WriteLine(((int)MyQueue.Dequeue())+1);

Debug.WriteLine(MyQueue.Count);
MyQueue.Clear();

Stack

Stack is very similar to Queue the only difference is that Stack stores object in a last-in, first-out fashion. To work with the stored object Stack exposes Push method which adds new object to the collection, Pop method which extracts the object with removing it from the collection, Peek method which extracts the object without removing it from the collection, Clear method which removes all the objects, and Count property which shows the number of objects in the collection.

Example:

Note: the example below requires System.Collections and System.Diagnostics namespaces.

Stack MyStack = new Stack();
MyStack.Push(2000);
MyStack.Push(new object());
MyStack.Push("Last Item");
Debug.WriteLine(MyStack.Count);
if (MyStack.Peek() is string)
    Debug.WriteLine(string.Concat((string)MyStack.Pop()," is the first to be out."));

Debug.WriteLine(MyStack.Count);
MyStack.Clear();

Hashtable

Hashtable is a dictionary collection which means it keeps data in form of key and value pairs. Each collection entry is stored in one DictionaryEntry structure which in turn contains a key and a value. Key and value can be any object; a key cannot be null.  The primary purpose of dictionaries is to look up pairs.

Working with Hashtable is easy; you can use Add method to add new pairs, indexer to access each value, Remove method to remove a pair, ContainsKey method to verify existence of a key in the collection, ContainsValue to verify existence of a value in the collection, Keys property gets all the keys in the collection, Values property to get all the values in the collection, and Clear method to remove all the pairs from the collection.

Example:

Note: the example below requires System.Collections and System.Diagnostics namespaces.

Hashtable MyHashtable=new Hashtable();
MyHashtable.Add("MyKey1","MyValue");
MyHashtable.Add("MyKey2", DateTime.Now);

foreach (DictionaryEntry EachPair in MyHashtable)
    Debug.WriteLine(EachPair.Value);
if (MyHashtable.ContainsKey("MyKey1"))
    Debug.WriteLine(MyHashtable["MyKey1"]);
if (MyHashtable.ContainsValue("MyValue"))
    MyHashtable.Remove("MyKey1");

MyHashtable.Clear();

ListDictionary

ListDictionary is identical to HashTable in terms of interface but is more efficient for fewer than 10 items. See HashTable for an example on how to use this collection.

HybridDictionary

When the number of items is not known, HybirdDictionary can be used in place of HashTable or ListDictionary. HybridDictionary starts off internally as ListDictionary and converts to HashTable when the number of items in the collection gets higher than 10. HybirdDictionary also has the same interface as HashTable and ListDictionary. See HashTable for an example on how to use this collection.

OrderedDictionary

OrderedDictionary combines the power of arrays and dictionaries. In other words, working with it is much similar to HashTabe but it also provides users with properties and methods to allow items to be accessed by index. In addition to HashTable properties and methods, you can use Item property to access each item, Insert to add a new dictionary entry to a specific index in the collection, and RemoveAt to remove dictionary entries and a given index.

StringDictionary

StringDictionary is specialized dictionary collection that only stores string keys and values. Working with StringDictionary is the same as HashTable.

SortedList

Similar to Hashtable, SortedList is a dictionary collection and values are kept in key and value pairs. Therefore, all the above methods and properties for Hashtable also apply SortedList. In addition SortedList sorts the entries as soon as they are added to the collection and lets entries be accessed by index.  Note that index may change after adding or removing entries because the entries are sorted. 

Other useful methods of SortedList are IndexOfKey that returns index of a key in the collection, IndexOfValue that returns the first index of a value in the collection, GetKey that returns a key of a specific index, and GetByIndex that returns value of a specific index.

Example:

Note: the example below requires System.Collections and System.Diagnostics namespaces.

SortedList MySortedList = new SortedList();
MySortedList.Add("MyKey1","MyValue");
MySortedList.Add("MyKey2", DateTime.Now);

foreach (DictionaryEntry EachPair in MySortedList)
    Debug.WriteLine(EachPair.Value);

Debug.WriteLine(MySortedList.IndexOfKey("MyKey2"));
Debug.WriteLine(MySortedList.IndexOfValue("MyValue"));
Debug.WriteLine(MySortedList.GetKey(0));
Debug.WriteLine(MySortedList.GetByIndex(1));

if (MySortedList.ContainsKey("MyKey1"))
    Debug.WriteLine(MySortedList["MyKey1"]);
if (MySortedList.ContainsValue("MyValue"))
    MySortedList.Remove("MyKey1");

MySortedList.Clear();

BitArray

BitArray is a resizeable collection of bits and capable of performing boolean operations. To create a new instance you need to specify the length of the collection. This collection does not provide Add method; therefore, the only way to increase the capacity of it is through modification of its length property.

NameValueCollection

NameValueCollection is a dictionary collection that is able to store multiple values per key. All keys and values for this collection are of type string. To get values of a specific key, you can use GetValues method; also you can use index to access values of a key and since there can be more than one value per key, the collection returns a comma separated list of key values. You can use Add method to add new items and Clear method to remove all the items.

Example:

Note: the example below requires System.Collections.Specialized and System.Diagnostics namespaces.

NameValueCollection MyNameValueCollection = new NameValueCollection();
MyNameValueCollection.Add("FirstKey", "FirstKeyFirstValue");
MyNameValueCollection.Add("FirstKey", "FirstKeySecondValue");
MyNameValueCollection.Add("SecondKey", "SecondKeyFirstValue");
MyNameValueCollection.Add("SecondKey", "SecondKeySecondValue");
Debug.WriteLine(MyNameValueCollection.GetValues("FirstKey")[0]);
Debug.WriteLine(MyNameValueCollection.GetValues(1).Length);
Debug.WriteLine(MyNameValueCollection[1]);
MyNameValueCollection.Clear();

Tuesday, July 22, 2008

How to page validate when cross-page posting

It is necessary to page validate before processing the information received from the client-side. It's done with checking Page.IsValid on each page but how about when cross-page posting?

You can examine PreviousPage.IsValid on the page where you post back to in order to verify validation of the first page.

Monday, July 21, 2008

Serializing and deserializing objects

To serialize an object, you simply create an instance of  BinaryFormatter which is part of System.Runtime.Serialization.Formatters.Binary namespace and use Serialize or Deserialize methods.

The following example shows how an object can be serialized and deserialized. I used memory stream for my example; you can also use other kinds of stream such as FileStream. SerializingObject is the object that's being serialized. I serialize it then deserialize it to its original type which is DataTable.

Here is the example:

using(MemoryStream = new MemoryStream())
{

DataTable SerializingObject =new DataTable();

BinaryFormatter MyBinaryFormatter = new BinaryFormatter();
MyBinaryFormatter .Serialize(MyMemoryStream , SerializingObject);
MyMemoryStream .Position = 0;
DataTable DeserializingObject= (DataTable)MyBinaryFormatter.Deserialize(TableMemoryStream)

}

Importing namespace to the client-side code

Although client side code is not recommended to contain any code-behind code, some times it's required to write some server-side code on client-side file (aspx files). One example of this situation is when using  ASP.Net Repeater control; programmer might need to call a function to shape the fields to the required specification; therefore, the function has to be called on the aspx file. The need to access server-side code calls for importing namespaces. The problem here is the fact that imported namespaces to aspx.cs or aspx.vb are not seen by the same pages' aspx file.

Using the following piece of code will allow you to import namespaces to the aspx files to be used by server-side code.

<%@ Import Namespace="MyNamespace" %>

Sunday, July 20, 2008

Converting binary to Hexadecimal String in SQL Server

Here is a stored procedure that can cast binary values to hexadecimal. It becomes very handy when working with binary fields. Unfortunately, SQL Server does not have a build-in cast for converting binary to hexadecimal.

 

create procedure sp_hexadecimal

@binvalue varbinary(255)

as

declare @charvalue varchar(255)

declare @i int

declare @length int

declare @hexstring char(16)

select @charvalue = '0x'

select @i = 1

select @length = datalength(@binvalue)

select @hexstring = "0123456789abcdef"

while (@i <= @length)

begin

declare @tempint int

declare @firstint int

declare @secondint int

select @tempint = convert(int, substring(@binvalue,@i,1))

select @firstint = floor(@tempint/16)

select @secondint = @tempint - (@firstint*16)

select @charvalue = @charvalue + substring(@hexstring, @firstint+1, 1) + substring(@hexstring, @secondint+1, 1)

select @i = @i + 1

end

select 'sp_hexadecimal'=@charvalue

 

Source:

http://support.microsoft.com/kb/104829

Saturday, July 12, 2008

Reading and Writing to Streams

In the following example, I used FileStream to explain how reading and writing to steams work.

The example is self explanatory. It reads the data from TestRead.dat and writes it to TestWrite.dat.

ReadCount is 0 when Read has reached the end of the file; otherwise it is 1<=ReadCount<=100. ReadCount can change every time that Read method is called in the loop.

Buffer length can be modified but please note that it has to be able to accommodate the number of bytes returned by Read method.

 

using (FileStream ReadStream = new FileStream("c:\\TestRead.dat", FileMode.Open))
            {
                using (FileStream WriteStream = new FileStream("c:\\TestWrite.dat", FileMode.Create))
                {
                    byte[] Buffer = new byte[101];

                    int ReadCount = 0;
                    do
                    {
                        ReadCount = ReadStream.Read(Buffer, 0, 100);
                        WriteStream.Write(Buffer, 0, ReadCount);

                    } while (ReadCount != 0);
                }
            }

Thursday, June 12, 2008

Convert regular ASPX pages to content pages

 

1) Remove DOCTYPE.

2) Remove html, head, body, and form HTML tags.

3) Add the following to the page directive: MasterPageFile="~/MyMasterPage.master"

4) Add <asp:Content ID="Content1" ContentPlaceHolderID="MyContentPlaceHolderId" runat="server">My page contents</asp:Content>

All the page contents should be surrounded by <asp:Content> tag. Therefore, My Page Contents should be replaced by the remaining  HTML code.