Background work completed never fired - c#

After background process DoWork() the control is exit from the block but it never fire a RunWorkerCompleted() and one more thing is isBusy is still true
Please help me
Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
{
sendFile.Send();
}));
This is my FileReadWrite.cs file
Whenever I used this file in xaml class file it worked but there I am using Dispatcher in DispatcherObject class from WindowBase.dll but in another .cs file I can't use that DispatcherObject class that's why I am using Dispatcher.CurrentDispatcher.Invoke()
public class FileReadWrite
{
public int SourceId;
public int DestinationId;
public string FileName;
public WebSocket WebSocket;
public int SplitSize;
public int ReferenceId;
BinaryWriter _binaryWriter;
public int _totalsequence = 0;
public int progvalue;
public static double totallength;
public static double calculate, sendlen;
public static int post;
public double calc, count, len, sentsize;
public static int FileSendCount = 0;
public static List<byte[]> FileList = new List<byte[]>();
public BackgroundWorker _worker = new BackgroundWorker();
public FileReadWrite()
{
_worker.DoWork += _worker_DoWork;
_worker.RunWorkerCompleted += _worker_RunWorkerCompleted;
}
void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
FileCloseMessage fileclosemsg = new FileCloseMessage();
fileclosemsg.Source = SourceId;
fileclosemsg.Destination = DestinationId;
fileclosemsg.Date = DateTime.Now;
fileclosemsg.Sequenceno = 0;
fileclosemsg.totalsequence = _totalsequence;
byte[] bytess = fileclosemsg.GetBytes();
FileList.Add(bytess);
}
void _worker_DoWork(object sender, DoWorkEventArgs e)
{
using (BinaryReader b = new BinaryReader(File.Open(FileName, FileMode.Open)))
{
int pos = 0;
int length = (int)b.BaseStream.Length;
totallength = Convert.ToDouble(length);
byte[] bytes = new byte[SplitSize];
while (pos < length)
{
if (pos + SplitSize > length)
{
bytes = new byte[length - pos];
}
len = Convert.ToDouble(length);
bytes = b.ReadBytes(bytes.Length);
FileContentMesssage fileContentMesssage = new FileContentMesssage();
fileContentMesssage.Content = bytes;
fileContentMesssage.ReferenceId = ReferenceId;
pos += SplitSize;
fileContentMesssage.SequenceNo = pos / SplitSize;
_totalsequence++;
byte[] filebytes = fileContentMesssage.GetBytes();
FileList.Add(filebytes);
}
}
}
public async void Send()
{
_worker.RunWorkerAsync();
}
public void FileReceive(byte[] bytes)
{
try
{
if (_binaryWriter != null)
_binaryWriter.Write(bytes);
}
catch (Exception ex)
{
}
}
public string FileCreate()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string filename = Path.GetFileName(FileName);
string fullfilename = string.Format("{0}{1}", path, filename);
_binaryWriter = new BinaryWriter(File.Open(fullfilename, FileMode.Create));
return (fullfilename);
}
public void FileClose()
{
_binaryWriter.Close();
}
public byte[] FileSend()
{
byte[] bytess = FileList[FileSendCount];
FileSendCount++;
return (bytess);
}
public void FileClosed()
{
FileSendCount = 0;
FileList.Clear();
post = 0;
sendlen = 0;
calculate = 0;
totallength = 0;
_totalsequence = 0;
}
}

Related

Why isn't it possible to read my byteBuffer String out?(c#)

