tri pm

tri pm

  • NA
  • 1
  • 758

how to add dynamic rules based on user input to webconfig ?

Feb 1 2015 10:14 PM
I want to add a rule, the location path and allow roles determined based on user input .. example TextBox1 to provide location path and textbox 2 to provide a rule for the user.
I want the results in a web config as below:
 
<location path="Report/Default.aspx">
 <system.web> <authorization>
<allow roles="USER"/>
 </authorization> </system.web>
</location>

so far my c # code like this:
but I am confused to apply as I want :
 protected void AddRoleRule(string location, string selectedrole){        
Configuration config = WebConfigurationManager.OpenWebConfiguration(Server.MapPath("~/Web.config"));
 XmlDocument xDoc = new XmlDocument();
xDoc.Load(config.FilePath);
//if the rule exists update the rule

//create location element and the path attribute with it's value set to the
 //selected page
XmlElement newLocationelement = xDoc.CreateElement("location");
XmlAttribute newLocationAttrib = xDoc.CreateAttribute("path");
newLocationAttrib.Value = TextBox1.Text;
 newLocationelement.Attributes.Append(newLocationAttrib);
XmlElement newSystemWebelement = xDoc.CreateElement("system.web");
 XmlElement newAuthorizationelement = xDoc.CreateElement("authorization");
//create the allow element
XmlElement newAllowelement = xDoc.CreateElement("allow");
XmlAttribute newAllowAttrib = xDoc.CreateAttribute("roles");
 newAllowelement.Attributes.Append(newAllowAttrib);
//create the deny element
XmlElement newDenyelement = xDoc.CreateElement("deny");
 XmlAttribute newUsersAttrib = xDoc.CreateAttribute("users");
newUsersAttrib.Value = "*";
 newDenyelement.Attributes.Append(newUsersAttrib);
 newAuthorizationelement.AppendChild(newAllowelement);
newAuthorizationelement.AppendChild(newDenyelement);
newLocationelement.AppendChild(newSystemWebelement);
newSystemWebelement.AppendChild(newAuthorizationelement);
xDoc.DocumentElement.AppendChild(newLocationelement);
xDoc.PreserveWhitespace = true;
//write to web.config file using xml writer
XmlTextWriter xwriter = new XmlTextWriter(config.FilePath, null);
xDoc.WriteTo(xwriter);
xwriter.Close();
}