Write In Config File Problem - c#

hi
this code works fine and my config file changes correctly.
//Local Variable Declaration
System.Configuration.Configuration oConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(
Request.ApplicationPath);
if (oConfig .AppSettings.Settings["CompanyName"] == null)
{
oConfig AppSettings.Settings.Add("CompanyName", "MyCompanyName");
oConfig .Save();
}
but when I want to use a property for this purpose Nothing happend in Config File.
// Property Declaration
private System.Configuration.Configuration _oRootConfig;
public System.Configuration.Configuration oRootConfig
{
get
{
return
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(
Request.ApplicationPath);
}
set { _oRootConfig = value; }
}
if (oRootConfig.AppSettings.Settings["CompanyName"] == null)
{
oRootConfig.AppSettings.Settings.Add("CompanyName", "MyCompanyName");
oRootConfig.Save(System.Configuration.ConfigurationSaveMode.Modified, true);
}
now i have two question:
1-why this code doesnot work ,and there
is no error.
2-if i want to programn in object oriented
manner ,what can i do to fix this property
if the problem is related to the property.
thanks

You're reopening the config on every get, do this instead:
get
{
if(this._oRootConfig == null)
this._oRootConfig = (System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath));
return this._oRootConfig;
}

this line of code:
get
{
return (System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath));
}
set { _oRootConfig = value; }
you are not setting _oRootConfig in your get. You need this code:
get
{
_oRootConfig = (System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath));
return _oRootConfig;
}
set
{
_oRootConfig = value;
}

Related

C# VSTO word AddIn Throws value does not fall within expected error

I am new to VSTO word Addin,the end goal is to check if the custom document property exists.Read all the available articles online with no breakthrough.
Started of with this code
public void chk()
{
if (this.Application.ActiveDocument.CustomDocumentProperties["ObjectType"].Value = 0)
{
MessageBox.Show("Please select an object");
}
}
This throws the error
Value does not fall within bounds error
Modified the code to create a custom document property object as below and it gives me the same error on
if(this.Application.ActiveDocument.CustomDocumentProperties["ObjectType"].Value
= 0)
public void chk()
{
dynamic properties = null;
properties = this.Application.ActiveDocument.CustomDocumentProperties;
properties.Add("Name",false,Office.MsoDocProperties.msoPropertyTypeString, "ObjectType");
properties.Add("LinkToContent",false, Office.MsoDocProperties.msoPropertyTypeBoolean,false);
properties.Add("Type",false,Office.MsoDocProperties.msoPropertyTypeNumber, 0);
if(this.Application.ActiveDocument.CustomDocumentProperties["ObjectType"].Value = 0)
{
MessageBox.Show("Please select an object");
}
}
Requesting you to suggest the steps to fix the issue. Please let me know if more information is required.
You can iterate over all properties and check their names, compare two approaches:
void TestProperties()
{
Microsoft.Office.Core.DocumentProperties properties;
properties = (Office.DocumentProperties)this.CustomDocumentProperties;
if (ReadDocumentProperty("Project Name") != null)
{
properties["Project Name"].Delete();
}
properties.Add("Project Name", false,
Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
"White Papers");
}
private string ReadDocumentProperty(string propertyName)
{
Office.DocumentProperties properties;
properties = (Office.DocumentProperties)this.CustomDocumentProperties;
foreach (Office.DocumentProperty prop in properties)
{
if (prop.Name == propertyName)
{
return prop.Value.ToString();
}
}
return null;
}

StackOverflow in SelectSingleNode

