Libusbdotnet HID Read (Event Driven) Error - hid

I used LibUSbDotNet for read USB data from my Hardware using Event Driven operation. My hardware pumps out data at two different intervals. (2000 ms and 300 ms). The buffer size is 7 bytes.
The code works fine for sometimes afterwards the reading is slowed. instead of 2000 and 300 ms the data receives at 4000 and 2000 ms.
Please help me resolve this issue guys...
regards
John
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LibUsbDotNet;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.Main;
namespace ATE_BackEnd
{
public partial class Main_Form : Form
{
public static IDeviceNotifier UsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier();
UsbDeviceFinder MyUsbFinder;
UsbDevice MyUsbDevice;
UsbEndpointReader EPReader;
UsbEndpointWriter EPWriter;
int bytesWritten;
public DateTime LastDataEventDate = DateTime.Now;
public Main_Form()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
UsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;
}
void OpenUSB(int VendorID, int ProductID)
{
toolStripStatusLabel.Text = "Opening USB";
MyUsbFinder = new UsbDeviceFinder(VendorID, ProductID);
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) { USBConnection_label.Text = "USB Not Connected"; CloseUSB(); }
else
{
USBConnection_label.Text = "USB Connected";
USBInfo_label.Text = "VID = " + MyUsbDevice.Info.Descriptor.VendorID.ToString() +
", PID = " + MyUsbDevice.Info.Descriptor.ProductID.ToString();
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
EPReader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01, 7);
EPWriter = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
EPReader.DataReceived += OnUsbDataReceived;
EPReader.DataReceivedEnabled = true;
}
}
void WriteUSB(int Site)
{
toolStripStatusLabel.Text = "Writing Data...";
ErrorCode ECWriter = EPWriter.Write(Encoding.Default.GetBytes(Site.ToString()), 100, out bytesWritten);
if (ECWriter != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
}
void CloseUSB()
{
toolStripStatusLabel.Text = "Closing USB";
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
EPReader.DataReceived -= OnUsbDataReceived;
EPReader.DataReceivedEnabled = false;
EPReader.Dispose();
EPWriter.Dispose();
}
MyUsbDevice = null;
UsbDevice.Exit();
}
void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
{
toolStripStatusLabel.Text = "Device Notify Message: " + e.EventType.ToString();
if (e.EventType.ToString() == "DeviceRemoveComplete") { USBConnection_label.Text = "USB Disconnected"; CloseUSB(); }
else if (e.EventType.ToString() == "DeviceArrival") { USBConnection_label.Text = "USB Connected"; OpenUSB(4660, 1); }
}
void OnUsbDataReceived(object sender, EndpointDataEventArgs e)
{
toolStripStatusLabel.Text = "Receiving Data!!!";
byte[] s1stat = e.Buffer;
S1SOT_textBox.Text = s1stat[0].ToString();
S2SOT_textBox.Text = s1stat[1].ToString();
S1EOT_textBox.Text = s1stat[2].ToString();
S2EOT_textBox.Text = s1stat[3].ToString();
S1BIN_textBox.Text = s1stat[4].ToString();
S2BIN_textBox.Text = s1stat[5].ToString();
TowerLamp_textBox.Text = s1stat[6].ToString();
Time_label.Text = (DateTime.Now - LastDataEventDate).TotalMilliseconds.ToString();
LastDataEventDate = DateTime.Now;
}
private void Main_Form_FormClosing(object sender, FormClosingEventArgs e)
{
toolStripStatusLabel.Text = "Closing App";
CloseUSB();
}
private void Main_Form_Load(object sender, EventArgs e)
{
toolStripStatusLabel.Text = "Opening App";
OpenUSB(4660, 1);
}
private void Write_button_Click(object sender, EventArgs e)
{
CloseUSB();
OpenUSB(4660, 1);
WriteUSB(Write_comboBox.SelectedIndex+1);
}
}
}

Related

Unity Darkrift2 Game isn't connecting to server from different pc