I wrote a basic server client program with c# and Unity to create my own network. During the process I wrote a byteBuffer to send data over the network. Everything works, but to send or receive the String. (I can send Integers and other dataforms succesfully).
My DLL file:
public class ByteBuffer : IDisposable
{
private List<byte> Buff;
private byte[] readBuff;
private int readpos;
private bool buffUpdated;
private bool disposedValue;
#region "Helpers"
public ByteBuffer()
{
this.buffUpdated = false;
this.disposedValue = false;
this.Buff = new List<byte>();
this.readpos = 0;
}
public long GetReadPos() =>
((long)this.readpos);
public byte[] ToArray() =>
this.Buff.ToArray();
public int Count() =>
this.Buff.Count;
public int Length() =>
(this.Count() - this.readpos);
public void Clear()
{
this.Buff.Clear();
this.readpos = 0;
}
#endregion
#region"Write Data"
public void WriteByte(byte Inputs)
{
Buff.Add(Inputs);
buffUpdated = true;
}
public void WriteBytes(byte[] Input)
{
this.Buff.AddRange(Input);
this.buffUpdated = true;
}
public void WriteInteger(int Input)
{
this.Buff.AddRange(BitConverter.GetBytes(Input));
this.buffUpdated = true;
}
public void WriteString(string Input)
{
this.Buff.AddRange(BitConverter.GetBytes(Input.Length));
this.Buff.AddRange(Encoding.ASCII.GetBytes(Input));
this.buffUpdated = true;
}
#endregion
#region "read Data"
public string ReadString(bool Peek = true)
{
int count = this.ReadInteger(true);
if (this.buffUpdated)
{
this.readBuff = this.Buff.ToArray();
this.buffUpdated = false;
}
string str = Encoding.ASCII.GetString(this.readBuff, this.readpos, count);
if ((Peek & (this.Buff.Count > this.readpos)) && (str.Length > 0))
{
this.readpos += count;
}
return str;
}
public byte ReadByte(bool Peek = true)
{
if (Buff.Count > readpos)
{
if (buffUpdated)
{
readBuff = Buff.ToArray();
buffUpdated = false;
}
byte ret = readBuff[readpos];
if (Peek & Buff.Count > readpos)
{
readpos += 1;
}
return ret;
}
else
{
throw new Exception("Byte Buffer is past its Limit!");
}
}
public byte[] ReadBytes(int Length, bool Peek = true)
{
if (this.buffUpdated)
{
this.readBuff = this.Buff.ToArray();
this.buffUpdated = false;
}
byte[] buffer = this.Buff.GetRange(this.readpos, Length).ToArray();
if (Peek)
{
this.readpos += Length;
}
return buffer;
}
public int ReadInteger(bool peek = true)
{
if (this.Buff.Count <= this.readpos)
{
throw new Exception("Byte Buffer Past Limit!");
}
if (this.buffUpdated)
{
this.readBuff = this.Buff.ToArray();
this.buffUpdated = false;
}
int num = BitConverter.ToInt32(this.readBuff, this.readpos);
if (peek & (this.Buff.Count > this.readpos))
{
this.readpos += 4;
}
return num;
}
#endregion
//IDisposable
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if(disposing)
{
this.Buff.Clear();
}
this.readpos = 0;
}
this.disposedValue = true;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
My SendData Class:
class ServerSendData{
public static ServerSendData instance = new ServerSendData();
public void SendDataToClient(int index, byte[] data)
{
ByteBuffer.ByteBuffer buffer = new ByteBuffer.ByteBuffer();
buffer.WriteBytes(data);
Network.Clients[index].myStream.BeginWrite(buffer.ToArray(), 0, buffer.ToArray().Length, null, null);
buffer = null;
}
public void SendWelcomeMessage(int index)
{
ByteBuffer.ByteBuffer buffer = new ByteBuffer.ByteBuffer();
buffer.WriteInteger(1); //paket nummer 1
buffer.WriteByte(2);
buffer.WriteString("A");
SendDataToClient(index, buffer.ToArray());
}
}
My HandleData Class:
public class ClientHandleData: MonoBehaviour{
public void HandleData(byte[]data)
{
int packetNum;
ByteBuffer.ByteBuffer buffer = new ByteBuffer.ByteBuffer();
buffer.WriteBytes(data);
packetNum = buffer.ReadInteger();
buffer = null;
if (packetNum == 0)
{
return;
}
else
{
HandleMessages(packetNum, data);
}
}
public void HandleMessages(int packetNum, byte[] data)
{
switch (packetNum)
{
case 1:
HandleWelcomeMessage(data);
break;
}
}
public void HandleWelcomeMessage(byte[] data)
{
ByteBuffer.ByteBuffer buffer = new ByteBuffer.ByteBuffer();
buffer.WriteBytes(data);
Debug.Log("Test");
int nummer = buffer.ReadInteger();
Debug.Log("Test1: "+nummer);
byte bt = buffer.ReadByte();
Debug.Log("Test2: " +bt);
message = buffer.ReadString();
Debug.Log("Test3");
Debug.Log(nummer);
Debug.Log(message);
Debug.Log(bt);
buffer = null;
}
}
My Log result looks like:
Test
Test1: 1
Test2: 2
Working with Unity 2018.2.11f1 personal 64 bit

