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
Related
I'm new to C#. I'm using .NET IdentityModel with AWS Cognito User Pools and attempting to get logout to work. CreateEndSessionUrl sets post_logout_redirect_uri but Cognito requires logout_uri. I'm attempting to use the extra parameter but getting a Parameter Count Mismatch.
Here is my code:
StringDictionary cognitoParameters = new StringDictionary();
cognitoParameters.Add("client_id", OAuthConfiguration.ClientId);
cognitoParameters.Add("logout_uri", OAuthConfiguration.EndsessionEndpointPath);
var endsessionEndpoint = OAuthConfiguration.Authority.TrimEnd('/') + "/" + OAuthConfiguration.EndsessionEndpointPath;
var requestUrl = new RequestUrl(endsessionEndpoint);
var endSessionUrl = requestUrl.CreateEndSessionUrl(
idTokenHint: HttpContext.Current.GetToken(OidcConstants.ResponseTypes.IdToken),
postLogoutRedirectUri: OAuthConfiguration.Host,
state: null,
extra: cognitoParameters
);
The CreateEndSessionUrl documentation says "The extra parameter can either be a string dictionary or an arbitrary other type with properties. In both cases the values will be serialized as keys/values." I assume I'm creating the string dictionary incorrectly somehow.
The error I get is:
Message: Parameter count mismatch.
Exception type: System.Reflection.TargetParameterCountException
Stack trace:
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at IdentityModel.Internal.ValuesHelper.ObjectToDictionary(Object values)
at IdentityModel.Client.RequestUrlExtensions.CreateEndSessionUrl(RequestUrl request, String idTokenHint, String postLogoutRedirectUri, String state, Object extra)
at Indice.Kentico.Oidc.EndSessionOidcHandler.EndSession()
at Indice.Kentico.Oidc.EndSessionOidcHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Can someone help me understand how to properly format and include the extra parameter? I actually don't need the idTokenHint, postLogoutRedirectUri, or state if they can be excluded.
I figured out that I needed to create a Dictionary instead of a StringDictionary:
IDictionary cognitoParameters = new Dictionary<string,string>() {
{ "client_id", OAuthConfiguration.ClientId },
{ "logout_uri", OAuthConfiguration.Host.TrimEnd('/') + "/SignOut.ashx" }
};
It is working now.
I received the following error message when running SSIS package. The Script Task is using Microsoft Visual C# 2008. Can you please help me to fix the problem?
Thank you very much! I also attach error message:
Error: 2015-12-22 02:58:08.28
Code: 0x00000001
Source: Script Task
Description: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)
at System.Windows.Forms.MessageBox.Show(String text)
at ST_d27b216cd7d64713b54c81f6ac28d805.csproj.ScriptMain.Main()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
End Error
DTExec: The package execution returned DTSER_FAILURE (1).
C# code:
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_d27b216cd7d64713b54c81f6ac28d805.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
// TODO: Add your code here
System.IO.FileInfo fi;
String FilePath = null;
DateTime ModifiedTime = (DateTime)Dts.Variables["File_Modified"].Value;
DateTime LoadDate = (DateTime)Dts.Variables["File_Last_Load_Date"].Value;
Dts.Variables["isModified"].Value = false;
FilePath = Dts.Variables["SourceFolder"].Value.ToString();
ModifiedTime = System.IO.File.GetLastWriteTime(FilePath);
Dts.Variables["File_Modified"].Value = ModifiedTime;
// fi.LastWriteTime;
int result = DateTime.Compare(ModifiedTime, LoadDate);
if (result > 0)
{
MessageBox.Show("File Modified after last load in staging");
Dts.Variables["isModified"].Value = true;
}
else
{
MessageBox.Show("file is not modified since last load");
Dts.Variables["isModified"].Value = false;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
The error message extracted from your stack trace is:
Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
You have to remember that although when you are debugging your SSIS package you have a nice UI (BIDS or SQL Server Tools shells depending on your environment) but really it is not designed to be have a UI. What would you expect to happen when this package is deployed to a server and called by a SQL Job? i.e. Where would the message box show? Who would click "OK" to allow the thread to resume?
You probably want to just fire an information event if you are looking to post feedback, something like:
bool fireAgain = false;
Dts.Events.FireInformation(0, "Script Task", "File Modified after last load in staging", String.Empty, 0, ref fireAgain);
The error is raised because your script task is trying to display a message box and showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Therefore if you want to output a message, you could use Dts.Log instead, see the MSDN documentation for further details.
Very strange error, basically I fire off a thread once a user has logged into my app which loads data from an xml file using this code snippet:
public static T Deserialize<T>(String Path)
{
T Result = Activator.CreateInstance<T>();
try
{
if (File.Exists(Path))
{
using (FileStream fs = new FileStream(Path, FileMode.Open))
{
if (fs.Length > 0)
{
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(T));
Result = (T)s.Deserialize(fs);
}
fs.Close();
}
// force clean up!
GC.Collect();
}
return Result;
}
catch (Exception ex)
{
Console.WriteLine("Deserialize '{0}' : {1}", Path, ex.ToString());
return Result;
}
}
The XML file that it is loading is about 3MB, if that matters. EVERY single time it fails on one particular file with this exception:
Deserialize 'C:\bin\Debug\Settings\Objects.xml' :
System.Threading.ThreadAbortException: Thread was being aborted.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object
obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Xml.Serialization.TempAssembly.InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, String
encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at Classes.XmlSerializer.Deserialize[T](String Path) in
c:\Classes\XmlSerializer.cs:line 82 Unable to load previous data!
System.Threading.ThreadAbortException: Thread was being aborted.
at Classes.XmlSerializer.Deserialize[T](String Path) in
c:\Classes\XmlSerializer.cs:line 96
at Controllers.ObjectDataCollection.ObjectThread.LoadData() in c:\Controllers\ObjectDataCollection.cs:line 74
I am at a complete loss as to how to debug this further. I know for a fact the thread isn't being aborted because the next line after the attempted deserialization is a loop which scans for things, and it runs perfectly fine (the thread isn't restarted, it's only started it one place).
Does anyone have any ideas as to how I can debug this further? I'm at a complete loss here. Here is all the code: http://pastebin.com/F30vD9KL
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.
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.