How can I convert a string to a stream? - c#

I would like to parse some JSON:
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(STMsgObj));
STMsgObj[] messages = (STMsgObj[])serializer.ReadObject(stream);
foreach(STMsgObj aMsg in messages){
MessageBox.Show(aMsg.body, "Data Passed", MessageBoxButton.OK);
}
}
}
How can I convert e.Result into a stream?
Exception:
System.InvalidCastException was unhandled
Message=InvalidCastException
StackTrace:
at StockTwits.ViewModels.StreamPage.webClient_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

Try the following:
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
{
// Your code here, using stream.
}

Call DownloadDataAsync instead.
You can then pass new MemoryStream(e.Result) from the DownloadDataCompleted event.
If you really want to stick with DownloadStringAsync, you can pass XmlReader.Create(new StringReader(e.Result)).

Given that WebClient wraps an API that is already stream based means there are a number of unnecessary conversions. You might want to consider swapping your WebClient for plain old HttpWebRequest, which hands you a stream out of the box.
HttpWebRequest req=(HttpWebRequest)WebRequest.Create(myUrl);
using(var resp=req.GetResponse())
using(var stream=resp.GetResponseStream())
{
...
}

Your JSON data isn't an array.

Related

ArgumentOutOfRange exception on ConfigureAwait(false)

