ASP.NET Storing data to container class - c#

The problem is that when I read data from txt file with button_1 I place it in container class. When I want to print container data with button_2 in web site -container becoming empty. So the question is how to store data into container class?
Container:
public class Matrix
{
public int[,] matrix;
public Matrix()
{
matrix = new int[6, 6];
}
public void AddNumber(int numb, int i, int j)
{
matrix[i, j] = numb;
}
}
Web form:
public partial class Forma : System.Web.UI.Page
{
Matrix m = new Matrix();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
{
}
protected void Start_Button(object sender, EventArgs e)
{
char[] separators = {' ', '\n', '\r', '\t'};
int numb = 0;
int Counter = 0;
if (!FileUpload1.HasFile)
{
Label1.Text = "Nepasirinkote failo!";
}
else
{
Label1.Text = string.Empty;
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
string[] allNumbers = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
numb = int.Parse(allNumbers[Counter]);
Counter++;
m.AddNumber(numb, i, j);
}
}
Label1.Text = m.matrix[0, 5].ToString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = m.matrix[0, 5].ToString(); //Container infroamtion dissapears
}
}

As opposed to a SmartClient application, a web application creates a new instance of your page class for each request. So the code
Matrix m = new Matrix();
is called whenever you call the page or a postback occurs. So there is a new instance of the matrix and the previous one is gone the moment the first request ends.
There are some methods to store data between requests, each with their ups and downs:
You can store the data in ViewState. Be aware that the ViewState is transferred to the client and sent back to the server, so you only want to do this with small amounts of data.
You can store the data in Session cache. This can reduce the amount of users your application can handle per server because for each user the memory is allocated. Also, if you have a multi-server environment (Web farm), you need to make sure that each server can access the Session cache because a new request can usually be handled by a different server.
The common pattern that is used with database data is to re-read data for the new request. As you get the file by upload, you could store the data in a database when receiving the file and re-read from the database. You'd need to make sure that you purge the data in the database in case it is not needed permanently.
This link provides an overview of the various state management methods that are available in ASP.NET WebForms. Be aware that some of them are user-specific whereas others are shared by all users.

Related

Chart Upgrade in C# make Lagging Application

WindowForm Application, i'm trying to use chart for displaying Datafrom serial port connected to an arduino.
I can read my data and save them to a table in an array after formating the serial data :
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
serialDataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ShowData(object sender, EventArgs e)
{
var charsToRemove = new string[] { "\r" };
foreach ( var c in charsToRemove)
{
serialDataIn = serialDataIn.Replace(c, string.Empty);
}
data = serialDataIn.Split('\n');
data = data.Take(data.Count() - 1).ToArray();
if(pulse_Generated==true)
{
dataPulse = data;
dataMultiPulse = dataMultiPulse.Concat(dataPulse).ToArray();
pulse_Generated = false;
Display_MultiPulse();
Display_Pulse();
}
Display();
}
After than, i'm trying to update 3 chart.
The first one is updated after each data reception (~500ms):
private void Display()
{
chSignal.Series.Clear();
chSignal.Series.Add("Serie1");
chSignal.Series[0].ChartType = SeriesChartType.Line;
// Add point to chart
for (int j = 0; j < data.Length; j++)
{
chSignal.Series[0].Points.AddXY(j, data[j]);
}
Array.Clear(data, 0, data.Length);
//Temporisation pour l'affichage
Thread.Sleep(500);
Restart_Measure();
}
The seconde and the third one are updated after à click button (Pulse generation):
*Seconde one*
private void Display_Pulse()
{
chPulse.Series.Clear();
chPulse.Series.Add("Serie1");
chPulse.Series[0].ChartType = SeriesChartType.Line;
// Add point to chart
for (int j = 0; j < dataPulse.Length; j++)
{
chPulse.Series[0].Points.AddXY(j, dataPulse[j]);
}
Array.Clear(dataPulse, 0, dataPulse.Length);
//Temporisation pour l'affichage
Thread.Sleep(500);
}
*Third one*
private void Display_MultiPulse()
{
var graphDonnee = chMultiPulse.ChartAreas[0];
graphDonnee.AxisX.Maximum = dataMultiPulse.Length - 1;
chMultiPulse.Series.Clear();
chMultiPulse.Series.Add("Serie1");
chMultiPulse.Series[0].ChartType = SeriesChartType.Line;
// Add point to chart
for (int j = 0; j < dataMultiPulse.Length; j++)
{
chMultiPulse.Series[0].Points.AddXY(j, dataMultiPulse[j]);
}
}
The first two work normaly. But the third one updating only when i stop the serial communication betwin my WinFormApp and my arduino.
Further, when a want to generate a "pulse" commande. Normaly i write in a rich text box the pulse characteristic. And the rich text box only update when i stoped the serial communication (as the third chart).
My question is, where my code become blocking ? I go 2 chart out of 3 that work fine.

