Dynamic connString (now stored in session, bad) - asp.net

I working on a project where the connString is stored in a session variable. The problem is that the session runs out when the user is not around for a while (makes sense), thereby making the user having to log in again to create a new connection.
The user selects his database from a list of ODBC connection configured on the web server, therefore the different connStrings the user can chose from cannot be stored in the web.config as the user can add new ones as they wish.
I was wondering how to fix this problem. Should I just tell the user not to leave his computer for 20mins+ or can I perhaps store the connString someplace else? Ive seen websites making a pop-up saying "your session will expire in 5 mins, press ok to continue using the site", or something like that.
Furthermore it is not a possbility to make a static varible as the website is shared between many users, so if user1 choses "connString1" and user2 choses "connString2" afterwards, then user1 will unfortunatly be running on "connString2" aswell.
Hope you can help :)
**
Can this be a solution?:
I create a "BasePage" which my pages inherit from. In this basepage i create a hiddenfield and add the connString to the value property on load. Furthermore I will encrypt the connString so the user cannot see the value in the source code.
Then, if the session has a timeout, i will restore the session by using the value in the hiddenfield and the site will not crash.

Can you store the user's connection string preference in their Profile and then persist their profile? http://odetocode.com/articles/440.aspx
You should also be able to do this for anonymous users.
As an aside, I don't know how secure the Profile APIs are, they should be fine, but just in case, you might want to store an Enum value and then map that to a Connection string in your code.

You could use the app.config to get and set config files. Take a look at this to see implementation of storing files. Its just as easy to get settings.
ConfigurationManager doesn't save settings
//Edit: If you don't want the user to be able to see your connectionstring name then you can provice an another in hidden_html or cookie or session cookie. In this example I use a cookie. THis should solve your problem.
To set cookie:
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["ConnectionString"] = "MyCOnnectionValue";
myCookie.Expires = DateTime.Now.AddDays(1d);//For one day.
Response.Cookies.Add(myCookie);//Will store the cookie within the users browser so your code can read from it at every request.
then:
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["ConString"] != null)
{ userSettings = Request.Cookies["UserSettings"]["ConString"]; }
}
string connectionStringNameToUse;
if(userSettings =="Connection1"){
connectionStringNameToUse = "here you can have your name of connectionsstring";
}etc with ypur other connectionsstrings here.
//Then use your connectionsstring here:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringNameToUse ].ToString()))
{
cn.Open();
using (SqlCommand command = new SqlCommand
("delete TBL from RatingListObjects TBL where ( TBL.TradeObject1Id = #MY_ID ) or ( TBL.TradeObject2Id = #My_ID ) ", cn))
{
command.Parameters.Add(new SqlParameter("#MY_ID", customerToRemove.TradeObjectId));
command.ExecuteNonQuery();
}
}
On the other hand. I would go for saving the users database of choice in with the other user data in the db. But this is doable if you only want the user to have a chosen connectionsstring a certain time, set by the program. It wont allow them to see the connections string name. Hopes this helps, good luck!

Related

ASP.NET modify connectionstring at runtime

