my application is not responding when spamming a number generator button, I do not know what I am doing wrong.
Number is being added at least when bigger than 9999.
private void button17_Click_1(object sender, EventArgs e)
{
byte[] buffer = Guid.NewGuid().ToByteArray();
var FormNumber = BitConverter.ToUInt16(buffer, 0);
int IDNumber = FormNumber;
for (; ; )
{
if (IDNumber > 9999)
{
listBox1.Items.Add(FormNumber);
break;
}
else
{
//repeat
}
}
}
This is an example of the button which causes my whole program to stop responding, when button is being spammed, sometimes even after the first try it just stops,
Im using Visual Studio 2017, Winforms C#
Yeah because IDNumber maybe less than at 9999 at any time, you don't have any handle conditions if IDNumber is less
better do it this way
for (; ; )
{
byte[] buffer = Guid.NewGuid().ToByteArray();
var FormNumber = BitConverter.ToUInt16(buffer, 0);
int IDNumber = FormNumber;
if (IDNumber > 9999)
{
listBox1.Items.Add(FormNumber);
break;
}
else
{
//repeat
}
}
Actually I've added return
private void button17_Click_1(object sender, EventArgs e)
{
byte[] buffer = Guid.NewGuid().ToByteArray();
var FormNumber = BitConverter.ToUInt16(buffer, 0);
int IDNumber = FormNumber;
for (; ; )
{
if (IDNumber > 9999)
{
listBox1.Items.Add(FormNumber);
break;
}
else
{
//repeat
}
return;
}
}
and it works, looks like program wasn't able to exit the loop properly...
Related
I am creating a Javafx chat app which also allows for file transfer. My issue is I open a FileOutputStream for the received file within the below method. I can see my listener.statusTransferring() updating the UI only if I enable Platform.runLater. I think I now need to enable the same on the fos.write(b, 0, tmpTransferred) within the while loop but don't know how to do this. I have tried unsuccessfully wrapping the whole method within Platform runlater. Note: If I don't use platform runlater I don't get any errors however the UI does not update until the file transfer is complete eg listener.statusCompleted() is called;. The error I get now as a result of the fos being in Platform runlater. is below.. Line 185 is fos.write(b, 0, tmpTransferred); The other listener calls appear to work fine. Just not listener.statusTransferring(); or listener.transferUpdate(); which utilise the fos. Any help will be greatly appreciated. Also for your own sanity I am a self taught google programmer. Yep the worst kind I am sure. Thanks in advance.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at net.thebowdens.net.FileReceiver.transfer(FileReceiver.java:185)
at net.thebowdens.net.DefaultMessageResponder.fileSend(DefaultMessageResponder.java:543)
public boolean transfer() {
listener.statusConnecting();
received = false;
cancel = false;
try {
if (sSock != null) {
sock = sSock.accept();
listener.statusTransferring();
Platform.runLater(() ->{
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
is = sock.getInputStream();
final byte[] b = new byte[1024];
transferred = 0;
percent = 0;
int tmpTransferred = 0;
int tmpPercent = 0;
int transCounter = 0;
bCounter.prepare();
while (!cancel && (tmpTransferred = is.read(b)) != -1) {
fos.write(b, 0, tmpTransferred);
transferred += tmpTransferred;
percent = (int) ((transferred * 100) / size);
bCounter.addBytes(tmpTransferred);
transCounter++;
if (percent > tmpPercent || transCounter >= 250) {
transCounter = 0;
tmpPercent = percent;
listener.transferUpdate();
}
}
if (!cancel && transferred == size) {
received = true;
listener.statusCompleted();
}
else {
listener.statusFailed();
}
}
}
catch (final IOException e) {
LOG.log(Level.SEVERE, e.toString());
listener.statusFailed();
}
finally {
stopReceiver();
cleanupConnections();
}
return received;
}
Keep in mind that you should use Platform.runLater only for updating the UI, everything else should be outside it otherwhise the UI will become unresponsive.
I suggest you to to refactor your code according to this.
Well after much discussion over the correct language and other issues I solved my problem of the UI updating. I had two issues. My choice selector and Filechooser methods were not on the Javafx application thread (hope this is the right terminology) so I had to do the following:
private ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
#Override
public void run() {
Platform.runLater(() -> {
try {
receiveRequest(tmpUser, fileRes, user, fileName, size, fileHash);
} catch (IOException | ServerException | CommandException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
});
I then had to do the same within the Filechooser and file accept method for the transfer class UI to update
executorService.execute(new Runnable() {
#Override public void run() {
if (fileRes.transfer()) {
ui.showSystemMessage("Successfully received " + fileName +
" from " + user + ", and saved as " + fileRes.getFile().getName());
}
else {
ui.showSystemMessage("Failed to receive " + fileName + " from " + user);
fileRes.cancel();
}
}
});
}
I'm working on a simple multi-staged registration page for a site I'm building, and I give the user the choice of choosing programs/programming languages he knows using checkboxes:
but when I hit the "next" button, in order to go to the next stage, the checkbox I checked isn't set to true, but checkbox no. 18 is set to true(although I didn't check it)
I'm certain it has something to do with the stage before this one, in which I'm building dynamically radio buttons in which the user is choosing his profession (such as Artist, singer and etc').
there are 17 radio buttons, and they are somehow interfering with the next stage, in which the checkbox's checked values are only starting from checkbox no. 18 as I mentioned earlier.
here is some of the code:
else if (int.Parse(ViewState["DivID"].ToString()) == 2)
{
// save the Birthday Date, Language and country of the user.
ViewState["year"] = int.Parse(DropDownYear.SelectedValue);
ViewState["month"] = int.Parse(DropDownMonth.SelectedValue);
ViewState["day"] = int.Parse(DropDownDay.SelectedValue);
ViewState["Language"] = int.Parse(langDropDown.SelectedValue);
ViewState["Country"] = int.Parse(CountryDropDown.SelectedValue);
// ---------------------------------------------
// change from part 2 of the registration to part 3
registrationP2.Visible = false;
BindProfessions(radios, Page);
registrationP3.Visible = true;
radios.Visible = true;
}
else if (int.Parse(ViewState["DivID"].ToString()) == 3)
{
// change from part 3 of the registration to part 4
ViewState["Profid"] = CheckRadio(radios);
registrationP3.Visible = false;
BindKnowledge(CheckboxCon, Page);
registrationP4.Visible = true;
CheckboxCon.Visible = true;
// ---------------------------------------------
//next.Visible = true;
}
else if(int.Parse(ViewState["DivID"].ToString()) == 4)
{
List<int> v = GetCheckBox(CheckboxCon);
ViewState["Knowids"] = GetCheckBox(CheckboxCon);
}
Binding methods:
public static void BindProfessions(HtmlControl ctrl, Page thispage)
{
List<Profession> Plist = Profession.GetProfessionList();
foreach (Profession p in Plist)
{
HtmlInputRadioButton rd_button = new HtmlInputRadioButton();
const string GROUP_NAME = "Professions";
rd_button.Name = GROUP_NAME;
string LinkID = "P" + p.ProfessionID.ToString();
rd_button.Attributes["id"] = LinkID;
RegisterUserControl userprofession = (RegisterUserControl)thispage.LoadControl("~/RegisterUserControl.ascx");
userprofession.imgP = p.ProfPath;
userprofession.fieldName = p.ProfName;
userprofession.IDnum = p.ProfessionID;
userprofession.RadioName = LinkID;
userprofession.EnableViewState = false;
rd_button.EnableViewState = false;
ctrl.Controls.Add(rd_button);
rd_button.Value = p.ProfessionID.ToString();
ctrl.Controls.Add(userprofession);
}
}
public static void BindKnowledge(HtmlControl ctrl, Page thispage)
{
List<Knowledge> Plist = Knowledge.RetKnowledgeList();
foreach (Knowledge p in Plist)
{
HtmlInputCheckBox rd_button = new HtmlInputCheckBox();
const string GROUP_NAME = "knowledge";
rd_button.Name = GROUP_NAME;
string LinkID = "Know" + p.ProgramID.ToString();
rd_button.Attributes["id"] = LinkID;
rd_button.Value = p.ProgramID.ToString();
RegisterUserControl userprofession = (RegisterUserControl)thispage.LoadControl("~/RegisterUserControl.ascx");
userprofession.imgP = p.ProgPath;
userprofession.fieldName = p.PName;
userprofession.IDnum = p.ProgramID;
userprofession.RadioName = LinkID;
userprofession.EnableViewState = false;
rd_button.EnableViewState = false;
ctrl.Controls.Add(rd_button);
ctrl.Controls.Add(userprofession);
}
}
checking methods for both radios and checkbox :
public static int CheckRadio(HtmlControl ctrl)
{
try
{
int counter = 0;
int id = -1;
foreach (Control rdButton in ctrl.Controls)
{
if (rdButton is HtmlInputRadioButton)
{
HtmlInputRadioButton bu = (HtmlInputRadioButton)rdButton;
if (bu.Checked)
{
counter++;
id = int.Parse(bu.Value);
}
}
}
if (counter > 1)
{
return -1;
}
return id;
}
catch (Exception e)
{
return -1;
}
}
public static List<int> GetCheckBox(HtmlControl ctrl)
{
List<int> id_list = new List<int>();
foreach (Control rdButton in ctrl.Controls)
{
if (rdButton is HtmlInputCheckBox)
{
HtmlInputCheckBox bu = (HtmlInputCheckBox)rdButton;
if (bu.Checked)
{
id_list.Add(int.Parse(bu.Value));
}
}
}
return id_list;
}
}
when debugging you can see, that if I choose the first 3 professions, the values returned to me in the List<int> v are 18, 19, and 20
photo: debugging photo
I should mention that after I create the dynamic usercontrols and checkbox/radion buttons, I'm creating them again at postback in protected void Page_Load.
I'm stuck on this for days, and I don't know from where the problem emanates, is it because of ViewState, or the way I'm creating the controls... I really don't know.
Thanks in advance, Idan.
edit:
I played with it a bit, and have found out that when I disable the Binding of the professions which I have initiated earlier in Page_load it does work correctly, page load code look at the second if statement :
protected void Page_Load(object sender, EventArgs e)
{
IsPageRefresh = false;
if (!IsPostBack)
{
ViewState["DivID"] = 1;
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"].ToString();
}
if (int.Parse(ViewState["DivID"].ToString()) == 3)
{
//BindProfessions(radios, Page);
}
else if(int.Parse(ViewState["DivID"].ToString()) == 4)
{
BindKnowledge(CheckboxCon, Page);
}
}
the problem is that I still need to initiate it again after hitting the button in order to get the checked value, how can I fix this thing, and why this is happening? your help would very much be appreciated.
The problem happens because the page recognize that I added 17 new checkbox's, and than when I go over them the first 17 are not checked until the 18'th(the first one of the ones that I checked) what ends up not checking the right checkbox....
And to make it clears I add the other radio buttons to a different div on the page, I don't know what is happening here
for anyone who has the same problem.
I ended up creating the object in Page_PreInit() and it solved the problem, it is recommended(by things I read) to create dynamic objects in Page_PreInit, before anything else is happening to the page.
protected void Page_PreInit(object sender, EventArgs e)
{
try
{
if (!IsPostBack && Session["DivID"] == null)
{
Session["DivID"] = 1;
}
if ((int)Session["DivID"] == 3)
{
InitBindProfessions(Page);
}
else if ((int)Session["DivID"] == 4)
{
InitBindKnowledge(Page);
}
}
catch
{
Response.Redirect("HomePage.aspx");
}
}
InitBindKnowledge and InitBindProfessions are just like BindKnowledge and BindProfession but without adding usercontrols to the control tree
i have a very large database of images from the web which i am categorizing (downloaded locally).
so i have a website (locally) to do this, but the db queries were taking long, so i got an idea to "preload" the next page, so that only the very first load of the page would be slow. I save the list of items loaded in a seperate thread in session. So far so good.
I wanted to optimize further, and did some testing on what took the longest, and loading the images to check the size to see if i needed to scale them (set image height and width on the img obj) - so i wanted to do this with a parallel.foreach loop - but after doing this, my buttons on the page stopped responding? i can see the page runs through the page_load event when i press a button, but it doesn't reach the buttons "code":
protected virtual void btnSaveFollowPosts_Click(object sender, EventArgs e)
{...}
any take on what i am doing wrong? i have tried to limit the degree of paralellelism to 1 just to see if that would fix it - but it did not.
Update - code:
trying to boil it down:
protected void Page_Load(object sender, EventArgs e)
{
Search(false);
}
protected void Search(bool updateCounters)
{
if (Session[SessionItems] == null)
{
if (Session[SessionItemsCache] == null)
{
//if is being constructed, wait, else construct
//if construction is not running
if (Session[SessionCacheConstructionRunning] == null)
{
StartPreLoadContent();
}
while (Session[SessionCacheConstructionRunning] != null)
{
Thread.Sleep(25); //block main thread untill items ready
}
}
List<ContentView> contentViewList = Session[SessionItemsCache] as List<ContentView>;
Session[SessionItemsCache] = null; //clean preload cache
Session[SessionItems] = contentViewList; //save in current usage storage
Filltable(ref tblContent, contentViewList);
//preload next batch
StartPreLoadContent();
}
else
{
List<ContentView> contentViewList = Session[SessionItems] as List<ContentView>; //get items from session
Session[SessionItems] = contentViewList; //save in current usage storage
Filltable(ref tblContent, contentViewList);
}
}
protected void StartPreLoadContent()
{
Session[SessionCacheConstructionRunning] = true;
//start task
Thread obj = new Thread(new ThreadStart(RunPreLoadContent));
obj.IsBackground = true;
obj.Start();
}
protected void RunPreLoadContent()
{
using (DBEntities entities = new DBEntities())
{
entities.CommandTimeout = 86400;
IQueryable<ContentView> query = entities.ContentView.Where(some criterias);
List<ContentView> contentViewListCache = query.ToList();
ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 7;
Parallel.ForEach(contentViewListCache, options, content =>
{
try
{
Interlocked.Increment(ref imageSizeCount);
string path = Path.Combine(basePath, content.LocalPath);
int imageSize = 150;
using (System.Drawing.Image realImage = System.Drawing.Image.FromFile(path))
{
double scale = 0;
if (realImage.Height > realImage.Width)
{
scale = (double)realImage.Height / imageSize;
}
else
{
scale = (double)realImage.Width / imageSize;
}
if (scale > 1)
{
content.ImageHeight = (int)((double)realImage.Height / scale);
content.ImageWidth = (int)((double)realImage.Width / scale);
content.ImageScaled = true;
}
content.ShowImage = true;
}
}
catch (Exception)
{
}
});
Session[SessionItemsCache] = contentViewListCache;
Session[SessionCacheConstructionRunning] = null; //cache ready
}
protected virtual void btnSave_Click(object sender, EventArgs e)
{
try
{
//save
...some reading and saving going on here...
//update
Session[SessionItems] = null;
Search(true);
}
catch (Exception error)
{
ShowError(error);
}
}
I agree with a previous comment: you should probably do this logic earlier in the page lifecycle. Consider overriding OnInit and putting it there.
Also, you could try this line of code instead of your current thread code (which is more suited to Windows not Web programming):
using System.Threading.Tasks;
Task.Run(() => { RunPreLoadContent(); });
I have two methods that record audio every 10 minutes, alternating each method, properly recorded during the first 6 or 7 hours, but then I generates large files to twice normal to hear hear bad but only happens with a method other Normal still recording. I use to record WaveInEnvent since the method is inside a thread, I think problem is in OnDataAvailable.
Here the code used:
wavein = new WaveInEvent();
wavein.Dispose();
wavein.DeviceNumber = 0;
wavein.NumberOfBuffers = 11;
wavein.BufferMilliseconds = 1000;
wavein.WaveFormat = new WaveFormat(8000, 16, 2);
wavein.DataAvailable += OnDataAvailable;
wavein.RecordingStopped += OnRecordingStopped;
writer = new WaveFileWriter(outfilename, wavein.WaveFormat);
bufferedWaveProvider = new BufferedWaveProvider(wavein.WaveFormat);
bufferedWaveProvider.DiscardOnBufferOverflow = true;
wavein.StartRecording();
private void OnDataAvailable(object sender, WaveInEventArgs e)
{
if (this.InvokeRequired)
{
//Debug.WriteLine("Data Available");
this.BeginInvoke(new EventHandler<WaveInEventArgs>(OnDataAvailable), sender, e);
}
else
{
if (writer != null)
{
try
{
for (int i = 0; i < e.BytesRecorded; i += 2)
{
short sample = (short)((e.Buffer[i + 1] << 8) | e.Buffer[i + 0]);
float sample32 = sample / 32768f;
writer.WriteByte(e.Buffer[i + 0]);
writer.WriteByte(e.Buffer[i + 1]);
}
}
catch (Exception ex)
{
// Log error
}
}
}
}
I am trying to download around 1000 images. For that first I am generating random number, converting this text to image. After this on button click, I am downloading this generated image. This is working fine. Now I want to run this loop for 1000 times so that I can download thousand images. The below code works fine when the loop is running once, but when the loop is running 1000 times, its not working as I am expecting.
Also, I want to change the destination folder where this images should be downloaded. How can I do that?
Below if I change value of variable i to 1000, the output is not what I am expecting
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1; i++)
{
CallBUttonClick();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var s = GenerateRandomCode();
RandomImage ci = new RandomImage(s.ToString(), 300, 75);
this.Response.Clear();
this.Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=downloadedFile.JPG");
ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
ci.Dispose();
}
protected void CallBUttonClick()
{
Button1_Click(Button1, null);
}
private string GenerateRandomCode()
{
Random r = new Random();
string s = "";
for (int j = 0; j < 5; j++)
{
int i = r.Next(3);
int ch;
switch (i)
{
case 1:
ch = r.Next(0, 9);
s = s + ch.ToString();
break;
case 2:
ch = r.Next(65, 90);
s = s + Convert.ToChar(ch).ToString();
break;
case 3:
ch = r.Next(97, 122);
s = s + Convert.ToChar(ch).ToString();
break;
default:
ch = r.Next(97, 122);
s = s + Convert.ToChar(ch).ToString();
break;
}
r.NextDouble();
r.Next(100, 1999);
}
return s;
}
}
Adding RandomImage.cs class file
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System;
public class RandomImage
{
//Default Constructor
public RandomImage() { }
//property
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}
//Private variable
private string text;
private int width;
private int height;
private Bitmap image;
private Random random = new Random();
//Methods declaration
public RandomImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
this.image.Dispose();
}
private void SetDimensions(int width, int height)
{
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width,
"Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height,
"Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}
private void GenerateImage()
{
Bitmap bmp = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(bmp);
Font font = new Font(FontFamily.GenericSansSerif, 28);
SizeF stringSize = graphics.MeasureString(this.text, font);
bmp = new Bitmap(bmp, (int)stringSize.Width+30, (int)stringSize.Height+30);
graphics = Graphics.FromImage(bmp);
graphics.DrawString(this.text, font, Brushes.White, 0, 0);
font.Dispose();
graphics.Flush();
graphics.Dispose();
this.image = bmp;
}
}
Hi you need to save you bitmap file on physcial folder. I have modified you code. Please see below code
private void GenerateImage()
{
Bitmap bmp = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(bmp);
Font font = new Font(FontFamily.GenericSansSerif, 28);
SizeF stringSize = graphics.MeasureString(this.text, font);
bmp = new Bitmap(bmp, (int)stringSize.Width + 30, (int)stringSize.Height + 30);
graphics = Graphics.FromImage(bmp);
graphics.DrawString(this.text, font, Brushes.White, 0, 0);
font.Dispose();
graphics.Flush();
graphics.Dispose();
bmp.Save("C:\\" + this.text + ".jpg");
this.image = bmp;
}
I have also removed below code from button click and rested, it is working fine.
//this.Response.Clear();
//this.Response.ContentType = "image/jpeg";
//Response.AppendHeader("Content-Disposition", "attachment; filename=downloadedFile.JPG");
//ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
//ci.Dispose();
That's not how the ASP.NET Page Life Cycle works. If you use the Response object to serve a download, you can serve ONE file.
You are approaching the problem from the wrong side; you say "I am trying to download around 1000 images". That is a process on the client side, on the browser if you will.
Yet you are trying to solve this on the server side.
You want 1000 downloads, so you have to initiate 1000 downloads from the client, and let the server side, the one Page you're writing for that, live through that 1000 times.
In other words, you cannot "push download" multiple files from the server, you have to request them one by one.