Store XSD inside WCF webservice - c#

Im developing a WCF web service with receives always and only XML.
So i need to validate that input XML using their XSD. The question is, can i save them inside web service? Locally i can access XSD files via relative path into IIS Express root folder which i created manually. I tried add the XSD files in VS project but i just cant a find them on runtime.
I'm using the Shemas like this: Image1 Link
IIS XSD'd Folder Path Workaround: Image2 Link
At the moment, its working fine, the problem will be when i try deploy the service somewhere on internet.
Thank you.
tl;dr: Can i send some XSD when deploying the webservice or its just impossible?

Files that belong to your solution should be physically part of it. Once that is the case you can use for instance HostingEnvironment.MapPath; or look at the answers to this question. Note that there is a possible issue with HostingEnvironment.MapPath when the WCF service is self hosted.
A possible solution is this method:
public static string MapPath(string path)
{
if (HttpContext.Current != null)
return HttpContext.Current.Server.MapPath(path);
return HostingEnvironment.MapPath(path);
}
The parameter path needs to be of the format "~/XSD/MyFile.xsd", with the folder "XSD" being located in the root of your WCF service.
NEVER create folders in c:\program files (x86)\iis express.

You can add the XSD as a resource, then load it from your assembly. Add the XSD to your project, and under the "Properties Explorer", set the "Build Action" to "Embedded Resource". You can then read the file with:
var schemaSet = new XmlSchemaSet();
schemaSet.Add("", XmlReader.Create(typeof(SomeClassInTheSameAssembly).Assembly
.GetManifestResourceStream("Full.Namespace.XsdName.xsd")));
See Working with Embedded Resources or Loading XmlSchema files out of Assembly Resources for more.

One way you can do it is by using an application setting in your config file that will hold a base file location such as:
<appSettings>
<add key="BaseDir" value="C:\your\folder\names" />
</appSettings>
Then in your program, when you need a file, you would do something like this:
string fileLocation = System.Configuration.ConfigurationManager.AppSettings["BaseDir"] +
#"\your\file\location\file.xsd";
To use System.Configuration.ConfigurationManager, you will need to add a reference to System.Configuration.

Related

Multiple applications with single app.config [duplicate]

