VB .NET (.NET 2.0) Class Library configuration - vb.net

I have created a class library in VB .NET. Some code in the library connects to the database. I want to create a config file that would hold the connection string.
I have created a "Settings.settings" file and stored the connection string in there.
When a class library having a settings file is built, it generates a ".dll.config" file which has the key value pairs defined in the settings file.
Problem with this is when i change the connection string in the ".dll.config" file, the library does not references these changes. I would still need to recompile the class library which would then overwrite my changes in the .dll.config file.
I need to be able to change the connection strings on the fly without having to recompile the library.
Is there a mechanism in VB.NET class library (.NET 2.0) that would let me do this?
Passing the connection string to the class library from the web page that uses its method is not a option.
I have listed a sample below, this is how i would access the string.
Public Function getsettings(ByVal Setting As String) As String
If Setting = "Demo" Then
Return My.Settings.Demo
Else
Return My.Settings.Live
End If
End Function

If you have an application which uses your library called MyApp, then the connection string defined in MyApp.exe.config will be available to your library. Generally speaking the client program should set the configuration environment, not the library.
If GetApplicationSetting("connectionString") Is Nothing Then
Throw New Exception("Could not retrieve connection string from .config file")
Else
Return ConfigurationManager.AppSettings.Item("connectionString")
End If
Make sure you have the System.Configuration framework loaded to access the ConfigurationManager.
EDIT 1: If you are using it in a web-application, then set the connection string in web.config.
EDIT 2: If you set the connection string in the ConnectionStrings section of the .exe.config or web.config you can access it using :
ConfigurationManager.ConnectionStrings("MyConnectionString")

Config files are specific to the application. So if your DLL is used by an application, the app.config or web.config needs to have the entries you are trying to use in the DLL config.
Unfortunately the "Not an option" is probably the correct option.

We have multiple libraries that have the same requirement. We set it up so that our class library directly retrieves the connection string from the web.config file of the application that is using it. When you say:
Passing the connection string to the
class library from the web page that
uses its method is not a option.
In theory, the web page is not passing the con str as a parameter, but the class library is just directly taking it from the web.config file.

Related

IIS looking at wrong path for MVC configuration file

When I run MVC4 my application using Visual Studio Development Server, my application is able to load all configuration files correctly. But when I try to run it under the Local IIS Web server, it throws this error
{"Could not find a part of the path 'C:\\Windows\\SysWOW64\\inetsrv\\~\\nhibernate.config'."}
It's looking at the wrong folder. The config file is directly in the root of my web project. Why is this happening. How can I fix it. I'm pretty sure that nhibernate looks for this file in order to load it's properties. Unless you know how to move nhibernate configuration files into the web.config file, please don't recommend that, I get a "Unrecognized configuration section hibernate-configuration" when ever I copy it over
Edit:
by the way, I'm pretty sure it's looking at the following key in appSettings my app settings section
<add key="nhibernate.config" value="~/nhibernate.config" />
Edit2:
here is the stack trace that goes into how Nhibernate is getting this value, and trying to find the configuration file
at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting)
at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader)
at NHibernate.Cfg.Configuration.Configure(XmlReader textReader)
at NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig)
at NHibernate.Cfg.Configuration.Configure(String fileName)
at AndroMDA.NHibernateSupport.DefaultSessionManager.BuildSessionFactory()
So it wasn't actually NHibernate that was using this file. My boss decided to use something called AndroMDA to generate code, and part of that generation was some NHibernate Support that I couldn't see into.
If anybody is interested, I created a new implementation of ISessionManager, which looks exactly like DefaultSessionManager except for the following member function and variable.
public class ServerMapSessionManager : ISessionManager
{
//other interface implementation...//
public static HttpServerUtility Server { get; set; }
public String TranslateConfigPath(String virtualPath)
{
return Server.MapPath("/"+virtualPath);
}
}
Then in App_start I call the following
SessionManagerFactory.SessionManager = new MVCFramework.Core.Common.ServerMapSessionManager();
MVCFramework.Core.Common.ServerMapSessionManager.Server = Server;