I am making online multiplayer game with Darkrift2 and with Unity.
I deeply know how to make games but i am new at online part.
I made the game succesfully with LAN.
I done the server side.
But just the game that opened with server can connect.
I am putting the server to my pc and go and open the game in another pc.
It can't connect.
I could definitely make an obvious mistake but IPV4 ADDRESS IS SAME AS PC'S IPV4 ADDRESS AND PORT NO IS SAME ON EVERY PC.
Also there is no firewall ban, Game is opening in another pc's.
By the way probably you don't have to read the whole code, Just the connection part.
Client
NetworkManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DarkRift.Client.Unity;
using DarkRift;
using Tags;
using DarkRift.Client;
using UnityEngine.InputSystem;
using System.Net;
using System.Linq;
public class NetworkManager : MonoBehaviour
{
IPAddress IPv4;
public UnityClient client;
public GameObject Bug;
public Transform[] PlayerBegin;
public Light DirLight;
public List<GameObject> Bugs;
private void Awake()
{
IPv4 = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.First(
f => f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
Debug.Log(IPv4);
client.Connect(IPv4, client.Port, true);
client.MessageReceived += OnMessageReceived;
//DontDestroyOnLoad(gameObject);
}
private void OnDestroy()
{
client.MessageReceived -= OnMessageReceived;
}
public void Interaction(byte Condition)//legdeathi de içine koyunca sorun yaratır mı? sanırım hayır
{
using (DarkRiftWriter writer = DarkRiftWriter.Create())
{
writer.Write(client.ID);
writer.Write(Condition);
using (Message message = Message.Create((ushort)Models.Tags0.InteractionType, writer))
{
client.SendMessage(message, SendMode.Reliable);
}
}
}
public void PosRot(Vector3 Pos, Quaternion Rot, bool ThereIsPos)
{
XYZ Position=null;
if (ThereIsPos)
{
Position = new XYZ();
Position.X = Pos.x;
Position.Y = Pos.y;
Position.Z = Pos.z;
}
XYZ Rotation = new XYZ();
Rotation.X = Rot.x;
Rotation.Y = Rot.y;
Rotation.Z = Rot.z;
float RotW = Rot.w;
using (DarkRiftWriter writer = DarkRiftWriter.Create())
{
writer.Write(client.ID);
var tag = Models.Tags0.Rot;
if (ThereIsPos)
{
tag = Models.Tags0.PosRot;
writer.Write(Position);
}
writer.Write(Rotation);
writer.Write(RotW);
using (Message message = Message.Create((ushort)tag, writer))
{
client.SendMessage(message, SendMode.Unreliable);
}
}
}
public int PlayerId;
public ushort PlayerCount;
private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
using (Message message = e.GetMessage())
{
using (DarkRiftReader reader = message.GetReader())
{
if (message.Tag == (ushort)Models.Tags0.InteractionType)
{
ushort Id = reader.ReadUInt16();
GameObject tarantula = Bugs[Id].transform.GetChild(0).gameObject;
byte Interaction = reader.ReadByte();
Spider s = tarantula.GetComponent<Spider>();
switch (Interaction)
{
case 0: s.Attack(); break;
case 1:
s.DefenceGetBug();
break;
case 2:
s.DefenceOff();
break;
case 3:
s.Death();
break;
case 4:
s.LegsHealthDown();
break;
default:
s.LegHealthDown(s.Legs[Interaction - 5], 3);
break;
}
}
byte ThereIsPos=0;
if(message.Tag == (ushort)Models.Tags0.PosRot)
{
ThereIsPos = 1;
}
else if(message.Tag == (ushort)Models.Tags0.Rot)
{
ThereIsPos = 2;
}
if (ThereIsPos != 0)
{
ushort Id = reader.ReadUInt16();
GameObject tarantula = Bugs[Id].transform.GetChild(0).gameObject;
if (ThereIsPos == 1)
{
XYZ Position = reader.ReadSerializable<XYZ>();
tarantula.transform.position = new Vector3(Position.X, Position.Y, Position.Z);
}
XYZ Rotation = reader.ReadSerializable<XYZ>();
float RotW = reader.ReadSingle();
tarantula.transform.rotation = new Quaternion(Rotation.X, Rotation.Y, Rotation.Z, RotW);
}
if (message.Tag == (ushort)Models.Tags0.NewPlayer)
{
PlayerCount = (ushort)(reader.ReadUInt16() + 1);
//Debug.Log("PlayerCount : " + PlayerCount);
PlayerId = Bugs.Count;//Player No
//Debug.Log("PlayerId : " + PlayerId);
while (PlayerId < PlayerCount)
{
Debug.Log("Player Spawn" + PlayerId);
GameObject bug = Instantiate(Bug, PlayerBegin[PlayerId].position, Quaternion.identity, null);
bug.name = "Bug" + PlayerId;
Spider spider;
spider = bug.GetComponentInChildren<Spider>();
spider.nm = this;
spider.DirLight = DirLight;
//spider.transform.position = PlayerBegin[PlayerId].position;
//PosChange(spider.gameObject.transform.position);
if (client.ID != PlayerId)
{
//spider.enabled = false;
bug.transform.Find("Camera").gameObject.SetActive(false);
bug.transform.Find("CM FreeLook1").gameObject.SetActive(false);
bug.transform.Find("Camera Late").gameObject.SetActive(false);
bug.transform.Find("Canvas").gameObject.SetActive(false);
bug.GetComponentInChildren<PlayerInput>().enabled = false;
}
Bugs.Add(bug);
PlayerId++;
}
}
}
}
}
}
Server code .Net (only the main class):
using System;
using DarkRift.Server;
using DarkRift;
using Tags;
namespace Bug_Wars_Online
{
public class BugWarsOnline : Plugin
{
public override bool ThreadSafe => false;
public override Version Version => new Version(1, 0, 0);
public BugWarsOnline(PluginLoadData pluginLoadData) : base(pluginLoadData)
{
ClientManager.ClientConnected += OnClientConnected;
ClientManager.ClientDisconnected += OnClientDisconnected;
}
private void OnClientConnected(object sender, ClientConnectedEventArgs e)
{
Console.WriteLine("Connected");
e.Client.MessageReceived += OnMessageReceived;
using (DarkRiftWriter writer = DarkRiftWriter.Create())
{
writer.Write(e.Client.ID);
writer.Write(0);
using (Message message = Message.Create((ushort)Models.Tags0.NewPlayer, writer))
{
foreach (IClient client in ClientManager.GetAllClients())
{
//if (client.ID != e.Client.ID)
{
client.SendMessage(message, SendMode.Reliable);
Console.WriteLine("Player" + client.ID + " Connected");
Console.WriteLine("ClientManager.Count" + ClientManager.Count);
}
}
}
}
}
private void OnClientDisconnected(object sender, ClientDisconnectedEventArgs e)
{
Console.WriteLine("Disconnected");
//destroy et!
}
private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
using (Message message = e.GetMessage())
{
if (message.Tag == (ushort)Models.Tags0.PosRot|| message.Tag == (ushort)Models.Tags0.Rot)
{
foreach (IClient client in ClientManager.GetAllClients())
{
if (client.ID != e.Client.ID)
{
client.SendMessage(message, SendMode.Unreliable);
}
}
}
if (message.Tag == (ushort)Models.Tags0.InteractionType)
{
foreach (IClient client in ClientManager.GetAllClients())
{
if (client.ID != e.Client.ID)
{
client.SendMessage(message, SendMode.Reliable);
}
}
}
}
}
}
}
Okay I should have enter the ipv4 address of server’s pc.

Cloud load failed with error code 7 using Unity GoolePlayGames plugin

