Parsing JSON object with Windows Phone 7 - c#

I'm trying to read from a Uri which i created and to display it on windows phone 7 app.
(I'm doing this tutorial:http://msdn.microsoft.com/en-us/windowsmobile/Video/hh237494).
My problem is that the program doesnt get into the OpenReadCompletedEventHandler and i dont know why. (i putted message box in order to debug and i found out that the program doesnt get into the OpenReadCompletedEventHandler). Here is the relevant code:
void myButton_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://localhost:44705/Service1.svc/GetAllBrands");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenWriteAsync(uri);
MessageBox.Show("opening sucsseded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
MessageBox.Show("OpenRead Handler");
// OpenWriteCompletedEventArgs temp = (OpenWriteCompletedEventArgs)e;
DataContractJsonSerializer serializer = null;
try
{
serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Brand>));
ObservableCollection<Brand> Brands = serializer.ReadObject(e.Result) as ObservableCollection<Brand>;
foreach (Brand b in Brands)
{
int id = b.BrandId;
string name = b.BrandName;
listBrands.Items.Add(id + " " + name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance!

I have never used this but a quick google takes me to this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openreadcompleted.aspx
This should tell you why it's not working - because you are using a read event for a write operation. You should be using OpenWriteCompletedEventHandler with OpenWriteAsync as per this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openwritecompleted.aspx

Related

SVN credentials

I have an issue where I keep getting an error
No provider registered for 'svn.ssl.server' credentials
I am using the same code that works on another SVN server, but a new server I setup can't seem to connect even though I can connect no problem through a web browser.
//SVN Client repo sync
public void DownloadSVNStartup(string url, string path)
{
using (SvnClient client = new SvnClient())
{
try
{
client.CleanUp(path); //will go to catch block since there's no working copy yet I
//want to checkout for the first time then next time this part
//will work.
SvnUI.Bind(client, this);
SvnCheckOutArgs sco = new SvnCheckOutArgs();
sco.AllowObstructions = false;
}
catch (Exception ex)
{
MessageBox.Show("Line 88");
MessageBox.Show(ex.ToString());
myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
client.Configuration.SetOption("servers", "global", "http-auth-types", "basic;digest");
client.Authentication.Clear();
client.Authentication.ForceCredentials("user", "password");
try
{
client.Authentication.SslServerTrustHandlers += delegate (object sender,
SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = false; // Save acceptance to authentication store
};
Object[] args = { url, path };
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += backgroundWorker1_DoWork;
worker.RunWorkerAsync(args);
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show("Line126");
MessageBox.Show(ex.ToString());
myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //connect to the Svn
//server
{
try
{
Object[] arg = e.Argument as Object[];
string url = (string)arg[0];
string path = (string)arg[1];
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Prevents saving/loading config to/from disk
client.Authentication.ForceCredentials("user", "password");
client.CheckOut(new Uri(url), path); //fails here with the error No provider registered for 'svn.ssl.server' credentials
client.CleanUp(path);
client.Update(path);
client.CleanUp(path);
}
}
catch (Exception ex)
{
MessageBox.Show("Line166", ex.Message.ToString());
MessageBox.Show(ex.ToString());
}
}
I have searched for hours for solutions and can't find anything.
Both servers are setup with same port, same HTTPS settings and created certificates, same VisualSVN server editions.
I have tried only the one solution that I could find as this is not a common issue at all.
This is supposed to fix that error but it doesn't.
client.Authentication.SslServerTrustHandlers += delegate (object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = false; // Save acceptance to authentication store
};
I fixed it with adding an event handler for the certificate
private void SslClientCertificateHandlers(object sender, SvnSslClientCertificateEventArgs e)
{
e.Save = true;
e.CertificateFile = #"where you want to save certs";
}

C# Serial Port communication issue

I have a problem with a small C# application.
The application has to connect through a serial port to a bar code scanner which reads a Data Matrix code. The Data Matrix code represents an array of bytes which is a zip archive. I read a lot about the way SerialPort.DataReceived work but I can't find an elegant solution to my problem. And the application should work with different bar code scanners so i can't make it scanner specific. Here is some of my code:
using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using Ionic.Zip;
namespace SIUI_PE
{
public partial class Form1 : Form
{
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
return;
}
_serialPort.Handshake = Handshake.None;
_serialPort.ReadBufferSize = 10000;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
_serialPort.Open();
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[10000];
_serialPort.Read(data, 0, 10000);
File.WriteAllBytes(Directory.GetCurrentDirectory() + "/temp/fis.zip", data);
try
{
using (ZipFile zip = ZipFile.Read(Directory.GetCurrentDirectory() + "/temp/fis.zip"))
{
foreach (ZipEntry ZE in zip)
{
ZE.Extract(Directory.GetCurrentDirectory() + "/temp");
}
}
File.Delete(Directory.GetCurrentDirectory() + "/temp/fis.zip");
}
catch (Exception ex1)
{
MessageBox.Show("Corrupt Archive: " + ex1.ToString());
}
}
}
}
So my question is: How can I know that I read all the bytes the scanner sent?
The code I've got for reading barcode data, which has been working flawlessly in production for several years looks like this:
Note, my app has to read standard UPC barcodes as well as GS1 DataBar, so there's a bit of code you may not need...
The key line in this is:
string ScanData = ScannerPort.ReadExisting();
which is found in the DoScan section, and simply reads the scan data as a string. It bypasses the need to know how many bytes are sent, and makes the rest of the code easier to deal with.
// This snippet is in the Form_Load event, and it initializes teh scanner
InitializeScanner();
ScannerPort.ReadExisting();
System.Threading.Thread.Sleep(1000);
// ens snippet from Form_Load.
this.ScannerPort.DataReceived += new SerialDataReceivedEventHandler(ScannerPort_DataReceived);
delegate void DoScanCallback(); // used for updating the form UI
void DoScan()
{
if (this.txtCouponCount.InvokeRequired)
{
DoScanCallback d = new DoScanCallback(DoScan);
this.Invoke(d);
return;
}
System.Threading.Thread.Sleep(100);
string ScanData = ScannerPort.ReadExisting();
if (isInScanMode)
{
try
{
HandleScanData(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan");
}
}
}
void ScannerPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// this call to sleep allows the scanner to receive the entire scan.
// without this sleep, we've found that we get only a partial scan.
try
{
DoScan();
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to handle scan event in ScannerPort_DataReceived." + System.Environment.NewLine + ex.ToString());
}
}
void Port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(e.EventType.ToString());
}
private void HandleScanData(string ScanData)
{
//MessageBox.Show(ScanData + System.Environment.NewLine + ScanData.Length.ToString());
//Determine which type of barcode has been scanned, and handle appropriately.
if (ScanData.StartsWith("A") && ScanData.Length == 14)
{
try
{
ProcessUpcCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process UPC coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else if (ScanData.StartsWith("8110"))
{
try
{
ProcessDataBarCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process DataBar coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan" + System.Environment.NewLine + ScanData);
}
}
private void InitializeScanner()
{
try
{
ScannerPort.PortName = Properties.Settings.Default.ScannerPort;
ScannerPort.ReadBufferSize = Properties.Settings.Default.ScannerReadBufferSize;
ScannerPort.Open();
ScannerPort.BaudRate = Properties.Settings.Default.ScannerBaudRate;
ScannerPort.DataBits = Properties.Settings.Default.ScannerDataBit;
ScannerPort.StopBits = Properties.Settings.Default.ScannerStopBit;
ScannerPort.Parity = Properties.Settings.Default.ScannerParity;
ScannerPort.ReadTimeout = Properties.Settings.Default.ScannerReadTimeout;
ScannerPort.DtrEnable = Properties.Settings.Default.ScannerDtrEnable;
ScannerPort.RtsEnable = Properties.Settings.Default.ScannerRtsEnable;
}
catch (Exception ex)
{
MessageBox.Show("Unable to initialize scanner. The error message received will be shown next. You should close this program and try again. If the problem persists, please contact support.", "Error initializing scanner");
MessageBox.Show(ex.Message);
Application.Exit();
}
}
As stated in the doc for SerialPort.DataReceived, "Use the BytesToRead property to determine how much data is left to be read in the buffer."
here is the doc for SerialPort.BytesToRead
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx

event handler cannot be executed

I got a problem in my WP-7 app.
I have an event when I read from the cloud - OpenReadCompletedEventHandler,
but somehow when the event occurs the EventHandler cannot be executed.
Here is my functions:
public void SetCategories()
//set the Companies table from Shret.net DataBase
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://api.sherut.net/?method=Category");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer serializer = null;
try
{
serializer = new DataContractJsonSerializer(typeof(Categories));
var categories = (Categories)serializer.ReadObject(e.Result);
// foreach (Company c in companies.data)
// MessageBox.Show(c.Name + " " + c.CompanyID+" "+c.CompanyGUID);
//לכתוב לבסיס נתונים באפליקציה
BuildCategoriesDB(); //build the local data base
AddCategoriesData(categories);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It reads from the cloud, but it doesn't go inside the handler: webClient_OpenReadCompleted
Check to make sure the event is being created and "thrown".

error in C# project

here are my two functions:
public void SetCompanies()
//set the Companies table from Shret.net DataBase
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://api.sherut.net/?method=Company");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenWriteCompletedEventArgs e)
{
try
{
DataContractJsonSerializer serializer = null;
var companies = (Companies)serializer.ReadObject(e.Result);
foreach (Company c in companies.data)
{
MessageBox.Show(c.Name + " " + c.CompanyID);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
and this is the error i get:
"No overload for 'webClient_OpenReadCompleted' matches delegate
'System.Net.OpenReadCompletedEventHandler'"
i dont understand why, because i wrote the handler after this function......
Thanks in advance!
OpenReadCompleted doesn't take OpenWriteCompletedEventArgs.

Simple webclient request returning MS.InternalMemoryStream

I have a simple webclient that connects to a webpage and returns the data. The code is as follows:
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("https://domain.com/register.php?username=" + txtbUser.Text);
webClient.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
//Process web service result here
MessageBox.Show(e.Result.ToString());
}
else
{
//Process web service failure here
MessageBox.Show(e.Error.Message);
}
}
The data coming from e.Result is MS.InternalMemoryStream and not the data coming back from the webpage, the data coming back from the webpage should just be a 0 or 1. Any idea's?
thanks,
Nathan
.ToString() returns the name of the class - in this case, InternalMemoryStream. You have to READ the stream to get the result. Check this out

Categories