App config asp.net - c#

Let's say I have a class called AppConfig:
public static class AppConfig
{
private static XDocument config =
public static AppConfig()
{
}
}
How do I XDocument.Load the ~App.Config file? Isn't it something like Server.SOMETHING? What namespaces do I need to include>

XDocument.Load(HttpContext.Current.Server.MapPath("~/web.config"));
is probably what you're looking for. This helper class "Server" lives on the "current" HttpContext inside the System.Web namespace, so add a
using System.Web;
to your code.
Marc

I think what is his problem, he is not able to get server class in his class
Server is property of the Page class that your page inherits from, it not a
global. if you are trying to access from a class, use
HttpContext.Current.Server.MapPath("");
and add reference
using System.Web;
OR can be get directly
System.Web.HttpContext.Current.Server.MapPath("");

I'm not sure why you're trying to do that ... if you want to access the values in your web.config or app.config (for client apps) there is already a wrapper class set up to do that named My.Settings.
Those app.config and web.config files are a pain in the keester to deal with directly.

Related

Get Applicaton Path for iOS and Android

I once used SQLite for my android application. I made a Queries.cs file where I had all the queries stored (createDatabase, insertDatabase etc). I had a string as a class variable where I stored the path ot the folder I wanted to put in my .db file. It looked like this:
private string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
Now I want the same or at least the folder where the application sits in. But this time I need a way that'll be supported from iOS and form Android because it is necessary for this project. Do you know how I can do that?
Many thanks in advance
There is no unified way provided in Xamarin.Forms for this. You can leverage the DependencyService to reach it from your shared code and still differentiate per platform. This could look like this, define an interface in your shared code:
public interface IFilesystemService
{
string GetAppRootFolder();
}
Now create an implementation on Android like this:
public class FilesystemServiceAndroid : IFilesystemService
{
public string GetAppRootFolder()
{
return System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
}
}
For iOS the idea is the same, only the implementation may differ. You can, of course, extend this class as you like with the ability to read or write files for example.
Don't forget to adorn your namespace of the implementation with the [assembly: Xamarin.Forms.Dependency (typeof (FilesystemServiceAndroid ))] attribute. Like so:
[assembly: Xamarin.Forms.Dependency (typeof (FilesystemServiceAndroid ))]
namespace YourAppName
{
public class FilesystemServiceAndroid : IFilesystemService
{
// ... code here
}
}
You can now retrieve it in your shared code like this: var path = DependencyService.Get<IFilesystemService>().GetAppRootFolder();
You should use a Dependency Service in order to get platform specific file paths. A great tutorial on how to use SQLite in Xamarin.Forms can be found here which can be used in platform specific code as well.

C# Can I make a namespace accessible everywhere in my dot net web site for code-behind and classes

I have an extension method for String that I want to be available on every code behind and class in my solution. The method is sitting in a particular namespace. I'd like everywhere to have access to that namespace without me having to include it in every class.
I've used the "namespaces" tag in the web config to successfully include it on every aspx page, but this does not make it accessible on code behind or elsewhere.
So, is there a similar way to include a namespace everywhere?
So, is there a similar way to include a namespace everywhere?
No, I am afraid that there isn't. If you place the extension method in some of the root namespaces then it will be in scope for the child namespaces. For example:
namespace Foo
{
public static class Extensions
{
public static void Go(this string value)
{
...
}
}
}
will be in scope inside all classes declared in Foo.* namespaces. So you might put the extension method in a root namespace which has the same name as your project and then it will be available everywhere because all classes are automatically generated in child namespaces (unless you change that).
Just put you extensions class into System namespace and it will be available for every String object.
namespace System
{
public static class Extensions
{
public static void M1(this string value)
{
...
}
}
}
No, you cannot.
The namespace section of web.config only provides those namespaces to the markup, but not code-behind.
<configuration>
<system.web>
<pages>
<namespaces>
<add namespace="System.Data" />
<add namespace="System.Text"/>
</namespaces>
</pages>
</system.web>
</configuration>
You must explicitly add namespaces via the using statement in code-behind or add to one of the already included namespaces like System, but that is not recommended.
You'll have put a using statement on every code file that intends to have access to the namespace, you can't "gloabally include."
Usually, it's good form to put your various utilities, static classes, and extension classes in a "Common" project that your other projects all have a dependency on. I've seen this pattern re-used a lot:
Using YourNameSpace.Common.Utilities;

Nancy: is there a Server.MapPath("~/") equivalent?

I can't seem to find an equivalent in Nancy for System.Web.HttpContext.Current.Server.MapPath() in the Nancy framework.
I just want to load a textfile relative to the application service.
I see this in the assembly
using Nancy;
using System;
namespace Nancy.Hosting.Self
{
public class FileSystemRootPathProvider : IRootPathProvider, IHideObjectMembers
{
public FileSystemRootPathProvider();
public string GetRootPath();
}
}
I'm not sure how to use.
update: I just figured out anything I need to load can just be read/written from the bin/relase/ directory. Is that the assumed way to do it in a Nancy Self Hosting environment? I guess that would make sense.
You can take a dependency on IRootPathProvider and use that to call GetRootPath() that will give you the root of your application and you can add from there (I would recommend using Path.Combine)
If you need this in a static class (such as an HtmlHelpers extension) where the IRootPathProvider dependency can't be injected, at least AFAIK, you can use AppDomain.CurrentDomain.BaseDirectory which is what DefaultRootPathProvider uses under the hood for .Net 4.x: https://github.com/NancyFx/Nancy/blob/master/src/Nancy/DefaultRootPathProvider.cs

