A simple solution to the error is to add a login to SQL Server for
IIS APPPOOL\ASP.NET v4.5 and grant appropriate permission to the database.Open SQL Server Management Studio > Right click ‘Security’ > New > Login
IIS APPPOOL\ASP.NET v4.5 and grant appropriate permission to the database.Yes! For people doing custom implementation to create a Read Only Dictionary, there is now a .NET BCL implementation of the same in .NET 4.5.
A ReadOnlyDictionary is a useful data container when you are sending data across layers of an application and you want to ensure the data is not modified across the layer.
A good use case for this is Configuration information that is critical for functioning of an application. We may want multiple layers of the application to have access to the configuration information (and a dictionary is a very good way to pass configuration around) but no one should be able to update the configuration directly without going through the required checks and balances. In the following sample, we will look a small such sample.
Step 1: Create a new Console Application in Visual Studio 2012 CP. Name the Solution ‘ReadOnlyCollectionSample’.
Step 2: Add two Window Class Library projects, ConfigurationLibrary and ConfigurationConsumer.
Step 3: In the ConfigurationLibrary project, add a Class called ConfigurationContainer

Step 4: Setting up the ConfigurationContainer
- In the ConfigurationContainer, add a field _mutableConfiguration for type Dictionary<string, string>. This is where we will load our configuration.
- In the constructor, initialize the _mutableConfiguration dictionary and add some key value pairs to it.
- Add a property called Configuration with the type ReadOnlyDictionary<string, string> with a getter only. The Getter will return a new instance of ReadOnlyDictionary<string, string>. The Read Only Dictionary is initiated using the _mutableConfiguration.
- Add a public method AddToConfiguration(key, value). This method will add/update a configuration key/value pairs from outside.
- Add a method ConfigurationAllowed that returns a Boolean. This contains the logic that decides if a particular configuration parameter can be updated or not and update it accordingly. Essentially we have restricted users from updated the Configuration and we will be controlling the update via this method.
- The final class looks as follows:

Step 5: Setting up the ConfigurationConsumer
- Rename the Class1 to ConfigurationConsumer
- Declare a field of type IReadOnlyDictionary<string, string> called _config.
- In the Constructor initialize the _config field by using the Configuration property of an instance of ConfigurationContainer
- Add a method DoSomething() that checks if a “key” called configuration exists and prints a message with the value if it does. If the “key” does not exist it prints a different message.
- Add another method called BeNaughtyWithConfiguration(). Try to cast the _config read-only dictionary into an ordinary IDictionary. Now add a key to the IDictionary instance. The full listing is as follows

Step 6: Using the Configuration in ReadOnlyCollectionSample
- In the Program.cs’ main method instantiate the ConfigurationConsumer and call the DoSomething() method
- Add a Console.ReadLine() to wait for user input before executing the next line.
- Call the BeNaughtyWithConfiguration() method
- The Final code is as follows

Build and run the sample. The output on the console will be something as follows:

As we see, the value from the Read only dictionary was extracted successfully.
Next we hit enter and the code tries to execute the BeNaughtyWithConfiguration method. Wham! We get the following exception:

As we can see, our ReadOnly configurations are safe from type conversion into updatable counterparts.
If you add a watch for the convertToReadWrite.IsReadOnly property, you will find it to be ‘True’.

In our above sample, the Dictionary was that of primitive type ‘string’ that is itself immutable. However if you had a read only dictionary of type say ConfigElement, where ConfigElement is defined as follows:

The ReadOnlyDictionary in this case would not be able to prevent changes to the ConfigElement instance. So if someone retrieved the ConfigElement from the readonly dictionary and updated the Value property, the property would get change in the instance that’s in the Dictionary.

This code will give us the following output

As we can see the element got updated in the Dictionary.
To conclude, the new ReadOnlyDictionary<T,T> generic type in .NET 4.5 fulfills a long standing feature request for the BCL. It will be very useful for scenarios where read only Dictionaries need to be exposed. One such case is shown above.
The final code (including use of the ConfigElement type) is available here. Repo at: https://github.com/devcurry/ReadOnlyCollectionSample
Note: We have tested the code on the following combinations
1. VS 2012 RC + Windows 7
2. Win8 CP with VS11 Beta to run the code sample. It is going to work on Win8 RP + VS 2012 RC as well.
ZipFile.ExtractToDirectory(@”D:\devcurry.zip”, @”D:\devcurry\”);
ZipFile.CreateFromDirectory(@”D:\devcurry”, @”D:\devcurry.zip”);
using (ZipArchive zipArchive =
ZipFile.Open(@"C:\Archive.zip", ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in zipArchive.Entries)
{
using (Stream stream = entry.Open())
{
//Do something with the stream
}
}
}





file = .\SolutionZip\Properties\AssemblyInfo.cs addFile = SolutionZip\Properties\AssemblyInfo.cs