I need to change dataset connectionstrings to point to different DBs at run time.
I've looked at a number of solutions however they all seem to be related to WinForms or web application projects or other technology slightly different than what I'm using, so I haven't figured out how apply them.
The application is like a discussion. It's a web site project based on code originally written under VS2005, and there's no budget (or personal talent!) for major changes at this time. The app is written in vb.net; I can understand answers in c#. I'm working in VS2013.
The app has three typed datasets pointing to one MDF, call it "MainDB.mdf". There are dozens of tableadapters among the three datasets.
I'm going to deploy the app it as an "alpha/demo" version. I would like to use the same code base for all users, and a separate physical version of MainDB for each user, to reduce chances that the users crash each other.
The initial demo access URL will contain query string information that I can use to connect the user with the right physical database file. I should be able to identify the database name and thus the connection string parameters from the query string information (probably using replace on a generic connection string). If necessary I could use appsettings to store fully formed connection strings, however, I would like to avoid that.
I would like to be able to change the connection strings for all the datasets at the time that the entry point pages for the app are accessed.
Changing the tableadapter connection strings at each instantiation of the tableapters would require too much code change (at least a couple of hundred instantiations); I'd just make complete separate sites instead of doing that. That's the fall back position if I can't dynamically change the connectionstrings at runtime (or learn some other way to make this general scheme work).
Any suggestions on how to approach this would be appreciated.
Thanks!
UPDATE: Per comments, here is a sample instantiation of tableadapter
Public Shared Sub ClearOperCntrlIfHasThisStaff( _
varSesnID As Integer, varWrkprID As Integer)
Dim TA As GSD_DataSetTableAdapters.OPER_CNTRLTableAdapter
Dim DR As GSD_DataSet.OPER_CNTRLRow
DR = DB.GetOperCntrlRowBySesnID(varSesnID)
If IsNothing(DR) Then
Exit Sub
End If
If DR.AField = varWrkprID Then
DR.AField = -1
TA.Update(DR)
DR.AcceptChanges()
End If
End Sub
UPDATE: Below is the test code I tried in a test site to modify the connectionString in a single instantiation of a tableadapter. It feeds a simple gridview. I tried calling this from Page_Load, Page_PreLoad, ObjectDataSource_Init, and Gridview_Databind. At the concluding response.writes, the wrkNewConnString looks changed to TestDB2, and the TA.Connection.ConnectionString value looks changed to TestDB2, but the displayed gridview data is still from TestDB1. Maybe it needs to be called from somewhere else?
Sub ChangeTableAdapter()
Dim wrkNewConnStr As String = ""
Dim wrkSel As Integer
wrkSel = 2
wrkNewConnStr = wrkNewConnStr & "Data Source=.\SQLEXPRESS;"
wrkNewConnStr = wrkNewConnStr & "AttachDbFilename=D:\9000_TestSite\App_Data\TESTDB1.MDF;Integrated Security=True;User Instance=True"
Select Case wrkSel
Case 1
wrkNewConnStr = wrkNewConnStr.Replace("TESTDB1", "TESTDB1")
Case 2
wrkNewConnStr = wrkNewConnStr.Replace("TESTDB1", "TESTDB2")
Case 3
wrkNewConnStr = "Data Source=localhost; Initial Catalog=test01;"
wrkNewConnStr = wrkNewConnStr & " User ID=testuser1; Password=testuserpw1"
End Select
Try
Dim TA As New DataSetTableAdapters.NamesTableAdapter
TA.Connection.ConnectionString = wrkNewConnStr
Response.Write("1 - " & wrkNewConnStr)
Response.Write("<br/>")
Response.Write("2 - " & TA.Connection.ConnectionString)
Catch ex As Exception
Dim exmsg As String = ex.Message
Response.Write(exmsg)
End Try
End Sub
The connection string:
<add name="TestDB1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=D:\9000_TestSite\App_Data\TESTDB1.MDF;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
UPDATE: the following post has lots of solutions, however, they seem to focus on web application projects, that have a project file with settings, which this web site project does not.
link with possible solutions
UPDATE: this next link was brought to my attention, and in working on it I did get it to work, however, it still relies either on having a web application project (with project file) or modifying each table adapter as they are instantiated. So, while I'm not going to implement it, I believe that is the technical answer.
modifying connection strings
sorry if this answer is too late, but I have exactly the same problem and eventually came up with a solution using Reflection.
My solution was to "save" a new default value for the connection string in the settings at run time, which means any further use of the table adapter uses the the new connection string.
It should be noted the term "save" is misleading as the new value is lost when the application closes.
Have tested and worked perfectly.
public void ChangeDefaultSetting(string name, string value)
{
if (name == null)
throw new ArgumentNullException("name");
if (value == null)
throw new ArgumentNullException("value");
Assembly a = typeof({Put the name of a class in the same assembly as your settings class here}).Assembly;
Type t = a.GetType("{Put the full name of your settings class here}");
PropertyInfo propertyInfo = t.GetProperty("Default");
System.Configuration.ApplicationSettingsBase def = propertyInfo.GetValue(null) as System.Configuration.ApplicationSettingsBase;
//change the "defalt" value and save it to memory
def[name] = value;
def.Save();
}

Is using DirectoryServices.NativeObject slow/bad?

In an ASP.NET 4 application, I have existing code to access a user's Active Directory information (potentially under Windows Authentication or FBA) like this:
// authType taken from run-time config file, default below
AuthenticationTypes authType = AuthenticationTypes.Secure;
string path = "LDAP://" + domain;
DirectoryEntry entry = new DirectoryEntry(path);
entry.AuthenticationType = authType;
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
// set search Filter/Properties etc. ..., nice and correctly
SearchResult result = search.FindOne();
It has always worked fine for me, on my LAN. But I get no feedback from customer sites (other than it works). I now note a post like http://www.justskins.com/forums/directoryentry-nativeobject-slow-with-203410.html, implying this COM way of going via DirectoryEntry.NativeObject might be inefficient or ill-advised? On the other hand, I see here LDAP search using DirectoryServices.Protocols slow, implying it is OK?
This code probably dates from .NET 1/2, when perhaps System.DirectoryServices had less in it; it came from some MS example for using ADSI somewhere.
In a word: I don't want to change the code just for the sake of it, but will if faster. Is there actually nowadays any superior method(s) in DirectoryServices which I should be using?

Obfuscating a url