UWP with UDP StreamWriter in OSC format

I have following class take care the udp Sending
public static async Task SendStringUdpAsync(HostName remoteHost,
string remotePort, string message)
{
using (var socket = new DatagramSocket())
{
var stream = (await socket.GetOutputStreamAsync(
remoteHost, remotePort)).AsStreamForWrite();
using (var writer = new StreamWriter(stream))
{
await writer.WriteLineAsync(message.ToString());
await writer.FlushAsync();
}
}
}
But instead send a string, I want to send a custom class in udp
public class OSCString : IOSCValue<string>
{
static int PaddingLength = 4;
public string Contents { get; }
public char TypeTag { get { return 's'; }}
public byte[] Bytes { get; }
public OSCString(string contents)
{
Contents = contents;
Bytes = GetBytes();
}
public byte[] GetBytes()
{
byte[] bytes = new byte[GetByteLength()];
Encoding.ASCII.GetBytes(Contents, 0, Contents.Length, bytes, 0);
return bytes;
}
public int GetByteLength()
{
return GetPaddedLength(Contents.Length);
}
public static int GetPaddedLength(int length)
{
int terminatedLength = length + 1;
int paddedLength = (int)(Math.Ceiling(terminatedLength / (float)PaddingLength) * 4);
return paddedLength;
}
public static OSCString Parse(BinaryReader reader)
{
List<byte> bytes = new List<byte>();
byte current = reader.ReadByte();
while(current != 0)
{
bytes.Add(current);
current = reader.ReadByte();
}
string str = Encoding.ASCII.GetString(bytes.ToArray());
OSCString oscString = new OSCString(str);
int bytesToBurn = oscString.Bytes.Length - bytes.Count - 1;
for(int i = 0; i < bytesToBurn; i++)
{
reader.ReadByte();
}
return oscString;
}
}
I try DataWriter and StreamWrite, dont work too well.
The UWP take out the socket class, is there any Streamwrite can do the job?
I figure this out
var socket = new DatagramSocket();
//socket.MessageReceived += SocketOnMessageReceived;
using (var stream = await socket.GetOutputStreamAsync(remoteHost, remotePort))
{
using (var writer = new DataWriter(stream))
{
// var data = Encoding.UTF8.GetBytes(message);
writer.WriteBytes(packet.Bytes);
writer.StoreAsync();
}
}
Everything works great!!!!!!!!!

Child class can't acess data from parent class