I get the following log during on-device debugging
Error:
*** [Play Games Plugin DLL] ERROR: Cloud load failed with status code 7
Basically the OnStateLoaded() callback function always returns the boolean success = false and I can't figure out the reason why.
All that the plugin debugging logs mention is "Cloud load failed with status code 7".
According to the android doc, 7 is a generic "developer error", see https://developer.android.com/reference/com/google/android/gms/appstate/AppStateStatusCodes.html#STATUS_DEVELOPER_ERROR
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set
to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID
Created a new project in Unity
Added the play games plugin (Assets/Import Package.../Custom
Package)
Set the application ID (Google Play Games/Android Setup...)
Switched the platform to Android (File/Build Settings...)
Set the player settings (bundle identifier and the keystore info)
Added a new script component to the camera
Saved everything and hit build and run.
Here are the contents:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
void Start () {
slot0 = new GameData(0,"waiting for login....");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.Data =" loading....";
slot0.LoadState();
}
else {
Debug.LogWarning("Authentication failed!");
}
};
// make Play Games the default social implementation
PlayGamesPlatform.Activate();
// enable debug logs
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
protected void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,100);
Rect dataRect = new Rect( 10, 150, Screen.width,100);
Rect b1Rect = new Rect(10, 400, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth,
b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
// logged in, so show the load button and the contents of the saved data.
if(GUI.Button(b1Rect, "Load")) {
slot0.LoadState();
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
// just save a string, incrementing the number on the end.
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
slot0.SaveState();
}
GUI.Label(statusRect, slot0.State);
}
// Class to handle save/load callbacks.
public class GameData : OnStateLoadedListener {
int slot;
string data;
string state;
public GameData(int slot, string data) {
this.slot = slot;
this.data = data;
this.state = "Initialized, modified";
}
public void LoadState() {
this.state += ", loading";
((PlayGamesPlatform)Social.Active).LoadState(0, this);
}
public void SaveState() {
byte[] bytes = new byte[data.Length * sizeof(char)];
System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
this.state += ", saving";
((PlayGamesPlatform) Social.Active).UpdateState(slot, bytes, this);
}
public void OnStateLoaded(bool success, int slot, byte[] data) {
if (success) {
Debug.Log ("Save game slot : " + slot + " loaded: " + data);
if (data != null) {
char[] chars = new char[data.Length / sizeof(char)];
System.Buffer.BlockCopy(data, 0, chars, 0, data.Length);
this.data = new string(chars);
this.state = "loaded";
} else {
Debug.Log ("Saved data is null");
this.data = "";
this.state = "loaded, but empty";
}
} else {
// handle failure
Debug.LogWarning ("Save game slot : " + slot + " failed!: ");
this.data = "";
this.state = "loading failed!";
}
}
public byte[] OnStateConflict(int slot, byte[] local, byte[] server) {
// resolve conflict and return a byte[] representing the
// resolved state.
Debug.LogWarning("Conflict in saved data!");
state = "conflicted";
// merge or resolve using app specific logic, here
byte[] resolved = local.Length > server.Length ? local : server;
char[] chars = new char[resolved.Length / sizeof(char)];
System.Buffer.BlockCopy(resolved, 0, chars, 0, resolved.Length);
this.data = new string(chars);
return resolved;
}
public void OnStateSaved(bool success, int slot) {
Debug.Log ("Save game slot : " + slot + " success: " + success);
state = "saved";
}
public string Data {
get {
return data;
}
set {
data = value;
state += ", modified";
}
}
public int Slot {
get {
return slot;
}
}
public string State {
get {
return state;
}
}
}
}
The error code 7 is because the Cloud Save API has been deprecated and is only currently accessible to existing games that have used the API. The Unity plugin version 0.9.11 has been updated to use the SavedGames API.
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID Created a new
project in Unity
Added the play games plugin (Assets/Import
Package.../Custom Package)
Set the application ID (Google Play
Games/Android Setup...)
Switched the platform to Android (File/Build
Settings...)
Set the player settings (bundle identifier and the
keystore info)
Added a new script component to the camera Saved
everything and hit build and run.
Here is my script:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
using GooglePlayGames.BasicApi.SavedGame;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
bool mSaving;
private Texture2D mScreenImage;
// Use this for initialization
void Start () {
slot0 = new GameData("New game");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.State = "Click load or save";
}
else {
Debug.LogWarning("Authentication failed!");
}
};
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.EnableSavedGames()
.Build();
PlayGamesPlatform.InitializeInstance(config);
// Activate the Play Games platform. This will make it the default
// implementation of Social.Active
PlayGamesPlatform.Activate();
// enable debug logs (note: we do this because this is a sample; on your production
// app, you probably don't want this turned on by default, as it will fill the user's
// logs with debug info).
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
public void CaptureScreenshot() {
mScreenImage = new Texture2D(Screen.width, Screen.height);
mScreenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
mScreenImage.Apply();
}
protected virtual void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,200);
Rect dataRect = new Rect( 10, 250, Screen.width,100);
Rect b1Rect = new Rect(10, 800, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth, b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
if(GUI.Button(b1Rect, "Load")) {
mSaving = false;
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
4,false,false,SavedGameSelected);
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
mSaving = true;
CaptureScreenshot();
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Save game progress",
4,true,true,SavedGameSelected);
}
GUI.Label(statusRect, slot0.State);
}
public void SavedGameSelected(SelectUIStatus status, ISavedGameMetadata game) {
if (status == SelectUIStatus.SavedGameSelected) {
string filename = game.Filename;
Debug.Log("opening saved game: " + game);
if(mSaving && (filename == null || filename.Length == 0)) {
filename = "save" + DateTime.Now.ToBinary();
}
if (mSaving) {
slot0.State = "Saving to " + filename;
}
else {
slot0.State = "Loading from " + filename;
}
//open the data.
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(filename,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
SavedGameOpened);
} else {
Debug.LogWarning("Error selecting save game: " + status);
}
}
public void SavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
if( mSaving) {
slot0.State = "Opened, now writing";
byte[] pngData = (mScreenImage!=null) ?mScreenImage.EncodeToPNG():null;
Debug.Log("Saving to " + game);
byte[] data = slot0.ToBytes();
TimeSpan playedTime = slot0.TotalPlayingTime;
SavedGameMetadataUpdate.Builder builder = new
SavedGameMetadataUpdate.Builder()
.WithUpdatedPlayedTime(playedTime)
.WithUpdatedDescription("Saved Game at " + DateTime.Now);
if (pngData != null) {
Debug.Log("Save image of len " + pngData.Length);
builder = builder.WithUpdatedPngCoverImage(pngData);
}
else {
Debug.Log ("No image avail");
}
SavedGameMetadataUpdate updatedMetadata = builder.Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game,updatedMetadata,data,SavedGameWritten);
} else {
slot0.State = "Opened, reading...";
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game,SavedGameLoaded);
}
} else {
Debug.LogWarning("Error opening game: " + status);
}
}
public void SavedGameLoaded(SavedGameRequestStatus status, byte[] data) {
if (status == SavedGameRequestStatus.Success) {
Debug.Log("SaveGameLoaded, success=" + status);
slot0 = GameData.FromBytes(data);
} else {
Debug.LogWarning("Error reading game: " + status);
}
}
public void SavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
Debug.Log ("Game " + game.Description + " written");
slot0.State = "Saved!";
} else {
Debug.LogWarning("Error saving game: " + status);
}
}
public class GameData {
private TimeSpan mPlayingTime;
private DateTime mLoadedTime;
string mData;
string mState;
static readonly string HEADER = "GDv1";
public GameData(string data) {
mData = data;
mState = "Initialized, modified";
mPlayingTime = new TimeSpan();
mLoadedTime = DateTime.Now;
}
public TimeSpan TotalPlayingTime {
get {
TimeSpan delta = DateTime.Now.Subtract(mLoadedTime);
return mPlayingTime.Add(delta);
}
}
public override string ToString () {
string s = HEADER + ":" + mData;
s += ":" + TotalPlayingTime.TotalMilliseconds;
return s;
}
public byte[] ToBytes() {
return System.Text.ASCIIEncoding.Default.GetBytes(ToString());
}
public static GameData FromBytes (byte[] bytes) {
return FromString(System.Text.ASCIIEncoding.Default.GetString(bytes));
}
public static GameData FromString (string s) {
GameData gd = new GameData("initializing from string");
string[] p = s.Split(new char[] { ':' });
if (!p[0].StartsWith(HEADER)) {
Debug.LogError("Failed to parse game data from: " + s);
return gd;
}
gd.mData = p[1];
double val = Double.Parse(p[2]);
gd.mPlayingTime = TimeSpan.FromMilliseconds(val>0f?val:0f);
gd.mLoadedTime = DateTime.Now;
gd.mState = "Loaded successfully";
return gd;
}
public string Data {
get {
return mData;
}
set {
mData = value;
mState += ", modified";
}
}
public string State {
get {
return mState;
}
set {
mState = value;
}
}
}
}

