Loading Providers in Medium Trust Mode using WebConfigurationManager

Problem:

Recently I uploaded a ASP.NET2.0 website with a hosting provider (shared environment), and started getting this error when ever I wanted to load the providers declared on the config file:

[SecurityException: Request for the permission of type
‘System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089′ failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean
isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +59
   System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean
useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs,
String msgPath, Boolean bFromProxy) +678
   System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +114
   System.Configuration.Internal.InternalConfigHost.StaticOpenStreamForRead(String streamName) +80
  
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.Op
enStreamForRead(String streamName, Boolean assertPermissions) +115
  
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.Op
enStreamForRead(String streamName) +7
   System.Configuration.Internal.DelegatingConfigHost.OpenStreamForRead(String streamName) +10
   System.Configuration.UpdateConfigHost.OpenStreamForRead(String streamName) +42
   System.Configuration.BaseConfigurationRecord.InitConfigFromFile() +443


Background

To develop this site I used

  • ASP.NET2.0
  • MS Ajax
  • .NetTiers
  • SQL Server 2000

After doing further investigation by looking deep into the code and the internal exceptions:

 
System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean
ignoreLocal) at
System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors
schemaErrors) at System.Configuration.Configuration..ctor(String
locationSubPath, Type typeConfigHost, Object[]
hostInitConfigurationParams) at
System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInter
nalConfigConfigurationFactory.Create(Type
typeConfigHost, Object[] hostInitConfigurationParams) at
System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel
webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site,
String locationSubPath, String server, String userName, String
password, IntPtr tokenHandle) at
System.Web.Configuration.WebConfigurationManager.OpenWebConfigurationImpl(WebLevel
webLevel, ConfigurationFileMap fileMap, String path, String site,
String locationSubPath, String server, String userName, String
password, IntPtr userToken) at
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(String
path) at Something.DataAccessLayer.DataRepository.LoadProviders() in
DataRepository.cs:line

I figured out the following line of code is failing in the DataRepository.cs of .NetTiers, where it is trying to load the Configuration Object using the System.Configuration.WebConfigurationManager.

Configuration  config = System.Configuration.WebConfigurationManager.OpenWebConfiguration(“~”);

In this case .Nettiers DataRepository.cs tries to loads the config and then iterates through the sections and finds the desired section by using the Object Model. Infact it tries to load all the .nettiers related providers by iterating through the config sections.

An example may be “.NetTier config section”.

<configSections>
  <section name=”netTiersService” type=”Something.DataAccessLayer.Bases.NetTiersServiceSection, Something.DataAccessLayer” allowDefinition=”MachineToApplication” restartOnExternalChanges=”true” />
Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null”/>
</configSections>

<netTiersService defaultProvider=”SqlNetTiersProvider”>
  <providers>
    <add name=”SqlNetTiersProvider” type=”Something.DataAccessLayer.SqlClient.SqlNetTiersProvider, Something.DataAccessLayer.SqlClient” connectionStringName=”SomethingConnectionString” useStoredProcedure=”false” providerInvariantName=”System.Data.SqlClient”/>
  </providers>
</netTiersService>


Replicating the same error in Development Environment:

After doing a bit of googling I soon realised the above piece of code requires <trust level =”Full”/>

Probably the web hosting provider is running the application in “Medium” trust level and its causing the issue.

To successfully replicate the same error in development environment I added  <trust level=”Medium”> in my web.config.
<system.web>
  <trust level=”Medium”/>
  …
</system.web>


This made life easier to solve the issue when I replicated the same error in the dev environment.

Solution

To fix the issue I used WebConfigurationManager.GetSection instead of WebConfigurationManager.OpenWebConfiguration which runs fine in the trust level “Medium”. Here is the code.

ConfigurationSection ntsSection = (ConfigurationSection)WebConfigurationManager.GetSection(“netTiersService”);


also needed to add the requiredPermission = “false” attribute in web.config files in the section name “netTierService”.

<section name=”netTiersService” type=”Something.DataAccessLayer.Bases.NetTiersServiceSection, Something.DataAccessLayer” allowDefinition=”MachineToApplication” restartOnExternalChanges=”true” requirePermission=”false”/>

Conclusion

Bottom line is if we want to load the providers using the WebConfigurationManager in a medium trust mode, we need to make sure that we use “System.Configuration.WebConfigurationManager.GetSection” Method instead of “System.Configuration.WebConfigurationManager.OpenWebConfiguration” method. And make sure the section node has requiredPermission=”false” defined. This should work in Medium Trust Level.

Working with *Specified Properties.

Problem:

The value of DateTime property is assigned but its not included in the serialized xml.