Improving number guessing game code

I'm trying to make a small guessing game where it generates a random number, and the user enters in a number using a TextBox and Button. Currently it is creating the random number and doing everything I want, but every time the user presses submit on the button, it generates a new random number for them to guess
I am very new to ASP.NET type stuff, so my code is probably inefficient and incorrect lol, so I have two particular questions.
How can I improve my code to make it work better/work at all.
Do I need a runner class to make it work, and how would I do so?
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
public WebPageSeparated()
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}
}
Several things are wrong with your code:
You should never create a new instance of your page (new WebPageSeparated()). A new instance is created every time you navigate to the page (by entering its URL in the browser) and whenever you cause a PostBack (e.g. by clicking an asp:button).
If you want to have some code, which runs only the first time the page is invoked (i.e. not during a PostBack, only when navigating to the page), then you should wrap that code in a if (!IsPostBack) {} block.
Because a new instance of the page is created for each PostBack, you cannot store any state (the random number) in an instance-field of the page. You have to find another place where you store the state, e.g:
in a static field, e.g: private static int randNum
note: this is not recommended, since the static field is shared between all instances of your page (doesn't work if multiple users are on your website at the same time)
in a session variable, e.g. Session["randNum"] = randomNum.Next(0, 10)
in the ViewState of the page, e.g. ViewState["randNum"] = ...
this is what I'd recommend for your sample
in a database
With all these points in mind, your Page_Load method would look something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
ViewState["randNum"] = randNum;
}
else
{
randNum = (int) ViewState["randNum"];
}
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
}
Also, in the case, the user guesses the correct number, you should generate and store a new random number (as done inside the if (!IsPostBack)).
Finally, some topics you might want to read more about: Page Lifecycle, PostBack, Viewstate, Session-state
The reason is asp.net postback all the data to server for every action performed in the browser. Since you are generating a random number in the constructor your facing this issue. I guesss this will help you.
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
protected void Page_Load(object sender, EventArgs e)
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}

how to load groups in listView using Facebook SDK C#

I am using Facebook SDK c# to make windows application.
I try to load all page which I like it is successful.
The problem is when I press the load page button it load this data 1 more to become have duplicate, and get every page I like it 2 times
my code
private void button2_Click(object sender, EventArgs e)
{
string[,] friends;
FacebookClient fb = new FacebookClient(AppSettings.Default.AccessToken);
dynamic Grouplist = fb.Get("/me/likes");
int count = (int)Grouplist.data.Count;
friends = new string[count, 1];
for (int i = 0; i < count; i++)
{
listView3.Items.Add(Grouplist.data[i].name);
}
}
listView3.Items.Clear();
for (int i = 0; i < count; i++)
{
listView3.Items.Add(Grouplist.data[i].name);
}

.net - How to add controls dynamically?

I want to add dynamic controls
Like the below image I want to do
I am struggling to do that
If I click Add More Experience button I want to display another rows
I tried with user control but it is not working properly.
Below code is working fine but if I add controls then close the browser page and then open the browser again added controls are coming.
I think the problem is static int i=0;
static int i = 0;
protected void addnewtext_Click(object sender, EventArgs e)
{
i++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
placeHolder.Controls.Add(ac);
placeHolder.Controls.Add(new LiteralControl("<BR>"));
}
}
Please provide your ideas? Thanks in advance
As per my comment, when using a static variable within an ASP.Net page, it will be shared amongst all users until the application pool or server is restarted.
Instead you should really be using a ViewState or similar to read/write the value.
private int controlCount
{
get
{
int val = 0;
try
{
val = (int)Page.ViewState["ControlCount"];
}
catch(Exception e)
{
// handle exception, if required.
}
return val;
}
set { Page.ViewState["ControlCount"] = value; }
}
protected void addnewtext_Click(object sender, EventArgs e)
{
int i = controlCount++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
placeHolder.Controls.Add(ac);
placeHolder.Controls.Add(new LiteralControl("<BR>"));
}
}

