managing connection string on dropdown selection now the question is this "connection" object is not working in another webform because i need to use this connection on hole app using this connection object how to solve
String connection = String.Empty;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text.Equals("RVL LOGISTICS (I) PVT LTD"))
{
connection = ConfigurationManager.ConnectionStrings["CompMasterConnectionString"].ConnectionString;
}
else if (DropDownList1.SelectedItem.Text.Equals("SIMONS SHIPPING PVT LTD"))
{
connection = ConfigurationManager.ConnectionStrings["DUM01ConnectionString"].ConnectionString;
}
else
{
DropDownList2.Enabled = false;
}
}
Page state is not persistent: it goes out of memory once the page is rendered.
You have to store the value elsewhere in order to reuse it. Where you save it depends on where you want to use it.
Some options:
Pass it through an URL. This might have security implications;
View state;
Session object storage;
Application object storage.
Related
Im having trouble converting wpf to asp.net using mqtt. My code did not show any error but when i launch and input some text and a button click,it will show me an error
"An exception of type 'System.NullReferenceException' occurred in WebApplication4.dll but was not handled in user code"
public partial class Testing : System.Web.UI.Page
{
MqttClient client;
string clientId;
protected void Page_Load(object sender, EventArgs e)
{
}
public void MainWindow()
{
string BrokerAddress = "test.mosquitto.org";
client = new MqttClient(BrokerAddress);
// register a callback-function (we have to implement, see below) which is called by the library when a message was received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
// use a unique id as client id, each time we start the application
clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
}
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
txtReceived.Text = ReceivedMessage;
}
protected void btnPublish_Click(object sender, EventArgs e)
{
if (txtTopicPublish.Text != "")
{
// whole topic
string Topic = "" + txtTopicPublish.Text + "";
// publish a message with QoS 2
client.Publish(Topic, Encoding.UTF8.GetBytes(txtPublish.Text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('You have to enter a topic to publish!')</script>");
}
}
It seems to be a lack of understanding of the ASP.NET page lifecycle.
In WPF, the lifecycle spans from when you run the program til when it is closed; it is statefull. ASP.NET is not; whatever you do in a Page_Load (and the other lifecycle events) will be disposed with the completion of rendering the page.
You have a few ways of solving your problem.
You can keep the MqttClient instance in the Application object. This keeps the instance alive from when the AppPool starts (instantiate the client in the Application_Start event in Global.asax. It is fired when the AppPool starts) and until it shuts down (Application_End, where you get the opportunity to shut your MqttClient down gracefully if you want/need to). It is shared between all users and can be accessed anywhere with Application[key] where key is any string, "MqttClient" for example.
You can keep it in the Session object the same way you would in the Application object. You can use Sesson_Start and Session_End in the same way. The Session object is unique to each user, in terms of it staying alive until the user stops browsing your website.
You can instantiate MqttClient every time you need it or with every Page_Load.
I get the link in "https://www.youtube.com/watch?v=SIs7ZsMCUWA&t=327s"
I want to change from aspx to winform
the problem:
in aspx
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TokenQueue"] == null)
{
Queue<int> queueTokens = new Queue<int>();
Session["TokenQueue"] = queueTokens;
}
}
protected void btnPrinToken_Click(object sender, EventArgs e)
{
Queue<int> tokenQueue = (Queue<int>)Session["TokenQueue"];
lblStatus.Text = " Terdapat " + tokenQueue.Count.ToString() + " Antrian ";
if (Session["LastTokenNumberIssued"] == null)
{
Session["LastTokenNumberIssued"] = 0;
}
int nextTokenNumberTobeIssued = (int)Session["LastTokenNumberIssued"] + 1;
Session["LastTokenNumberIssued"] = nextTokenNumberTobeIssued;
tokenQueue.Enqueue(nextTokenNumberTobeIssued);
AddTokensToListBox(tokenQueue);
}
in c# can't read session?
Session["TokenQueue"] = queueTokens;
how to use session in c# winform?
Session normally helps us to maintain information for a user across multiple pages in a web application. When you are converting any web application to windows application you need to know the certain aspects of web application. As session is pretty common in most of web application frameworks. You can achieve same behavior by static variables in any language. In C# you can make a class to hold such information in static variables like this
internal static class SESSIONWINFORM
{
public static string TokenQueue = string.Empty;
public static DateTime LastLogin = DateTime.MinValue;
// more variables as you needed
}
Then you assign these variables values at particular events of your windows application for example in login method to save logged in time like this
protected bool login(string username, string password) {
if (succesfullLogic)
{
SESSIONWINFORM.LastLogin = DateTime.Now;
....
}
}
And to show in a Label1 to user his last login in a WinForm. You can set it text like this
Label1.Text = SESSIONWINFORM.LastLogin;
You don't need sessions since Windows apps run within the user context. There is always a single user.
I would advice to make the variable a static variable, since then it really is shared for the lifetime of the session, as it would in ASP.NET. What if you make a Session class in your Winforms project and mimic the session behavior? That would make it easier to exchange code between your projects.
I'm using a List<> as a container for some data returned from database, like this:
List<BookInfo> result {get;set;}
protected void SearchButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
result = (new BookInfo()).Search(TextBox1.Text);
ListView1.DataSource = result;
ListView1.DataBind();
}
}
Everything works ok. But when I'm trying to sort this List in other event like this one, it's empty.
protected void ListView1_Sorting(object sender, ListViewSortEventArgs e)
{
IComparer<BookInfo> comparer = new BookInfoOrdering();
if (result != null)
{
result.Sort(comparer);
}
ListView1.DataSource = result;
ListView1.DataBind();
}
I'd just like to know why is it happening. One solution is to call the search method and get the data again but isn't it unnecessary?
You were trapped by the same trap that many people are trapped by many times - it's the page lifecycle. ASP.NET fools you by pretending that you had one environment including server and browser, but that's not the case. HTTP is state-less. If you need to persist state between two requests, you have several options:
Serialize the state into the so-called ViewState such as to send it to the browser and post it back to the server
Save it in a database
Save it in the session
Introduce caching for the data that need to be retrieved, that is, sequential calls to BookInfo.Search with equal parameter values don't issue a new database request (or whatever else is required to get the data)
This would work in a desktop application, but not a asp.net website. Server side data retrieved from one postbacks is not stored for the next postback.
There are several methods for storing data between postbacks. For example using the Session State of the website:
// storing
HttpContext.Current.Session["list"] = result;
// retrieving
List<BookInfo> temp = (List<BookInfo>)HttpContext.Current.Session["list"];
you should also be able to retrieve the list from the ListView where it was bound.
IComparer<BookInfo> comparer = new BookInfoOrdering();
List<BookInfo> temp = (List<BookInfo>)ListView1.DataSource;
temp.Sort(comparer);
ListView1.DataSource = temp;
ListView1.DataBind();
I have a webpage with a button that does postback, connects to an external database to download some data and perform some database updates. The issue I have is the possibility that two or more people runs this download simultaneously or while the function is still running, which may cause problems.
How do I create some form of semaphore so that if the second person clicks the button, he'll get a message saying it's currently being updated?
Use a proper transaction on your external database and apply row locking there as needed; the DB system should handle the concurrency just fine.
At the first sight, I would use an ASP.NET Application variable enclosed in a lock statement to check and update it if needed.
protected void Page_Load(object sender, EventArgs e)
{
if (!GetSem_SomeoneIsDownloading())
{
PerformDownload();
ClearSem_SomeoneIsDownloading();
}
else
{
DisplayMessageSomeoneIsDownloadingAlready();
}
}
bool GetSem_SomeoneIsDownloading()
{
bool isSomeoneDownloading;
Application.Lock();
isSomeoneDownloading = (bool)(Application["SomeoneIsDownloading"] ?? false);
if (!isSomeoneDownloading)
Application["SomeoneIsDownloading"] = true;
Application.UnLock();
return isSomeoneDownloading;
}
void ClearSem_SomeoneIsDownloading()
{
Application.Lock();
Application["SomeoneIsDownloading"] = false;
Application.UnLock();
}
Is there anyway to detect when a user logins if there is already another session with the same username, and block him from logging in again or send him a message?
You could always implement the events in global.asax.
Implement Application_Start() to setup a System.Collections.Dictionary (or at your preference) and store that in the Application[] collection, when a user logsin, add the username. Remove from the collection in Session_End(). Remember to use the 'lock' keyword while working with the collection :)
Have fun!
Example:
[page.aspx]
public partial class page : System.Web.UI.Page {
protected bool Login(string userName) {
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null) {
lock (d) {
if (d.Contains(userName)) {
// User is already logged in!!!
return false;
}
d.Add(userName);
}
}
Session["UserLoggedIn"] = userName;
return true;
}
protected void Logout() {
Session.Abandon();
}
}
[global.asax]
<%# Application Language="C#" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e) {
Application["UsersLoggedIn"] = new System.Collections.Generic.List<string>();
}
void Session_End(object sender, EventArgs e) {
// NOTE: you might want to call this from the .Logout() method - aswell -, to speed things up
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty ? (string)Session["UserLoggedIn"];
if (userLoggedIn.Length > 0) {
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null) {
lock (d) {
d.Remove(userLoggedIn);
}
}
}
}
</script>
I've implemented this where when a user logs in it sets a flag in the DB that they are logged in. It was an int representing how many times they are logged in. We allowed two. Then would just check that when validating the user.
You can, by keeping track of users logged in, in your global.asax by using the Application object.
In the Session_Start method or your login method, you can check if the user is stored in the Application object.
On the Session_End method or in your logoff method, you'll need to remove the user from the Application object.
Don't store it in the DB if you cannot identify user logout event (they may click logout, close the tab, close the whole browser, or may just shutdown the computer...).
Use session to do the same checking instead.
You could store the SessionID of a user in a database. On each login, store a combination of Unique username and SessionID into the database. In the masterpage you include the query to the database, to check wether the last login for the currently used username was from the same session. If not, abandon the session and redirect to the login page.
The behaviour I posted should log out the second user. You may change the Session.Abandon to your desired behaviour