Hello I have function which creates/updates fields in app.exe.config file
public static void UpdateConfig(string FieldName, string FieldValue, ConfigSelector SectionName = ConfigSelector.AppSettings)
{
switch (SectionName)
{
case ConfigSelector.Execption:
{
// MessageBox.Show("gg");
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
if (xmlDoc.SelectSingleNode("configuration/Execption") != null)
{
if (xmlDoc.SelectSingleNode("configuration/Execption/List") != null)
{
// create new node <add key="Region" value="Canterbury" />
var nodeRegion = xmlDoc.CreateElement("add");
nodeRegion.SetAttribute("key", FieldName);
nodeRegion.SetAttribute("value", FieldValue);
xmlDoc.SelectSingleNode("configuration/Execption/List").AppendChild(nodeRegion);
}
else
{
var List = xmlDoc.CreateElement("List");
xmlDoc.SelectSingleNode("configuration/Execption").AppendChild(List);
UpdateConfig(FieldName, FieldValue, SectionName);
}
}
else
{
var List = xmlDoc.CreateElement("Execption");
xmlDoc.SelectSingleNode("configuration").AppendChild(List);
UpdateConfig(FieldName, FieldValue, SectionName);
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("Execption/List");
break;
}
}
}
Function works first Check if xpath configuration/Execption exist, if not exist it creates this path and recalls function again, second time check if configuration/Execption/List path exist if not creates path and recalls function again, and third time adds required fields which is fieldname and fieldvalue,
but I getting System.StackOverflowException in line:
if (xmlDoc.SelectSingleNode("configuration/Execption") != null)
Did I miss something?
You are calling UpdateConfig recursively, with the exact same arguments already passed to it
UpdateConfig(FieldName, FieldValue, SectionName);
Since the recursive call happens before the xmlDoc.Save(), it always works on the same content.
Saving before doing the recursive call should fix the issue.
You don't save the document after adding the new element, so when you are loading the file in the next iteration the new element isn't there, and xmlDoc.SelectSingleNode("configuration/Execption") != null is still false, so the code creates the element again in infinite recursion and you get StackOverflowException.
Just save the document after you change it
else
{
var List = xmlDoc.CreateElement("Execption");
xmlDoc.SelectSingleNode("configuration").AppendChild(List);
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
UpdateConfig(FieldName, FieldValue, SectionName);
}

How to find prevent ResourceManager to default back to default Resource file?

Ive got some code which works somehow good, with except of one tiny little problem.
I have 3 resource files:
- Resource.da.resx (cultureID = 6)
-Resource.en.resx (cultureID = 9)
-Resource.resx - default
If browser loads and it would like to have "en" or "en-US" culture, this method works fine. However if i ask for german ("de") culture getResourceSet returns default Resource set, which i would like to prevent, to just find out that this resource set is not available. Can it be done?
public bool doesCultureExist(string cultureName)
{
try
{
global::System.Resources.ResourceManager rm =
new global::System.Resources.ResourceManager("Resources.Resource", global::System.Reflection.Assembly.Load("App_GlobalResources"));
var cult = CultureInfo.GetCultureInfo(cultureName);
ResourceSet rs = rm.GetResourceSet(cult, true, true);
if (rs != null)
{
return true;
}
else { return false; }
}
catch
{
return false;
}
}
Have you tried passing a false as the third .GetResourceSet() parameter (tryParents), like:
ResourceSet rs = rm.GetResourceSet(cult, true, false);
?

Field Value change not being saved

I am trying to change a field value dynamically from back-end, but looks like the changes are not being saved.
Code
item is fetched from the master database.
using (new EditContext(item))
{
item.Editing.BeginEdit();
try
{
//Value is updated here from "" to Test
item.Fields["Content"].Value = "Test";
}
finally
{
//item.Fields["Content"].Value is "" again.
item.Editing.AcceptChanges();
item.Editing.EndEdit();
}
}
UPDATE
As #sitecore climber said, I did change my code back to use -
new Sitecore.SecurityModel.SecurityDisabler()
However, the issue was caching. The updated value was displayed in the content editor, only after I had cleared the cache and restarted the browser.
To get around that, I disabled caching before making the edit and turned it back on once the editing was done.
CacheManager.Enabled = false;
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Editing.BeginEdit();
try
{
item.Fields["Content"].Value = "Test";
}
finally
{
item.Editing.EndEdit();
}
}
CacheManager.Enabled = true;
Please add : (new Sitecore.SecurityModel.SecurityDisabler())
EditContext containts next lines of code :
public EditContext(Item item)
{
Assert.ArgumentNotNull((object) item, "item");
this._item = item;
this._item.Editing.BeginEdit();
}
so you don't need here if you have in your code
item.Editing.BeginEdit();
your code must be :
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Editing.BeginEdit();
try
{
//Value is updated here from "" to Test
item.Fields["Content"].Value = "Test";
}
finally
{
//item.Fields["Content"].Value is "" again.
// Remove AcceptChanges I never use it , for editing .
// item.Editing.AcceptChanges();
item.Editing.EndEdit();
}
}
I updated my answer, did you check on content editor if are any changes ?
Can you clear cache, and check again. It's really strange why is not working I guess can be a caching problem .
Try using SecurityDisabler if it helps..
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Editing.BeginEdit();
try
{
//Value is updated here from "" to Test
item.Fields["Content"].Value = "Test";
}
finally
{
//item.Fields["Content"].Value is "" again.
item.Editing.AcceptChanges();
item.Editing.EndEdit();
}
}

ReSharper "Possible NullReferenceException" wrong with FileInfo?

I just started using ReSharper and I'm trying to identify why it thinks this code is wrong.
var file = new FileInfo("foobar");
return file.Directory.FullName;
It highlights file.Directory as a "Possible System.NullReferenceException". I'm not sure how this is possible because the file object can never be null and I can't figure out how the DirectoryInfo object returned from the FileInfo object could ever be null.
The Directory property can indeed be null. The implementation of the property is roughly
public DirectoryInfo Directory {
get {
string directoryName = this.DirectoryName;
if (directoryName == null) {
return null;
}
return new DirectoryInfo(directoryName);
}
}
It can definitely return null. Here is a concrete example
var x = new FileInfo(#"c:\");
if (x.Directory == null) {
Console.WriteLine("Directory is null"); // Will print
}

Categories