.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Problem in the Console Applications app.config file for .NET 4.0

Posted By:      Posted Date: October 21, 2010    Points: 0   Category :.NET Framework


I am developing a console application.  I am going to use that in 3 environments. I have placed a key in the appsetting section and i am expecting the value to be overwritten by the respective config file specified during the build time.

    <appSettings file="Stage.config">
        <add key="DataConfiguration.ActiveLocation" value="Production"/>
        <add key =name="Dev.Local" providerName="System.Data.SqlClient" connectionString="data source=Test\SQLSERVER2005;initial catalog=ABCD;user id=admin;password=asdh511"/>

And the Stage.config values are

<add key="DataConfiguration.ActiveLocation" value="Staging"/>


View Complete Post

More Related Resource Links

Problem when using Activator.CreateObject and reading App.Config file

Hello, this is the scenario. I have an application that load at runtime severals dll. these dll are actually "adapters" that wraps calls to web services, database and so on. The app.config of the "main" application stores in config sections all information necessary to each adapter (i.e.Web ServiceURL..) and I have created inside each adapter a class to ready those values the loading at run time the DLL has been implemented by storing all necessary types into a dictionary of generics and when I need to instanciate it I call the Activate.CreateObject and I pass the specific type (I means the name of the Adapter class) The problem is that the adapter class itself is not able to get the config value because ConfigSection has not been initialized. If I write: IInterfaceAdap adapt = new myAdapter() -> I read the config data IInterfaceAdap adapt = (IInterfaceAdap)Activator.CreateObject (type) -> now way to read the data stored in the App.Config. I think that I undertood the problem but I'm not able to find a workaround to read data store in the app.config!! I need help please!!  

While Importing Excel 2007 file to Datatable - headerrow problem


Hi there,


I am trying to simply extract an excel data from an uploaded file an put it into a datatable. In this case the excel file has 3 rows but when I fill the datatable I only see row count of 2.

I tried changing HDR:NO; to HDR:YES and vice versa, but no luck. 

What am I doing wrong? (Note: the excel file cannot have a  headerrow)


string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pFilePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR:NO;\"";
            OleDbConnection conn = new OleDbConnection(connstr);
            DataTable dtTables = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            string strTablename = dtTables.Rows[0]["TABLE_NAME"].ToString();
            string strSQL = "SELECT * FROM [" + strTablename + "]";

            OleDbCommand cmd = new OleDbCommand(strSQL, conn);

            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            //At this point row count=2 which doesn't make sense




Problem in accessing resource file dynamically.


Steps I have followed are
1.I have created myres.en-GB.resx file at C:.
2.then created locale specific myres.en-GB.resources using resgen at c: only,
resgen c:\myres.en-GB.resx
3.Linked the Resource File to Assembly using AL.exe which is giving me assembly at c: only.
Al /t:lib /embed:myres.en-GB.resources /out:ClassLibrary1.dll
4.I have created one web application using vs 2008 & then build it.
5.Then placed both resource file & dll in web applications Bin\en-GB folder.
6.Anf finally written code at page load like
 CultureInfo info = new CultureInfo("en-GB");
            Thread.CurrentThread.CurrentCulture = info;
            Assembly asd = Assembly.Load("ClassLibrary1");
            ResourceManager res = new ResourceManager("myres.en-GB", asd.GetSatelliteAssembly(info));
            string sdf = res.GetString("Lab1");

but after running application I m getting following error
MissingManifestResourceException", "Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Cla

Razor View Engine and Add Namespace in Web.Config Problem



I am working on a MVC project with Razor view engine and I have the following:


This only works if I have on the same view the following:

  @using SquishIt.Framework;

However, on my Web.Config I have the following:


      <!-- Namespaces -->
        <add namespace="System"/>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="Microsoft.Web.Mvc"/>
        <add namespace="SquishIt.Framework"/>


So if "SquishIt.Framework" namespace is added on Web.Config why do I need to have the @using on the view?

File Download Problem


Hi everyone,

I am using a download handler to handle the downloading of files from my website.  I am using a slightly modified code from the Microsoft article http://support.microsoft.com/kb/812406

Everything is working fine and downloading, even with large files, but it does not show the file size for any of the files to download. Even if theyre really small.

