Asp.net Mvc c# dynamic Session - c#

I have one application with multi-database login I want to use dynamic session where I can save the user name and his connection string then I could realize session data for the special one in the case log off and also to void sometimes mixed between session data values in saving user data as sometimes when I save data for example for database 1 I find it saved in another database while another user is login for the second one
my trial is
List<String> ConnectionSessions = new List<string>();
List<String> usernamevalue= new List<string>();
ConnectionSessions.Add(query[0].ConnString);
usernamevalue.Add(x.Split('-').First());
foreach (string section in ConnectionSessions)
{
foreach (var uname in usernamevalue)
{
Session[uname] = section;
}
}
My question how can I call this section and use it is valued in different controles and is my idea right as i know each user has his own session

Related

Foreach in not iterating through values

I am developing an application where I have to perform some update operation on each machine in the database. Every machine has a unique Id. Then there is also an area code under which several machines come. Area codes are also unique. I am reading these ids from the database and storing them in a list and then I want to hit the API one by one using these Ids. The API will give me a response which I have to read and update the database accordingly . I am using foreach but I don't know what mistake I am doing that it is not iterating to the second element(second id) of the list and I am not able to call the function with the 2nd Id to hit the API.
public static void ProcessIds(string areacode1, string areacode2)
{
// this is working fine I am getting correct values
List<IntermediateAPIRequest.IntermediateIds> Ids =
GetIntermediateIDList(areacode1, areacode2);
APIRequest apiRequest = new APIRequest();
foreach (IntermediateAPIRequest.IntermediateIds id in Ids)
{
//code for creating API request--this now fetches the 1st Id from
// the list and creates the request
APIresponse result = GetAPIResponsePerID(URL, id.machineID, apiRequest);
//Code for dealing with the response, for the time being I am
// simply displaying it onto the console.
} // end of foreach loop
}
I am able to read the response properly. The main issue is that I am not able to call the api with the 2nd value in the list.
Please let me know if I need to add more code for clarification.

How to loop through multiple connection strings in a db and query them?

I don't know how to loop through my local database and add the values to this string:
string credentials = #"server = 127.0.0.1;
user id = system;
port = 3308;
Password = 975315";
https://i.imgur.com/6B4YFw7.png
I kind of need something like this:
string credentials = #"server = IDindb;
user id = IDindb;
port = Portindb;
Password = Pwindb";
foreach(rowofdata in localdb)
{
MySqlConnection con = new MySqlConnection(credentials);
con.Open(); //Opens the connection
MySqlCommand cmd = new MySqlCommand(sqlQuery, con); //Sends the
query to "show slave status"
Create a new table in browser that shows if server is running or not.
}
This is quite a good homework assignment - It touches frontend, database, networking and middleware, and importantly it forces you to properly think through all the little decisions of what might go wrong, e.g.
what do you do when the server doesn't respond (write "server down
into your html table)
how do you trap this without your own code failing.
What if the servers take a really long time to respond? Timeout?
Should you be doing this to each server in succession, or
all at once, adding their responses into the table as you go?
What I'm saying is you should think about your overall solution some more before diving into the code.
To answer the question, assuming you have some code to connect to the local db and query the table, rowofdata will be a recordset, with each row populated per the row in your image.
Extract the server, user, password etc credentials from it:
var masterHost = rowofdata["Master_Host"].ToString();
and create the connection string inside the for-loop.
var credentials = $"server={masterHost};user id={userId}; port={portId}; Password={password}";
The Create new Table in browser part will depend on which platform/language you're writing in. And in any case shouldn't be done here, unless you're intent on mixing db access with html (#Razor? classic asp?).
Store the server / status values in a list (of server object, with status etc), then subsequently use them to populate the html.
(Or build the html table and render that, and use ajax to request the status of each).
(unrelated - how do you plan on implementing the stop/start/fix button code?)

Pulling external website URL parameters

Currently I have a MVC Registration page which is implemented in an external website.
My question is I need to now extract the previous website's querystring for a certain parameter and read it into my page to register a user into the designated group.
So the workflow looks as follows :
User hits the external website (example: www.test1.com/default.aspx?Code=123asd) with a code in the querystring
user selects Register Now and gets directed to my page.
How will I be able to read the previous querystring code into my MVC page? I do not have access to that website.
EDIT
I currently have a foreach statement which reads the current querystring but this is not pulling the previous request's querystring:
private static string getCode()
{
string nothing = null;
string[] queryStringParaArray = HttpContext.Current.Request.UrlReferrer.Query.Substring(1).Split('=');
if (queryStringParaArray.Length > 0)
{
foreach (var para in queryStringParaArray)
{
if (para.Contains("Code"))
return queryStringParaArray[2];
}
}
return nothing;
}
Have you tried HttpRequest.UrlReferrer property which contains URL of the client's previous request that linked to the current URL. This returns a Uri object and thus you can access the Query property to get the query string value of it.
HttpContext.Request.UrlReferrer
**SideNote: As already commented, there is no guarantee that the referred URL would be present and thus it could be null as well. So would suggest you to pass that query string information directly to your MVC controller while clicking on Register button.