C:\> SolutionZip.exe mySolution\ solutionName.zip
The problem of passing current method details haunted my team and me when we were asked to add logging to every available business layer method in a two year old project, that had no logging and empty try { } catch { } blocks. We eventually worked around it by using a mix of reflection and string literals to get the current method name. But in my guts I hated the fact that I had to use reflection to do logging. This was 5 years ago using C# 2.0.
Come VS 2012 and C# 5, we will have access to three attributes that do specifically the task that we had hacked around then. These attributes are
These can be used in any logging method to retrieve the calling method and log it. In this post, we will see how we can use Log4Net’s rolling file Appender* and the Caller Info Attributes to log errors in an application
Note: Appenders for log4Net are like Providers and serve as an extension point for Log4Net. The RollingFileAppender logs errors to a file and rolls over to a new file if the current file passes certain criteria like a date based roll over or size of file based roll over. You also have SQL Appenders and Xml Appenders and host of log outputs possible using Log4Net.
Create a new Console Application in Visual Studio 2012 (aka VS 11)

We will simply log key-strokes as input at the Console window and depending on type of keys pressed throw exceptions with different methods. We end the execution when users press the Escape key. The code for this is in the LoopInfintely() method shown below.

To show that the Caller Info Attributes work at the method level we are logging Errors from a method called LogError as shown below

Logger class above is a Singleton wrapper around Log4Net. Before we look at the code for it, let us see the steps to install and configure Log4Net.
If there was ever anything to complain about Log4Net it was setting up a basic workable Appender in one go. Thanks to Nuget and the Community that has been rectified. Install Log4Net using the following command in the Package Manager Console
PM> install-package log4net
Next install a Rolling File Appender configuration using the following package
PM> log4net.samples.rollingfileappender
The above inserts the following configuration section in the App.config

The configuration section is as follows

With this as a default, Rolling File Appender has been setup that rolls over daily. We have updated the file location and the converstionPattern as highlighted above. The conversion Pattern ensures the fields are Pipe ( | ) separated, making them easy to import into excel and monitor.
With Log4Net in place let’s implement our Wrapper class Logger
The Log wrapper is a singleton class that creates one instance of the Log4Net logger and exposes methods for logging different levels of messages. For example it has methods Error, Warning and Debug to log corresponding levels in Log4Net.
It is initialized as follows

The GetLogger factory method initialized the LogManager.
The log4net.Config.XmlConfigurator.Configure() uses the configuration defined in the App.config
The Initialize method is called the first time _log is used. We have a guard clause to check if _log has been initialized. If not, the Initialize() method is called.
So far we have a sample application that waits for key-strokes at the console and throws exception with different messages depending on what type of key is hit. Numeric keys result in Debug level logs, Function keys result in Warning level errors and all others result in Error level logs.
Now we look at the wrapper functions in our Logger class and see how we are obtaining trace information. As seen below we have three attribute decorated optional parameters called memberName, sourceFilePath and sourceLineNumber. These are decorated with the Caller* attributes. We can now very easily use these input params in our logs as shown below. The beauty of the implementation is ONLY your logger wants this information so it is specified only in the logger not in every method call to the logger. This by my standards is Magic!

Actually there is not much of magic here, if you notice the three pieces of information they are static once the code is compiled. So the compiler simply replaces the optional parameters with the static values of MethodName, FilePath and SourceLineNumber in the method call at runtime. Basically the compiler is writing a bit of code/text for us at compile time.
I had initially specified the log format to be pipe ( | ) separated. So we can open the file in Excel and specify custom separator as ( | ). Part of the log looks as follows

As we can see in Column D we have the details of the Method (where the error occurred), the File in which it occurred and the line number at which the error occurred. The Debug and Warn logs were from the LoopInfinitely whereas Error logs are from the LogError method. In column E we have the exception message and as we can see we have thrown messages based on type of keys typed.
The caller info attributes have primarily been added to aid runtime debugging and error handling. This is a very robust low-level language support.
As seen above it greatly helps writing better trace routines for runtime issue debugging. Also they are simply optional parameters, so you can at any point override the default values and pass in custom values in the parameters.
The Caller Info values are emitted as actual strings into IL at compile time and are not affected by obfuscation.
Another use for the CallerMemberName attribute is implementation of the INotifyPropertyChange interface. Without the CallerMemberName we would need to pass in the property name as a mandatory parameter.
Fork this on Github or Download the entire source code
http://msdn.microsoft.com/en-us/library/hh534540%28v=vs.110%29.aspx
public class MyReader
{
public int Read(byte [] buffer, int offset, int count);
}
public class MyReader
{
public IAsyncResult BeginRead(
byte [] buffer, int offset, int count,
AsyncCallback callback, object state);
public int EndRead(IAsyncResult asyncResult);
}
public class MyReader
{
public void ReadAsync(byte [] buffer, int offset, int count);
public event ReadCompletedEventHandler ReadCompleted;
}
public delegate void ReadCompletedEventHandler(
object sender, ReadCompletedEventArgs eventArgs);
public class ReadCompletedEventArgs : AsyncCompletedEventArgs
{
public int Result { get; }
}
public class MyReader
{
public Task<int> ReadAsync(byte [] buffer, int offset, int count);
}

…
{
…
int bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false));
…
}