I'm working on an asset management website where in whenever an asset is issued to a user the system would send an email notification with a url in it that would show the user all the assets issued to him. I could have used the query string to pass the user ID but again people could abuse it to view assets issued to other users. My client doesn't wants the user to authenticate themselves when they click on the link. So i need something that would hide the parameters being passed in the query string or at least make them obscure. I've read about url encoding, GUID etc. but i'm not sure what to do. I'm just a beginner. Please pardon my ignorance and point me in the right direction.
Taken what you have said, that you're just a beginner, and assuming that this will be public, you can do the easiest way:
Create a new table in your database and called for example tbl_links, as columns just add 3
user_id (foreigner key to the user table)
guid (primary key, unique)
settings (nvarchar(250)
When you need to send an email, create a new row for the user, for example:
Guid guid = Guid.New();
String settings = "date_from:2012/01/01;date_to:2013/01/01";
And insert it one the database, where the link that you put in the email, should have the guid, for example, http://domain.com/info/?g=....
You could append Json to that settings column and parse it into an object again in the code, ask a new question if you want to take this route.
I personally use a security algorithm to pass only the user_id but you did said you're a beginner, so I only showed you the easy and still valid way.
P.S. for security reasons, you should say in the email that your link is only valid for the next 4 hours or so you can prevent people from generating GUIDs in order to try and get some information.... Simple add a create_date column of type datetime and use that to see if the link already expired or not...
For obscuring URL parameters, you want to use a modified Base64 encoding. Please keep in mind that obscurity is not security, and Base64 encoding something does not in any way make anything secure.
If you're intending to use this for authentication purposes, I think you should reconsider. Look into public key encryption and digital signatures as a starting point.
Trying to secure access to a URL is not the right approach. Give the urls away freely and authenticate your users instead.
I would also highly recommend using SSL for serving up this data.
Security through obscurity fails 100% of the time once the obscurity is not longer obscure.
What you can do is to add some prefix and suffix to the id and the encrypt that string. Something like this:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
string prefix = "lhdsjñsdgñdfj";
string suffix = "dfknsfñn3ih";
var strToEncode = prefix + "|" + id + "|" + suffix;
var encoded = EncodeTo64(str);
var decoded = DecodeFrom64(encoded).Split('|');
if( decoded.length != 3 || decoded[0] != prefix || decoded[2] != suffix )
throw new InvalidArgumentException("id");
var decodedId = decoded[1];

ASP.NET / VB.NET Check If a (different) User IsInRole

I have an ASP.NET application on our company's intranet. And a funky security requirement.
I need to check to see if a given username is in a certain role. I cannot use
Page.User.IsInRole("MyDomain\MyGroup")
because
Page.User.Identity.Name
Returns an empty string. Because of some lovely specifications for this program, I have to keep anonymous access enabled in IIS. Seems to rule out any page.user.identity stuff.
So I did find a way to (at least) get the current user (from System.Environment.UserName), but I need to bounce it against the domain group to see if they're in it. Or, better yet, get a list of users within a given domain so I can check myself. Something like...
Dim UserName as String
UserName = System.Environment.UserName
If User(UserName).IsInRole("MyDomain\MyGroup") Then
MyFunction = "Success"
End If
-OR -
Dim GroupUsers as String()
GroupUsers = GetDomainUserNames("MyDomain\MyGroup")
Anybody have any ideas?
You can call IsUserInRole from the Roles static class. Here is a sample and some reference materials.
Roles.IsUserInRole(username, rolename);
link: http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.isuserinrole.aspx

Storing multiple values in cookies

I have very large website which uses a lot of cookies. There are approx. 14 different cookies are there. I have different cookies for each item. When a user surfs the site they will have 14 cookies in their browser. I do not want this.
I want a single cookie for my site that will have 14 items and I can add,edit and delete them. I tried many ways but I am not able to do this.
I need to put some run time cookies as well save the user name in cookie. After the user logs in I want to save their personal site address in it. Eventually I want both the user name and personal site address both. I want to save user name before and then when user goes to his personal site then i will store personal site name run time.
Does any one have an idea how I could do this?
Matthew beat me to it, but yes, see the ASP.NET Cookies Overview...
To write and read a single cookie with multiple key/values, it would look something like this:
HttpCookie cookie = new HttpCookie("mybigcookie");
cookie.Values.Add("name", name);
cookie.Values.Add("address", address);
//get the values out
string name = Request.Cookies["mybigcookie"]["name"];
string address = Request.Cookies["mybigcookie"]["address"];
There is a section in the ASP.NET Cookies Overview that discusses how to implement multiple name-value pairs (called subkeys) in a single cookie. I think this is what you mean.
The example from that page, in C#:
Response.Cookies["userInfo"]["userName"] = "patrick"; //userInfo is the cookie, userName is the subkey
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); //now lastVisit is the subkey
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
EDIT: From the Cookies Overview (emphasis added):
Modifying and Deleting Cookies:
You
cannot directly modify a cookie.
Instead, changing a cookie consists of
creating a new cookie with new values
and then sending the cookie to the
browser to overwrite the old version
on the client.
Modifying and Deleting Cookies: You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

Resources