Use data from DataTable in all forms

In the class I execute a stored procedure and return a DataTable.
public DataTable getUserInfo(int abid)
{
DataTable tbl = new DataTable();
string constring =ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("getUserInfo", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ABID", abid);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(tbl);
}
}
return tbl;
}
Then in the code behind of the default.aspx.cs page I call the class and using a foreach loop I get all the data I need.
DataTable tbl = new DataTable();
tbl = u.getUserInfo(abid);
foreach (DataRow row in tbl.Rows)
{
string firstName = row["firstName"].ToString();
string lastName = row["lastName"].ToString();
string fullname = row["fullname"].ToString();
string Phone = row["phone"].ToString();
}
This solution works if I only had to use the data in this page only. I need the same data to use in different pages in the project. Of course, I could call the class every time and create different data tables and store them in different variables, but I know it's not very efficient. I'm sure there's a better way to do this.
Is there a way that I could create global variables? For instances I load the datatable into those variables and I can use them throughout the project? Or any other solution?
Thanks
If that data is shared among different users then use Cache object. See: ASP.NET Caching: Techniques and Best Practices.
But if that data is unique to each user then store that information in a Session object. But remember, Sessions are maintained for each user on Server, If you keep too much data in Session then it will require more resources from the Server.
See: ASP.NET Session State Overview
To store information in Session
//To store
Session["UserInfo"] = tbl;
To retrieve
DataTable tbl = Session["UserInfo"] as DataTable;
if (tbl != null)
{
//Datatable found;
}
Session object can be accessed on multiple pages.
You also have other options to maintain state across pages in ASP.Net, like Cookies. See
ASP.NET State Management Overview
Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server. As we all know, HTTP is a stateless protocol, it can't hold client information on a page.
If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information. We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis. Have a look at the following diagram:
State management using session is one of the best ASP.NET features, because it is secure, transparent from users, and we can store any kind of object in it.
Advantages:
It helps maintain user state and data all over the application.
It is easy to implement and we can store any kind of object.
Stores client data separately.
Session is secure and transparent from the user.
Disadvantages:
Performance overhead in case of large volumes of data/user, because session data is stored in server memory.
Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.
Reference:
1.http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
I suggest that you implement a lazy-loading solution to this.
Since static member are shared across all requests to the application, you can cache data that you know isn't going to change. Obviously you have to be careful about caching too much or for too long, or you're going to run int RAM issues. You'll also have to consider concurrency.
Here's a simplified example: create a class that represents a user, and then create a static method, LoadByID(int id), and a static Dictionary to stored already-loaded users. Then, when a page requests a user, serve them the item from the cache if it already exists.
//... user instance fields ...
private static Dictionary<int, User> cache = new Dictionary<int, User>();
private static object lockObj = new object();
public static User LoadByID(int id)
{
lock (lockObj) //Prevent double-adding items
{
if (cache.ContainsKey(id))
{
return cache[id]; //We've already loaded the record.
}
else
{
//Some function that actually calls the database
//and constructs user objects
User loaded = LoadUserInternal(id);
cache.Add(id, loaded)
return loaded;
}
}
}
private static User LoadUserInternal(int id)
{
//Load and construct the user
}

C# webservices maintain session from another webservice

I have a webshop running which contains parts of cars. The prices next to the parts are loaded from a webservice running else where. This webservice only contains one webmethod: GetArticleInformation.
In this webservice there is a link to another webservice WebshopServiceClient running elsewhere which contains the info about the cars and holds the prices.
Now when a user select a part of the vehicle he wants to buy the first webservice is called and the method GetArticleInformation is executed. In this method I want to create a session which hold the logon of the second webservice ( the database ). In this way I want to prevent that for every call a new logon is required.
[WebMethod(EnableSession = true)]
public GetBackItems GetArticleInformation(User user, Items items)
{
//Create session if needed
client = (WebshopServiceClient)Session["SphinxLogon"];
if (client == null)
{
client = new WebshopServiceClient();
bool done = client.Logon();
if (done)
{
Session["SphinxLogon"] = client;
}
}
//Get information and send it back
...
}
Now when the user in the webshop selects a part the session is created but the next time the user selects a part the session is null again.
What am I doing wrong or what am I missing?
I would consider 'talking' to the various web-services via an internal 'proxy'-procedure -- fired up on app-start for example -- which would handle all traffic etc with the services. That way the individual client sessions do not have to logon or maintain a session with the services but can still be managed via the proxy. Individual clients would get a 'ticket' from the proxy which then could be part of their session and could be used to manage it.

Categories