Service-Unavailable(503) Error in Smack XEP-0198: Stream Management

I am using below class to enable stream management("urn:xmpp:sm:3") in our ejabberd server(we have latest version of ejabberd). But when I send the Enable packet to server it says Service Unavailable(503). But when I use "yaxim" it works perfectly. Please help me to solve this problem. Thanks.
public class XmppStreamHandler {
public static final String URN_SM_3 = "urn:xmpp:sm:3";
private static final int MAX_OUTGOING_QUEUE_SIZE = 20;
private static final int OUTGOING_FILL_RATIO = 4;
private XMPPConnection mConnection;
private boolean isSmAvailable = false;
private boolean isSmEnabled = false;
private boolean isOutgoingSmEnabled = false;
private long previousIncomingStanzaCount = -1;
private String sessionId;
private long incomingStanzaCount = 0;
private long outgoingStanzaCount = 0;
private Queue<Packet> outgoingQueue;
private int maxOutgoingQueueSize = MAX_OUTGOING_QUEUE_SIZE;
private ConnectionListener mConnectionListener;
public XmppStreamHandler(XMPPConnection connection, ConnectionListener connectionListener) {
mConnection = connection;
mConnectionListener = connectionListener;
startListening();
}
/** Perform a quick shutdown of the XMPPConnection if a resume is possible */
public void quickShutdown() {
if (isResumePossible()) {
mConnection.quickShutdown();
// We will not necessarily get any notification from a quickShutdown, so adjust our state here.
closeOnError();
} else {
mConnection.shutdown();
}
}
public void setMaxOutgoingQueueSize(int maxOutgoingQueueSize) {
this.maxOutgoingQueueSize = maxOutgoingQueueSize;
}
public boolean isResumePossible() {
return sessionId != null;
}
public boolean isResumePending() {
return isResumePossible() && !isSmEnabled;
}
public static void addExtensionProviders() {
addSimplePacketExtension("sm", URN_SM_3);
addSimplePacketExtension("r", URN_SM_3);
addSimplePacketExtension("a", URN_SM_3);
addSimplePacketExtension("enabled", URN_SM_3);
addSimplePacketExtension("resumed", URN_SM_3);
addSimplePacketExtension("failed", URN_SM_3);
}
public void notifyInitialLogin() {
if (sessionId == null && isSmAvailable)
sendEnablePacket();
}
private void sendEnablePacket() {
debug("sm send enable " + sessionId);
if (sessionId != null) {
isOutgoingSmEnabled = true;
// TODO binding
StreamHandlingPacket resumePacket = new StreamHandlingPacket("resume", URN_SM_3);
resumePacket.addAttribute("h", String.valueOf(previousIncomingStanzaCount));
resumePacket.addAttribute("previd", sessionId);
mConnection.sendPacket(resumePacket);
} else {
outgoingStanzaCount = 0;
outgoingQueue = new ConcurrentLinkedQueue<Packet>();
isOutgoingSmEnabled = true;
StreamHandlingPacket enablePacket = new StreamHandlingPacket("enable", URN_SM_3);
enablePacket.addAttribute("resume", "true");
mConnection.sendPacket(enablePacket);
}
}
private void closeOnError() {
if (isSmEnabled && sessionId != null) {
previousIncomingStanzaCount = incomingStanzaCount;
}
isSmEnabled = false;
isOutgoingSmEnabled = false;
isSmAvailable = false;
}
private void startListening() {
mConnection.forceAddConnectionListener(new ConnectionListener() {
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception e) {
}
public void reconnectingIn(int seconds) {
}
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException &&
((XMPPException)e).getStreamError() != null) {
// Non-resumable stream error
close();
} else {
// Resumable
closeOnError();
}
}
public void connectionClosed() {
previousIncomingStanzaCount = -1;
}
});
mConnection.addPacketSendingListener(new PacketListener() {
public void processPacket(Packet packet) {
// Ignore our own request for acks - they are not counted
if (!isStanza(packet)) {
trace("send " + packet.toXML());
return;
}
if (isOutgoingSmEnabled && !outgoingQueue.contains(packet)) {
outgoingStanzaCount++;
outgoingQueue.add(packet);
trace("send " + outgoingStanzaCount + " : " + packet.toXML());
// Don't let the queue grow beyond max size. Request acks and drop old packets
// if acks are not coming.
if (outgoingQueue.size() >= maxOutgoingQueueSize / OUTGOING_FILL_RATIO) {
mConnection.sendPacket(new StreamHandlingPacket("r", URN_SM_3));
}
if (outgoingQueue.size() > maxOutgoingQueueSize) {
// Log.e(XmppConnection.TAG, "not receiving acks? outgoing queue full");
outgoingQueue.remove();
}
} else if (isOutgoingSmEnabled && outgoingQueue.contains(packet)) {
outgoingStanzaCount++;
trace("send DUPLICATE " + outgoingStanzaCount + " : " + packet.toXML());
} else {
trace("send " + packet.toXML());
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
return true;
}
});
mConnection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
if (isSmEnabled && isStanza(packet)) {
incomingStanzaCount++;
trace("recv " + incomingStanzaCount + " : " + packet.toXML());
} else {
trace("recv " + packet.toXML());
}
if (packet instanceof StreamHandlingPacket) {
StreamHandlingPacket shPacket = (StreamHandlingPacket) packet;
String name = shPacket.getElementName();
if ("sm".equals(name)) {
debug("sm avail");
isSmAvailable = true;
if (sessionId != null)
sendEnablePacket();
} else if ("r".equals(name)) {
StreamHandlingPacket ackPacket = new StreamHandlingPacket("a", URN_SM_3);
ackPacket.addAttribute("h", String.valueOf(incomingStanzaCount));
mConnection.sendPacket(ackPacket);
} else if ("a".equals(name)) {
long ackCount = Long.valueOf(shPacket.getAttribute("h"));
removeOutgoingAcked(ackCount);
trace(outgoingQueue.size() + " in outgoing queue after ack");
} else if ("enabled".equals(name)) {
incomingStanzaCount = 0;
isSmEnabled = true;
mConnection.getRoster().setOfflineOnError(false);
String resume = shPacket.getAttribute("resume");
if ("true".equals(resume) || "1".equals(resume)) {
sessionId = shPacket.getAttribute("id");
}
debug("sm enabled " + sessionId);
} else if ("resumed".equals(name)) {
debug("sm resumed");
incomingStanzaCount = previousIncomingStanzaCount;
long resumeStanzaCount = Long.valueOf(shPacket.getAttribute("h"));
// Removed acked packets
removeOutgoingAcked(resumeStanzaCount);
trace(outgoingQueue.size() + " in outgoing queue after resume");
// Resend any unacked packets
for (Packet resendPacket : outgoingQueue) {
mConnection.sendPacket(resendPacket);
}
// Enable only after resend, so that the interceptor does not
// queue these again or increment outgoingStanzaCount.
isSmEnabled = true;
// Re-notify the listener - we are really ready for packets now
// Before this point, isSuspendPending() was true, and the listener should have
// ignored reconnectionSuccessful() from XMPPConnection.
mConnectionListener.reconnectionSuccessful();
} else if ("failed".equals(name)) {
// Failed, shutdown and the parent will retry
debug("sm failed");
mConnection.getRoster().setOfflineOnError(true);
mConnection.getRoster().setOfflinePresences();
sessionId = null;
mConnection.shutdown();
// isSmEnabled / isOutgoingSmEnabled are already false
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
return true;
}
});
}
private void removeOutgoingAcked(long ackCount) {
if (ackCount > outgoingStanzaCount) {
// Log.e(XmppConnection.TAG,
// "got ack of " + ackCount + " but only sent " + outgoingStanzaCount);
// Reset the outgoing count here in a feeble attempt to re-sync. All bets
// are off.
outgoingStanzaCount = ackCount;
}
int size = outgoingQueue.size();
while (size > outgoingStanzaCount - ackCount) {
outgoingQueue.remove();
size--;
}
}
private static void addSimplePacketExtension(final String name, final String namespace) {
ProviderManager.getInstance().addExtensionProvider(name, namespace,
new PacketExtensionProvider() {
public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
StreamHandlingPacket packet = new StreamHandlingPacket(name, namespace);
int attributeCount = parser.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
packet.addAttribute(parser.getAttributeName(i),
parser.getAttributeValue(i));
}
return packet;
}
});
}
private void debug(String message) {
System.out.println(message);
}
private void trace(String message) {
System.out.println(message);
}
public static class StreamHandlingPacket extends UnknownPacket {
private String name;
private String namespace;
Map<String, String> attributes;
StreamHandlingPacket(String name, String namespace) {
this.name = name;
this.namespace = namespace;
attributes = Collections.emptyMap();
}
public void addAttribute(String name, String value) {
if (attributes == Collections.EMPTY_MAP)
attributes = new HashMap<String, String>();
attributes.put(name, value);
}
public String getAttribute(String name) {
return attributes.get(name);
}
public String getNamespace() {
return namespace;
}
public String getElementName() {
return name;
}
public String toXML() {
StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName());
// TODO Xmlns??
if (getNamespace() != null) {
buf.append(" xmlns=\"").append(getNamespace()).append("\"");
}
for (String key : attributes.keySet()) {
buf.append(" ").append(key).append("=\"")
.append(StringUtils.escapeForXML(attributes.get(key))).append("\"");
}
buf.append("/>");
return buf.toString();
}
}
/** Returns true if the packet is a Stanza as defined in RFC-6121 - a Message, IQ or Presence packet. */
public static boolean isStanza(Packet packet) {
if (packet instanceof Message)
return true;
if (packet instanceof IQ)
return true;
if (packet instanceof Presence)
return true;
return false;
}
public void queue(Packet packet) {
if (outgoingQueue.size() >= maxOutgoingQueueSize) {
System.out.println("outgoing queue full");
return;
}
outgoingStanzaCount++;
outgoingQueue.add(packet);
}
private void close() {
isSmEnabled = false;
isOutgoingSmEnabled = false;
sessionId = null;
}
}
when I send the Enable packet to server it says Service
Unavailable(503)
Service Unavailable means that the service is unavailable on the server. Does ejabberd support XEP-198? Did you enable it?
You should also consider switching to Smack 4.1.0-alpha, which also runs on Android and comes with Stream Management support. yaxim will soon switch to from it's custom XmppStreamHandler implementation to Smack 4.1.

