I have an application that changes your connectionstring in a webconfig in your unauthorized exception. Is there a way I can allow the file to be accessed? Thanks for any help.
Exception Message: System.UnauthorizedAccessExeption: Access to the path "PATH" is denied.
//File path to xml file
var adminConnectionStringConfig = new FileInfo(e.Data.Details.VSStudio.Solution.FullName).Directory
+ #"\Web.Admin\ConnectionStrings.config";
//Method that updates the xml file
private void SetupConnectionStrings(string path, string newDb)
{
var doc = new XmlDocument();
doc.Load(path);
XmlNode node = doc.SelectSingleNode("configuration/connectionStrings");
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].Attributes["name"].Value == "SYS")
{
//Get ConnectionString for client project
var connectionString = node.ChildNodes[i].Attributes["connectionString"].Value;
// Cut all
var dbName = node.ChildNodes[i].Attributes["connectionString"]
.Value.Substring(connectionString.IndexOf("Catalog="));
dbName = dbName.Replace("Catalog=", "");
//Db Name that we will now replace
dbName = dbName.Substring(0, dbName.IndexOf(";"));
// System.Diagnostics.Debugger.Launch();
doc.InnerXml = doc.InnerXml.Replace(dbName, newDb);
doc.Save(path);
break;
}
}
}
There are some steps that you can take.
First, I'd make sure that your XML file is not read-only.
If that doesn't work, than you can run the project as an admin. there are some directories that windows doesn't let you modify if you're not an admin.
If you right click on visual studio, and select run as administrator, then It will automatically debug your project as an admin.
Related
The code that you see was taken from MSDN. Upon testing it says invalid path for SOURCE. I agree. They want the source to be a URL in another Reporting Server. However what I need is to be able to copy a RDL file from my C:\ to the Reporting Server. How can I ?
static void move_report(string currentPath, string targetPath )
{
ReportingService2010 service = new ReportingService2010();
ReportingService2010 rs = new ReportingService2010();
rs.Url = "http://MHPDW2/ReportServer/" + "ReportService2010.asmx";
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
rs.MoveItem(currentPath, targetPath);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.OuterXml);
}
}
static void Main(string[] args)
{
string currentPath = "H:\\ITTFS2012\\SSRS\\DW15Reports\\Claims\\6.1 universe.rdl";
string targetPath = "http://MHPDW2/ReportServer/MidwestHealthPlan/Claims/HPMS/MCR Plan Code/H5685 2014 HPMS/";
move_report(currentPath,targetPath);
What does "H:\" drive resolve to and do you have access to the source location?
Team:
I found the answer. Everything is here ( including code )
I had to use the rs.CreateCatalogItem method.
https://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010.createcatalogitem.aspx
I'm working on a windows based project , in this project we used multiple settings files in order to set text of controls for example buttons.settings, lables.settings and .....
now I need to change the content of these settings files with other values at run time, for this reason we created same settings files with same column "Name" but different values, now I really have problem with changing content of these settings files.
I tried to change content of my tow settings file by loading and saving them as xmlDocument, but unfortunately my app.config doesnt change by new values.
I also used ConfigurationManager.RefreshSection ...
plz help me
thnx in advance
I'll start from describing my setup, just to be sure that we are on the same page.
Thats my setting file - Settings1.settings, with just one setting Test, & the default value being DefaultValue
At this point, the default value is also copied to app.config.
Now, I have a template whose settings which shall come into effect at run time, Its in the form of user.config. And this is how it looks like -
here is the code from working experiment -
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Settings1.Default.Test); // this shows "DefaultValue" in a message box
// Now change the user.config file with our template file -
//1. I get the location of user config
var fileForUser = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
//2. now I'll Place my template file, where user.config should be present
// create directory if it doesnt exist
if(Directory.Exists(Path.GetDirectoryName(fileForUser)) == false)
Directory.CreateDirectory(Path.GetDirectoryName(fileForUser)) ;
// I have kept my template at E:\template.config
File.Copy(#"E:\template.config", fileForUser, true);
MessageBox.Show(Settings1.Default.Test); // this still shows "DefaultValue" because the user.config is not reloaded
//3. Read the new setting
Settings1.Default.Reload();
MessageBox.Show(Settings1.Default.Test); // this shows "Default Value is changed to ABC" because the user.config is now reloaded
}
The App.config remains as it is & incase I delete the user.config or call Settings1.Default.Reset() then its the App.config which provides the application with default values
Hope it helps. Do let me know if it served yr purpose or not.
Update 1 Supporting the already tried approach by author of the question
Here is the working code to support yr approach, which will bring the settings file's setting in applicaion -
regret my typo - Lables2.settings, Lables.settings instead of Labels2.settings & Labels.settings
{
// 1. Open the settings xml file present in the same location
string settingName = "Lables2.SETTINGS"; // Setting file name
XmlDocument docSetting = new XmlDocument();
docSetting.Load(Application.StartupPath + Path.DirectorySeparatorChar + settingName);
XmlNodeList labelSettings = docSetting.GetElementsByTagName("Settings")[0].ChildNodes;
// 2. Open the config file
string configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
XmlDocument appSettingDoc = new XmlDocument();
appSettingDoc.Load(configFile);
XmlNodeList appConfigLabelSettings = appSettingDoc.GetElementsByTagName("userSettings")[0].
SelectNodes("WindowsFormsApplication2.Lables")[0].ChildNodes;
//ProjectName.Setting file
//3. update the config file
for (int i = 0; i < appConfigLabelSettings.Count; i++)
{
var v = appConfigLabelSettings.Item(i).ChildNodes[0];
v.InnerText = labelSettings.Item(i).InnerText;
}
//4. save & load the settings
appSettingDoc.Save(configFile);
Lables.Default.Reload();
MessageBox.Show(Lables.Default.Code); // test pass... shows A2
}
My project settings -
Thats the executable folder, where
And this is how the labels2.settings look like
Update 2 Approach without xml document
All the setup is same & this is much cleaner. Please try -
{
// 1. Open the settings xml file present in the same location
string settingName = "Lables2.SETTINGS"; // Setting file name
XmlDocument docSetting = new XmlDocument();
docSetting.Load(Application.StartupPath + Path.DirectorySeparatorChar + settingName);
XmlNodeList labelSettings = docSetting.GetElementsByTagName("Settings")[0].ChildNodes;
Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A1 GroupB1 NameC1
//2. look for all Lables2 settings in Label settings & update
foreach (XmlNode item in labelSettings)
{
var nameItem = item.Attributes["Name"];
Lables.Default.PropertyValues[nameItem.Value].PropertyValue = item.InnerText;
}
Lables.Default.Save(); // save. this will save it to user.config not app.config but the setting will come in effect in application
Lables.Default.Reload();
Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A2 GroupB2 NameC2
}
Perhaps its the problem with xmlDocument as mentioned here Changing App.config at Runtime
Please keep the setup same as my last response of label.settings & label2.settings.
And try this implementation
{
// 1. Open the settings xml file present in the same location
string settingName = "Lables2.SETTINGS"; // Setting file name
XmlDocument docSetting = new XmlDocument();
docSetting.Load(Application.StartupPath + Path.DirectorySeparatorChar + settingName);
XmlNodeList labelSettings = docSetting.GetElementsByTagName("Settings")[0].ChildNodes;
Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A1 GroupB1 NameC1
//2. look for all Lables2 settings in Label settings & update
foreach (XmlNode item in labelSettings)
{
var nameItem = item.Attributes["Name"];
Lables.Default.PropertyValues[nameItem.Value].PropertyValue = item.InnerText;
}
Lables.Default.Save(); // save. this will save it to user.config not app.config but the setting will come in effect in application
Lables.Default.Reload();
Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A2 GroupB2 NameC2
}
It works for me, & because its without xmldocument, I'm hopeful it'll work at yr end too. Do let me know the result.
XmlDocument doc = new XmlDocument();
//doc.Load(#"C:\Users\***\Documents\Visual Studio 2008\Projects\ChangingLablesRuntime\ChangingLablesRuntime\_Labels2.settings");
//doc.Save(#"C:\Users\SHYAZDI.IDEALSYSTEM\Documents\Visual Studio 2008\Projects\ChangingLablesRuntime\ChangingLablesRuntime\_Labels.settings");
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var root = doc.GetElementsByTagName("userSettings")[0];
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var Config = System.Configuration.ConfigurationManager.OpenExeConfiguration(#"path of app.config");
var root = doc.GetElementsByTagName("userSettings")[0];
doc.GetElementsByTagName("userSettings")[0].SelectSingleNode("Zeus._Labels").InnerText = doc.GetElementsByTagName("userSettings")[0].SelectSingleNode("ChangingLablesRuntime._Labels2").InnerText;
//var newEml = root.SelectSingleNode("ChangingLablesRuntime._Labels2");
//var oldEml = root.SelectSingleNode("Zeus._Labels");
//oldEml.InnerText = newEml.InnerText;
//oldEml.ParentNode.ReplaceChild(newEml, oldEml);
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("userSettings");
here is my code , lables2 is same as lables1 with different values, after running this code nothing happened.
this is piece of lables1.settings , that I want to replace with lables2.settings:
this is piece of lables2.settings :
and app.config related code :
I am using the following code to save my file into database using entity framework But for some reason it is giving me the error:
'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected
But it seems to save the file ok in database as the path and filename of C:\Users\David Buckley\Documents\Visual Studio 2012\Sis\StudentInformationSystem\admin\uploads\test.jpg which exsits but i persume I need to save it differently if I want to load it into an image control imageurl field property?.
try
{
int id = Convert.ToInt32(Request.QueryString["id"]);
if (id == -1) // we neeed a new record otherwise get the old one;
{
Student studentRecord = new Student();
_db.AddStudent(studentRecord);
_db.SaveChanges();
newRecordId = studentRecord.Student_ID;
Session["recordid"] = id;
_student = _db.GetStudentById(newRecordId);
}else
_student = _db.GetStudentById(id);
photoUpload.TargetFolder= Server.MapPath("~/admin/uploads/");
string fullPath = Server.MapPath( "~/admin/uploads/");
photoUpload.OverwriteExistingFiles = true;
string newFileName = "";
foreach (UploadedFile file in photoUpload.UploadedFiles)
{
string fileName = "test";
newFileName =fileName + file.GetExtension();
file.SaveAs(Path.Combine(fullPath, newFileName));
// impelement your database insert here...
}
string thumbPath;
thumbPath = ("~/images" + "/" + newFileName);
_student.Image = thumbPath;
_student.Student_Name = txtStudentName.Text;
_student.Student_FatherName = txtFathersName.Text;
_student.Registration_no = txtRegistrationNo.Text;
_student.Address1 = txtAddress1.Text.Trim();
_student.Address2 = txtAddress2.Text.Trim();
_student.Address3 = txtAddress3.Text.Trim();
_student.RelationWithGuadian = txtRelationshipGurdan.Text.Trim();
_student.GurdianName = txtGurdianName.Text.Trim();
_student.LastSchoolAtten = txtLastSchool.Text.Trim();
_student.Contact1 = txtContact1.Text.Trim();
_student.Contact2 = txtContact2.Text.Trim();
_student.DOB = rdDOB.SelectedDate.Value;
_db.SaveChanges();
}
catch (Exception ex)
{
}
To access the file from a web application, you will need to use a virtual path. But you are saving a physical path to the file in the database. Instead of saving the value of Path.Combine(fullPath, newFileName) in the database, you should be saving the value of "~/admin/uploads/" + newFileName.
The above works as long as your uploads/ directory is a descendant of your application directory. Alternatively, you can use a path that points to a directory outside of your application path by explicitly adding a virtual directory.
How to add a virtual directory in IIS express
How to add a virtual directory in IIS
Here is the structure of my application. I have an asp.net web application running at the root of a website. In a child directory I have WebServices\MyWCFService\. Outlined here:
\parentapp\
\parentapp\App_Data\
\parentapp\Web.config
\parentapp\other_parent_stuff
\parentapp\WebServices\
\parentapp\WebServices\MyWCFService\
\parentapp\WebServices\MyWCFService\bin\
\parentapp\WebServices\MyWCFService\bin\MyWCFService.dll
\parentapp\WebServices\MyWCFService\Web.config (WCF's .config)
\parentapp\WebServices\MyWCFService\other_wcf_stuff
Ultimately what I need to do is open the root application's web.config to get its connection strings so the WCF service can connect to the database info provided there. From the WCF, I can get its own web.config, but I need to go up to the website's root to get that web.config. I get the root directory by doing this:
string svcDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
DirectoryInfo rootDir = Directory.GetParent(svcDir).Parent.Parent;
string root = rootDir.FullName;
Now apperently to open the config file, you need to use the virtual path (instead of local file system path) like so:
VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(root, true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
And from there, I should be able to access the connection string by calling config.ConnectionStrings.ConnectionStrings["db_name"].
The problem is I can never get past the config declaration where I am getting an ArgumentOfOfRangeException. This was expected during testing since the root points to my VS Projects folder at C:\\Users\\me\\Documents\\Visual Studio 2012\\Projects. So I dropped a test web.config file in there, but I still get the exception. On the production servers, the path would point to the parent application's root folder, which contains the config file.
Also, keep in mind that within the WCF Service, HttpContext.Current is always null so I can't use its Request method to get the virtual path that way. Same goes for Server.MapPath. Any ideas? I am not opposed to going about this a different way, so long as ultimately, I can open the parent app's web.config.
I finally found the right ConfigurationManger method to use in this case, where a virtual path is not needed. Here is the code:
//web config subfolder and filename
const string WEB_CONFIG = "\\Web.config";
//open parent application's web.config file to get connection string to specific database
string svcDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
DirectoryInfo rootDir = Directory.GetParent(svcDir).Parent.Parent;
string root = rootDir.FullName;
string webconfigPath = root + WEB_CONFIG;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = webconfigPath;
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string connectionString = "";
if (configuration.ConnectionStrings.ConnectionStrings["db_name"].ConnectionString.Length > 0)
{
connectionString = configuration.ConnectionStrings.ConnectionStrings["db_name"].ConnectionString;
}
Works like a charm.
Here is how i ended up doing this:
public string GetConnectionStringValueFromParent(string key)
{
string value = string.Empty;
try
{
const string WEB_CONFIG = "\\Web.config";
string svcDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
DirectoryInfo rootDir = Directory.GetParent(svcDir).Parent;
string root = rootDir.FullName;
string webconfigPath = root + WEB_CONFIG;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = webconfigPath;
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
if (configuration.ConnectionStrings.ConnectionStrings[key].ConnectionString.Length > 0)
{
value = configuration.ConnectionStrings.ConnectionStrings[key].ConnectionString;
}
}
catch (Exception ex)
{
throw ex;
}
return value;
}
In the constructor of Form1 I did:
contentDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\SF_" + currentDate;
zippedFileDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Default_ZippedFile_Directory";
if (!Directory.Exists(zippedFileDirectory))
{
Directory.CreateDirectory(zippedFileDirectory);
}
if (!Directory.Exists(contentDirectory))
{
Directory.CreateDirectory(contentDirectory);
}
Checked with breakpoint first time zippedFileDirectory not exist create it and if exist nothing. Same for the contentDirectory.
Now I have the contentDirectory here:
C:\\Users\\bout0_000\\AppData\\Local\\Diagnostic_Tool_Blue_Screen\\Diagnostic Tool Blue Screen\\SF_04-08-13
Inside the contentDirectory I have something like 10 files.
Then zippedFileDirectory is:
C:\\Users\\bout0_000\\AppData\\Local\\Diagnostic_Tool_Blue_Screen\\Diagnostic Tool Blue Screen\\Default_ZippedFile_Directory
This directory is empty.
Then I have this Compress() method:
private void Compress()
{
string source = contentDirectory;
string output = zippedFileDirectory;
string programFilesX86 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) + "\\Diagnostic Tool\\7z.dll";
if (File.Exists(programFilesX86))
{
SevenZipExtractor.SetLibraryPath(programFilesX86);
}
string programFiles = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\Diagnostic Tool\\7z.dll";
if (File.Exists(programFiles))
{
SevenZipExtractor.SetLibraryPath(programFiles);
}
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.ArchiveFormat = OutArchiveFormat.Zip;
compressor.CompressionMode = CompressionMode.Create;
compressor.TempFolderPath = System.IO.Path.GetTempPath();
compressor.CompressDirectory(source, output);
Process.Start(Path.GetFullPath(zippedFileDirectory));
}
For some reason on the line:
compressor.CompressDirectory(source, output);
I'm getting the exception:
Access to the path 'C:\Users\bout0_000\AppData\Local\Diagnostic_Tool_Blue_Screen\Diagnostic Tool Blue Screen\Default_ZippedFile_Directory' is denied.
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Access to the path 'C:\Users\bout0_000\AppData\Local\Diagnostic_Tool_Blue_Screen\Diagnostic Tool Blue Screen\Default_ZippedFile_Directory' is denied.
I don't get it why this zippedFileDirectory is locked or access denied ?
If I select any other directory as source for example d:\test there is no problem.
It doesn't work because you pass a directory name for the second parameter to CompressDirectory.
You should pass a file name like....
string output = Path.Combine(zippedFileDirectory, "MyZipFile.7z");
.....
compressor.CompressDirectory(source, output);