C# For each line do this: - foreach

I have a background task doing a task, so my GUI doesn't freeze up.
The code is:
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
for (int index = 0; index < this.combos.Length; ++index)
{
string[] strArray = Strings.Split(this.combos[index], ":", -1, CompareMethod.Binary);
string username = strArray[0];
string pass = strArray[1];
//do stuff
and it does a task. The problem is, it only does the task for 1 line of text that is loaded, then it stops. I need to to continue for every line of code.
For instance, I user loads up their order numbers and wants to retrieve the status of every single on. The task is working fine when they press start, but only retrieves status for 1 code, not all of them.
This is how I call it:
private void button4_Click_1(object sender, EventArgs e)
{
thread.RunWorkerAsync();
}

Related

Problem with a task of printing inward triangle with stars

public class TulosteluaLikeABoss {
public static void tulostaTahtia(int maara) {
// part 1
int i = 0;
while (maara >i) {
System.out.print("*");
i++;
}
System.out.println("");
}
public static void tulostaTyhjaa(int maara) {
// part 1.1
int i = 0;
while (maara > i) {
System.out.print(" ");
i++;
}
}
//something is wrong below
public static void tulostaKolmio(int koko) {
// part 2
int j = koko;
int k = 0;
while (koko >= k) {
tulostaTahtia(k);
tulostaTyhjaa(j);
k++;
j = j-1;
}
}
// from here below is irrelevant
public static void jouluKuusi(int korkeus) {
// part 3
}
public static void main(String[] args) {
// Testit eivät katso main-metodia, voit muutella tätä vapaasti.
tulostaKolmio(5);
System.out.println("---");
jouluKuusi(4);
System.out.println("---");
jouluKuusi(10);
}
}
I'm trying to do a Java basics course and the task is to print an inward triangle using stars *
I got my program to print that, but when I try to submit, I get error message saying: When tried to call method tulostaKolmio(1), wrong amount of lines were printed. expected <1> but was <2>. I'm pretty annoyed by this, since I ran the code using tulostaKolmio(1) and the program printed just 1 line that had 1 star like it was supposed to. If the code looks strange it's because this is a 3 part task and I'm only doing the second part.
tulostaKolmio(1) assigns koko the value of 1. The while loop in the method will run (koko + 1) number of times. During the first run in the loop tulostaTahita(0) gets called (since k=0 right now), altough it will not print any starts at this call it will print a new line because you have that outside the while loop in the tulostaTahita method.
During the second run in the loop, k=1 and thus tulostaTahita(1) is called. This will print another line so in the end you are left with 2 lines (where the first one is empty).
To solve this you want to add an if statement to make sure tulostaTahita only prints a new line when maara is greater than 0.

Move Focus is not working properly on List Field

I am working on ListView section, in this, the user can search the content by name and directly move at the first element of List via pressing a keyboard button. Like, if you press button B from (right vertical manager) it will scroll the list and move focus to first record of B.
The code is working fine in simulator but it's not working on Touch device - I have BB 9380 Curve.
here is the code for :
LabelField a = new LabelField("A" , FOCUSABLE)
{
protected void paint(Graphics graphics)
{
graphics.setColor(0xC4C4C4);
super.paint(graphics);
}
protected boolean navigationClick(int status, int time)
{
//fieldChangeNotify(1);
injectKey(Characters.LATIN_CAPITAL_LETTER_A);
injectKey(Characters.LATIN_CAPITAL_LETTER_A);
return true;
}
};
private void injectKey(char key)
{
try
{
searchList.setFocus();
KeyEvent inject = new KeyEvent(KeyEvent.KEY_DOWN, key, 0);
inject.post();
/*inject.post();*/
} catch (Exception e) {
Log.d("In injectKey :: :: :: "+e.toString());
MessageScreen.msgDialog("In Inject Key "+e.toString());
}
}
Alternate Solution
I would recommend a different strategy for this. Instead of trying to simulate key press events, I would define one method that handles a keypress of a certain letter, or a touch click on that same letter's LabelField.
Source: blackberry.com
So, you can have code that handles key presses by using
protected boolean keyChar( char character, int status, int time )
{
// you might only want to do this for the FIRST letter entered,
// but it sounds like you already have the keypress handling
// the way you want it ...
if( CharacterUtilities.isLetter(character) )
{
selectLetter(character);
return true;
}
return super.keyChar( character, status, time );
}
and then also handle touch events:
LabelField a = new LabelField("A" , FOCUSABLE)
{
protected void paint(Graphics graphics)
{
graphics.setColor(0xC4C4C4);
super.paint(graphics);
}
protected boolean navigationClick(int status, int time)
{
char letter = getText().charAt(0);
selectLetter(letter);
return true;
}
};
then, simply define a method that takes in one character, and scrolls to the start of that part of the list:
private void selectLetter(char letter);
Key Injection
If you really, really want to simulate key presses, though, you might try changing the code so that it injects two events: key down, and then key up (you're currently injecting two key down events). This might be causing problems.
injectKey(Characters.LATIN_CAPITAL_LETTER_A, true);
injectKey(Characters.LATIN_CAPITAL_LETTER_A, false);
with
private void injectKey(char key, boolean down)
{
try
{
searchList.setFocus();
int event = down ? KeyEvent.KEY_DOWN : KeyEvent.KEY_UP;
KeyEvent inject = new KeyEvent(event, key, 0);
inject.post();
} catch (Exception e) { /** code removed for clarity **/
}
}
Additional Note
For UIs, I like to trigger events on the key up, or unclick events. I think this makes a better experience for the user. So, you could replace keyChar() with keyUp() and navigationClick() with navigationUnclick() if you want to do this.

c# drop down list selected count

yesterday i asked one question and got the answer from our friend here, and i ran successfully, also it have one problem with it. "Yester day My question is, when we selecting the drop down list then it should be shown by a label as "1" at very first time, again it'll be increas by selection", this is what the answer i got..,
static int count = 0;
private void bind()
{
ArrayList ar = new ArrayList();
ar.Add("first");
ar.Add("Second");
ar.Add("Third");
ar.Add("Four");
ar.Add("Five");
ar.Add("Six");
ar.Add("Seven");
CCddl.DataSource = ar;
CCddl.DataBind();
}
protected void CCddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (count == 0) count = 1;
Label12.Text = count++.ToString();
}
this code worked, but once the running window getting closed, then it lose the continuation, i mean again application getting run it'll shown again "1". But exactly what i want is, the number continuation should be end when the system day has change.
Try using the Application Settings feature. I added two user settings CountDate and Count in the Project->Property's->Settings and changed your SelectedIndexChangedEvent to
protected void CCddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (count == 0) count = 1;
Label12.Text = count++.ToString();
Properties.Settings.Default.CountDate = DateTime.Now.Date;
Properties.Settings.Default.Count = count;
Properties.Settings.Default.Save();
}
And right before you call your Bind Method during your form initialization put something like this.
if(Properties.Settings.Default.CountDate.Date != DateTime.Now.Date)
{
Properties.Settings.Default.Count = 0;
Properties.Settings.Default.CountDate = DateTime.Now.Date;
Properties.Settings.Default.Save();
}
else
count = Properties.Settings.Default.Count;
bind();
Added the Property Settings Image
You should somehow store the value in a database or something. With the date value. Then when the datechanges you just reset the value.