Now I have seen this question before on SO in a variant ways, but surprisingly not in this form:
I have a solution with multiple web services (projects) that need to talk to each other. After publishing each of these web services might end up on a different machine with a different database. To tell each web service where all other web services are, I want to maintain a single config file during development.
I would like to expect that after publishing the config to be present in each published project. And I would like to expect the config file to be editable after publishing, so I can swiftly migrate a certain web service and then just edit all config files of the other web services.
I don't want to do this in the database, for the config file its self should also hold connection settings to the database(s).
I came across the following ideas/thoughts/questions:
I have a dll project called 'common' that is referenced by other projects. Let's give that one a shared.config and build a class in that project that can be used to read out the shared.config by doing System.Configuration.ConfigurationManager.OpenExeConfiguration("shared.config"). Just need to make sure the shared.config will be published along with the DLL.
I would favor this solution, as it would also let me keep a web.config inside each project having just the project specific settings. And have the shared.config having the shared settings. But I read on SO that this should not be considered lightly and could have some unwanted side-effects, like file-access-issues; though I wonder if this would apply to my case. Also I would like to ask your help here on how to actually realize this as I don't think Visual Studio supports app.config for DLL projects out of the box.
I also thought about creating a shared.config file in the Solution Items. Then linking that file inside each project. And in the Web.config of each projects, add: <appSettings configSource="shared.config" /> pointing to the linked file in that project.
Though I cannot find any reason why not to do this, first implementation failed. It seems (at least during development), c# cannot find the linked shared.config file. I'm guessing linking files is not done instantly nor maintained after creating the linked file, but the file is only copied to the projects WHEN I do a publish. Thus leaving the file missing during development. Is this correct?
The config files are app specific. This mean that you can add a config file to a class library but the file will then by used by the app (windows service, webservice and so on) referencing the library.
Same thing for external configSource, this are app specific as well and need to be included withing the project using it.
So if your solution is composed by 2 projects you then need 2 config files. One for each project.
While for a windows based application(services, winforms) the expected folder for config files is the bin directory, for web based projects this will be the directory is the root folder of the virtual directory.
This said, using a shared config file looks the easier solution (and you don't have to copy the app.config from the class library for each project). Here are the steps :
Create a solution folder.
Add the config file to it.
Add the file as a reference for each project needing it. Right click the project and Add existing item - > Choose the file and Add as link
Ensure the file is always copied by setting the copy option (properties of the file) with Copy Always.
At this point you should have the config file deployed into your project directory everytime you compile the solution.
EDIT:
I'd avoid looking into the bin for config files within a web app, the
convention is that file should be in the root, so I would avoid the
first option.
Linked files end up in the bin after building the project. Try the same steps for importing the file but this time simply add it (not as link) and it will be deployed as content in the root of your site, so it can be always available.
If your hosting in IIS it is possible to have a single web.config file at the root site level but Giorgio is right in that app.config files are app specific. it is possible to use custom build steps to automate the copying of config files across multiple projects so personally I would go with that.
This actually drove me a bit crazy. In the end I fixed it like this:
Created a Shared.config file in the dll project 'common', having the contents look like any ordinary web.config/app.config.
Set the file to be Content and Copy Always, so it would surely be copied out to all projects that reference project common. (Though the config file will indeed end up in the bin folder.
Created the class SharedConfiguration inside the common project. The really tricky part was having to use OpenMappedExeConfiguration() , and getting the path to the executable directory (including bin, and without file:// in front of it).
Now when I want to access a setting from the shared settings, I do SharedConfiguration.instance.AppSettings.Settings["CubilisEntryPointUrl"].Value.
(I cannot use SharedConfiguration.instance.AppSettings["CubilisEntryPointUrl"] directly because of this issue)
.
public static class SharedConfiguration
{
public static readonly Configuration instance = GetConfiguration("Shared.config");
private static Configuration GetConfiguration(string configFileName)
{
ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
Uri uri = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
exeConfigurationFileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, configFileName);
return ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
}
}

I am making a wcf service application how do I get the full path of a xml file?

I am making a wcf service application how do I get the full path of a xml file? The file is on a visual studio project folder, is going to move to another computer and the path will be change.
Server.MapPath("/PathToYourFiles");
More info here https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath(v=vs.110).aspx
I removed using System.Web.dll;
and add the following:
string path = System.Web.Hosting.HostingEnvironment.MapPath("/fileName.xml");

How to give a folder path in app.config file in C#

I am creating an application in WPF.
In that I am using XML file to store some settings.
My app will run for every 10 sec. So it will use that XML file settings.
My issue is in My local system i am calling the XML file as D://Foldername/projectname/test.xml .
But after deployment it is storing in C://Programfiles/Projectname/test.xml .
So how to give a generic path so that it runs in all the client systems.
I am creating setup file to install in clients systems.
Please help me.
Open the project properties page.
Click on Settings tab.
Add a new item called "MyPath". Make it an Application Setting of type String and give it a sensible default path name as value.
Reference the value in code with Properties.Settings.Default.MyPath.
If you open the applications config there will be a setting called MyPath where you can override the path at runtime.
I suggest you to put the XML file in the same folder as your EXE file and then use Assembly to get its current path.
var cfgPath = Assembly.GetExecutingAssembly().Location + ".config"
Update
it's better to name your config file the same with your exe file but with ".config" extension.
If you are really using ClickOnce, I hardly recommend you to create your own directory for data and configuration files:
private static string GetDataDir()
{
var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"YourApplicationName");
if (!Directory.Exists(dataDir))
Directory.CreateDirectory(dataDir);
return dataDir;
}
The problem with storing the data in the directory of the executable is, that it will be at a different location. While debugging, it will be in you \bin directory. When the application is deployed by ClickOnce, you gonna have a bad time. The installation directory for a ClickOnce application is created for every version. So if you EVER update your application at "customers", all their settings will be lost.

Cannot use Server.MapPath to access a external file

I have a xml file which is in a folder in the solution. I tried to access it using Server.MapPath. It was working fine in a aspx page of a different project. When I tried to access the file in my class library project, I am not supposed to use Server.MapPath. So I tried with HttpContext.Current.Server.MapPath. Problem is this class library project is calling from a separate WCF service project, so current server is WCF service project's server. So it ended up with error path is not valid.
This is what I tried- HttpContext.Current.Server.MapPath("./folder/conf.xml.config")
Any solution?
System.Web is already imported.
You can create a virtual-directory inside the web-services. This virtual-directory will point to Physical location of "folder/conf.xml.config".
Once this is done, you can access it using your existing code like below...
Server.MapPath("folder/conf.xml.config")
Server.MapPath works only with files that are inside the website and is used by specifying a relative location:
string configFile = Server.MapPath("~/App_Data/config.xml.config");
If you want to access a file from some other location you will have to manually provide the absolute path to it:
string configFile = #"c:\work\some_folder\config.xml.config";

C# + File.OpenRead(path_to_file)

I am developing a HTML5 based WebApp being hosted in IIS7. This webapp sends requests to webservices being hosted in IIS7.
The service initialization looks up for a specific file e.g: "appfile.txt" as
FileStream stream = File.OpenRead("appfile.txt"); // opens file for reading.
This call when run as a console application looks up in the project\bin or output directory and able to locate the specified file.
But the same hosted in IIS7 looks up in "C:\windows\system32\inetsrv\appfile.txt".
Are there any configuration item having used in web.config locates the file from the Bin directory of the IIS7 application and not anywhere else?
Any help is much appreciated.
If the app file is in your web application folder, try using Server.MapPath to get The location of the file relative to the root of the web app:
File.OpenRead(Server.MapPath("~/appfile.txt"))
That should work. You probably need to set up the appfile.txt properties so it is copied to the output folder.
You can certainly create your own section in the web.config file to grab the file path that you want. It doesn't need to have been predefined. Then just use any XML reader you want.
Alternatively, you can make a .resx file very easily in Visual Studio and just populate the path there as a variable.
Thanks for all your valuable comments, I could resolve this issue myself using the following code snippets
string path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
string[] labs = File.ReadAllLines(path + "/appfile.txt");
This bit of code allows me to read the file contents without any issues.

Categories

Resources