WebServices & Namespace in C#

I have a web service with the namespace as the following:
namespace MyNS
{
class MyObject
{
//Implementation here
}
}
And I published the webservice and try to consume that webservice from the next C# Website.
I assigned the service name to "MyWS".
When I try to write the code
I have to write,
MyWS.MyObject obj = new MyWS.MyObject();
But I want to write
MyWS.MyNS.MyObject obj = new MyWS.MyNS.MyObject();
The problem is there might by MyObject class under other Namespaces. So, I want to identify my classes by NameSpaces.
What should I do to use Namespace in the coding?
I do not believe the original namespace is exposed as part of the WSDL, which is what the generation process uses to create the client end point.
This means there is no way to control what namespace your web service is used as.
However you can control what namespace your client end point uses. When you add the service reference, the bottom of the first page (Titled Add Service Reference, and containing Discovery controls) is a text box titled "Namespace". If you change that field to MyWS.MyNS when adding the service it should allow you to reference it as such.
The problem is there might by MyObject class under other Namespaces. So, I want to identify my classes by NameSpaces.
The compiler will give you an ambiguous reference error if you try to use conflicting object names. You will have to qualify them in that case.
So, if you want to give it a certain alias, just type the name as you want it.
namespace This.Is.My.Favorite.Namespace
{
public class MyObject()
{
//stuff
}
}
namespace MyNS.MyWS
{
class MyObject
{
//Implementation here
}
}

Strongly typed calls into web.config without duplicating the property names?

I searched here for the answer. I'm sorry if this has been asked before (as I suspect it has).
Summary: How can I have strongly typed calls into my web.config without duplicating the property names?
Details: In my code, I try to minimize string usage, and I don't like defining something twice.
Complementing both of these wonts is my restriction of AppSettings usage (and its strings) to one class, which I reference throughout the project. The AppSettings class exposes public properties:
12 public static string DateFormatString {
13 get {
14 return ConfigurationManager.AppSettings["DateFormatString"];
15 }
16 }
How can I keep this class and prevent the duplication (lines 12 & 14) of the property name?
Alternatively, what other solution might you recommend?
I like using Custom Configuration Handlers.
http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx
There's no duplication in your example: One DateFormatString is a property name and the other is a string. You're just following a convention which names the property identically to the lookup key for the value.
I do see one possible improvement. You should read the config file once in a static constructor and store the values instead of reading them from AppSettings every time a property is accessed.
I'd probably recommend deserializing the web.config into an object. You can then access all configuration entries as if they were properties (can't get much more strongly typed than that!)
I create a wrapper for everything that doesn't belong to me directly. This includes cache, session, configuration, external web services, etc. This allows me to encapsulate the dirty details of using that widget. In the case of configuration I have a bare bones configuration class that exposes the various properties that I have housed my app.config or web.config. This might look something like this:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using RanchBuddy.Core.Services.Impl;
using StructureMap;
namespace RanchBuddy.Core.Services.Impl
{
[Pluggable("Default")]
public class ConfigurationService : IConfigurationService
{
internal static int GetDefaultCacheDuration_Days()
{
return Convert.ToInt32(ConfigurationManager.AppSettings["DefaultCacheDuration_Days"]);
}
...
internal static LoggingType GetLoggingType()
{
string loggingType = ConfigurationManager.AppSettings["LoggingType"].ToString();
if(loggingType.ToLower() == "verbose")
{
return LoggingType.Verbose;
}
else if (loggingType.ToLower() == "error")
{
return LoggingType.Error;
}
return LoggingType.Error;
}
...
public static string GetRoot()
{
string result = "";
if(ConfigurationManager.AppSettings["Root"] != null)
{
result = ConfigurationManager.AppSettings["Root"].ToString();
}
return result;
}
}
}
Inside here you can do more than simply get values from the config file. You can convert a string to the type that it needs to be. You can use the string to determine an enum value to be returned. Etc. But the key is that any changes that ever need to be made regarding configuration can be made here. To include if you want to swap out the mechanism for the configuration store!
Build your own ConfigurationSection with the Configuration Section Designer, this way you don't have to use AppSettings at all... but you'll have your own collection of settings that will even have Intellisense in the web.config file.
One solution could be,
public enum Settings
{
None,
DateFormatString,
DefeaultUserPrefix,
SomeOtherValue
}
and then have a helper class like,
public static class ConfigurationHelper
{
public static Get<T>(Settings setting)
{
string output = ConfigurationManager.AppSettings[setting.ToString()];
if(string.isNullOrEmpty(output))
throw new ConfigurationErrorsException("Setting " + setting + " is not defined in Configuration file.");
return (T)output; //You can probably use Convert.* functions.
}
}
Your calling code will look like,
ConfigurationHelper.Get<string>(Settings.DateFormatString);
The above approach provides some level of strong typing but you still have to make sure that the settings name in config file matches with the name of the enum.
The best choice would be to auto-generate class based on the configuration file.
If you wanted strongly typed properties, you can write
public static string DateFormatString
{
get { return ConfigurationHelper.Get<string>(Settings.DateFormatString); }
}
Also, I would advice against reading the config file in constructor (premature optimization?). If you read the config file in constructor, it means that you can not change config file while application is running.
I have written a nuget package that does this (among other things). The accompanying blog post goes in to the details, but this simplified snippet shows the gist of it as related to your question.
public string DateFormatString =>
ConfigurationManager.AppSettings[MethodBase.GetCurrentMethod().Name.Replace("get_", "")];

Categories