I've the following function:
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(string));
dynamic handler = _c.Resolve(handlerType);
var test1 = await handler.Run(query);
var test2 = await handler.Run(query).ConfigureAwait(false);
The first await statement runs fine but the second statement gives me an ArgumentOutOfRange exception. I've really no idea why this is happening.
I'm using Autofac for resolving the my services.
Can you guys please help me with this?
EDITED:
at System.String.Substring(Int32 startIndex, Int32 length)
at Microsoft.CSharp.RuntimeBinder.Syntax.NameTable.Add(String key, Int32 length)
at Microsoft.CSharp.RuntimeBinder.Syntax.NameManager.Add(String key, Int32 length)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.GetName(Type type)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.LoadSymbolsFromType(Type originalType)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.AddMethodToSymbolTable(MemberInfo member, AggregateSymbol callingAggregate, MethodKindEnum kind)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.AddNamesInInheritanceHierarchy(String name, List`1 inheritance)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.PopulateSymbolTableWithName(String name, IEnumerable`1 typeArguments, Type callingType)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.PopulateSymbolTableWithPayloadInformation(SymbolTable symbolTable, ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments)
at Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder.PopulateSymbolTableWithName(SymbolTable symbolTable, Type callingType, ArgumentObject[] arguments)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindCore(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind(DynamicMetaObjectBinder payload, Expression[] parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind(DynamicMetaObjectBinder action, RuntimeBinder binder, DynamicMetaObject[] args, IEnumerable`1 arginfos, DynamicMetaObject onBindingError)
at Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder.FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
at System.Dynamic.DynamicMetaObject.BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
at System.Dynamic.InvokeMemberBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args)
at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Kairos.Services.ImportService.ImportService.<RunAsync>d__4.MoveNext() in F:\Sources\BZ\Kairos\Services\Kairos.Services.ImportService\ImportService.cs:line 61

RestSharp Moq Object Null Exception C# REST Unit Test

I'm having difficulties trying to figure this out. Any help is greatly appreciated. My restClient.Object gets a null exception. When I inspect the .Object of the restClient I get
Message: Exception has been thrown by the target of an invocation.
Inner Exception: Value cannot be null.Parameter name: source
Stack Trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__2()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock.GetObject()
at Moq.Mock.get_Object()
at Moq.Mock`1.get_Object()
Btw, I'm referring to this line of code:
var client = new IncidentRestClient(**restClient.Object**);
Am I mocking the object incorrectly?
[Test]
public void Insert_Method_Throws_exception_if_response_StatusCode_is_not_Created()
{
//Arrange
var restClient = new Mock<RestClient>();
restClient.Setup(x => x.Execute<RootObject>(It.IsAny<IRestRequest>()))
.Returns(new RestResponse<RootObject>
{
StatusCode = HttpStatusCode.BadRequest
});
var client = new IncidentRestClient(restClient.Object);
Assert.Throws<Exception>(() => client.CreateNewIncident(insertIncidentRequest));
}
Uninstalling and reinstalling Moq did not work for me. Instead, setting the CallBase property on the Mock object to true did the trick:
var restClientMock = new Mock<RestClient> { CallBase = true };
Issue has been resolved. I had to uninstall and reinstall Moq with nuget.

Throw ProtocolViolationException when download large size file in Windows Phone 7

I'm writing an app which need to download very large size files (usually more than 150MB) into the machine. I knew that the WebClient has buffer limit and able to be used in my case. Therefore, I followed the way of using HttpWebRequest to write my download function in here: http://dotnet.dzone.com/articles/2-things-you-should-consider?mz=27249-windowsphone7. The following is my code:
private void _downloadBook(string _filePath)
{
Uri _fileUri = new Uri(_filePath);
//DownloadFileName = System.IO.Path.GetFileName(_fileUri.LocalPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUri);
request.AllowReadStreamBuffering = false;
request.BeginGetRequestStream(new AsyncCallback(GetData), request);
}
private void GetData(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream str = response.GetResponseStream();
byte[] data = new byte[16 * 1024];
int read;
long totalValue = response.ContentLength;
while ((read = str.Read(data, 0, data.Length)) > 0)
{
if (streamToWriteTo.Length != 0)
Debug.WriteLine((int)((streamToWriteTo.Length * 100) / totalValue));
streamToWriteTo.Write(data, 0, read);
}
streamToWriteTo.Close();
Debug.WriteLine("COMPLETED");
}
However, it threw the ProtocolViolationException with the following stack:
System.Net.ProtocolViolationException was unhandled
Message=ProtocolViolationException
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.InternalBeginGetRequestStream(AsyncCallback callback, Object state)
at System.Net.Browser.ClientHttpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
at HHC_EbookReaderWP7.ComicPage._downloadBook(String _filePath)
at HHC_EbookReaderWP7.ComicPage.b__2()
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
Anything wrong with my code? or do I need to further on it? Thanks.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx
As adontz mentioned. Give us the exact line that throws the exception. And according the silverlight doc. you need to call begingetresponsestream instead of the sync. getresponsestream. It also shows you some reasons for a protocol violationexception. Check this with the WP7 documentation.
To get the exact line of the exception, goto Debug In the top menu bar of vs2010 and goto Exceptions and enable the checkboxes for "Thrown"
Hope this helps.

HttpWebResponse error, not found

I have a strange issue using HttpWebRequest, I'm trying to post a string to a service but HttpWebResponse keeps producing the following error;
"System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)\r\n at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass2.<EndGetResponse>b__1(Object sendState)\r\n at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__1(Object sendState)\r\n at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)\r\n at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)\r\n at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)\r\n at System.Delegate.DynamicInvokeOne(Object[] args)\r\n at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)\r\n at System.Delegate.DynamicInvoke(Object[] args)\r\n at System.Windows.Threading.Dispatcher.<>c__DisplayClass4.<FastInvoke>b__3()\r\n at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)\r\n at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)\r\n at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)\r\n at System.Delegate.DynamicInvokeOne(Object[] args)\r\n at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)\r\n at System.Delegate.DynamicInvoke(Object[] args)\r\n at System.Windows.Threading.DispatcherOperation.Invoke()\r\n at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)\r\n at System.Windows.Threading.Dispatcher.OnInvoke(Object context)\r\n at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)\r\n at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)\r\n at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)\r\n\r\n at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)\r\n at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n at ZabbixClient.MainPage.ResponseCallBack(IAsyncResult result)\r\n at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)\r\n at System.Threading.ThreadPool.WorkItem.doWork(Object o)\r\n at System.Threading.Timer.ring()\r\n"
My code looks like;
private void btnSignin_Click(object sender, RoutedEventArgs e)
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://monitor.co.uk", UriKind.Absolute));
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(RequestCallBack), myRequest);
}
void RequestCallBack(IAsyncResult result) {
HttpWebRequest myRequest = result.AsyncState as HttpWebRequest;
//need error checking for this part
Stream stream = myRequest.EndGetRequestStream(result);
using (StreamWriter sw = new StreamWriter(stream)){
sw.Write("{ \"jsonrpc\":\"2.0\",\"method\":\"user.authenticate\",\"params\":{\"user\":\"<login>\",\"password\":\"<password>\"},\"id\":2}");
}
myRequest.BeginGetResponse(ResponseCallBack, myRequest);
}
void ResponseCallBack(IAsyncResult result)
{
//get to the request object
HttpWebRequest myRequest = result.AsyncState as HttpWebRequest;
try
{
//need error checking here
HttpWebResponse response = myRequest.EndGetResponse(result)
as HttpWebResponse;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(sr.ReadToEnd()); });
}
}
catch (WebException webExcp)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(webExcp.ToString()); });
}
}
I just can't figure out what's going on, the URL is specified correctly and working, I read to use fiddle to monitor what was going on but nothing appears in fiddler suggesting it's not even getting to make a request? Any info would be appreciated. Thanks!
First, let me point out a problem in your code:
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(sr.ReadToEnd()); });
}
The stream will be closed by the time you will attempt to display the result. What you should do is have something like this:
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
String s = sr.ReadToEnd();
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(s); });
}
Yet, I am not sure why you want to display the response in a MessageBox instance - it will be basically unreadable - use the Output console for debugging purposes.
Back on topic - NotFound is usually returned by the server and has nothing to do with the request being processed by the OS. It is a very generic error and you need to make sure that what you are invoking is supported on the other end.
Make sure that you have a good Internet connection (on a side note).
I had the same problem.
I got a proxy server and the problem starts here. I started the emulator and then, kept enabling and disabling the proxy server. I find out that when the emulator is stated up it keeps the proxy configurations, even if you change the proxy it always keeps the inicial configurations.
Then, I disabled the proxy, started the emulator up and my application worked perfectly. The Windows Phone 7.1 httpWebRequest doesn't work fine with proxy. I didn't have the same problem using the Windows Phone 7 httpWebRequest. I just come across with this problem after converting my Windows Phone 7 application to Windows Phone 7.1.
Hope it can help you