List information disappearing

THIS IS HOMEWORK: I have a program that consists of two winforms and three classes. The program does the work it is supposed to do for the main form and displays it appropriately onto the textbox of the main form. In addition to displaying the information, it is also saved to a string list. The data consists of order information.
The string list passes that information along to a method in another class and stores it in a list as it is supposed to do. After this is done, I press a button which opens up another form. In this form I enter an order number. What is supposed to happen is that a method compares the order number entered with the row number of the list and return that information, whereupon it is displayed in the textbox of the second form.
That is what is supposed to happen. Instead, when it is time to compare the order number with the row number of the list, the list data is gone and I cannot figure out why. Here is my code that pertains:
private void btnPaymentButton_Click(object sender, EventArgs e)
{
amountPaid = double.Parse(this.txtAmountPaid.Text);
orderObject.GetChangeDue(orderObject.TotalAmountDue, amountPaid);
this.txtNumberOfPizzaOrdered.Clear();
this.txtNumberOfCokesOrdered.Clear();
this.txtAmountDue.Clear();
this.txtAmountPaid.Clear();
this.lblYourOrder.Visible = true;
this.rtxtYourOrder.Visible = true;
this.rtxtYourOrder.Text = orderObject.OrderSummary(amountPaid);
//storeOrderObject = new DailySummary(orderObject.OrderSummary(amountPaid));
storeOrderObject = new DailySummary(this.rtxtYourOrder.Text);
}
private void btnDailySummary_Click(object sender, EventArgs e)
{
DailySummaryForm form = new DailySummaryForm();
// this.Visible = false;
form.Show();
}
........
public class DailySummary
{
//declare variables
int numberOfCokes = 0,
numberOfPizzas = 0,
totalOfCokes = 0,
totalOfPizzas = 0,
orderNumberRequest = 0;
string orderFromForm1 = "",
getAllTheOrders = "",
getAnOrder = "";
List<string> pizzaOrderList = new List<string>();
public DailySummary(string orderForm)
{
orderFromForm1 = orderForm;
StoreOrder(orderFromForm1);
}
public DailySummary(int orderRequest)
{
orderNumberRequest = orderRequest;
GetOrder(OrderNumberRequest);
}
public int OrderNumberRequest
{
get
{
return this.orderNumberRequest;
}
}
//store order
public void StoreOrder(string orderFromForm1)
{
pizzaOrderList.Add(orderFromForm1);
}
//get the order
public string GetOrder(int OrderNumberRequest)
{
for (int row = 0; row < pizzaOrderList.Count; row++)
{
if (row == (OrderNumberRequest - 1))
{
getAnOrder = pizzaOrderList[row];
}
}
return getAnOrder;
}
........
public partial class DailySummaryForm : Form
{
int orderNumberRequest = 0;
//instantiate a from object
OrderForm formObject;
DailySummary summaryObject;
public DailySummaryForm()
{
InitializeComponent();
}
private void btnOrderNumberButton_Click(object sender, EventArgs e)
{
orderNumberRequest = int.Parse(this.txtOrderNumber.Text);
summaryObject = new DailySummary(orderNumberRequest);
this.rtxtDisplayOutput.Visible = true;
this.rtxtDisplayOutput.Text = summaryObject.GetAnOrder;
}
In your method btnPaymentButton_Click you create an instance of the DailySummary class, then later on when your in the DailySummaryForm you create a new instance of the DailySummary Class.
These instances are separate and therefore do not share the same values.
As your not persisting values to the DB you'll probably want to:
look into making your DailySummary Static (which will make it accessable throughout your
winform application). (It's not typically good practice to have too many global (static) variables hanging around, but without a persistence engine where you can store your Daily Summary you need a common place to look it up.
Pass the initialized instance of the DailySummary class to your DailySummaryForm. (The DailySummaryForm could expose a public property. The drawback of this method is if your switching between both forms and each form modified your summary class, your going to constantly have to pass it back and forth between the forms.
DailySummaryForm is creating a new instance of
DailySummary.
and that is why it is empty.

Categories

Resources