DotNetBlog der DotNet-Blog Alles rund um Microsoft .NET – von  Sascha H. Baumann

Archiv für die Kategorie ‘Allgemein’

C#: Lookup vs. Dictionary

Dienstag, 16. Februar 2010

The main difference between the Generic Classes Lookup and Dictionary is the uniqueness of the Key. While Dictionarys can only have a Key-Value once,
in Lookup it can occur multiple times.

Declaration is the same.

Lookup<int,string> myLookup = new Lookup<int,string>();

vs.

Dictionary<int,string> myDic = new Dictionary<int,string>();

Furter Reading:

* A nice article about using ToDictionary and ToLookup in Linq can be found @blog.donnfelker.com

Die Kultur de ist neutral. Sie kann nicht als die aktuelle Threadkultur festgelegt werden, da sie nicht zum Formatieren und Analysieren verwendet werden kann

Donnerstag, 14. Januar 2010

I got this message yesterday, while trying to save changes into entity framework. the whole thing was within an ASHX-Handler and I couldn’t figure out , what the deal was.

Now I found a solutions. Just add the following line at the beginning of your method /codeblock and you are fine:

C#

System.Threading.Thread.CurrentThread.CurrentUICulture =
     new System.Globalization.CultureInfo("de-DE");

VB.net

System.Threading.Thread.CurrentThread.CurrentUICulture = _
     New System.Globalization.CultureInfo("de-DE")

Extension Methods in VB.Net

Dienstag, 12. Januar 2010

My preferred .NET-language is C#, but as a consultant I have to write VB every once in a while. Here is a little introduction, how my beloved
Extension Methods work in VB.Net.

Just two steps:

Step1 – Create a new Module called for example “StringExtensions.vb” and add an Import –Statement for System.Runtime.CompilerServices

Step2 – Write your Extension Method, and put an <Extension()> directive on top. Here is an example:

<Extension()> _
    Public Function AddAbcX(ByVal mystring As String) As String
        Return myString + "ABC"
    End Function

Notice the _ behind the directive. Don’t forget this one.

You notive one additional thing. A while ago I read an article about Extension Methods and got the suggestion to add an X to each methodname.
So, if using intellisense, you will see directly if the method you’re about to call is an Extension Method or a build-in Method. Good idea I think.

Another suggestion – Put the method in the same namespace as the object it belongs to (I said namespace, not file!).

So you have your methods ready when you start using the object.

Cheers

Sascha

Happy new Year

Donnerstag, 31. Dezember 2009

Hello everyone,

I wish all of you a relaxing and successful 2010. See you on the other side :o )

Sascha

Silverlight 4 Beta released

Sonntag, 22. November 2009

As you might now, Microsoft has released the first beta for Silverlight 4 a few days ago. More about this beta, and other Silverlight related topics can be found on my Blog about Silverlight.

Cheers

Sascha

Visual Studio 2010 and .NET 4.0 Beta 2 now available for the public

Mittwoch, 21. Oktober 2009

Hello everyone,

I just checked, and found that now everyone can download the new Beta 2 of VS2010 and .NET Framework 4. Have fun trying, I know I will.

Download: Microsofts Visual Studio Page

MCTS Exam 70-536 – Generic Collections

Donnerstag, 15. Oktober 2009

Good News everyone !

For the fact that I’m faster in reading then in wring, I made a lot of progress in exam preparation and I’m a bit behind with my notes. Anyway, I share my notes about this topic with you today

General

  • Using Generics can improve performance by reducing the number of cast-operations.
  • Common generic Collections:
    1. List<T>
      Comparable to StringCollection and ArrayList
    2. Dictionary<T,U>
      Comparable to NameValueCollection, StringDictionary,OrderedDictionary,HybridDictionary, ListDictionary and Hashtable
    3. Queue<T>
      Comparable to normal Queue
    4. Stack<T>
      Comparable to normal Stack
    5. SortedList<T, U>
      Comparable to normal SortedList
    6. Collection<T>
      Comparable to CollectionBase
    7. ReadOnlyCollection<T>
      Comparable to ReadOnlyCollectionBase
  • You can Use Generics with any build in and Custom Type
  • Is’nt there more ? Lots of code samples which are not part of my notes :o )

MCTS Exam 70-536 – Collections and Dictionaries

Montag, 12. Oktober 2009

Good morning,

today I start with Collections and Dictionaries during my MCTS exam-preparation. As usual I provide my notes on that topic as a little help and motivation for other students.

Collections

  • namespaces where we find Collections are System.Collections and System.Collections.Specialized
  • Collectionstypes are:
    1. ArrayList – stores any type of object, expands as required. Accessable by zero based index or within a foreach_loop. Use .Add, .AddRange, .Remove, .Insert and .Sort (Objects need to implement IComparable), .Reverse (Reverse current order)
    2. Queue – First in, First out (FIFO) collection. Use .Enqueue and .Dequeue to add and remove objects and .Peek to lookup an object on a specified position. Use .Clear to remove all objects
    3. Stack – Last in, First out (LIFO) collection. Use .Push and .Pop to add and remove objects and .Peek to loopup an object on a specified position. Use .Clear to remove all objects
    4. StringCollection – As ArrayList, but strongly typed for strings, does not support sorting
    5. BitArray / BitVector – Collection of boolean values. BitVector is limited to 32 bits, BitArray stores more.
  • Thinking about IComparable, the method .CompareTo provides default sortorder while .Compare provides custom sortorder.
  • Dictionaries

  • Dictionary-Types are:
    1. Hashtable – name/value pairs that can be retrieved by name and index
    2. SortedList – sorted automatically by key. Array of DictionaryEntry objects
    3. StringDictionary – Hashtable that is strongly typed to string
    4. ListDictionary – Dictionary optimized for less then 10 items
    5. HybridDictionary – Advantage of ListDictionary when less then 10 items, otherwise behaves like a Hashtable
    6. NameValueCollection – pairs of strings, accessable by index or name(key). Can store multiple values for the same key.
  • MCTS Exam 70-536 – Encoding and Decoding

    Freitag, 09. Oktober 2009

    Good Day,

    normally I would write about Regular Expressions today, but I need a little bit more preparation on this topic. So I will skip it for now, and work on Encoding and Decoding.

    General

    • ASCII (American Standard Code for Information Interchange) is the foundation of the encodings
    • ASCII is 7 bit (0-127)
    • It includes English letters in upper and lower case, punctuation, numbers and some special characters
    • It does not include non-English characters
    • ANSI defined code pages for different character-sets using 8-bit (0-127 as ASCII, 128-255 special)
    • ASCII and ISO 8859 (ANSI) encodings are being replaced by Unicode, a massive code-page
    • Default of .NET Framework is Unicode UTF-16 (In some cases UTF-8)
    • System.Text namespace contains classes that provide encoding and decoding (UTF-32 encoding, UTF-16 encoding, UTF-8 encoding, ASCII encoding, ANSI/ISO encoding)
    • UTF-8 and UTF-7 are backward compatible with ASCII-Encoding, UTF-16 and UTF-32 are not.

    Encoding classes

    • use System.Text.Encoding.GetEncoding to get a special encoding object
    • use Encoding.GetBytes to convert a Unicode string to its byte representation
    • To Explore Code Pages use Encoding.GetEncodings to get a list of EncodingInfo Objects which represent available encodings

    Specify Encoding when reading or writing a file

    • Use the overload of the StreamWriter- and StreamReader-Constructor accepting Encoding-Object
    • Typically you don’t need to specify the encoding type when reading a file. Framework detects automatically.
    • For Example writing “Hello Kitty!!” to a file has the following sizes when choosing the encoding:
      • UTF-7 : 19 bytes
      • UTF-8 : 18 bytes
      • UTF-16: 32 bytes
      • UTF-32: 64 bytes
    • Notepad can not read UTF-7 and UTF-32 files correctly

    So far for now, next time I learn about Collections and Generics

    MCTS Exam 70-536 – Reading and Writing Streams and Files

    Dienstag, 06. Oktober 2009

    Good Morning folks,

    Today I read about streams and files, and as usual I provide my notes as a summary. enjoy !

    Textfiles

    • To read a textfile, we can use TextReader or StreamReader Class
    • To write a textfile, we can use TextWriter or StreamWriter Class
    • StreamReader derives from TextReader
    • Usually you use File.OpenText or StreamReader Constructor
    • Typically we use ReadLine or ReadToEnd Methods to read data
    • Dont forget to call Close on the Reader or Writer after finished reading or writing
    • To ensure, that no data is left in the buffer while keeping the file open use the Flush Method

    Binary Files

    • To read and write binary files, use BinaryReader and BinaryWriter
    • Generally serialization is more effective

    Strings

    • Use StringWriter to write data to StringBuilder
    • Not used very often, only in special scenarios

    MemoryStream

    • To create a stream in memory
    • Commonly used to store data temporarily that will be written to a file eventually
    • To Minimize the time a file is locked open, minimizes the potential for conflict
    • MemoryStream often is used with a StreamWriter, cause MS itself has only WriteByte/Write, and ReadByte/Read Methods that work with bytes and byte-arrays

    BufferedStream

    • Is used for custom stream implements
    • .NET Stream Classes have a build-in buffering logic, so you normally dont need to use BufferedStream. If you do so its redundant and inefficent

    Compressed Streams

    • You can only read or write bytes and byte-arrays directly, but you can use StreamWriter and StreamReader
    • Use GZipStream Class for GZIP-Compression and DeflatedStream class for Deflated Data Format
    • CompressionMode which is part of the constructor indicates simply if you are compressing or decompressing data

    Isolated Storage

    • Isolated Storage is a private file system
    • It requires fewer privileges than writing to filesystem
    • IS is isolated by user, application domain and assembly
    • Don’t use to store high-value secrets or sensitive data, because its not protected from high-trusted code, unmanaged code or trusted users of the computer
    • The access to a file is restricted to the user who created it
    • isolation by application domain is optional
    • In most case (almost always) you will use the isolation by application-domain
    • Classes to work with Isolated Storage (All in System.IO.IsolatedStorage)
      1. IsolatedStorageFile – Management of Isolated Storage Stores (Often Used Methods are .GetUserStoreForAssembly, .GetUserStoreForDomain, .GetStore
      2. IsolatedStorageFileStream – Access to read/write Isolated Storage files
      3. IsolatedStorageException – exception related to Isolated Sotrage
    • Code must be granted IsolatedStorageFilePermission

    Bad Behavior has blocked 132 access attempts in the last 7 days.