I am developing a Xamarin APP where I want to call the Web Service
I don't get any Result from the Web Service but the following Exception:
"An exception occurred during the operation, making the result invalid. Check InnerException for exception details."
I've seen a lot of YouTube Vedio and surfed the Internet for a long time, but I haven't found a solution.
This is my Web Service:
//web Service from ASMX project
public class WStest : System.Web.Services.WebService {
[WebMethod(MessageName = "Test", Description = "test")]
[System.Xml.Serialization.XmlInclude(typeof(Result))]
public Result test() {
Result result = new Result();
result.msg = "test successful";
result.flag = 1;
result.userNum = "usernummer";
return result;
}
}
this is just a part of Xammrain Code
private void Butsend_Click(object sender, EventArgs e) {
WStest.WStest test = new WStest.WStest();
test.testCompleted += Test_testCompleted;
test.testAsync(); //call Web Service
//throw new NotImplementedException();
}
private void Test_testCompleted(object sender, WStest.testCompletedEventArgs e)
{
try
{
var a = e.Result.msg;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message); //here I get the exception
}
}
and thanks for all Answers
You are throwing a bid again NotImplementedException (); at the end of the method, you can only comment :)
Related
I have a .NET appplication where there is a controller for receiving user requests, a service Service 1 which calls another service Service 2.
I have some code in the Service 2 where I query the database(DynamoDB) and get a 500 error in response when the user request values are incorrect. I want to handle this such that I catch this error/exception and send back the error message along with a 400 status code from the controller to the user. How should I modify the code to do this?
This is what I have tried. Currently, I'm just printing the error in Service 1 but I need to send it to the controller. Is sending the error message to the controller by throwing exceptions along the way the right way to do it?
The below code is similar to the actual code
Controller:
[HttpGet]
[Authorize(Policy = "Read-Entity")]
[Route("byParams/{param1}/{param2}")]
[Produces(typeof(DynamoResult<EntityResponse>))]
public async Task<IActionResult> ListByParams([FromQuery] DynamoQuery entityQuery)
{
try
{
return await HandleRequest(async () =>
{
return Ok((await _entityStore.ListByParams(entityQuery)));
});
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
Service 1:
public async Task<DynamoResult<EntityResponse>> ListByParams(DynamoQuery entityQuery)
{
results = new DynamoResult<Entity>();
try {
results = await GetPagedQueryResults(entityQuery);
}
catch (Exception e) {
Console.WriteLine(e);
}
return new DynamoResult<EntityResponse>
{
Data = results.Data.Select(_mapper.Map<EntityResponse>).ToList(),
};
}
Service 2:
private async Task<DynamoResult<TResponse>> GetPagedQueryResults(DynamoQuery query)
{
var results = new List<Document>();
try{
results = await search.GetNextSetAsync();
}
catch(Exception e){
throw new PaginationTokenException(e.Message);
}
return results;
}
[Serializable]
public class PaginationTokenException : Exception
{
public PaginationTokenException() { }
public PaginationTokenException(string message)
: base(message) {
throw new Exception(message);
}
public PaginationTokenException(string message, Exception inner)
: base(message, inner) { }
}
Assuming you want to hide implementation details from the controller (i.e. you don't want the controller to know/care that it's DynamoDB), I would create a custom exception and throw that from Service1.
Service1 would look something like this:
public async Task<DynamoResult<EntityResponse>> ListByParams(DynamoQuery entityQuery)
{
results = new DynamoResult<Entity>();
try {
results = await GetPagedQueryResults(entityQuery);
}
catch (Exception e) {
throw new MyCustomException('My error message', e);
}
return new DynamoResult<EntityResponse>
{
Data = results.Data.Select(_mapper.Map<EntityResponse>).ToList(),
};
}
In the controller you can then capture that exception explicitly:
[HttpGet]
[Authorize(Policy = "Read-Entity")]
[Route("byParams/{param1}/{param2}")]
[Produces(typeof(DynamoResult<EntityResponse>))]
public async Task<IActionResult> ListByParams([FromQuery] DynamoQuery entityQuery)
{
try
{
return await HandleRequest(async () =>
{
return Ok((await _entityStore.ListByParams(entityQuery)));
});
}
catch (MyCustomException e)
{
return BadRequest(e.Message);
}
}
I am testing WCF for potentially implementing an API for remote controlling a device that runs our Controller-Software (C#/.Net 4.6.1) on Windows.
I am currently trying to figure out how to throw and catch a FaultException from my service and catch it from a .Net client.
The problem I am having is that when running the code (in Debug-mode on VS 2015), the exception is not caught by the client, but VS ends up showing me the exception inside VS at the code-location of the service (Service.cs), where it is being thrown. The exception message is:
An exception of type 'System.ServiceModel.FaultException`1' occurred in WcfService.dll but was not handled in user code
Additional information: The argument value was not 1
where The argument value was not 1 is the custom message provide by me. Here are the relevant parts of my code. I hope somebody can spot, what I am doing wrong:
IService.cs:
[ServiceContract(CallbackContract = typeof(IMyEvents))]
public interface IService
{
[OperationContract]
[FaultContract(typeof(InvalidValueFault))]
string ThrowsFaultIfArgumentValueIsNotOne(int value);
...
}
[DataContract]
public class InvalidValueFault
{
private string _message;
public InvalidValueFault(string message)
{
_message = message;
}
[DataMember]
public string Message { get { return _message; } set { _message = value; } }
}
Service.cs:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant,
InstanceContextMode = InstanceContextMode.Single)]
public class Service : IService
{
private string defaultString;
public Service(string ctorTestValue)
{
this.defaultString = ctorTestValue;
}
public string ThrowsFaultIfArgumentValueIsNotOne(int value)
{
if (value == 1)
return string.Format("Passed value was correct: {0}", value);
// this is where the box with the exception is shown inside Visual Studio
throw new FaultException<InvalidValueFault>(new InvalidValueFault("The argument value was not 1"), new FaultReason("The argument value was not 1"));
}
...
}
Server.cs:
public class Server
{
private ServiceHost svh;
private Service service;
public Server()
{
service = new Service("A fixed ctor test value that the service should return.");
svh = new ServiceHost(service);
}
public void Open(string ipAdress, string port)
{
svh.AddServiceEndpoint(
typeof(IService),
new NetTcpBinding(),
"net.tcp://"+ ipAdress + ":" + port);
svh.Open();
}
public void Close()
{
svh.Close();
}
}
Client.cs:
public class Client : IMyEvents
{
ChannelFactory<IService> scf;
IService s;
public void OpenConnection(string ipAddress, string port)
{
var binding = new NetTcpBinding();
scf = new DuplexChannelFactory<IService>(
new InstanceContext(this),
binding,
"net.tcp://" + ipAddress + ":" + port);
s = scf.CreateChannel();
}
public void CloseConnection()
{
scf.Close();
}
public string ThrowsFaultIfArgumentValueIsNotOne(int value)
{
try
{
return s.ThrowsFaultIfArgumentValueIsNotOne(value);
}
catch (System.ServiceModel.FaultException<InvalidValueFault> fault)
{
Console.WriteLine("Exception thrown by ThrowsFaultIfArgumentValueIsNotOne(2):");
Console.WriteLine("Exception message: " + fault.Message);
//throw;
return "Exception happend.";
}
}
...
}
Program.cs (Test Program using the server and the client):
class Program
{
static void Main(string[] args)
{
// start server
var server = new Server();
server.Open("localhost", "6700");
Console.WriteLine("Server started.");
var client = new Client();
client.OpenConnection("localhost", "6700");
Console.ReadLine();
Console.WriteLine("Result for client.ThrowsFaultIfArgumentValueIsNotOne(1): {0}", client.ThrowsFaultIfArgumentValueIsNotOne(1));
Console.ReadLine();
Console.WriteLine("Result for client.ThrowsFaultIfArgumentValueIsNotOne(2): {0}", client.ThrowsFaultIfArgumentValueIsNotOne(2));
Console.ReadLine();
client.CloseConnection();
Thread.Sleep(1000);
server.Close();
}
}
If you generated your SOAP code from wsdl using vs tools then FaultException that is being thrown here is generic FaultException - meaning it is FaultException<fault_contract>. You what generic type exception that is by checking your service reference code and inspecting [System.ServiceModel.FaultContractAttribute()] attribute. This attribute has Type parameter which is you generic type.
So if you it looks something like this
[System.ServiceModel.FaultContractAttribute(typeof(MyFaultContract)]
[System.ServiceModel.OperationContractAttribute(Action = "SoapAction", ReplyAction = "*")]
SoapResponse SoapAction(SoapRequest request);
then your catch clause should look like this
try {
soapClient.SoapAction(new SoapRequest());
}
catch (FaultException<MyFaultContract> e) {
}
I had his issue recently (if i understood correctly)
1) VS -> DEBUG -> Options and Settings -> Debugging -> General
There UNTICK 'Break when exceptions cross AppDomain...'
2) DEBUG -> Exceptions and deselect the exceptions for common language runtime (both Thrown and user-unhandled) and try it again. If that solves the problem, you can seek which exception(s) you want to customize or just do this whenever testing exceptions across the AppDomain.
Ok. I found the answer to my question by luck. The error was due to running my code in Debug mode in Visual Studio, where VS catches the exception the moment it is thrown. In order for it to work correctly you need to disable some settings. To do this go to Tools->Option->Debugging->General and remove the checkmarks:
Enable the exception assistant
Enable just my code
I found this solution here.
Hey guys i followed the tutorial here for a school project, https://www.dougv.com/2015/08/posting-status-updates-to-twitter-via-linqtotwitter-part-2-plain-text-tweets/
But when i run it with google chrome nothing is showing up and it just stuck in http://localhost:2860/linq2twitter.aspx which is a blank page, i've checked my twitter the tweet has not been made as well.. from the other sample i've tried i think it is suppose to send me to a authentication page which requires me to login and stuff.. any help is appreciated. Here's my code :
namespace WebApplication3
{
public partial class linq2twitter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
class Program
{
static void Main()
{
Console.WriteLine("Program started.");
try
{
var result = Task.Run(() => SendTweet());
result.Wait();
if(result == null) {
Console.WriteLine("Tweet failed to process, but API did not report an error");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Program completed.");
Console.Read();
}
static async Task<Status> SendTweet()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = "<Twitter consumer key>",
ConsumerSecret = "<Twitter consumer secret>",
AccessToken = "<Twitter access token>",
AccessTokenSecret = "<Twitter access token secret>"
}
};
var context = new TwitterContext(auth);
var status = await context.TweetAsync(
"Hello World! I am testing #dougvdotcom's #LinqToTwitter demo, at " +
"https://www.dougv.com/2015/08/posting-status-updates-to-twitter-via-linqtotwitter-part-2-plain-text-tweets"
);
return status;
}
}
}
}
Fixed after regenerating my secrets and keys.. and removed unintentional spacebar for my keys in the code. Thx
So my service is a simple chat application between two wcf clients. Event callback works when I call events. After I close my client and run it again, and write a message again (to call the event) it throws me exception:
An exception of type 'System.ObjectDisposedException' occurred in
RussianRouletteServiceLibrary.dll but was not handled in user code
Additional information: Cannot access a disposed object.
The code for my service callback is as follows:
private static Action<User, UMessage> gameChat = delegate { };
public void Play()
{
IGameCallback subscriber =
OperationContext.Current.GetCallbackChannel<IGameCallback>();
gameChat += subscriber.PlayerSentMessage;
}
This is the event trigger:
public void SendMessage(User user, UMessage message)
{
try
{
gameChat(user, message);
}
catch (Exception ex)
{
throw ex;
}
}
I get this error every time I .ChannelFactory.Close(); .Close(); the client while closing form event is happening.
Is there anyone that knows how to fix this and is willing to share his knowledge?
Thank you in advance!
EDIT #1
This is the code of the client when it opens:
ConcurrencyMode.Multiple,
UseSynchronizationContext = false)]
public partial class GameForm : Form, IGameCallback
{
#region IGame Callbacks
public void PlayerSentMessage(User user, UMessage message)
{
string nickname = user.NickName == clientUser.NickName ? "You" : user.NickName;
this.Invoke(new MethodInvoker(() => lb_ChatBox.Items.Add(nickname + " : " + message.MessageContent)));
}
#endregion
private GameClient _gameClient = null;
private InstanceContext _instance = null;
private User clientUser = new User(){ Email = "zigm4s#gmail.com", Id = 0, FirstName = "Zigmas", LastName = "Slusnys", NickName = "Ziggy", Password = "test123"};
public GameForm()
{
string state;
if (_gameClient != null)
{
MessageBox.Show("nelygu null");
MessageBox.Show(_gameClient.State.ToString());
//_gameClient = new GameClient(new InstanceContext(this));
}
else
{
_gameClient = new GameClient(new InstanceContext(this));
MessageBox.Show(_gameClient.State.ToString());
}
InitializeComponent();
try
{
_gameClient.Open();
_gameClient.Play();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
This is when the client form is closing.
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
try {
if (_gameClient.State != System.ServiceModel.CommunicationState.Faulted)
{
MessageBox.Show("Closing client");
_gameClient.ChannelFactory.Close();
_gameClient.Close();
}
else
{
MessageBox.Show("Aborting client");
_gameClient.Abort();
}
}
catch(Exception ex)
{ MessageBox.Show(ex.ToString());}
}
EDIT #2
I found the mistake, on the service side i had delegates that were static. It doesn't throw this error when it's not static.
I've been trying to write a small program with these instructions:
In this assignment you should write a simple web application with one link on the front page of the web. If the link is clicked, the user will simply be routed to the front page again (using RedirectToAction). However, occasionally, the action method might throw an exception (but not always). Occasionally (one in every 5 occasions) the method should throw an ArgumentException, and occasionally (again, in maybe 1 in a 5), it should throw a custom Exception object you should declare yourself, called MyApplicationException.
In HomeController I have:
public class HomeController : Controller
{
List<Logger> m_loggers = new List<Logger>();
protected override void OnException(ExceptionContext fc)
{
base.OnException(fc);
Exception ex = fc.Exception;
Logger.Instance.Log(ex);
}
public ActionResult Index()
{
string strLogFile = System.Configuration.ConfigurationManager.AppSettings["LogFile"];
string strEmail = System.Configuration.ConfigurationManager.AppSettings["Email"];
try
{
RedirectToAction("Index");
using(MailMessage message = new MailMessage())
{
message.To.Add(strEmail);
message.Subject = "Villuskilaboð";
message.Body = "Upp hefur komið villa frá Skilaverkefni 4!";
using(SmtpClient client = new SmtpClient())
{
client.EnableSsl = true;
client.Send(message);
}
}
}
catch(Exception ex)
{
Random r = new Random();
int rand = r.Next(1000);
if(rand % 5 == 0)
{
throw new System.ArgumentException("Randon villuskilaboð handa þér!");
}
Debug.WriteLine(ex.Message +
Environment.NewLine +
ex.StackTrace);
}
return View();
}
Logger class:
public class Logger
{
List<LogMedia>m_loggers = new List<LogMedia>();
private static Logger theInstance = null;
public static Logger Instance
{
get
{
if (theInstance == null)
{
theInstance = new Logger();
}
return theInstance;
}
}
private Logger()
{
m_loggers = new List<LogMedia>();
//m_loggers.Add(new TextFileLogMedia { });
//m_loggers.Add(new EmailLogMedia { });
}
public void Log(Exception ex)
{
foreach(LogMedia log in m_loggers)
{
log.LogMessage(ex.Message + Environment.NewLine);
}
}
}
LogMedia
public class LogMedia
{
public virtual void LogMessage(string Message)
{
}
public class OutputWindowLogMedia: LogMedia
{
public override void LogMessage(string Message)
{
System.Diagnostics.Debug.WriteLine(Message);
}
}
public class TextFileLogMedia: LogMedia
{
public override void LogMessage(string Message)
{
//File.AppendAllText("c:\\Temp.Log.txt", Message);
}
}
public class EmailLogMedia: LogMedia
{
public override void LogMessage(string Message)
{
}
}
}
I´m stuck for now and seems not getting it to work, my Visual Studio crash and I get error up, don't think that is the exception, I´m so new to it so maybe it´s the box that should come up :) But the email never get to my account.
What am I still missing to make everything work? I know the file-thing isn't in this code, trying to make the other things to work first.
I've added information about my eMail in web.config.
You really need to rework your Index() method. I'm not in front of my computer with Visual Studio, but I'm surprised you code gets past the first line in your try. Having the RedirectToAction("Index") should throw a warning that the rest of the method will never be reached, and create an infinite loop when you try to access the method. The RedirectToAction("Index")` you have in your code does nothing as you don't return the results of that. Thank you Erik Noren
This would be how I'd structure your method instead:
public ActionResult Index() {
// No need to go higher, as it's always just as random with a modulo
int rnd = (new Random()).Next(5);
try {
switch (rnd) {
case 1: // Or any of the 5 numbers you want.
throw new ArgumentException();
case 4: // Again, any of the 5 numbers
throw new MyApplicationException();
default:
return RedirectToAction("Index");
}
}
catch (Exception ex) {
// Do your error logging here.
}
}