Best way to implement file access in C# - c#

Scenario - I need to access an HTML template to generate a e-mail from my Business Logic Layer. It is a class library contains a sub folder that contains the file. When I tried the following code in a unit test:
string FilePath = string.Format(#"{0}\templates\MyFile.htm", Environment.CurrentDirectory);
string FilePath1 = string.Format(#"{0}\templates\MyFile.htm", System.AppDomain.CurrentDomain.BaseDirectory);
It was using the C:\WINNT\system32\ or the ASP.NET Temporary Folder directory.
What is the best to access this file without having to use an app.config or web.config file?
[This is using a WCF Service]

You're running this from an ASP.Net app right? Use Server.MapPath() instead.
Also take a look at System.IO.Path.Combine() for concatenating paths.
[Edit]
Since you can't use System.Web, try this:
System.Reflection.Assembly.GetExecutingAssembly().Location
Or GetEntryAssembly().

I belive you are looking for
System.IO.Path.GetDirectoryName(Application.ExecutablePath);

I got this working on my site! I haven't been working on just this for the last 2 years!!!
I added this inside my system.serviceModel block of the web.config. It seems to make all the paths relative to where your service is installed.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
better late than never?

Use
System.Web.HttpServerUtility.MapPath( "~/templates/myfile.htm" )

Related

Dynamically change log target file using Enterprise Logging

So I'm trying to use enterprise logging in an application, and I want it to have multiple files, so far I have the following in my app.config file:
<add name="Normal" fileName="C:\MyApp\Logs.log" .../>
And in my code I'm simply using
Logging.Write("My log here");
Now what if I want to programatically change the file where it's being logged to C:\MyApp\MyDateHere_Logs.log, how could I approach this?
Haven't found a lot of solutions online. Thanks beforehand.
In the end I ended up creating a custom trace listener of my own and then changing the filename attribute on runtime by following the guide here.
You can access the attribute which stores your path by using Attribute["filename"] (assuming the attribute in your config file's trace listener node has the path in an attribute named "filename".)

How to set root path for static files in ServiceStack self-host

All of the ServiceStack self-host examples serve static files from the same directory as the console or service executable assembly.
Is there a way to change the rooth path to something else?
When I set Config.WebHostPhysicalPath to a different path from within AppHostHttpListenerBase.Configure, my html file had to exist in both places for ServiceStack to return anything.
I was wondering the same thing so I dug into the SS source and found an issue that prevents the Config.WebHostPhysicalPath from working with static files. You can read about it here: https://github.com/ServiceStack/ServiceStack/issues/352
Update 2012-12-03
My pull request for this issue has just been merged into ServiceStack/master.
https://github.com/ServiceStack/ServiceStack/pull/357

How to check Authentication Mode value in Web.Config without referencing System.Web

I have a class that needs to check the Authentication Mode from a web.config.
Ex:
<authentication mode="Forms" />
or
<authentication mode="Windows" />
Now, I know this can be done pretty easily with the following code:
AuthenticationSection sec = ConfigurationManager.GetSection("system.web/authentication");
if (sec.Mode == "Windows")
{ ... }
My problem is, this class/project is being referenced in my Web project, as well as a WinForms project. The WinForms project is requiring .NET 4.0 Client Profile Framework (we don't want to require the full .NET 4 Framework, if possible). If I'm not mistaken, the Client Profile does not contain System.Web.dll.
Is there a way that this value can be checked without referencing System.Web (and preferably without manually parsing the config file)?
I've tried:
object authSection = ConfigurationManager.GetSection("system.web/authentication");
if (authSection.ToString() == "Windows")
{ ... }
However the ToString() simply returns the string "System.Web.Configuration.AuthenticationSection".
Thank you!
I have used the above code to get the authentication mode. I just done few changes in your code. Please find here.
AuthenticationSection authSection = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication");
if (authSection.Mode.ToString() == "Windows")
Hey if your talking about a web config in the same project try using the following method.
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel)
Or you could use one of the other similar methods in the ConfigurationManager members. I can't test it for you at the moment but I'm pretty sure they should work. Because essentially they don't care what kind of conf file it is as long as there is one as since the inherited type of the web.config is a config, you should be able to access it just like any other and query for the particular field you need.
ConfigurationManager
Where in your code do you need to make a decision on this? If the user is authenticated at that point you could use IIdentity.AuthenticationType and process accordingly. For Forms this will always return Forms, for a Windows identity it typically NTLM, although it can be Negotiate or Kerberos.

configuration settings in asp.net

We have a static html/webform site, the site lacks search functionality, I was able to get yahoo BOSS (Build your Own Search Service) after a few hours yesterday, i got it working (still working on adding missing features like pagination) , I was wondering about the configuration options of the class, as I have a BossSearch.cs in App_Code, with some fields that are set at the top:
public class BossSearch
{
String sResultsPage = "~/searchResults.aspx";
String sSearchString="";
String sApiKey = ConfigurationSettings.AppSettings["BossApiKey"];
String sSite = "www.oursite.com"; //without http://
String sQuery = "http://boss.yahooapis.com/ysearch/web/v1/{0}%20+site:{1}?appid={2}&format=xml&start={3}&count={4}";
String sStart = "0";
Uri address;
WebProxy webproxy = new WebProxy("http://192.168.4.8:8080");
bool bUseProxy = true;
int nResultsPerPage = 10;
int nTotalResults = 0;
...
As you can see, i get the BossApiKey from the web.config file, but all others I have them in the declared in the class, should I put all of them in the web.config file? if I'm thinking of reusing the class (should i say class library?) in other websites as well? can I turn it into a dll and what would the advantages be? i read somewhere that a dll has its own config file, is this the way to store those settings?
Apologies for my ignorance, since I'm not that familiar with developing applications (still studying)
What you read about .NET assemblies having their own config files is not absolutely correct; a web site has web.config files, one in the root and zero/one in each subdirectory. If a .NET assembly that is in the application calls into the standard config API, it will get its data from that web.config.
The same goes for WinForms apps and the [appname].exe.config file; any assemblies included that use the standard config API will be getting their data from that.
All of that is not to say that any assembly could not define its own configuration mechanism which pulls its data from wherever it wants.
And yes; if you intend to reuse this code a good bit, you are thinking along the right lines; put the code in its own assembly, and have it get its data from Config files so you do not need to recompile it for each application.
If you declare all of them in a database or web.config, you don't need to recompile each time you reconfigure the search engine
I you're striving for reuse and ease of use, then I would recommend writing a custom configuration section for your control. This can be part of the dll you distribute to other application and will allow you to have the ultimate in flexibility and explicit portability to other .net apps.
Enjoy!
You should only store the value in a single place in your application. For an ASP.NET application, the web.config file is an appropriate place for these kind of things. You won't need to recompile your application if this value changes.
If you decide to put your code into a separate class library and still want to use a config file to store your api key, you should note that your appSetting key needs to be entered in the application or web site's config file - you can't define a config file for a class library.
One other approach that you might find useful would be to make a wrapper class to store your settings. You could have class with static methods to look up your appSettings key so that you get a nice, compile time, way to get the api key, rather than typing out the name of your appSettings key everywhere.

Wildcard mapping for ASP.NET and issues with PHP

I have an application written in .NET 3.5 with C# as the language. I'm using Web Forms, but using url routing with the routes defined in my global file. Everything is working as expected. In order for the pretty paths (see: user/665 instead of user.aspx?uid=665) to work properly, I had to add a wildcard mapping in IIS5.1 (local box, not test, staging, or production) the aspnet_isapi file for the 2.0 framework. Everything works fine.
Now, my site needs a plugin for PHP. However, the PHP files are now being serviced by ASP.NET due to the wild card mapping, and hence are not processed by the PHP interpretter. Is there any way to get around this? Would I have to add some sort of handler to my web app that will take all PHP requests being handled by the ASP.NET framework and have them routed to the PHP engine? Is there an easier way? Maybe a way to exclude them in the web.config (PHP files) and have them served by the proper PHP engine?
Thanks all!
-Steve
This is a solution, but is not an elegant way (IMHO):
Create a virtual directory
Have it point to the folder with the files (in this case, a PHP plugin)
Give it the proper permissions
Change the config options for the virtual directory in IIS and make sure the wildcard mapping for that directory is removed.
This works like a charm for my situation. However, is there any way to not have to deal with virtual directories?
The problem is that the PHP extension needs to be registered.
In IIS Manager right-click on Default Website -> Properties -> Home Directory -> Configuration
Under Application Mappings make sure that .php is added and is it pointing to PHP.EXE. There should be an entry like this: extension .php, executable path C:\PHP\PHP.EXE %s %s
From what I gather, the problem is that ASP.NET is attempting to route your PHP requests, so what I would do is add a StopRoutingHandler() to your routes in the global.asax. Something like this should work:
routes.Add(new Route("{resource}.php/{*pathInfo}", new StopRoutingHandler()));
Edit: Be mindful that routes are processed in order, so I would add this to the top of your routes.

Categories

Resources