i want to give the values of username,password and APIKey in web.config which are coming from database.means whatever the admin set username,password,APIkey that has to be set in web.config.
how can i change this.Any idea.
thank you.
private void UpdateConfig(string strKey, string strValue)
{
Configuration objConfig =
WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings =
(AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppsettings != null)
{
objAppsettings.Settings[strKey].Value = strValue;
objConfig.Save();
}
}
But it will restart your application domain every time you update the web.config file, so, updating the web.config frequently is not advisable.
Pls refer : Editing Web.config programatically
Related
i cant connect to sql 2012 in asp.net , c#
file: defalut.aspx -> page_Load
List<ozhatdata.tbl_diller> diller_result;
using (var ctx = new ozhatdata.bagDataContext())
{
diller_result = ozhatdata.DilIslemleri.GetAllLanguages(ctx);
}
int cnt = diller_result.Count ; // diller_result is null error
when i go to definition (F12) of the bagDataContext()
file: bag.designer.cs
public bagDataContext() :
base(global::ozhatdata.Properties.Settings.Default.ozhatprojeConnectionString15, mappingSource)
{
OnCreated();
}
when i go to definition (F12) of ozhatprojeConnectionString15
file: settings.designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute( "Data Source=.\\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;"+
"User ID=sa;Password=123; ")]
public string ozhatprojeConnectionString15 {
get {
return ((string)(this["ozhatprojeConnectionString15"]));
}
}
later i learned there is app.config file this line was present in app.config
<add name="Settings.ozhatprojeConnectionString15"
connectionString="Data Source=LIVE2RISE\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
i can connect to "user:sa pass:123" on "ms sql management studio"
!!!!error!!!!!!
System.NullReferenceException: Object reference not set to an instance of an object.
diller_result.count // this diller_result is null in debugger
line 36: for (int i = 0; i < diller_result.Count; i++)
Kaynak Dosya: c:\inetpub\wwwroot\site\Default.aspx.cs line : 36
im trying to figure out since yesterday.
please help me, thnks.
edit: after responce i tracked adn put a breakpoint
public static List<tbl_diller> GetAllLanguages(bagDataContext ctx = null)
{
try
{
//some stuf was here i deleted
}
catch (Exception ex)
{
string ms = ex.Message; // !!breakpoint
// the exception= coundt find stored procedure "dbo.getalllangs"
return null;
}
}
thank you. the problem is solved. it was caused by an evil try-cath duo.
i'll be more cautious with these "try catchs" from now on.
2nd time and Solution: this time eventhough i edit app.config, program uses old ConString from settings.designer.cs(i tracked it while debugging).
the program uses connString from setting.designer.cs too. app.config is not used/looked up/referred when Debugging
so we have to navigate in the solution>properties>settings.designer.cs edit connectionStrings there too.
i hope this helps anyone in future.
you can read this too:
Force regeneration of Settings.settings file after change in app.config
It seems that it is the call to ozhatdata.DilIslemleri.GetAllLanguagesthat did return a null value for diller_result.
You might want to check in that method what is causing it to return null.
I am mainlining one asp.net Project, this project is configured in IIS. The website is open for everyone, when i review the code in asp.net page, its checking window login "enterprise id" and allowing all users to view the all the aspx pages.
Now, my management team requested us to restrict those who are under junior level employees.(Junior engg, Developer, software engg).
I have written the query, passing enterprise id and validate grade, if its junior level , returning "0" values,else returning "1" values.
My questions is, I do not want go and edit each page and check this query and restrict each page.
can you please suggest , how can i implement simplest and best way to restric the users.
Thanks,
--------------------------------------- Update on 09/24/2015
Index.aspx
protected void Page_Load(object sender, EventArgs e)
{
string UserStatus = UtilFunctions.ValidateUser();
Response.Write(UserStatus);
if (UserStatus == "0")
{
Response.Write("<div><font color=red><h1>You are not authorized to view this page</h1></font></div>");
Response.End();
}
}
Utilifunctions.cs
public static String ValidateUser()
{
string CurrentUser = getLoggedOnUser();
using (System.Data.SqlClient.SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString))
{
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myConnection.Open();//Opens the Connection
myCommand.CommandText = "Select Permission From Temp_Validate Where EnterpriseId='" + CurrentUser + "'";
SqlDataReader IDReader = myCommand.ExecuteReader(); //Gets the ID
IDReader.Read();
string UserStatus = IDReader["Permission"].ToString();
IDReader.Close();
return UserStatus;
}
}
I implemented the above functionalite in my index.aspx page, if the userstatus equal to "0" , it will display the "You are not authrized to view this message" and it will end.
I have around 30 aspx page,its currently running in Production. I do not want go include the same code (index.aspx) in every page load to stop the user validation.
could you please suggest how can i implement without editing all pages.
Updated on 09/28 : Utilifunction.cs
public static String getLoggedOnUser()
{
String user = HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.IndexOf("\\") + 1);
if (user == "") user = "anonymous";
string UserStatus = IsValidUser(user);
if (UserStatus == "0")
{
HttpContext.Current.Response.Redirect("PSF_Error.aspx", true);
}
return user;
}
public static String IsValidUser(string currentUser)
{
using (System.Data.SqlClient.SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
{
using (SqlCommand myCommand = myConnection.CreateCommand())
{
//Gets email of the creator of current user
myConnection.Open();//Opens the Connection
myCommand.CommandText = "Select Permission From Temp_Validate Where EnterpriseId='" + currentUser + "'";
SqlDataReader IDReader = myCommand.ExecuteReader(); //Gets the ID
IDReader.Read();
string UserStatus = IDReader["Permission"].ToString();
IDReader.Close();
return UserStatus;
}
}
}
Index.aspx
Page_load
{
string CurrentUser = UtilFunctions.getLoggedOnUser();
}
You have a few options, here:
1) Set up role-based access with Owin or AspNet.Identity. This is probably your best option, but I couldn't find a good tutorial for you. Those packages are well-documented, however, and I'm sure you can figure them out with some effort.
2) Build a Roles table, and customize access yourself. The best example I found was here: http://www.codeproject.com/Articles/875547/Custom-Roles-Based-Access-Control-RBAC-in-ASP-NET
3) Redirect unauthorized users without the use of roles. So something like:
public ActionResult SecurePage(User u)
{
if(u.level == "junior"){
return RedirectToAction("CustomErrorPage");
} else {
return View();
}
}
I'm not sure that that option is terribly secure, but it should work.
Hope that helps!
after setting up roles you can use a web.config file in every directory specifying authorization and/or use the 'location' element in the web.config file.
First off, sorry about the confusing code. I've been using MVC, and you've clearly posted your code behind.
I don't think that you can achieve what you are trying to do, without adding your code to each page, or learning about roles. You could reduce some code duplication in a number of clever ways, but I can't think of anything that doesn't seem like a total hack.
If you want to, say, put all of your secure pages in the same directory, and restrict low-level access to that directory, you are going to have to filter by specific users or, if you can implement them, roles. As I understand it, the deny and allow nodes in your web.config file are setting server side (so IIS, probably) authorization rules, so the keywords and rules you can use are limited. Check this page out, for some basics:
http://weblogs.asp.net/gurusarkar/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config
While it is likely POSSIBLE to build a rule based on values in your DB, doing so would probably be far more work than it would be worth.
Sorry that I can't offer a more satisfactory answer, but I would recommend: 1) Get to work, and add a check to the code behind for each page, or 2) (and I highly suggest this option) close this question, and post another, about implementing roles in .net, and assigning roles to users, in code. If, say, you can use your login page to assign every junior-level user the custom role of Junior, and place all of your secure pages in a directory named SecurePages you could add the following code to your web.config, and achieve exactly what you are trying to do:
<location path="SecurePages">
<system.web>
<authorization>
<deny roles="Junior">
<deny users="*">
</authorization></system.web></location>
Good luck!
I need to save a value for all my website, is there a way to save it in a global variable in the server side like ViewData for example or is it better to save it in a cookie ?
This data is set using a dropdown list and cached in the controller.
Thanks.
In the Global.asax page
void Application_Start(object sender, EventArgs e)
{
// set your variable here
Application["myVar"] = "some value";
}
Inside the action
public ActionResult MyAction()
{
// get value
string value = Application["myValue"].ToString();
// change value
Application["myValue"] = "some NEW value";
}
You could store it in the Application state:
public ActionResult Foo()
{
HttpContext.Application["someKey"] = "some value";
...
}
and then later read from it:
string value = (string)HttpContext.Application["someKey"];
The values stored in the Application state are shared among all users of the website.
If you need to store user specific data you could use session or cookies depending on whether it is sensitive data or not.
Session would be the way if you are wanting to change the value, if the value is going to be static & is known before the application loads any data then you could store it in the Web.config and reference it from there.
Such as:
<appSettings>
<add key="MyStaticItem" value="Lulz" />
</appSettings>
So then if you want to retreive that string you can do:
Meh = ConfigurationManager.AppSettings["MyStaticItem"]
Meh would be Lulz
Can also use session like this:
Session["MyKey"] = "MyValue";
and retrieving like this:
var myVar = (string)Session["MyKey"];
if that's per user value.
Hope this is of help.
<appSettings>
<!-- Settings file for website! -->
<add key="DefaultCookieExpiryMins" value="30" />
</appSettings>
Why do I have to set everything as a string? Why can't I have different datatypes in there like int to help me stop having to cast everything?
This is why I prefer custom configuration sections over just putting key/value pairs in appSettings. See this MSDN article for more information on how to make your own configuration section. Once you have your own configuration section class, you should be able to access your settings as any data type you'd like.
I just use generics for things like this.
public static T GetConfigurationValue<T>(string keyName)
{
if (System.Configuration.ConfigurationManager.AppSettings[keyName] != null)
{
T result;
try
{
result = (T)Convert.ChangeType(System.Configuration.ConfigurationManager.AppSettings[keyName], typeof(T));
}
catch
{
return default(T);
}
return result;
}
throw new ArgumentException("A key with the name " + keyName + " does not exist in the current configuration.", keyName);
}
Usage: GetConfigurationValue<int>("DefaultCookieExpiryMins");
I am working with asp.net website project that some of pages need authentication. I am using asp.net membership.
I read some answers. e.g. make all of those pages in folder and create inner web.config that describe the privilege. This is one way solve the problem but I need way that is more fixable and effective.
If you don't want to hard code this in web.config(s) you will need to implement a "Base Page" type control.
Your base page class should inherit from System.Web.UI.Page, and would need to have a method you could call to say "User must be logged in" or "User must be in role x", and if the user isn't in that role, redirect to the login page (you can get this by calling FormsAuthentication.LoginUrl).
Your actual pages should inherit from this class rather than from System.Web.UI.Page directly. Then, in something like Init, or at the top of Page_Load, call
base.UserMustBeLoggedIn();
or
// Replace "AccessRole" with the name of your role
base.UserMustBeInRole("AccessRole");
And let the base page handle this.
If you would rather have the access rights stored in a database, then you could move all the processing to the base page, and in a suitable place in the page lifecycle, check the current URL against your database table, check the users role/authentication against the requirements and redirect as required.
Note that you can create page level security in the web config like so:
<configuration>
<location path="LockedPage.aspx">
<system.web>
<authorization>
<!-- Deny access to anonymous users -->
<deny users="?"/>
</authorization>
</system.web>
</location>
</configuration>
More information is available on MSDN: The Location Element and The Authorization Element.
You can try this code,
In the master Page load event write this code,
add a property
public bool m_bLoginRequired = true;
public bool IsLoginRequired
{
get { return m_bLoginRequired; }
set { m_bLoginRequired = value; }
}
try
{
// Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
Response.Cache.SetNoStore();
if (IsLoginRequired==true)
{
if ( Session.IsNewSession || HttpContext.Current.Session["Username"] == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage("Session Expired");
Response.End();
}
}
}
catch (Exception ex)
{
throw (ex);
}
now in Login page you need to write this code
FormsAuthentication.SetAuthCookie(this.txt_UserName.Text.Trim(), false); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.txt_UserName.Text.Trim(), DateTime.Now, DateTime.Now.AddMinutes(10), false, "HR");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Name = "jay";
Session["UserName"] = txt_UserName.Text.Trim();
Response.Cookies.Add(cookie);
txt_UserName.Text = "";
txt_Password.Text = "";
Response.Redirect("HomePage2.aspx");
now you ave to add pageinit event in the login page
protected void Page_PreInit(object sender, EventArgs e)
{
Master.IsLoginRequired = false;
}
if you want that the user can access an un authorized page then
in the pageinit event of that page
set the Master.IsLoginRequired=false;
also specify the loginurl in the web.config file.