I've got the following code , where i define some operations to be done within a class and its variables:
namespace PPF_Converter_v10
{
public class ProgramStuff
{
protected List<String> OpenedFiles { get; private set; }
protected List<String> ValidFiles { get; private set; }
protected List<String> InvalidFiles { get; private set; }
protected List<String> FileData { get; private set; }
protected string FileContents { get; private set; }
public ProgramStuff()
{
OpenedFiles = new List<string>();
ValidFiles = new List<string>();
InvalidFiles = new List<string>();
FileData = new List<string>();
FileContents = string.Empty;
}
public void SelectFiles()
{
using (var FileSelect = new OpenFileDialog())
{
FileSelect.Multiselect = true;
FileSelect.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
FileSelect.Filter = "PPF Files (*.ppf)|*.ppf|CIP Files (*.cip)|*.cip";
FileSelect.Title = "Seclect a PPF or CIP File";
DialogResult dr = FileSelect.ShowDialog();
if (dr == DialogResult.OK)
{
foreach(var File in FileSelect.FileNames)
{
OpenedFiles.Add(File);
}
}
}
}
public void ReadFiles()
{
foreach(var File in OpenedFiles)
{
using (var fs = new FileStream(File, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
FileContents = string.Empty;
var len = (int)fs.Length;
var bits = new byte[len];
fs.Read(bits, 0, len);
// Dump 1024 bytes per line
for (int ix = 0; ix < len; ix += 1024)
{
//drawTextProgressBar(ix, (int)fs.Length);
var cnt = Math.Min(1024, len - ix);
var line = new byte[cnt];
Array.Copy(bits, ix, line, 0, cnt);
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
//Creating a big string with output
FileContents += Encoding.ASCII.GetString(line);
}
FileData.Add(FileContents);
}
}
}
public void FileDefiniton()
{
foreach(var File in FileData)
{
bool b = File.Contains("/HDMZoneCoverageValue") && File.Contains("/CIP3AdmInkColors");
if(b)
{
ValidFiles.Add(File);
}
else
{
InvalidFiles.Add(File);
}
}
}
public string XMLOutputFolder()
{
string XMLOutput = string.Empty;
using (var XMLOut = new FolderBrowserDialog())
{
XMLOut.ShowNewFolderButton = true;
XMLOut.RootFolder = Environment.SpecialFolder.MyComputer;
DialogResult dr = XMLOut.ShowDialog();
if(dr == DialogResult.OK)
{
XMLOutput = XMLOut.SelectedPath;
}
return XMLOutput;
}
}
public void ConvertedPPFFolder(string ConvertedPPF)
{
using (var ConvFolder = new FolderBrowserDialog())
{
ConvFolder.ShowNewFolderButton = true;
ConvFolder.RootFolder = Environment.SpecialFolder.MyComputer;
DialogResult dr = ConvFolder.ShowDialog();
if (dr == DialogResult.OK)
{
ConvertedPPF = ConvFolder.SelectedPath;
}
}
}
}//Closing class ProgramStuff
//Creating a child class called FileManipulation - manipulate files
public class FileManipulation: ProgramStuff
{
protected string PPFColors;
protected string[] ColorsNames;
public void ColorExtraction()
{
MessageBox.Show(ValidFiles.Count.ToString());
foreach (var data in ValidFiles)
{
Regex ColorNameRegex = new Regex("CIP3AdmSeparationNames(.*)CIP3AdmPSExtent");
var RegexAux = ColorNameRegex.Match(data);
PPFColors = RegexAux.Groups[1].ToString();
PPFColors = PPFColors.Replace("] def./", "").Replace("[", "").Replace(" (", "(").Replace("(", "").Replace(")", "|");
PPFColors = PPFColors.Remove(PPFColors.Length - 1, 1);
ColorsNames = PPFColors.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
}
Then, i have my form declaration, where i instantiate both and use them:
public partial class Form1 : Form
{
private FileManipulation FileOp;
private ProgramStuff GetFiles;
public Form1()
{
InitializeComponent();
FileOp = new FileManipulation();
GetFiles = new ProgramStuff();
}
private void button1_Click(object sender, EventArgs e)
{
GetFiles.SelectFiles();
GetFiles.ReadFiles();
GetFiles.FileDefiniton();
}
The question is: i can do all operations i need using the instantiated class ProgramStuff (called GetFiles). But, right here, when i call a method from the child class:
private void button5_Click(object sender, EventArgs e)
{
FileOp.ColorExtraction();
}
I can't acess data stored on the parent class. When debugging, the List called ValidFiles has 0 elements ; and there were elements added to it on the parent class. Is there way for me access those elements ? Thats the main point of my question.
Thanks !
I think the issue you have is that you are instantiating Child and Parent Class:
FileOp = new FileManipulation();
GetFiles = new ProgramStuff();
and you are trying to use data stored in two different objects.
As I see it, you only have to instantiate Child Class:
FileOp = new FileManipulation();
Then you will have to use FileOp on your code calling child and parents methods.
I hope it helps.

ObservableCollection binary serialization and transfer over the network

There is a small problem ka. there is a class
public class PLayer
{
public String Name{get;set;}
public TimeSpan Tax { get; set; }
}
The main form
public partial class MainWindow : Window
{
public ObservableCollection<PLayer> PlayersInGame { get; set; }
public ObservableCollection<PLayer> PlayersInGame2 { get; set; }
public ObservableCollection<PLayer> PlayersOnBench { get; set; }
public MainWindow()
{
PlayersInGame = new ObservableCollection<PLayer>();
PlayersInGame2 = new ObservableCollection<PLayer>();
PlayersOnBench = new ObservableCollection<PLayer>();
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
String vName = "Игрок" + i.ToString();
PlayersInGame.Add(new PLayer { Name = vName, Tax = new TimeSpan(0) });
}
for (int i = 10; i < 20; i++)
{
String vName = "Игрок" + i.ToString();
PlayersInGame2.Add(new PLayer { Name = vName, Tax = new TimeSpan(0) });
}
Game.Items.Refresh();
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
if (Game.SelectedIndex > -1)
{
var temp = PlayersInGame[Game.SelectedIndex];
//PlayersInGame.RemoveAt(Game.SelectedIndex);
temp.Tax = new TimeSpan(0, 0, 5);
PlayersOnBench.Add(temp);
Game.Items.Refresh();
Bench.Items.Refresh();
}
if (Game2.SelectedIndex > -1)
{
var temp = PlayersInGame2[Game2.SelectedIndex];
//PlayersInGame2.RemoveAt(Game2.SelectedIndex);
temp.Tax = new TimeSpan(0, 0, 5);
PlayersOnBench.Add(temp);
Game2.Items.Refresh();
Bench.Items.Refresh();
}
}
private void timer_Tick(object sender, EventArgs e)
{
foreach (var x in PlayersOnBench)
{
x.Tax -= new TimeSpan(0, 0, 1);
}
List<int> Temp = new List<int>();
for (var i = 0; i < PlayersOnBench.Count; i++)
{
if (PlayersOnBench[i].Tax == TimeSpan.Zero)
{
Temp.Add(i);
}
}
for (int i = Temp.Count - 1; i >= 0; i--)
{
var s = PlayersOnBench[i];
PlayersOnBench.RemoveAt(Temp[i]);
//PlayersInGame.Add(s);
//Game.Items.Refresh();
}
Bench.Items.Refresh();
}
}
On the main form when you click on the button "Button2_Click" line is added to the ListView "Bench" with the addition of a timer. in the treatment of "timer_Tick" The timer is counting all the lines added to the "Bench". Contact ossushestvlyaetsya a Binding. My question is knowing binary serialization, how to transfer the contents of ListView "Bench" to the server to display in a ListView or ListBox. The binary serialization of the project has been in use for sending text fields.
Your question is kind of unclear on what you trying to achieve. In general, if you using binary serialization, it will convert your objects into byte array, you need to de-serialize inorder to get your object back. Below is a sample
BinaryFormatter m_formatter;
Byte[] m_stateData;
List<T> cloned_objList;
public binaryserializer(List<T> PlayersOnBench)
{
if ((!Object.ReferenceEquals(listToClone, null)) && (typeof(T).IsSerializable))
{
m_formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
try
{
m_formatter.Serialize(stream, PlayersOnBench);
}
catch { }
stream.Seek(0, SeekOrigin.Begin);
m_stateData = stream.ToArray();
}
}
}
public List<T> BenchStates
{
get
{
using (MemoryStream stream = new MemoryStream(m_stateData))
{
try
{
cloned_objList = (List<T>)m_formatter.Deserialize(stream);
}
catch (Exception) { }
}
return cloned_objList;
}
}

C# WaitHandle.WaitAll() is always waiting

Following is my code , the wait all method is always waiting .
class Program
{
static StreamWriter _fileStream;
static void Main(string[] args)
{
_fileStream = File.CreateText(#"C:\Praveen\HelloThread.txt");
List<ManualResetEvent> meList = new List<ManualResetEvent>();
ManualResetEvent currentEvent = new ManualResetEvent(true);
ManualResetEvent nextEvent = new ManualResetEvent(false);
meList.Add(currentEvent);
int length = 10;
Data data = null;
Console.WriteLine("Writing started...");
for (int i = 0; i < length; i++)
{
data = new Data { CurrentEvent = currentEvent, Number = i, NextEvent = nextEvent };
ThreadPool.QueueUserWorkItem(PrintMsg, data);
meList.Add(nextEvent);
currentEvent = nextEvent;
nextEvent = nextEvent = new ManualResetEvent(false);
}
CloseAll(meList);
Console.ReadLine();
}
private static void CloseAll(List<ManualResetEvent> meList)
{
Console.WriteLine("Requested to close all...");
while (WaitHandle.WaitAll(meList.ToArray()))
{
}
Console.WriteLine("Done with the writing...");
}
private static void PrintMsg(object state)
{
Data data = state as Data;
data.CurrentEvent.WaitOne();
string msg = "Hello times...";
for (int j = 0; j < 5; j++)
{
_fileStream.WriteLine(msg + data.Number);
Console.WriteLine(msg + data.Number);
}
data.NextEvent.Set();
}
}
public class Data
{
public ManualResetEvent CurrentEvent { get; set; }
public ManualResetEvent NextEvent { get; set; }
public int Number { get; set; }
}
What's going on , why it's always waiting , any idea ?
You have an infinite loop in your CloseAll method. WaitAll returns true when all events are signaled. You do not need the empty while loop, just add the line:
WaitHandle.WaitAll(meList.ToArray());

Categories

Resources