Zero dependency from the client configuration files for WCF services

Our aim is to have Zero dependency from the client configuration files for WCF services.
we are using ConfigurationChannelFactory() to create the channel and specify the ConfigSettings.
ConfigSettings is loaded using the following code
ConfigurationManager.OpenExeConfiguration(ConfigFilePath);
So we have to provide the ConfigFilePath here.
we have both windows and web clients.
we have used below approaches to find out the path
AppDomain.CurrentDomain.BaseDirectory + "bin\\" + executingAssembly.GetName().Name + ".dll"
Web client : AppDomain.CurrentDomain.BaseDirectory gives root folder of the
web applicaton so its works fine
Windows client : AppDomain.CurrentDomain.BaseDirectory gives path upto Debug/Release folder
so, its throws error
Assembly.GetExecutingAssembly().Location
Web client : Assembly.GetExecutingAssembly().Location gives path to the ASP.Net temp.
files , where we dont have the config files. So its throws an error.
Windows client : Assembly.GetExecutingAssembly().Location gives the correct location,
so its works fine.
In order to make it works in web clients, we have to add the following key in client's web.config files.
<hostingenvironment shadowcopybinassemblies="false">
but it adds a dependency to the clients.
Can you guys please help me to find the path without worrying about the clients?
have you tried this? I used GetCallAssembly() instead of GetExecutingAssembly() as this lives in a utility class in our project.
public static string AssemblyDirectory
{
get{
string codeBase = assembly.GetCallingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Could you just probe both paths? In other words, check the Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin") folder and if you can't find the config file in there, check the Assembly.GetExecutingAssembly().Location folder instead? Since you indicate that the first approach works for web but not Windows clients, while the second approach works for Windows clients but not web, go with both!

.net-WCF How do we create a client programatically?

How do I create a client programatically?
Open Visual Studio command prompt and move to client application folder using change directory command and type
svcutil.exe http://your_service_url/your_service_name.svc?wsdl
This will generate a configuration file (output.config) and a client class.
Client class name will be your_service_nameClient
Next you need to copy the <system.serviceModel> section from output.config to your App/Web config. Now your client application is ready to consume the service.
You can create client class object and invoke service methods.
Hope this will help you
You'll need to start the svcutil.exe process -- it could be done from a program, but it will generate source code, not binary code.
If you are new to WCF check out this site:
http://msdn.microsoft.com/en-us/netframework/dd939784.aspx
If you are only interested in learning how to create a client, this is the video for you:
http://channel9.msdn.com/shows/Endpoint/Endpoint-Screencasts-Creating-Your-First-WCF-Client/

Connection string in app.config in a class library

I am creating solution and inside I have three projects:
A WCF Service Library Project
A DataAccess Project (Class Library)
A Web site for hosting WCF service
The implementation of the service is on the project # 1, but in order to access the DataBase I use a second project that implements the data access using a class library project.
That problem is in order to get data access I need to configure a connection string, but that connection string must be configurable in a production environment, I meant in production I am going to deploy the site, which is a very simple project that contains only a reference WCF Service Library Project then a guy from database department will configure the connection string.
In development I have an app.config on the data access project but when I do the release that app.config is embedded on the dll.
Any ideas how can we achieve our purpose
The connection string must be in the application configuration file of the executing assembly. This means that you can provided the configuration file for your assembly along with the assembly itself but anyone who wants to use your assembly must update their configuration file to include the values that your assembly relies on.
The connection string in your app.config (data layer) is not embedded in the dll.
If you look in the app.config file in your data layer project, you will probably have a connectionStrings section. you need to put the connectionStrings in the web.config of your WCF service website.
This can be configured in your production environment.
I had a mistake, I was using a different name on the web.config of the WCF site, I just copy the the exact part of the app.config to the web.config and its working now.
Thanks for your help

Unable to debug web service project in Visual Studio 2008

I've been assigned a web app written in VB using VStudio.net 2003. I am trying to configure the source on my localhost (VStudio 2008) so I can explore and learn about the current app (before I begin any real changes) and I cannot get debugging working for the web service project(s).
Symptom 1:
"Unable to automatically step into the server. The remote procedure could not be debugged.
This usually indicates that debugging has not been enabled on the server.
See help for more information".
This happens when I try to F11 (stepInto) the proxy class which invokes my actual web method.
Symptom 2: Pre-setting a breakpoint in my .asmx file code on the statement that will be invoked does not work (i.e. the debugger simply doesn't stop).
Having described the situation, here's how my VStudio Solution is configured:
Service1 - project created from the VB - WEB - ASP.NET Web Service Application template; this Service1 project contains my main .asmx source code I want to debug. Web.config for this project contains compilation defaultLanguage="vb" debug="true"
ProxyService1 - a separate project created from the Windows - [VB]Class Library template; here the form1.vb file was deleted; I visited "Add Service Reference" -> Discover (Services in solution) and then in the "Compatibility" section I click "Add Web Reference". Then choosing the above Service1, I assign it a "web reference name" of WSservice1. This results in a Reference.VB file and when I build the ProxyService1 class a .DLL of the same name in the projects bin\Debug folder; this project has an App.Config file with compilation defaultLanguage="vb" debug="true"
Project1 - the main UI project with the .aspx and .vb files that call the webservice; project1 has a reference to ProxyService1.DLL; Web.config for this project contains compilation defaultLanguage="vb" debug="true". I arrive at a breakpoint in one of the files in this project called message.vb which looks roughly like this:
Public Class Message
Dim wsZipeee As New ProxyService1.WSservice1.myService
Dim dsMessage As DataSet
Public Function GetMessageByType(ByVal iMsgType As Integer) As DataSet
dsMessage = wsZipeee.GetMessageByType(iMsgType)
If I rightmouse/go to definition on the stmt above, here is the code in Reference.vb in my ProxyService1 project:
<System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/ZipeeeWebService/Zipeee/Get Message By Type", RequestElementName:="Get Message By Type", RequestNamespace:="http://tempuri.org/ZipeeeWebService/Zipeee", ResponseElementName:="Get Message By TypeResponse", ResponseNamespace:="http://tempuri.org/ZipeeeWebService/Zipeee", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _
Public Function GetMessageByType(ByVal iMsgType As Integer) As <System.Xml.Serialization.XmlElementAttribute("Get Message By TypeResult")> System.Data.DataSet
Dim results() As Object = Me.Invoke("GetMessageByType", New Object() {iMsgType})
Return CType(results(0),System.Data.DataSet)
End Function
For completeness, here is the corresponding webmethod in the .asmx file of the Service1 project:
<WebMethod(MessageName:="Get Message By Type")> _
Public Function GetMessageByType(ByVal iMsgType As Integer) As DataSet
con = New SqlConnection(sConnZipeee)
con.Open()
Everyplace in IIS I know to check and within the project properties I have checked for the proper Debug setting to be checked or set on. I've debugged other things that are set up like this but I am truly stuck on what I've missed on this "solution".
For info - if you have got here looking how to debug a .NET4 web service from VS2008/.NET3.5 app, you need to start the service in VS2010, set a break point in the service and then run your app from VS2008 as normal. The break point will be hit.
Without running the service in VS2010, you will get the error described by John above.
When I debug webservices, I usually select the option "Don't open a page. Wait for a request from an external application" in the Web section of my project properties (more info here). I also usually run the project in 2 instances of VS, one for webservice and one for client. I can put break points in the webservice and everything hits and I can see what is happening.
try to attach debugger on running aspnet_wp.exe process
I normally put of the logic to debug in class library that I can start with a console application for debug. This link will be useful too if you must debug as a service.