SomeClass msg = new SomeClass();
msg.generated_on = DateTime.Now ;

if we serialize this we will find this:

<?xml version=”1.0″?>
<SomeClass xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” />


as opposed to

<?xml version=”1.0″?>
<SomeClass xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” generated_on=”12/07/2007 6:29:28 PM” />

 

Here is the c# code of SomeClass

public class SomeClass
{

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public System.String generated_on;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool generated_onSpecified;

}

Clarification:

==========

if we create an object of SomeClass and assign a value to the

member generated_on

(example msg.generated_on = DateTime.Now)

the XmlSerializer is not 100% happy unless we also specify
true to member generated_onSpecified

(example msg.generate_onSpecified = true);

WSDL.exe
After looking at the proxy that I have with me now, which is generated by WSDL.exe, I also found for all Members that are bool and DateTime it creates an additional bool member with the suffix of “Specified” by default.

For example:
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public System.DateTime generated_on {}

/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool generated_onSpecified {}

If we look at the generated code we will find the same pattern is followed all over.


After investigating further I found:

Many of the types that are created by the Microsoft Visual Studio 2005 proxy generator include properties with names that are appended with “Specified”. These properties are used along with the property of the same name that does not include the “Specified” suffix.
If the *Specified property is not set to true, the request will be sent without the property. This can result in unpredictable Web service behavior.
read more….
https://msdn2.microsoft.com/en-us/library/bb402199.aspx

and looking more further into XmlSerialization:

If a schema includes an element that is optional (minOccurs = ‘0’), or if the schema includes a default value, you have two options. One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code. Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named “MyFirstName” you would also create a field named “MyFirstNameSpecified” that instructs the XmlSerializer whether or not to generate the XML element named “MyFirstName”.
read more…..
http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

 

Suggestion:

Bottom line is, make sure that generate_onSpecified is set to “true” if you want the value of the generated_on to be serialized properly.

SomeClass msg = new SomeClass();
msg.generated_onSpecified = true;
msg.generated_on = DateTime.Now ;

and then serialize, ….. it should be fine.

Thankyou and hope this helps

Be careful using Member Name with suffix "Specified", it has special meaning to the XmlSerializer

Members with names ending on ‘Specified’ suffix have special meaning to the XmlSerializer: they control serialization of optional ValueType members and have to be of type System.Boolean.

Here is a test class to generate the exception where I explicitly declared the ‘generating_bugSpecified’ Member to integer.

[System.Xml.Serialization.XmlIncludeAttribute(typeof(TestBugg))]
public class TestBug
{

[System.Xml.Serialization.XmlAttributeAttribute()]
public System.Int32 generating_bug;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public int generating_bugSpecified;

}

Try serializing this above class with XmlSerializer, ie.

TestBug bug = new TestBug();
bug.generating_bug = 10;
SerializeObjectToFile(bug,”c:\\temp\\msg.txt”);

public void SerializeObjectToFile( object objectToSerialize, string path)
{

File.Delete(path);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
x.Serialize(fs, objectToSerialize);
fs.Close()

}

You will find the following exception raised.

System.InvalidOperationException: There was an error reflecting type ‘WindowsApplication1.TestBug’. —> System.InvalidOperationException: Member ‘abug_genSpecified’ of type System.Int32 cannot be serialized. Members with names ending on ‘Specified’ suffix have special meaning to the XmlSerializer: they control serialization of optional ValueType members and have to be of type System.Boolean.
at System.Xml.Serialization.FieldModel..ctor(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDesc)
at System.Xml.Serialization.StructModel.GetFieldModel(FieldInfo fieldInfo)
at System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo)
at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel)
— End of inner exception stack trace —
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel)
at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)

Imagine Cup 2007 Australia – Winner Uni of Canberra

It was a unique experience for me to be part of Imagine Cup 2007 (Australia). I also congratulate University of Canberra. More details ….
source: http://www.apcmag.com/6514/now_the_blind_can_program_in_net
and some pics here: http://edwardhooper.com/2007/06/27/imaginecupaufinals/

APC Magazine Report

It’s not every day that a student programming competition delivers a solution with the power to change some people’s lives. The winners of Microsoft Australia’s Imagine Cup have come up with a system that makes it possible for blind people to program in C#.

The team, from the University of Canberra, presented their entry to a panel of judges at Microsoft’s Remix conference in Melbourne, Australia, yesterday. The judges, which included two Microsoft evangelists, a senior software engineer, a Melbourne politician and APC’s editor – were pleasantly surprised by the ambitious nature of the winning student project.

A judge, Andrew Coates, Microsoft Australia Developer Evangelist, said the entry was innovative and had the potential to change the lives of its users. Another judge, senior software engineer and Microsoft MVP, Shahed Khan, said the winning team had addressed a complex problem no-one had solved before.

Four students from Team APA (Audio Programming Assistant), showed the judging panel a solution in which they had customised Visual Studio to let blind users compile and run C# programs. They fired up Studio, covered their laptop’s screen, and demonstrated it was possible to code sight unseen with the help of functions that located and read out lines of code and used the Intellisense autocompletion feature. In short, they had pulled together the basic elements that allowed a blind programmer to design, write and debug a program.

Along with their customised version of Studio, they presented a customised IE browser that reads out the links on a web page and lets users fill in fields and dialog boxes. These two tools were also accompanied by a test website with programming lessons and help forums for blind programmers.

Coates was impressed by the APA system’s ability to emulate the productivity of Visual Studio in an audio environment, incorporating Intellisense. “It impressed me a lot and it shows the extensibility of their SDK (software development kit),” Coates said.

Team APA’s mentor, Dr Dat Tran, said the team entered the competition with a philosophy of creating something that would help others: “Our background is that we’re all IT people, but we wanted to do something useful, not just something that about entertainment.”

The judging panel selected Team APA after some robust internal discussion. The two other finalist entries were also good. A debate centred on whether Team APA’s target market, blind people who wanted to program in C#, was too limited and whether the blind programming solution was advanced enough in its development. By contrast, the other two finalists addressed wider markets and were close to full commercial deployment.

The team that placed second, “Smart Education,” also from the University of Canberra and also mentored by Dr Dat Tran, created a nifty centralised web service that provides lecture notes transcription, translation and collaboration for university and college students. It accepts a student’s photograph of a lecture whiteboard taken with a mobile phone, translates it into text or audio, and sends it to a mobile device. The Smart Education student team showed a full working service and the judges were impressed by the slickness of its components. Its market was definitely a large one: any university or college student who hates taking down notes from lecture whiteboards or presentations. This probably means every student in the universe.

The Smart Education service also enables students to share the notes with other students, translates them into foreign languages, and throws in a study scheduler service.

The third placed entry, “Question Answer Technology”, from Queensland University of Technology created a system that attaches a lecturers’ voice comments to individual Powerpoint slides during a lecture. It lets students log in remotely and download the relevant slides combined with the lecturer’s voice, to their mobile devices or PCs. The solution also lets students upload questions to the lecturer and receive the lecturer’s responses.

While the judging panel felt the second and third entries were impressive, we agreed with the assessment of one judge, Charles Sterling, a Microsoft Developer Evangelist, that they were essentially an amalgam of technologies and solutions that were already in existence and would inevitably face formidable competition when taken to market.

By contrast, there was nothing like Team APA’s blind programming solution. Judge Tony Lupton, the State member for Prahran in Victoria, felt Team APA’s entry would make a massive difference to the lives of some individuals.

To test their final decision, the judges also considered some other criteria, such as which team’s solution would most likely attract investment capital or a buyout offer. Again, they felt Team APA’s solution was the best candidate for this.

In the end, Team APA won because they were addressing a problem no-one had successfully addressed before. They also clearly benefited from Dr Tran’s mentoring, who not only guided the second-placed team, but also the first and second–placed teams in last year’s Imagine Cup competition.

FULL DETAILS – IMAGINE CUP FINALISTS

1st Place: Team APA (University of Canberra). Lets blind people program. The APA system has three main subsystems: APA Studio.NET is the programming tool that allows blind users to program in C#; APA Web Browser is a customised browser that reads out all the links on web pages; and the APA website uses web services to create a learning centre for blind people. (Team members: Phillip Haines, Ngoc Thuy Duong Khuu, Van Tieu Vinh and Ping Lin. Mentor is Dr Dat Tran).

First Prize is a share in $2,000 cash and a trip to the Imagine Cup world finals in Korea in mid August.

2nd Place: Smart Education (University of Canberra). Lets students share their notes from lectures, translates handwritten lecture whiteboard notes into text, translates text into audio files and translates notes into different languages – all via a centralised web service. (Team members – Shafquat Zaman Khan, Jagdish Mehra, Muhammad Meherban Arif – mentor is Dr Dat Tran).

Prize is a share in $1,000 and an Xbox 360 for each team member.

3rd place: Question Answer Technology (Queensland UNiverity of Technology) – A Powerpoint plugin records metadata so that audio from a lecture presentation can be supplied with the appropriate slides to students who are accessing the presentation remotely. Students can then upload questions and comments in the form of audio files for each slide (Team members – Andrew Tan, David Lei, Chien Soon Jon – mentor is Dr On Wong).

Prize is copy of Vista Ultimate and Office 2007 for each team member and a share in $500 cash prize.