Here is my code for the handler

public class DownloadHandler : IHttpHandler

        public void ProcessRequest(HttpContext context)
            string path = "";
                path = context.Server.UrlDecode(context.Request.QueryString["src"]).DecryptString();
            catch(Exception ex)
            System.IO.Stream iStream = null;

            byte[] buffer = new Byte[10000];

            int length;

            long dataToRead;

            string filename = System.IO.Path.GetFileName(path);

                iStream = new System.IO.FileStream(context.Server.MapPath("~/" + path), System.IO.FileMode.Open,
                            System.IO.FileAccess.Read, System.IO.FileShare.Read);


Problem download file from SQL Server


Hello everyone. I am having an issue downloading files that I have store in SQL Server. I have no problem in a WinForm. What am I doing wrong in my code?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim sch As New clsReport
        Dim fileData As New clsReport.Letter
        fileData = sch.DownloadLetter(Session("LetterID"))
        Dim ms As System.IO.MemoryStream = fileData.fil

        Dim fil As Byte() = ms.ToArray
        Dim nam As String = fileData.name
        Dim ext As String = fileData.ext
        If Not fil Is Nothing Then
                ' Response.Clear()
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + nam & "." & ext)
                ' Response.AddHeader("Content-Disposition", nam & "." & ext)
                Response.AddHeader("Content-Length", fil.Length.ToString)
                Response.ContentType = "Application/octet-stream"
                Response.Buffer = True
            Catch ex As Exception
            End Try

        End If

    End Su

reading excel file problem



i have 200 rows in my excel file. im using OleDbConnection to read the excel file.

The problem is that it will read all the blank rows from row 200 onwards. Is there a configuration im missing ? or is there a way to import all rows that has data? Here's some of my code.

string excelConnectionString =
               "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + filePath + ";" +
                "Extended Properties=Excel 8.0";

OleDbConnection excelConnection =
                    new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO'");

OleDbCommand cmd = new OleDbCommand("Select * from [list$]",excelConnection);

How to set WebService NameSpace in web.config file?


I am trying to put the namespace value as a key in web.config file, so that when I deploy this on production, I just have to change the namespace key in the config file only, not on all of my webservice cs files. But When I try to browse this webservice after changing this code I get compilation error.


    <add key="NameSpace" value="http://csi-dev-deep/"/>

MyWebService.cs (this code works)

[WebService(Namespace = "http://csi-dev-deep/")]

MyWebService.cs code changed to the following gives compilation error.
[WebService(Namespace = ConfigurationManager.AppSettings["NameSpace"].ToString())]

Compiler Error Message: CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Your help is highly appreciated.

Thank you.

Generating MS Word doc from mht file gives smart quote problem


I have a word document to be generated using ASP.Net/VB.net.

So I have a word document template saved as .mht file on the web server.

In my ASP.Net code,I read this mht file content and replace certain string line Description$$ with the actual description from the database.Then save this content as .doc file.

This works fine but shows a box symbol when I have smart quotes " (not this one as I cannot type it here.The double quote which you see in MS Word,the slanted double quote).

I dont know how to make my word doc generated, show the exact double quote as in MS word.

If any of you have any idea of this please reply.

Thank you

"Mixed mode assembly is built against version 'v2.0.50727'.... " issue and use custom config file

Hi, My Winform applilcation has used Microsoft.SqlServer.Management.Common namespace(assembly :Microsoft.Sqlserver.smo.dll/Microsoft.Sqlserver.ConnectionInfo.dll) and developed in .NET 4.0. Problem:Application is throw an exception when it tries to use above assembly reference methods. Full error text is shown below, "Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information. " Error is resolved when we include "app.config" file with below code, <?xml version="1.0"?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> But, I need to keep configuration file as "renamed.config" and not to include app.config file as of the project requirement.I have set configuration file as "renamed.config" file using below code, //AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "d:\\reanmed.config" ); I have also included <Startup> element in this "renamed.config" configuration file and removed the app.config file.But it raise me below error, it always expect app.config file with <Startup> element to resolve this iss

what is .htc file and how do I add this file to my asp.net 2.0 web applications