MSMQ Listener (windows service) can't receive messages independently after installation

I have two services running asynchronously. service1 is posting messages to MessageQueue which is in service2 (response queue).
Service2 is picking up each and every message from the queue and processing it.
problem is when ever service1 stops running because it finished sending messages.... service2 is not able to read the messages(still service2 is running) from the queue(still queue has some messages to read).
It is like service 2 becomes dormant when service one ended and the app is closed. Is this behavior expected?? Is there a solution.
I would like to have my service2(msmq listener) to continue to receive messages independently from Service 1.
using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.ServiceModel;
using System.ServiceProcess;
using System.Threading;
using LOGGER;
using MSMQ.INTERFACE;
using RightFax;
using Tools.Helper;
using Microsoft.VisualBasic;
using RFCOMAPILib;
using FAXHandlerClass = FAXHandlerClass;
using FAXHandlerState = CONTENT.SYSTEM.FAXHandlerState;
namespace MSMQ.LISTENER
{
public partial class Service1 : ServiceBase
{
public static FaxServer RFFaxApi;
private const string LogClass = "MSMQ.LISTENER.PROGRAM::";
private static bool _mBoolMustStop;
private static readonly RF2MQCounter Counter = new RF2MQCounter();
private static RFaxServerStatus _rightFaxServerStatus;
public static FAXHandlerState MThState = new FAXHandlerState();
private IMessageQueueHandler _queue;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
var logRoust = "OnStart";
Generic.ConfigParam = LoadConfig.Invoke(LogClass);
//Ping the server
PingReply rep;
var mac = PingServer.Mac(out rep, Generic.ConfigParam.RightFax.server);
if (rep != null)
{
Logger.Log(string.Format(#"Pinging {0} [{1}]", mac, rep.Address));
Logger.Log(string.Format("Reply From {0} : time={1} TTL={2}", rep.Address, rep.RoundtripTime,
rep.Options.Ttl));
//Connect to the Right Fax Server
Actions.Connect(LogClass, Counter, ref RFFaxApi);
//Start readin gthe queue
IMessageQueueHandler _queue = new Test();
var threadQueuet = new Thread(_queue.StartRead);
Logger.Log(string.Format("Start reading {0} queue...",
Generic.ConfigParam.MSMQ.responseQueue));
threadQueuet.Start();
}
else
{
Logger.Log(string.Format("Not able to get a reply From {0} : time={1} TTL={2}", rep.Address,
rep.RoundtripTime, rep.Options.Ttl));
}
}
catch (PingException e)
{
throw;
}
catch (Exception e)
{
Logger.Log(string.Format("{0} ::Not able to start the MSMQ.LISTENER Service on : {1} Mesage:: {2}", LogClass, Generic.ConfigParam.RightFax.server, e.Message ));
throw;
}
}
protected override void OnStop()
{
if (_queue != null)
_queue.StopRead();
Logger.Log(string.Format("Stopping MSMQ.LISTENER Service {0} queue...", Generic.ConfigParam.MSMQ.responseQueue));
}
/// <summary>
/// Connect to the Rightfax server
/// </summary>
/// <param name="ref">Used for logging the routine</param>
/// <returns>The RightFax server connection status</returns>
/// <remarks></remarks>
public static RFaxServerStatus ConnectToRightFax(string #ref)
{
var logRoust = #ref + LogClass + "CONNECTION::";
var retryCounter = 0;
Generic.ConfigParam = LoadConfig.Invoke(LogClass,Counter);
Logger.Log(string.Format("{0} - Connecting to {1} as user {2}", logRoust, Generic.ConfigParam.RightFax.server, ""));
_rightFaxServerStatus = RFaxServerStatus.Connecting;
try
{
if ((RFFaxApi != null))
RFFaxApi.CloseServer();
}
catch
{
//We do nothing.... We will destroy the object anyway
//return false;
}
RFFaxApi = null;
do
{
MThState.AddEventState = new FAXHandlerClass(FaxHandlerStateEnum.ConnectingRfax);
try
{
//**********************************************************************************************
// This section determines how quickly we try to reconnect
// Try the 1st 5 times 5 second apart
// the 2nd 5 times 30 seconds apart
// the 3rd 5 times 60 seconds apart
// every 300 seconds (5 mins) forever after that
//**********************************************************************************************
int sleepInterval;
if (retryCounter > 15)
{
sleepInterval = 300000;
}
else
{
if (retryCounter > 10)
{
sleepInterval = 60000;
}
else
{
sleepInterval = retryCounter > 5 ? 30000 : 5000;
}
}
//**************************************************
// Connect to the RightFax Server
//**************************************************
Logger.Log(string.Format("{0} - Attempt # {1}", logRoust, retryCounter));
if (retryCounter > 0)
{
Logger.Log(string.Format("{0} - Waiting # {1} seconds before trying to reconnect.", logRoust, sleepInterval / 1000));
Thread.Sleep(sleepInterval);
}
Logger.Log(string.Format("{0} - Initializing Connection to RightFax.", logRoust));
RFFaxApi = new FaxServer
{
ServerName = Generic.ConfigParam.RightFax.server.Trim(),
UseNTAuthentication = RFCOMAPILib.BoolType.False,
AuthorizationUserID = Generic.ConfigParam.RightFax.userID,
AuthorizationUserPassword = Generic.ConfigParam.RightFax.password,
Protocol = (CommunicationProtocolType)Generic.ConfigParam.RightFax.communicationProtocol
};
//Verify if the RightFax Service is runing before connecting
//var controller = new ServiceController("RightFax Server Module", _rfFaxApi.ServerName);
//if ((controller.Status.Equals(ServiceControllerStatus.Running)))
//{
try
{
RFFaxApi.OpenServer();
_rightFaxServerStatus = RFaxServerStatus.Connected;
retryCounter = 0;
Logger.Log(string.Format("{0} - Connected to {1} (V. {2}) as user {3}", logRoust, RFFaxApi.ServerName, RFFaxApi.Version, RFFaxApi.AuthorizationUserID));
}
catch (Exception ex)
{
Logger.Log(string.Format("{0} - ERROR Connected to {1} (V. {2}) as user {3} MESSAGE: {4}", logRoust, RFFaxApi.ServerName, RFFaxApi.Version, RFFaxApi.AuthorizationUserID, ex.Message));
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
//Its OK not to end the loop. This is possibly a temporary error condition.
Logger.Log(string.Format("{0} - Connection failed Message: {1}", logRoust, ex.Message), EventLogEntryType.Warning);
}
catch (Exception ex)
{
if (Strings.InStr(ex.Source, "RFComAPI.FaxServer") > 0 | Strings.InStr(ex.Source, "Interop.RFCOMAPILib") > 0)
{
//Its OK not to end the loop. This is possibly a temporary error condition.
Logger.Log(string.Format("{0} - Connection failed : Message {1} ", logRoust, ex.Message), EventLogEntryType.Warning);
}
else
{
_rightFaxServerStatus = RFaxServerStatus.NotConnected;
Logger.Log(string.Format("{0} - Connection failed. Message: {1}", logRoust, ex.Message), EventLogEntryType.Error);
throw new Exception(string.Format("{0} - Connection failed. Message: {1}", logRoust, ex.Message));
}
}
finally
{
retryCounter += 1;
}
} while (!(_rightFaxServerStatus == RFaxServerStatus.Connected | _mBoolMustStop));
return _rightFaxServerStatus;
}
}
}
---------------------------------------------
using System.Net.NetworkInformation;
using System.ServiceProcess;
using System.Threading;
using LOGGER;
using MSMQ.INTERFACE;
using .RightFax;
using Tools.Helper;
using RFCOMAPILib;
using FAXHandlerState = HandlerState;
namespace MSMQ.LISTENER
{
static class Program
{
private const string LogClass = "MSMQ.LISTENER.PROGRAM::";
public static FaxServer RFFaxApi;
private static bool _mBoolMustStop;
private static readonly RF2MQCounter Counter = new RF2MQCounter();
private static RFaxServerStatus _rightFaxServerStatus;
public static FAXHandlerState MThState = new FAXHandlerState();
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Run();
//OR comment above to be able to Debug
//Uncomment below to start in debug mode
// Start();
}
private static void Run()
{
var servicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(servicesToRun);
}
public static void StartThreadProc(object stateInfo)
{
Start();
}
public static void Start()
{
try
{
var logRoust = "OnStart";
Generic.ConfigParam = LoadConfig.Invoke(LogClass);
//Ping the server
PingReply rep;
var mac = PingServer.Mac(out rep, Generic.ConfigParam.RightFax.server);
if (rep != null)
{
Logger.Log(string.Format(#"Pinging {0} [{1}]", mac, rep.Address));
Logger.Log(string.Format("Reply From {0} : time={1} TTL={2}", rep.Address, rep.RoundtripTime,
rep.Options.Ttl));
//Connect to the Right Fax Server
Actions.Connect(LogClass, Counter, ref RFFaxApi);
//Start readin gthe queue
IMessageQueueHandler _queue = new Isoconvoceresponse();
var threadQueuet = new Thread(_queue.StartRead);
Logger.Log(string.Format("Start reading {0} queue...",
Generic.ConfigParam.MSMQ.responseQueue));
threadQueuet.Start();
}
else
{
Logger.Log(string.Format("Not able to get a reply From {0} : time={1} TTL={2}", rep.Address,
rep.RoundtripTime, rep.Options.Ttl));
}
}
catch (PingException e)
{
throw;
}
}
}
}
___________________________
namespace MSMQ.INTERFACE
{
public interface IMessageQueueHandler
{
void StartRead();
void StopRead();
}
}
--------------
using System;
using System.Diagnostics;
using System.Globalization;
using System.Messaging;
using System.Net.NetworkInformation;
using System.ServiceModel;
using System.ServiceProcess;
using System.Threading;
using CONTENT.SYSTEM;
using LOGGER;
using MSMQ.INTERFACE;
using RightFax;
using RightFax.Tools.Helper;
using RFCOMAPILib;
using MessageQueue = System.Messaging.MessageQueue;
using RF2MQCounter = RF2MQCounter;
namespace MSMQ.LISTENER
{
public class Test : IMessageQueueHandler
{
private MessageQueue _queue;
private readonly string _queueName;
private const string LogClass = ".MSMQ.LISTENER::";
private readonly ManualResetEvent manualResetEvent = new ManualResetEvent(true);
private long handle ;
/// <summary>
///
/// </summary>
public Test()
{
const string logroust = LogClass + "Isoconvoceresponse";
Generic.ConfigParam = LoadConfig.Invoke(logroust);
_queueName =Generic.ConfigParam.MSMQ.responseQueue;
}
/// <summary>
///
/// </summary>
public void StartRead()
{
// System.Diagnostics.Debugger.Break();
const string logRoust = LogClass + "StartRead::";
try
{
Logger.Log(String.Format("{0} - Start Reading the {1} Queue .", logRoust, Generic.ConfigParam.MSMQ.responseQueue ));
_queue = new MessageQueue(_queueName) {Formatter = new XmlMessageFormatter(new[] {typeof (string)})};
_queue.MessageReadPropertyFilter.SetAll();
var objDefProps = new System.Messaging.DefaultPropertiesToSend
{
Priority = MessagePriority.High,
Recoverable = true,
UseDeadLetterQueue = true,
UseJournalQueue = true,
};
_queue.DefaultPropertiesToSend = objDefProps;
_queue.PeekCompleted += QueuePeekCompleted;
_queue.BeginPeek();
//_queue.ReceiveCompleted += QueueReceiveCompletedd;//Event handler
//_queue.BeginReceive();
}
catch (Exception ex)
{
Actions.SetGenericFlagOff(handle.ToString(CultureInfo.InvariantCulture),Generic.ConfigParam.dbConnectionString);
Logger.Log(
String.Format("{0} - Start Reading the {1} failed : Error: {2}.", logRoust, Generic.ConfigParam.MSMQ.responseQueue, ex.Message),
EventLogEntryType.Error);
throw;
}
}
public static void OnServiceFaulted(object sender, EventArgs e)
{
Logger.Log(string.Format("{0} ::Service Faulted: {1} Mesage:: {2}", LogClass, Generic.ConfigParam.RightFax.server, e.ToString()));
}
public void StopRead()
{//make the process synchronous before closing the queue
manualResetEvent.WaitOne();
if (_queue == null) return;
_queue.Close();
_queue = null;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void QueuePeekCompleted(object sender, PeekCompletedEventArgs e)
{
// System.Diagnostics.Debugger.Break();
const string logRoust = LogClass + "QueuePeekCompleted::";
var message = _queue.EndPeek(e.AsyncResult);
_queue.Receive();
_queue.BeginPeek();
var allMessagesOnResponseQueue = _queue.GetAllMessages();
foreach (var msg in allMessagesOnResponseQueue)
{
Logger.Log(String.Format("{0} - Messages QueuePeekCompleted event handler {1}", logRoust, message.Label + " - " + message.Id));
}
do
{
try
{
if (message.MessageType == MessageType.Acknowledgment)
switch (message.Acknowledgment)
{
case Acknowledgment.Purged:
Logger.Log("Message Purged {0}", message.Body.ToString());
break;
case Acknowledgment.QueueExceedMaximumSize:
Logger.Log("Message Queue Exceed MaximumSize {0}", message.Body.ToString());
break;
case Acknowledgment.QueuePurged:
Logger.Log("Message Queue Purged {0}", message.Body.ToString());
break;
case Acknowledgment.ReceiveTimeout:
Logger.Log("Message ReceiveTimeout {0}, Now restarting MSMQ.LISTENER Service",
message.Body.ToString());
var controller = new ServiceController("MSMQ.LISTENER", "STHA38994.iad.ca.inet");
if (controller.Status.Equals(ServiceControllerStatus.Running))
controller.Start();
break;
case Acknowledgment.ReachQueue:
Logger.Log("Message Reached Queue {0}", message.Body.ToString());
break;
case Acknowledgment.Receive:
Logger.Log("Message Received {0}", message.Body.ToString());
break;
}
/
if (message.MessageType == MessageType.Normal)
{
var messageDetail = message.Label.Split(' ');
var pdfFileDetails = messageDetail[1].Split('_');
handle = Convert.ToInt64(pdfFileDetails[0]);
var isSucessfull = false;
FaxServer faxServer = null;
if (MSMQ.LISTENER.Service1.RFFaxApi == null)
{
Generic.ConfigParam = LoadConfig.Invoke(LogClass);
var counter = new RF2MQCounter();
Actions.Connect(LogClass, counter, ref faxServer); //you can pass a null faxserver
}
if (faxServer != null)
{
try
{
Logger.Log("Getting Fax {0}", handle.ToString(CultureInfo.InvariantCulture));
var rfaxFax = Actions.GetFax(handle, ref faxServer);
Logger.Log("Getting Fax {0} SUCESS", handle.ToString(CultureInfo.InvariantCulture));
Generic.NumberOfRecordsSent++;
Logger.Log("Processing message {0}", handle.ToString(CultureInfo.InvariantCulture));
isSucessfull = RFServiceClass.ProcessMessage(message, ref rfaxFax);
Logger.Log("Processing message SUCESS {0}",
handle.ToString(CultureInfo.InvariantCulture));
}
catch (Exception ex)
{
Generic.NumberOfRecordsSent--;
Logger.Log(
String.Format("{0} - ERROR processinf fax from the queue.. {1}", logRoust,
ex.Message), EventLogEntryType.Error);
Actions.SetGenericFlagOff(handle.ToString(CultureInfo.InvariantCulture),
Generic.ConfigParam.dbConnectionString);
}
}
}
}
catch (MessageQueueException msq)
{
var messageDetail = message.Label.Split(' ');
var pdfFileDetails = messageDetail[1].Split('_');
long handle = Convert.ToInt64(pdfFileDetails[0]);
Actions.SetGenericFlagOff(handle.ToString(CultureInfo.InvariantCulture), Generic.ConfigParam.dbConnectionString);
switch (msq.MessageQueueErrorCode)
{
case MessageQueueErrorCode.IOTimeout:
Logger.Log(
String.Format("{0} - Error Message IOTimeout Exception: {1}.", logRoust, msq.Message),
EventLogEntryType.Error);
Actions.SetGenericFlagOff(handle.ToString(CultureInfo.InvariantCulture),Generic.ConfigParam.dbConnectionString );
break;
default:
Logger.Log(
String.Format("{0} - Error Message DEFAULT Exception: {1}.", logRoust, msq.Message),
EventLogEntryType.Error);
break;
}
}
catch (Exception ex)
{
Actions.SetGenericFlagOff(handle.ToString(CultureInfo.InvariantCulture), Generic.ConfigParam.dbConnectionString);
Logger.Log(
String.Format("{0} - Error QueuePeekCompleted: {1}.", logRoust, ex.Message),
EventLogEntryType.Error);
message = null;
}
} while (message != null);
}
}
public override string ToString()
{
return _queueName;
}
}
}

filtering datagrid using combobox

I had created a datagridview like this
public void gridviewsetup()
{
tbl_Aplication.Columns.Add("1", "Empid");
tbl_Aplication.Columns.Add("2", "Emp no");
tbl_Aplication.Columns.Add("3", "Emp Name");
tbl_Aplication.Columns.Add("4", "Department ");
tbl_Aplication.Columns.Add("5", "Designation");
tbl_Aplication.Columns.Add("6", "Shift");
tbl_Aplication.Columns.Add("7", "Start Time");
tbl_Aplication.Columns.Add("8", "End Time");
tbl_Aplication.Columns.Add("9", "OT");
tbl_Aplication.Columns.Add("10", "Reversed Swipe Out");
tbl_Aplication.RowTemplate.Height = 18;
}
and i had populated a data table to fill the data dgridview
public void filldatagrid()
{
if (cmb_dept.Text.Trim() != "")
{
Datatable employedata = empreg.getallemployeeshiftdetails(int.Parse(cmb_dept.SelectedValue.ToString()), Program.LOCTNPK);
tbl_Aplication.Rows.Clear();
tbl_Aplication.DataSource = null;
for (int i = 0; i < employedata.Rows.Count; i++)
{
tbl_Aplication.Rows.Add();
tbl_Aplication.Rows[i].Cells[1].Value = employedata.Rows[i][0];
tbl_Aplication.Rows[i].Cells[2].Value = employedata.Rows[i][1];
tbl_Aplication.Rows[i].Cells[3].Value = employedata.Rows[i][2];
tbl_Aplication.Rows[i].Cells[4].Value = employedata.Rows[i][3];
tbl_Aplication.Rows[i].Cells[5].Value = employedata.Rows[i][4];
tbl_Aplication.Rows[i].Cells[6].Value = employedata.Rows[i][5];
tbl_Aplication.Rows[i].Cells[7].Value = employedata.Rows[i][6];
tbl_Aplication.Rows[i].Cells[8].Value = employedata.Rows[i][7];
tbl_Aplication.Rows[i].Cells[9].Value = 0;
tbl_Aplication.Rows[i].Cells[10].Value = employedata.Rows[i][7];
}
}
}
now i want to filter data in the datagrid with the designation selected in the combobox without going back to database ,I did it like this but it shows error
private void cmb_designation_SelectedIndexChanged(object sender, EventArgs e)
{
if (desgflag != 0)
{
if (cmb_dept.SelectedValue!=null )
{
// tbl_Aplication.DataSource = employedata;
((DataTable)tbl_Aplication.DataSource).DefaultView.RowFilter = " designationnName like '%" + cmb_dept.Text.Trim() + "%' ";
}
}
}
I had done it
private void cmb_department_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (cmb_department.Text.Trim() == "" || cmb_department.Text.Trim() == null)
{
tbl_DestinationData.DataSource = dt;
}
else
{
((DataTable)tbl_DestinationData.DataSource).DefaultView.RowFilter = " Dept like '%" + cmb_department.Text.Trim() + "%' ";
}
}
catch (Exception )
{
throw;
}
}