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

Artikel mit ‘Exam 70-536’ getagged

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

MCTS Examen 70-536 – Filesystem

Freitag, 02. Oktober 2009

Hi there

We now leave types behind and go to the input/output chapter. I have to say, writing along while learning takes more time then just reading, but i hope it pays out at the end my having more information stuck in my brain ;o)

Drive Enumerating

  • Use DriveInfo.GetDrives to get a List of Drives connected to the system
  • You get a Collection over which you can loop
  • Available Information: AvailableFreeSpace, DriveFormat, DriveType, IsReady, Name, RootDirectory,TotalFreeSpace, TotalSize, VolumeLabel

Files and Folders

  • You can browse a folder by using an instance of DirectoyInfo and call .GetFiles or .GetDirectories
  • You can create a directory by using an instance of DirectoryInfo and call .Create
  • You can check if a directory Exists by DirectoryInfo.Exists
  • Static File Operations: File.Create, File.CreateText, File.Copy, File.Move, File.Delete
  • Alternative: Use an instance of FileInfo and call .Create, .CreateText, .CopyTo, .MoveTo, .Delete

Filesystem Monitoring

  • Use System.IO.FileSystemWatcher (responds to updated, new and renamed files etc)
  • FSW works Eventbased (Changed-Event, Create-Event, Delete-Event, Rename-Event etc.) and provides FileSystemEventArgs (except Rename, this provides RenamedEventArgs
  • You can configure the Watcher with:
    1. Filter (Filename, you can use wildcards)
    2. NotifyFilter (Defines, what changes causing a notification (One or more): Filename, Size, LastAccess etc)
    3. Path (Folder to be monitored)

MCTS Examen 70-536 – Classes

Samstag, 26. September 2009

Hello everyone,

a new day, a new learning experience. Today I work on the “Classes” chapter of my exam-preperation and will share the most interesting parts with you.

Inheritance

  • Inheritance and Interfaces provide a way to improve a systems consistency
  • via Inheritance you can create new classes from existing once
  • With inheritance there comes the possibility to use derived classes interchangeably. That is calles polymorphism. You can for example pass an object of type specialobject (Inheriting of object) to a method which excepts an object.

Interfaces

  • Interfaces are contract defining required members the new class must provide. For example the IComparable Interface defines a member method called CompareTo. Every class that implements IComparable must implement this Method.
  • Commonly used Interfaces: IComparable, IFormattable, IEuatable, ICloneable, IConvertible, IDisposable
  • Example Interface:

    public interface IMyInterface
    {
    bool DoSomething();
    string Message {get; set; }
    int MyNumber {get;set;}
    }
  • “Extract Interface” is a build in Refactoring-Method of Visual Studio

Partial Classes

  • A Class-Definintion can be split into different .cs files. This must be declared by using “partial” keyword in class definition (ex. public partial class}

Generics

  • With Generics you can define a type and leav some details unspecified. You dont have to specify the type of certain parameters or members, instead you can define them, when using the new type
  • Generics will be a bigger part of the exam
  • In System.Collections.Generic you can find some Generics like Dictionary, Queue, SortedDictionary or SortedList.
  • Advantages: Reduced run-time-errors (More typesafe) and improve performance (avoids boxing and unboxing)
  • Example of Definition:

    class MyGeneric
    {
    public T t;
    public U u;

    public MyGeneric(T _t, U _u)
    {
    t = _t;
    u = _u;
    }
    }

  • Important: Code needs to compile for every possible usage !
  • Comsuming Example:

    var test = new MyGeneric("hallo",12);
  • Constraints for the Types used (T and U in the example above) can be defined.

    class MyGeneric where T : IDisposable
  • You can use Interfaces, Baseclasses,Constructors and Reference of value types as constraints

Events

  • object (Event senders) can trigger events when an action takes place (User clicks button, method completed etc.)
  • Event Receivers can handle these events when they occure
  • A Delegate is a reference (pointer) to a method that itself has no code.
  • The Delegates signature must match the signature of the handling method
  • Things to do, to create a custom event:
    1. Create Delegate: public delegate void MyEventHandler(object sender, EventArgs e);
    2. Create event: public event MyEventHandler MyEvent;
    3. Fire Event
      if (MyEvent != null)
      {
      // Invoke Delegate
      MyEvent(this, new EventArgs());
      }
    4. You can create your own EventArgs. Just create a new Class, that inherits from EventArgs.

Attributes

  • Attributes describe Methods or Properties. You can get this information by reflection.
  • Commonly used attributes for: Security Privileges, capability (ex.Serialization), description (title, copyright…)
  • Attribute Types derive from System.Attribute
  • Example – AssemblyAttributes in AssemblyInfo.cs : [assembly: AssemblyTitle("title")]
  • Declaring capabilities:

    [Serializable]
    class MyClass
    {
    }

    Without this Attribute, a class is not serializable.
  • Declaring Security Requirements

    [assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, Read=@"C:\settings.ini")]
    namespace MyNamespace
    {
    ...
    }

Type Forwarding

  • Move a type from one assembly to another without needing recompile
  • TypeForwardedTo – Attribute
  • Example:

    using System.Runtime.CompilerServices;
    [assembly:TypeForwardedTo(typeof(TargetLib.MyType))]
  • Works only for components referenced by existing applications
  • To use Forwarding, do the following:
    1. Add TypeForwardedTo attribute to source assembly
    2. Cut Typedefinition from source and paste to destination
    3. Re-Compile both.
  • What have I learned ?

    I havent used Attributes very often, so it was a good brush-up, and the Type-Forwarding Part was new for me, so I learned something today – Hurray ! :o )

    Next Topic will be “Type Conversion” .. .stay tuned !


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