what is .htc file and how do I add this file to my asp.net 2.0 web applications   give me idea or tell me how to do that\ thank you maxmax

Setting maxItemsInObjectGraph in a WCF REST config file???

Hi All, I am trying to create a new WCF Rest service. I used the online VS2010 WCF REST 4.0 template as a base. I have a service up and running and have been testing it using IE/Firefox (currently it is a read only API, so I have no need to post anything back to the service). I have an issue when the number of items being returned is too large, IE give me a "Internet Explorer cannot display the webpage" I turned on tracing and was able to confirm the issue is with the maxItemsInObjectGraph property (defaults to 65536) <Message>Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. </Message> Using the defualt WCF Web.config file I have no clue how to set this value as it doesnt seem like a standardEndpoint can have this value set, or have a custom binding or behaviour assigned to them (at least I don't know how to set them). Here is the default web.config file the template created. Does anyone know how i can update/increase the maxItemsInObjectGraph property?      <system.serviceModel>    <diagnostics>      <endToEndTracing propagateActivity="true" activityTracing="true"   &nb

How to set anonymous access to IIS 7 from web config file im using asp.net 2.0 C#

HiI have developed asp.net 2.0 website with crystal report now what my problem is whenever i go to crystal report page its by default going to login.aspx or default.aspx though i didt set any login to my asp.net page..I talk with my hosting provider they said that the asp.net impersonate is enable..I think in IIS 7 authentication if i set anonymous access enable, will it work fine?so i need to know how to enable anonymous access from my webconfig ..so please let me know how to do?

Site File Structure, Folders, Learning project, subweb, web.config

I am just learning asp.net.  I purchased an "ASP.Net 3.5 web programming in C#" book, which I like allot.  I am on chapter 3 and want to complete a shopping cart exercise from the book.  I have to create several folders and files.  The exercise has the files and under the root directory and a few folders below that.  I already have a site that I've been learning on.  Can I create a subfolder on my site and put all the files in there?  Like the subfolder is the root of the project.   Here is list of Folders and files... Code/CartItem.cs Code/Product.cs Data/Cars.mdb Images/car.jpg Cart.aspx Order.aspx Web.config ................................ On my website I want to create a subfolder to keep alll the files in, as so... ShoppingCart/Code/CartItem.cs ShoppingCart/Code/Product.cs ShoppingCart/Data/Cars.mdb ShoppingCart/Images/car.jpg ShoppingCart/Cart.aspx ShoppingCart/Order.aspx ShoppingCart/Web.config ................................ Can I have two web.cong files?, one in the subfolder?  Or do I have to use the single, web.config file in the root directory of the site?  Are there any other pitfalls or trouble I might get into setting up my file structure like this?  Anything I should be aware of? Any thoughts or advice would be appreciated. Thanks, Mike   

Web Folder problem : This file cannot be saved to this location because there is no connection to th

When I check out a Word 2007 document from a list, I cannot save it back to the server.  I get:   This file cannot be saved to this location because there is no connection to the server.  Check your network connection and try again.   I am using a Virtual Machine (Virtual PC).  I have the Microsoft Loopback adapter installed.    The server has a static IP address and is a domain controller. I am able to access the web folder through Windows Explorer.   How do I set up Office, Sharepoint and Webdav so that I can check files out of sharepoint and save them back, on a virtual machine?

How to move PrincipalPermissionAttribute from CS file to app.config?

I'm really struggling with the following scenario: I have a WCF service where the methods of the implementation of my service contract are decorated with one, or many, PrincipalPermission attribute(s). For instance: [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")] [PrincipalPermission(SecurityAction.Demand, Role = "MyGroup_1")] public void DoSomething() { //Work done here } [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")] public void DoSomethingElse() { //Work done here } So in this case, method DoSomething(), could be called by users either members of the "Administrators" group or the "MyGroup_1" group. And only Administrators should be allowed to make calls to DoSomethingElse(). My problem is I want to put this in the app.config file, but I can't find any way to do this. How can I "move" these decorations from my CS file to the app.config?  

File Upload Problem

I have a colleague that just cannot upload any files over 6mb to sharepoint. I have checked all his IE settings and everything is normal / the same as mine. anyone come across this before?Sharepoint Customiser
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend