I am trying to access data in a C# packet I've created, however I keep getting null as a response. What am I doing wrong? - c#

Okay, so I'm working with custom network code for pretty much the first time. I have a packet created to transfer some game information back and forth, however beyond the initial content if I try to access some of the commands, I get "null" - though on the server side, it's showing as properly populated.
I have a feeling that this has to do with the setup in receiving the data. The code for the packet follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum DataIdentifier
{
Message,
Command,
LogIn,
LogOut,
Null
}
public class Packet
{
private DataIdentifier dataIdentifier;
private string name;
private string player;
private string playerData;
private string message;
private string command;
private string x;
private string y;
private string z;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Player
{
get
{
return player;
}
set
{
player = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string Command
{
get
{
return command;
}
set
{
command = value;
}
}
public DataIdentifier DataIdentifier
{
get
{
return dataIdentifier;
}
set
{
dataIdentifier = value;
}
}
public string PlayerData
{
get
{
return playerData;
}
set
{
playerData = value;
}
}
public string X
{
get
{
return x;
}
set
{
x = value;
}
}
public string Y
{
get
{
return y;
}
set
{
y = value;
}
}
public string Z
{
get
{
return z;
}
set
{
z = value;
}
}
public Packet()
{
this.DataIdentifier = DataIdentifier.Null;
this.message = null;
this.name = null;
this.player = null;
this.playerData = null;
this.x = null;
this.y = null;
this.z = null;
this.command = null;
}
public Packet(byte[] dataStream)
{
// Read the data identifier from the beginning of the stream (4 bytes)
this.DataIdentifier = (DataIdentifier)BitConverter.ToInt32(dataStream, 0);
// Read the length of the name (4 bytes)
int nameLength = BitConverter.ToInt32(dataStream, 4);
// Read the length of the message (4 bytes)
int msgLength = BitConverter.ToInt32(dataStream, 8);
// Read the name field
if (nameLength > 0)
this.name = Encoding.UTF8.GetString(dataStream, 12, nameLength);
else
this.name = null;
// Read the message field
if (msgLength > 0)
this.message = Encoding.UTF8.GetString(dataStream, 12 + nameLength, msgLength);
else
this.message = null;
}
public byte[] GetDataStream()
{
List<byte> dataStream = new List<byte>();
// Add the dataIdentifier
dataStream.AddRange(BitConverter.GetBytes((int)this.DataIdentifier));
// Add the name length
if (this.name != null)
dataStream.AddRange(BitConverter.GetBytes(this.name.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the message length
if (this.message != null)
dataStream.AddRange(BitConverter.GetBytes(this.message.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the name
if (this.name != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.name));
// Add the message
if (this.message != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.message));
if (this.playerData != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.playerData));
}
if (this.command != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.command));
}
if (this.x != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.x));
}
if (this.y != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.y));
}
if (this.z != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.z));
}
return dataStream.ToArray();
}
}
This is how the packet is recieved:
// Receive all data
this.clientSocket.EndReceive(AR);
// Initialise a packet object to store the received data
Packet receivedData = new Packet(this.dataStream);
// Evaulate command played
if (PacketDelegate != null)
{
PacketDelegate(receivedData);
}
// Reset data stream
this.dataStream = new byte[8142];
// Continue listening for broadcasts
clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveCallback), null);
And this is the delegate function responsible for handling a packet:
public void RecievePacket(Packet Communication)
{
// Check and manipulate the contents of the packet here //
}
I have confirmed that I can get name, DataIdentifier, and Message, but it's the additional information I've added to the packet itself - player/data, command, x,y,z, I can't seem to get.
My thought is that the problem exists in establishing Packet(byte[] dataStream). However, I'm not quite sure how to calculate or add the additional variables to this. Can anyone give me some tips on how to do so?

Related

C# Class Properties 'tied' to a file? (See Perl::Tie)

In perl there's a rather simple method of tying a data structure to a file, whether it be a string, hash(dictionary in C#) or a simple array/list.
I've cobbled together my own half-assed solution in C# but I was wondering if there's a more inbuilt way to achieve this functionality?
Edit in response to comment below--The question, directly: Is there an inbuilt way to "tie" a class/dictionary to a file so any changes in either is reflected in the other? (Without doing as I've done below)
(Tieing a dictionary means that any changes in the dictionary are immediately reflected/updated in the file and declaring a tied var loads the object from disk if it already exists; see PerlTie )
My pseudo-tie'd class is below:
#region options
private float _Opacity;
public float Opacity {
get {
return Opacity;
}
set {
_Opacity = value;
this.Save();
}
}
private Font _Font;
public Font Font {
get {
return _Font;
}
set {
_Font = value;
this.Save();
}
}
private Color _FontColor;
public Color FontColor {
get {
return _FontColor;
}
set {
_FontColor = value;
this.Save();
}
}
private Color _BGColor;
public Color BGColor {
get {
return _BGColor;
}
set {
_BGColor = value;
this.Save();
}
}
private Point _Location;
public Point Location {
get {
return _Location;
}
set {
_Location = value;
this.Save();
}
}
private Size _Size;
public Size Size {
get {
return _Size;
}
set {
_Size = value;
this.Save();
}
}
private ushort _HistoryLines;
public ushort HistoryLines {
get {
return _HistoryLines;
}
set {
_HistoryLines = value;
this.Save();
}
}
private ChatType _ChatModes;
public ChatType ChatModes {
get {
return _ChatModes;
}
set {
_ChatModes = value;
this.Save();
}
}
private bool _Debugging;
public bool Debugging {
get {
return _Debugging;
}
set {
_Debugging = value;
this.Save();
}
}
#endregion options
private FontConverter FontConvert;
private FileInfo SettingsFile;
private MLogConf() {
}
public MLogConf(string stateFile) {
FontConvert = new FontConverter();
try {
if (!Directory.Exists(Path.GetDirectoryName(stateFile)))
Directory.CreateDirectory(Path.GetDirectoryName(stateFile));
if (!File.Exists(stateFile)) {
FileStream fs = File.Create(stateFile);
fs.Close();
}
SettingsFile = new FileInfo(stateFile);
if (SettingsFile.Length == 0) {
this.SetDefaultOptions();
} else {
if (!this.Load()) {
throw new FileLoadException("Couldn't load settings file");
}
}
} catch (Exception ex) {
Trace.Write($"Failed to create MLogConf({nameof(stateFile)}) {ex.Message + Environment.NewLine + ex.StackTrace}");
}
}
private bool Load() {
if (SettingsFile == null)
return false;
try {
byte[] data = File.ReadAllBytes(SettingsFile.FullName);
using (MemoryStream m = new MemoryStream(data)) {
using (BinaryReader reader = new BinaryReader(m)) {
_Opacity = reader.ReadSingle();
_Font = (Font)(FontConvert.ConvertFromString(Encoding.ASCII.GetString(Convert.FromBase64String(reader.ReadString()))));
_FontColor = Color.FromArgb(reader.ReadInt32());
_BGColor = Color.FromArgb(reader.ReadInt32());
_Location = new Point(reader.ReadInt32(), reader.ReadInt32());
_Size = new Size(reader.ReadInt32(), reader.ReadInt32());
_HistoryLines = reader.ReadUInt16();
_ChatModes = (ChatType)reader.ReadInt32();
_Debugging = reader.ReadBoolean();
}
}
} catch (Exception e) {
Trace.WriteLine($"Exception reading binary data: {e.Message + Environment.NewLine + e.StackTrace}");
return false;
}
return true;
}
private bool Save() {
try {
using (FileStream fs = new FileStream(SettingsFile.FullName, FileMode.Create)) {
using (BinaryWriter writer = new BinaryWriter(fs)) {
writer.Write(_Opacity);
writer.Write(Convert.ToBase64String(Encoding.ASCII.GetBytes((string)FontConvert.ConvertTo(Font, typeof(string)))));
writer.Write(_FontColor.ToArgb());
writer.Write(_BGColor.ToArgb());
writer.Write(_Location.X);
writer.Write(_Location.Y);
writer.Write(_Size.Width);
writer.Write(_Size.Height);
writer.Write(_HistoryLines);
writer.Write((int)_ChatModes);
writer.Write(_Debugging);
}
}
} catch (Exception e) {
Trace.WriteLine($"Exception writing binary data: {e.Message + Environment.NewLine + e.StackTrace}");
return false;
}
return true;
}
private bool SetDefaultOptions() {
this._BGColor = Color.Black;
this._ChatModes = ChatType.Alliance | ChatType.Emote | ChatType.FreeCompany | ChatType.Linkshell | ChatType.Party | ChatType.SayShoutYell | ChatType.Tell;
this._Opacity = 1f;
this._Font = new Font("Verdana", 50);
this._FontColor = Color.CornflowerBlue;
this._Location = new Point(100, 400);
this._Size = new Size(470, 150);
this._HistoryLines = 512;
this._Debugging = false;
return this.Save();
}
I suppose you are looking for an easy way to store class instances in files.
Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
The shortest solution I've found for C# here some time ago was Json.NET from Newtonsoft, available as NuGet package. It will do all the 'long class-properties-to-string code' for you and leave you with string ready to be written in file.
Official site can provide code examples: http://www.newtonsoft.com/json
Save to file:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }
Read from file:
string json = #"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys

I don't see any pictures in my RSS

I have problem. I programming Windows Phone 8.0 application and i don't see anything pictures in my app. Probably error is in regex, because in debug regImg don't have any matches
Class MainPage.xaml.cs
string strURL = "https://news.google.com/news? cf=all&ned=pl_pl&hl=pl&topic=b&output=rss"; // URL of RssFeeds.
and class ImageFromRssText.cs
public class ImageFromRssText : IValueConverter
{
// Get images from each SyndicationItem.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
List<ImageItem> listUri = GetHtmlImageUrlList(value.ToString());
return listUri;
}
/// <summary>
/// Get the URL of the all pictures from the HTML.
/// </summary>
/// <param name="sHtmlText">HTML code</param>
/// <returns>URL list of the all pictures</returns>
public static List<ImageItem> GetHtmlImageUrlList(string sHtmlText)
{
// The definition of a regular expression to match img tag.
Regex regImg = new Regex(#"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// The search for a matching string.
MatchCollection matches = regImg.Matches(sHtmlText);
int i = 0;
List<ImageItem> imgUrlList = new List<ImageItem>();
// Get a list of matches
foreach (Match match in matches)
{
imgUrlList.Add(new ImageItem("img" + i, match.Groups["imgUrl"].Value));
i++;
}
return imgUrlList;
}
Ok. I wrote a little bit in a different way in second project(yesterday I wrote a project of a new). Although the problem is the same, then it does not load picture. Function HasImage always return false(Although when picture exists) and variabe Image is null(rest of variables are OK)
public class FeedItemViewModel : System.ComponentModel.INotifyPropertyChanged
{
// Declaration - Title, Image, Lead, Url
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged("Title");
}
}
// All from RSS (Image and lead)
private string _lead;
public string Lead
{
get
{
return _lead;
}
set
{
_lead = value;
// Load picture
try
{
if (TryParseImageUrl(_lead, out _imageUrl))
_imageUrl = _imageUrl.Replace("//", "http://");
}
catch { }
OnPropertyChanged("Lead");
}
}
private string _imageUrl;
public Uri Image
{
get
{
if (HasImage)
return new Uri(_imageUrl, UriKind.RelativeOrAbsolute);
return null;
}
}
// Check if picture exists
public bool HasImage
{
get
{
return (!string.IsNullOrEmpty(_imageUrl) && Uri.IsWellFormedUriString(_imageUrl, UriKind.RelativeOrAbsolute));
}
}
// Download url news
private string _url;
public string Url
{
get
{
return _url;
}
set
{
_url = value;
OnPropertyChanged("Url");
}
}
public void OnOpenUrl()
{
var wb = new Microsoft.Phone.Tasks.WebBrowserTask();
wb.Uri = new Uri(_url);
wb.Show();
}
// 3 method parse image
private static bool TryParseImageUrl(string description, out string result)
{
string str = ParseAnyImageInTheDescription(description);
result = str;
return (!string.IsNullOrEmpty(str) && Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute));
}
private static string ParseAnyImageInTheDescription(string item)
{
if (item == null) { return null; }
return ParseImageUrlFromHtml(item);
}
private static string ParseImageUrlFromHtml(string html)
{
Match match = new Regex("src=(?:\\\"|\\')?(?<imgSrc>[^>]*[^/].(?:jpg|png|jpeg))(?:\\\"|\\')?").Match(html);
if ((match.Success && (match.Groups.Count > 1)) && (match.Groups[1].Captures.Count > 0))
{
return match.Groups[1].Captures[0].Value;
}
return null;
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}

Load serialized data in multiple applications C#

Scenario:
I have a program which uses a simple class to generate game data. Using the said program, I write the data out using serialization and BinaryFormatter to a file to be used by a second program. Reading the data from this initial program works without issue.
Problem:
It's probably down to my ignorance to how serialized files are handled, but I cannot then load this data into a second program, the actual game itself.
saveGame code (in program 1):
static List<GameData> gameData;
static GameData currentData;
private void saveGame(Sudoku sdk) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = null;
try {
if(!File.Exists(gameDataFile[currentDifficulty])) {
file = File.Open(gameDataFile[currentDifficulty], FileMode.CreateNew);
} else {
file = File.Open(gameDataFile[currentDifficulty], FileMode.Append);
}
currentData = setGameData(sdk);
bf.Serialize(file, currentData);
savePuzzleLog();
} catch(Exception e) {
Debug.LogException("saveGame", e);
}
if(file != null) {
file.Close();
}
}
loadGameData: (in program 2)
public static List<GameData> gameData;
public bool loadGameData() {
if(gameData == null) {
gameData = new List<GameData>();
} else {
gameData.Clear();
}
bool loadData = true;
bool OK = false;
if(File.Exists(gameDataFile[currentDifficulty])) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(gameDataFile[currentDifficulty], FileMode.Open);
while(loadData) {
try {
GameData gd = new GameData();
gd = (GameData)bf.Deserialize(file);
gameData.Add(gd);
OK = true;
if(file.Position == file.Length) {
loadData = false;
}
} catch(Exception e) {
Debug.LogException(e);
loadData = false;
OK = false;
}
}
if(file != null) {
file.Close();
}
} else {
Debug.LogWarning(gameDataFile[currentDifficulty] + " does not exist!");
}
return OK;
}
GameData Class: (1st program)
[Serializable]
class GameData {
private int gameID;
private List<int> contentArray;
private int difficultyValue;
public GameData(List<int> data = null) {
id = -1;
difficulty = -1;
if(content != null) {
content.Clear();
} else {
content = new List<int>();
}
if(data != null) {
foreach(int i in data) {
content.Add(i);
}
}
}
public int id {
get {
return this.gameID;
}
set {
this.gameID = value;
}
}
public int difficulty {
get {
return this.difficultyValue;
}
set {
this.difficultyValue = value;
}
}
public List<int> content {
get {
return this.contentArray;
}
set {
this.contentArray = value;
}
}
}
GameData Class: (2nd program) The only difference is declaring as public
[Serializable]
public class GameData {
private int gameID;
private List<int> contentArray;
private int difficultyValue;
public GameData(List<int> data = null) {
id = -1;
difficulty = -1;
if(content != null) {
content.Clear();
} else {
content = new List<int>();
}
if(data != null) {
foreach(int i in data) {
content.Add(i);
}
}
}
public int id {
get {
return this.gameID;
}
set {
this.gameID = value;
}
}
public int difficulty {
get {
return this.difficultyValue;
}
set {
this.difficultyValue = value;
}
}
public List<int> content {
get {
return this.contentArray;
}
set {
this.contentArray = value;
}
}
}
What my question is, is how do I save the data out in one program and be able to load it using a different program without getting serialization errors or do I need to use an alternate save/load method and/or class structure?
When I had to do it i made it this way :
An independant dll (assembly) containing the class holding the data (for you the GameData class), and utility methods to save/load from a file.
Your two other projects must then reference this dll (assembly) and you should be able to (de)serialize correctly.
What I think the issue is in your case is that the BinaryFormatter does not only save the data in the file, but also the complete Type of the serialized object.
When you try to deserialize in another similar object, even if the structure is the same, the full name of the class is not (because the assembly name is not).
OK, I've sorted it using the advice given. Instead of using BinaryFormatter I have used BinaryWriter and BinaryReader as follows...
In program 1 (the creator):
private byte[] setByteData(Sudoku sdk) {
List<int> clues = sdk.puzzleListData();
byte[] bd = new byte[puzzleSize];
SudokuSolver solver = new SudokuSolver();
List<int> solution = solver.Solve(sdk.Copy(), false, currentDifficulty).puzzleListData();
for(int i = 0; i < puzzleSize; i++) {
bd[i] = Convert.ToByte(solution[i] + (clues[i] == 0 ? 0xF0 : 0));
}
return bd;
}
private GameData setGameData(Sudoku sdk) {
List<int> clues = sdk.puzzleListData();
GameData gd = new GameData();
gd.id = puzzleList.Items.Count;
gd.difficulty = currentDifficulty;
SudokuSolver solver = new SudokuSolver();
List<int> solution = solver.Solve(sdk.Copy(), false, currentDifficulty).puzzleListData();
for(int i = 0; i < puzzleSize; i++) {
gd.content.Add(solution[i] + (clues[i] == 0 ? 0xF0 : 0));
}
return gd;
}
private List<int> getByteData(byte[] data) {
List<int> retVal = new List<int>();
foreach(byte i in data) {
if(i > 9) {
retVal.Add(i - 0xF0);
} else {
retVal.Add(0);
}
}
return retVal;
}
private string getGameData(List<int> data) {
string retVal = "";
foreach(int i in data) {
if(i > 9) {
retVal += (i - 0xF0).ToString();
} else {
retVal += i.ToString();
}
}
return retVal;
}
private void saveGame(Sudoku sdk) {
FileStream file = null;
BinaryWriter bw = null;
try {
if(!File.Exists(gameDataFile[currentDifficulty])) {
file = File.Open(gameDataFile[currentDifficulty], FileMode.CreateNew);
} else {
file = File.Open(gameDataFile[currentDifficulty], FileMode.Append);
}
bw = new BinaryWriter(file);
currentData = setGameData(sdk);
byte[] bd = setByteData(sdk);
bw.Write(currentData.id);
bw.Write(currentData.difficulty);
bw.Write(bd);
savePuzzleLog();
} catch(Exception e) {
Debug.LogException("saveGame", e);
}
if(file != null) {
if(bw != null) {
bw.Flush();
bw.Close();
}
file.Close();
}
}
In program 2: (the actual game)
public bool loadGameData() {
if(gameData == null) {
gameData = new List<GameData>();
} else {
gameData.Clear();
}
bool loadData = true;
bool OK = false;
if(File.Exists(gameDataFile[currentDifficulty])) {
FileStream file = File.Open(gameDataFile[currentDifficulty], FileMode.Open);
BinaryReader br = new BinaryReader(file);
while(loadData) {
try {
GameData gd = new GameData();
gd.id = br.ReadInt32();
gd.difficulty = br.ReadInt32();
gd.content = getByteData(br.ReadBytes(puzzleSize));
gameData.Add(gd);
OK = true;
if(file.Position == file.Length) {
loadData = false;
}
} catch(Exception e) {
Debug.LogException(e);
loadData = false;
OK = false;
}
}
if(file != null) {
file.Close();
}
} else {
Debug.LogWarning(gameDataFile[currentDifficulty] + " does not exist!");
}
return OK;
}
The class structure is the same as before but using this method has resolved my issue and I can now create the data files using my creator and load the data comfortably using the actual game.
Thanks all for your assistance and advice to help me get this sorted.

BioMetric FingerPrint

I am using ZKFinger SDK2.3.3.1 version and Device
Communication Protocol SDK(32Bit Ver6.2.4.1 -- DLL Version : zkemkeeper.dll - 6.2.4.1. I have a small USB fingerprint scanner. When I scan the fingerprint,
I get an array of bytes . I saved it to disc in a bitmap file and jpg both and the fingerprint looks quite good scanned. To set the fingerprint template to a user on the device, i decomporessed fingerprint image, and then call SetUserTmp Function of zkemkeeper.dll.
I am getting size error , (-3) in code.
How can i go further? What is my mistake?
Below is my code for transfering finger from USB device to BioMetric device
bool fullImage = false;
zkfpEng.SaveJPG("Myfirstfinger.jpg");
string strtmp, sRegTemplate;
object pTemplate;
sRegTemplate = zkfpEng.GetTemplateAsStringEx("9");
pTemplate = zkfpEng.DecodeTemplate1(sRegTemplate);
// Note: 10.0Template can not be compressed
zkfpEng.SetTemplateLen(ref pTemplate, 602);
zkfpEng.SaveTemplate("Myfirstfingerprint.tpl", pTemplate);
byte[] TmpData = new byte[700];
TmpData =ObjectToByteArray(pTemplate);
if (bIsConnected == false)
{
MessageBox.Show("Please connect the device first!", "Error");
return;
}
int idwFingerIndex = Convert.ToInt32(cbFingerIndex.Text.Trim());
int idwEnrollNumber = Convert.ToInt32(txtUserID.Text.Trim());
int iTmpLength = 0;
string sdwEnrollNumber = txtUserID.Text.Trim();
axCZKEM1.EnableDevice(iMachineNumber, false);
Cursor = Cursors.WaitCursor;
bool IsSetTmp = false;
IsSetTmp = axCZKEM1.SetUserTmp(iMachineNumber, idwEnrollNumber, idwFingerIndex, ref TmpData[0]);
int errCode = 0;
axCZKEM1.GetLastError(ref errCode);
MessageBox.Show(IsSetTmp.ToString() + " " + errCode.ToString());
if (IsSetTmp == true)
{
MessageBox.Show("User template set successfully!", "Success");
}
else
{
MessageBox.Show("User template not set successfully!", "Error");
}
i think you don't have to convert it to image file, just like Remin said.
here some example. i'm using xaf and mysql db
private void DownloadUserInformationAction_Execute(object sender, SimpleActionExecuteEventArgs e)
{
IObjectSpace os = Application.CreateObjectSpace();
Terminal terminal = (Terminal)View.SelectedObjects[0];
//create new czkemclass obj
CZKEMClass myCZKEMClass = new CZKEMClass();
//connecting the device
myCZKEMClass.Connect_Net(terminal.IPAddress, terminal.Port);
//Initialize variable for store temporary user information
int tMachineNo = 0;
string tEnrollNo = "";
string tName = "";
string tPassword = "";
int tPrivilage = 0;
bool tEnabled = false;
int tFingerIndex;
int tFlag = 0;
string tTemplateData = "";
int tTemplateLength = 0;
myCZKEMClass.EnableDevice(terminal.DeviceId, false);
myCZKEMClass.ReadAllUserID(terminal.DeviceId);
myCZKEMClass.ReadAllTemplate(terminal.DeviceId);
while (myCZKEMClass.SSR_GetAllUserInfo(tMachineNo, out tEnrollNo, out tName, out tPassword, out tPrivilage, out tEnabled))
{
for (tFingerIndex = 0; tFingerIndex < 10; tFingerIndex++)
{
if (myCZKEMClass.GetUserTmpExStr(tMachineNo, tEnrollNo, tFingerIndex, out tFlag, out tTemplateData, out tTemplateLength))
{
EmployeeBiometric employeeBiometric = new EmployeeBiometric(terminal.Session);
//employeeBiometric.EnrollNumber = tEnrollNo;
XPCollection<Employee> employees = new XPCollection<Employee>(terminal.Session);
employeeBiometric.Employee = employees.Where(emp => emp.EnrollNo == tEnrollNo).FirstOrDefault();//(emp => emp.Sequence.ToString() == tEnrollNo).FirstOrDefault();
employeeBiometric.UserName = tName;
employeeBiometric.Password = tPassword;
employeeBiometric.Privilege = (Privilege)Enum.ToObject(typeof(Privilege), tPrivilage);
employeeBiometric.Enabled = tEnabled;
employeeBiometric.FingerprintIndex = tFingerIndex;
employeeBiometric.FingerprintTemplate = tTemplateData;
employeeBiometric.TemplateLength = tTemplateLength;
terminal.Session.CommitTransaction();
}
}
}
myCZKEMClass.EnableDevice(terminal.DeviceId, true);
}
that's method for downloading the your fingerprint image from device to your apps.
and here you can upload it back to another device
private void UploadUserInformationAction_Execute(object sender, PopupWindowShowActionExecuteEventArgs e)
{
IObjectSpace os = Application.CreateObjectSpace();
EmployeeBiometric employeeBiometric = (EmployeeBiometric)View.SelectedObjects[0];
EmployeeBiometricParameter param = (EmployeeBiometricParameter)e.PopupWindowViewCurrentObject;
//create new czkemclass obj
CZKEMClass myCZKEMClass = new CZKEMClass();
//connecting the device
myCZKEMClass.Connect_Net(param.Terminal.IPAddress, param.Terminal.Port);
myCZKEMClass.EnableDevice(param.Terminal.DeviceId, false);
int myCount = View.SelectedObjects.Count;
//Set specific user to fingerprint device
for (int i = 1; i <= myCount; i++)
{
int tMachineNo = param.Terminal.DeviceId;
string tEnrollNo = employeeBiometric.Employee.EnrollNo;//Sequence.ToString();
string tName = employeeBiometric.UserName;
string tPassword = employeeBiometric.Password;
int tPrivilege = (int)employeeBiometric.Privilege;
bool tEnabled = employeeBiometric.Enabled;
int tFingerIndex = employeeBiometric.FingerprintIndex;
string tTmpData = employeeBiometric.FingerprintTemplate;
int tFlag = 1;
if (myCZKEMClass.SSR_SetUserInfo(tMachineNo, tEnrollNo, tName, tPassword, tPrivilege, tEnabled))
{
myCZKEMClass.SetUserTmpExStr(tMachineNo, tEnrollNo, tFingerIndex, tFlag, tTmpData);
}
}
myCZKEMClass.RefreshData(param.Terminal.DeviceId);
myCZKEMClass.EnableDevice(param.Terminal.DeviceId, true);
}
and this is my "Terminal" Class
public partial class Terminal : XPCustomObject
{
Guid fOid;
[Key(AutoGenerate = true), Browsable(false)]
public Guid Oid
{
get { return fOid; }
set { SetPropertyValue<Guid>("Oid", ref fOid, value); }
}
private Branch _Branch;
[RuleRequiredField("", DefaultContexts.Save, "Branch required")]
public Branch Branch
{
get
{
return _Branch;
}
set
{
SetPropertyValue("Branch", ref _Branch, value);
}
}
string fDescription;
[RuleUniqueValue("", DefaultContexts.Save, "The value was already registered within the system.", ResultType = ValidationResultType.Warning)]
[RuleRequiredField("", DefaultContexts.Save, "Description required")]
public string Description
{
get { return fDescription; }
set { SetPropertyValue<string>("Description", ref fDescription, value); }
}
string fIPAddress;
[Size(15)]
public string IPAddress
{
get { return fIPAddress; }
set { SetPropertyValue<string>("IPAddress", ref fIPAddress, value); }
}
private int _Port;
public int Port
{
get
{
return _Port;
}
set
{
SetPropertyValue("Port", ref _Port, value);
}
}
string fDeviceDescription;
public string DeviceDescription
{
get { return fDeviceDescription; }
set { SetPropertyValue<string>("DeviceDescription", ref fDeviceDescription, value); }
}
private int _DeviceId;
public int DeviceId
{
get
{
return _DeviceId;
}
set
{
SetPropertyValue("DeviceId", ref _DeviceId, value);
}
}
private bool _Disabled;
public bool Disabled
{
get
{
return _Disabled;
}
set
{
SetPropertyValue("Disabled", ref _Disabled, value);
}
}}
Read the FP as string and push the same string to the Biometric device without any compression or conversion.

itunes listening to

within windows live messenger, it is possible to share the song you are currently listening to. what would i need to do to get this working within c# like libarys etc cannot find the correct documentation on google.
You'll need to use the iTunes SDK to interact with iTunes from .NET. So there's your Google search term. :)
Here's a start:
http://blogs.msdn.com/b/noahc/archive/2006/07/06/automating-itunes-with-c-in-net.aspx
http://blogs.msdn.com/b/dancre/archive/2004/05/08/128645.aspx
Here is a script for LinqPad in C# which does as requested. (see LinqPad.com)
Bonus! Artwork view.
It looks like this:
<Query Kind="Program">
<Namespace>iTunesLib</Namespace>
<Namespace>System.Security.Cryptography</Namespace>
</Query>
void Main()
{
var track = new iTunesApp().CurrentTrack;
if (track == null)
"nothing playing".Dump();
else
new Viewer(track,true).Dump();
}
public class Viewer
{
const string PREFIX = "itlps-";
private IITFileOrCDTrack store;
private bool materialize;
public string album { get { return store.Album; } }
public string band { get { return store.Artist; } }
public string song { get { return store.Name; } }
public string desc { get { return store.Description; } }
public int? artCnt { get {
if (store.Artwork == null) return null;
else return store.Artwork.Count; }
}
public IEnumerable<ImageViewer> art { get {
if (materialize)
{
foreach(var artT in store.Artwork)
{
var art = artT as IITArtwork;
string ext = ".tmp";
switch(art.Format)
{
case ITArtworkFormat.ITArtworkFormatBMP:
ext = ".BMP";
break;
case ITArtworkFormat.ITArtworkFormatJPEG:
ext = ".JPG";
break;
case ITArtworkFormat.ITArtworkFormatPNG:
ext = ".PNG";
break;
}
string path = Path.Combine(Path.GetTempPath(),PREFIX+Path.GetRandomFileName()+ext);
art.SaveArtworkToFile(path);
yield return new ImageViewer(path);
}
}
yield break; }
}
public Viewer(IITFileOrCDTrack t,bool materializeArt = false)
{
store = t;
materialize = materializeArt;
}
public Viewer(IITTrack t,bool materializeArt = false)
{
store = t as IITFileOrCDTrack;
materialize = materializeArt;
}
}
public class ImageViewer
{
public string hash { get { return _hash.Value; } }
static private string _path { get; set; }
public object image { get { return _image.Value; } }
static private SHA1Managed sha = new SHA1Managed();
private Lazy<object> _image = new Lazy<object>(() => {return Util.Image(_path);});
private Lazy<string> _hash = new Lazy<string>(() =>
{
string hash = string.Empty;
using (FileStream stream = File.OpenRead(_path))
{
byte [] checksum = sha.ComputeHash(stream);
hash = BitConverter.ToString(checksum).Replace("-", string.Empty);
}
return hash;
});
public ImageViewer(string path)
{
_path = path;
}
}
last i checked this functionality is included out of the box all you need is to have itunes and windows live messenger installed and activate "what im listening to" and it shows this in your messenger status. if you are looking to create a bot that messages this out to a contact that is a different story tho that you will need to write a script for

Categories