Custom XNA Game loop in Windows

I'm trying to figure out how to manage the whole game loop manually in a Windows game, without using the regular Game Microsoft.Xna.Framework.Game class.
The reason for this is using the regular Game class causes some stuttering in my game. Not much, but because of the specific nature of the game it is still quite visible.
After trying a bunch of different settings (vsync, fixedtimestep, various framerates etc.) I decided to try write my own Game class to have full control of the timing. I am not sure that will fix it, but at least this way I have full control.
Basically I need to:
Set up the game window
In a loop: Do all rendering as usual, and then flush the result to the screen, manage backbuffers etc.
Anyone knows how to do this? It sounds quite easy in fact, but could not find any documentation on how to do it.
Not sure what I am doing wrong, but I have the following code (just for testing, timing will be handled differently), and the loop will run for a little while then stop. Once I pass my mousepointer over the window the loop will run for a little while again.
private void Application_Idle(object pSender, EventArgs pEventArgs)
{
Thread.Sleep(500);
//Message message;
//while (!PeekMessage(out message, IntPtr.Zero, 0, 0, 0))
{
gametime.update();
Update(gametime);
Draw(gametime);
GraphicsDevice.Present();
}
}
If enabling the "while PeekMessage", the loop will run continuously, but ignoring the sleep and also stopping when the mouse is moving over the window. Not sure what is going on here...
I think optimally I would just want to do something simple like this in the main render loop:
while (alive)
{
Thread.Sleep(100);
gametime.update();
Update(gametime);
Draw(gametime);
GraphicsDevice.Present();
}
But in this case the window remains blank, as it seems the window is not actually being redrawn with the new content. I tried a form.Refresh(), but still no go... Any ideas?
(added xbox information)
for windows you Basically need to create a Form and Show it, then store its handle and the form itself.
Using this handle you can create a GraphicsDevice.
Then you hook Application.Idle to your own function that calls your update and render.
For example
public class MyGame
{
public Form form;
public GraphicsDevice GraphicsDevice;
public MyGame()
{
form = new Form();
form.ClientSize = new Size(1280, 1024);
form.MainMenuStrip = null;
form.Show();
}
public void Run()
{
PresentationParameters pp = new PresentationParameters();
pp.DeviceWindowHandle = form.Handle;
pp.BackBufferFormat = SurfaceFormat.Color;
pp.BackBufferWidth = 1280;
pp.BackBufferHeight = 1024;
pp.RenderTargetUsage = RenderTargetUsage.DiscardContents;
pp.IsFullScreen = false;
pp.MultiSampleCount = 16;
pp.DepthStencilFormat = DepthFormat.Depth24Stencil8;
GraphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter,
GraphicsProfile.HiDef,
pp);
Application.Idle += new EventHandler(Application_Idle);
Application.Run(form);
}
private void Application_Idle(object pSender, EventArgs pEventArgs)
{
Message message;
while (!PeekMessage(out message, IntPtr.Zero, 0, 0, 0))
{
/* Your logic goes here
Custom timing and so on
Update();
Render();
*/
}
}
void Render()
{
GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.Black, 1, 0);
//Your logic here.
GraphicsDevice.Present();
}
[StructLayout(LayoutKind.Sequential)]
private struct Message
{
public IntPtr hWnd;
public int msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public Point p;
}
[return: MarshalAs(UnmanagedType.Bool)]
[SuppressUnmanagedCodeSecurity, DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint
messageFilterMin, uint messageFilterMax, uint flags);
}
EDIT 1
For xbox you may just be able to place your own custom run function with your game loop in a throttled while true loop. Inside that run outside the top of the while true you will probably have to do the graphics device initialization and verification with IntPtr.Zero as your handle
EDIT 2
i use something like this ( got from http://www.koonsolo.com/news/dewitters-gameloop/ )
private long nextGameTick;
private Stopwatch stopwatch;
const int ticksPerSecond = 60;
const int skipTicks = 1000 / ticksPerSecond;
private const int maxSkip = 10;
`constructor
stopwatch = Stopwatch.StartNew();
nextGameTick = stopwatch.ElapsedMilliseconds;
`loop
int loops = 0;
long currentTick = stopwatch.ElapsedMilliseconds;
while ( (ulong)(currentTick - nextGameTick) > skipTicks && loops < maxSkip)
{
Update(16.667f);
nextGameTick += skipTicks;
loops++;
}
PreRender();
Render();
PostRender();
EDIT 3
Creating a content manager was a little more work, but still managable. You need to create a class that implements IServiceProvider. This class takes a GraphicsDevice in its constructor in order to create the next class the implements IGraphicsDeviceProvider. in addition I implement GetService like this
//in implementer of IServiceProvider
public object GetService ( Type serviceType )
{
if ( serviceType == typeof ( IGraphicsDeviceService ) )
{
return myGraphicsService;
}
return null;
}
For convenience i also add a method to the class to create and return managers
//in implementer of IServiceProvider
public ContentManager CreateContentManager( string sPath )
{
ContentManager content = new ContentManager(this);
content.RootDirectory = sPath;
return content;
}
In addition i create a class that implements IGraphicsDeviceService and takes a reference to my GraphicsDevice. then I create a property and field in it like so
//in implementer of IGraphicsDeviceService
private GraphicsDevice graphicsDevice;
public GraphicsDevice GraphicsDevice
{
get
{
return graphicsDevice;
}
}
So the call ends up being somehting like
MyServiceProvider m = new MyServiceProvider(graphicsDevice);
ContentManager content = m.CreateContentManager("Content");
where
MyServiceProvider(GraphicsDevice graphicsDevice)
{
myGraphicsService = new MyGraphicsDeviceService(graphicsDevice);
}
MyGraphicsDeviceService(GraphicsDevice gfxDevice)
{
graphicsDevice = gfxDevice;
}
-Sorry for fragmenting the code around but its not something i wrote too recently so im having difficulty remembering parts.
EDIT 4
i had an odd case with my custom game i just remembered when i new the Form for it i
had to bind
private void IgnoreAlt(object pSender, KeyEventArgs pEventArgs)
{
if (pEventArgs.Alt && pEventArgs.KeyCode != Keys.F4)
pEventArgs.Handled = true;
}
to
form.KeyUp += IgnoreAlt;
form.KeyDown += IgnoreAlt;
otherwise i got some horrible stalls.

Problem while adding a new value to a hashtable when it is enumerated

`hi
I am doing a simple synchronous socket programming,in which i employed twothreads
one for accepting the client and put the socket object into a collection,other thread will
loop through the collection and send message to each client through the socket object.
the problem is
1.i connect to clients to the server and start send messages
2.now i want to connect a new client,while doing this i cant update the collection and add
a new client to my hashtable.it raises an exception "collection modified .Enumeration operation may not execute"
how to add a NEW value without having problems in a hashtable.
private void Listen()
{
try
{
//lblStatus.Text = "Server Started Listening";
while (true)
{
Socket ReceiveSock = ServerSock.Accept();
//keys.Clear();
ConnectedClients = new ListViewItem();
ConnectedClients.Text = ReceiveSock.RemoteEndPoint.ToString();
ConnectedClients.SubItems.Add("Connected");
ConnectedList.Items.Add(ConnectedClients);
ClientTable.Add(ReceiveSock.RemoteEndPoint.ToString(), ReceiveSock);
//foreach (System.Collections.DictionaryEntry de in ClientTable)
//{
// keys.Add(de.Key.ToString());
//}
//ClientTab.Add(
//keys.Add(
}
//lblStatus.Text = "Client Connected Successfully.";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_receive_Click(object sender, EventArgs e)
{
Thread receiveThread = new Thread(new ThreadStart(Receive));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void Receive()
{
while (true)
{
//lblMsg.Text = "";
byte[] Byt = new byte[2048];
//ReceiveSock.Receive(Byt);
lblMsg.Text = Encoding.ASCII.GetString(Byt);
}
}
private void btn_Send_Click(object sender, EventArgs e)
{
Thread SendThread = new Thread(new ThreadStart(SendMsg));
SendThread.IsBackground = true;
SendThread.Start();
}
private void btnlist_Click(object sender, EventArgs e)
{
//Thread ListThread = new Thread(new ThreadStart(Configure));
//ListThread.IsBackground = true;
//ListThread.Start();
}
private void SendMsg()
{
while (true)
{
try
{
foreach (object SockObj in ClientTable.Keys)
{
byte[] Tosend = new byte[2048];
Socket s = (Socket)ClientTable[SockObj];
Tosend = Encoding.ASCII.GetBytes("FirstValue&" + GenerateRandom.Next(6, 10).ToString());
s.Send(Tosend);
//ReceiveSock.Send(Tosend);
Thread.Sleep(300);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
You simply can't modify a Hashtable, Dictionary, List or anything similar while you're iterating over it - whether in the same thread or a different one. There are concurrent collections in .NET 4 which allow this, but I'm assuming you're not using .NET 4. (Out of interest, why are you still using Hashtable rather than a generic Dictionary?)
You also shouldn't be modifying a Hashtable from one thread while reading from it in another thread without any synchronization.
The simplest way to fix this is:
Create a new readonly variable used for locking
Obtain the lock before you add to the Hashtable:
lock (tableLock)
{
ClientTable.Add(ReceiveSock.RemoteEndPoint.ToString(), ReceiveSock);
}
When you want to iterate, create a new copy of the data in the Hashtable within a lock
Iterate over the copy instead of the original table
Do you definitely even need a Hashtable here? It looks to me like a simple List<T> or ArrayList would be okay, where each entry was either the socket or possibly a custom type containing the socket and whatever other information you need. You don't appear to be doing arbitrary lookups on the table.
Yes. Don't do that.
The bigger problem here is unsafe multi-threading.
The most basic "answer" is just to say: use a synchronization lock on the shared object. However this hides a number of important aspects (like understanding what is happening) and isn't a real solution to this problem in my mind.

Resources