Error in Binding datasource to combobox

I have the below mentioned method where i am binding DataSource to the combobox control.
// floorLocnList is coming from a webservice method
private void lstFloor_BindFloor(FloorLocModel[] floorLocnList)
{
this.comboBox1.DataSource = floorLocnList;
this.comboBox1.DisplayMember = "Location";
this.comboBox1.ValueMember = "FloorLoc";
}
and class defined like this
[Serializable]
public class FloorLocModel
{
private int floorLoc;
private string location;
public int FloorLoc
{
get
{
return this.floorLoc;
}
set
{
this.floorLoc = value;
}
}
public string Location
{
get
{
return this.location;
}
set
{
this.location = value;
}
}
}
Shows Error Value Does not Fall within the Expected Range after reaching the assignment of value to ValueMember
Bug Detail:
at System.Windows.Forms.ListControl._SetDataBinding(Object newDataSource, BindingMemberInfo newDisplayMember, Boolean fForceRebind)
at System.Windows.Forms.ListControl.set_ValueMember(String value)
at IdineSmart.frmLogin.lstFloor_BindFloor(FloorLocModel[] floorLocnList)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Windows.Forms.Control.TASK.Invoke()
at System.Windows.Forms.Control._InvokeAll()
at System.Windows.Forms.Control.WnProc(WM wm, Int32 wParam, Int32 lParam)
at System.Windows.Forms.ListView.WnProc(WM wm, Int32 wParam, Int32 lParam)
at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
at Microsoft.AGL.Forms.EVL.EnterModalDialog(IntPtr hwnModal)
at System.Windows.Forms.Form.ShowDialog()
at IdineSmart.frmMain.frmMain_Load(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form._SetVisibleNotify(Boolean fVis)
at System.Windows.Forms.Control.set_Visible(Boolean value)
at System.Windows.Forms.Application.Run(Form fm)
at IdineSmart.Program.Main()
It was working fine, but i dono suddenly it started giving me the problem. When i debug the code valuemember is displaying empty string even though i assigned it,might be this is the problem but how it can happen like this. Please help me.
Thanks in advance.
I'm not sure, but I think I had the same problem.
Try to change the sequence - DataSource at the end.
this.comboBox1.DisplayMember = "Location";
this.comboBox1.ValueMember = "FloorLoc";
this.comboBox1.DataSource = floorLocnList;
I Found it at last. Its all because of the error message that shown. But the actual problem was i had few user controls in the project that was targeted the platform Pocket PC 2003 SDK and the main project was targeted Pocket PC 2005 SDK. So i made all my project to target the same SDK then problem solved.
Any way thanks for the response.

Categories

Resources