I am using Vs2010 -> Extensibility->Shared Add-in
Connect.cs file
public class Connect : Object, Extensibility.IDTExtensibility2, IRibbonExtensibility
{
public string GetCustomUI(string RibbonID)
{
return MyResources.customUI;
}
}
The Ribbons gets created using this above code.
I have Class customRibbons.cs
public class Create_Custom_Ribbons : IRibbonExtensibility
{
Outlook.Application applicationObject;
public Create_Custom_Ribbons(Outlook.Application application)
{
try
{
applicationObject = application;
GetCustomUI("");
}
catch(Exception ex)
{
MessageBox.Show(""+ex.StackTrace);
}
}
public string GetCustomUI(string RibbonID)
{
return MyResource.customUI;
}
}
and on Connect.cs
public void OnStartupComplete(ref System.Array custom)
{
try
{
customRibbons.Create_Custom_Ribbons cu = new
customRibbons.Create_Custom_Ribbons(applicationObject);
}
catch (Exception ex)
{
MessageBox.Show("" + ex.StackTrace);
}
}
But the Ribbons is not getting created.Please can anyone tell me what am i doing wrong or any other way to achieve this.I am not able to understand y it is not getting created.
See my reply at the Office Dev group: http://social.msdn.microsoft.com/Forums/en-US/outlookdev/thread/394ac918-f32f-4c7b-9dee-a6d45f1bdf46
Related
I am using Entity Framework. Below is an example of a list method for an Actors context in my ActorsDao class. If you imagine my application is like imdb, there will be CRUD methods for various other contexts such as Movies, Directors, Genres, Reviews, Studios etc.
Regardless of the method or context, I handle errors in the same way. Due to my many methods across many contexts, my catch section is always exactly the same.
Obviously, I could create an error handling class, put the code in there, and just call a method in that class from the catch block.
However, I'm wondering if there a way to omit the TRY...CATCH from each method and set up a global error handler for the methods in my entity framework layer?
I would only want this global error handler to handle these errors and not errors from the rest of the application.
I seem to remember in Java Spring, you could annotate a class or method with the name of a method, and all errors would be passed to that without the need of a TRY...CATCH. I'm wondering if there is something similar for .NET (or a third party library with such functionality)?
public List<Actor> ListActors()
{
List<Actor> actorList = new List<Actor>();
using (var context = new ActorContext())
{
try
{
actorList = context.Actors.ToList<Actor>();
}
catch (Exception e)
{
//Handle error code
}
}
return actorList;
}
EDIT
I did some more research and found this code from here https://stackoverflow.com/a/4851985/1753877
private void GlobalTryCatch(Action action)
{
try
{
action.Invoke();
}
catch (ExpectedException1 e)
{
throw MyCustomException("Something bad happened", e);
}
catch (ExpectedException2 e)
{
throw MyCustomException("Something really bad happened", e);
}
}
public void DoSomething()
{
GlobalTryCatch(() =>
{
// Method code goes here
});
}
Would using a delegate like this be OK? It certainly meets my requirements.
You can create a class like this and extend the controller from this class.
Error Handler class looks like this :
package com.wes.essex.rest;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.wes.essex.bean.ErrorResponse;
public class SkyNewsController {
private static final Logger LOGGER = LoggerFactory.getLogger(SkyNewsController.class);
#ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleError(Exception ex) {
LOGGER.info("start");
LOGGER.error(ex.getMessage(), ex);
ErrorResponse error = new ErrorResponse();
error.setTimestamp(ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT));
LOGGER.debug("error : {} ", error);
ResponseEntity<ErrorResponse> response = null;
if (ex instanceof ConstraintViolationException) {
error.setReasonCode(HttpStatus.BAD_REQUEST.value());
ConstraintViolationException constraintException = (ConstraintViolationException) ex;
Set<ConstraintViolation<?>> set = constraintException.getConstraintViolations();
String errorMessage = "Input Validation Failed:";
for (ConstraintViolation<?> constraintViolation : set) {
errorMessage += constraintViolation.getMessageTemplate() + ",";
}
errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
error.setErrorMessage(errorMessage);
response = new ResponseEntity<ErrorResponse>(error, HttpStatus.BAD_REQUEST);
} else {
error.setReasonCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
error.setErrorMessage(ex.getMessage());
response = new ResponseEntity<ErrorResponse>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
}
This would be the baean class for error response :
package com.wes.essex.bean;
public class ErrorResponse {
private static final long serialVersionUID = 5776681206288518465L;
private String timestamp;
private String errorMessage;
private int reasonCode;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public int getReasonCode() {
return reasonCode;
}
public void setReasonCode(int reasonCode) {
this.reasonCode = reasonCode;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
I am really stuck on calling my function InlogLeerling() from .cs file Login.cs into MainPage.xaml.cs.
I did try everything and I already found some answers but I do not understand how I can get it working in my project. When i call the function InlogLeerling() I get the error There is no argument given that corresponds to the required formal parameter 'mainpage' of 'Login.InlogLeerling(MainPage)'
Here is the code I am using in my Login.cs
namespace VerlofXamarin.Logical_Layer
{
public class Login
{
public string pu_Gebruikersnaam, pu_Wachtwoord, pu_LogLeerling;
string Gebruikersnaam
{
get { return pu_Gebruikersnaam; }
set { pu_Gebruikersnaam = value; }
}
string Wachtwoord
{
get { return pu_Wachtwoord; }
set { pu_Wachtwoord = value; }
}
public MainPage mainpage;
private void InlogLeerling(MainPage mainpage)
{
Data_Layer.Verbinding vv = new Data_Layer.Verbinding();
this.mainpage = mainpage;
try
{
if(string.IsNullOrEmpty(pu_Gebruikersnaam) == true || string.IsNullOrEmpty(pu_Wachtwoord) == true)
{
mainpage.pu_LeerlingLog = "Vul gebruikersnaam en wachtwoord in!";
return;
}
vv.con.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT leerlinggebruikersnaam, leerlingwachtwoord FROM arabignl_project.myfirstmodule$leerlinglogin WHERE (leerlinggebruikersnaam = #gebruiker AND leerlingwachtwoord = #wachtwoord)", vv.con);
cmd.Parameters.AddWithValue("#gebruiker", pu_Gebruikersnaam.ToString());
cmd.Parameters.AddWithValue("#wachtwoord", pu_Wachtwoord.ToString());
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
mainpage.pu_LeerlingLog = "Inloggen gelukt";
}
}
else
{
mainpage.pu_LeerlingLog = "Inloggen mislukt";
}
reader.Close();
}
catch (MySqlException ex)
{
mainpage.pu_LeerlingLog = ex.ToString();
}
finally
{
vv.con.Close();
}
}
}
}
And the MainPage.xaml.cs
namespace VerlofXamarin
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public Login login;
public string pu_LeerlingLog
{
get { return LoginLog.Text; }
set { LoginLog.Text = value; }
}
public string pu_LeerlingGebruikersnaam
{
get { return LeerlingGebruikersnaam.Text; }
}
public string pu_LeerlingWachtwoord
{
get { return LeerlingWachtwoord.Text; }
}
public void LoginKlik(Login login)
{
this.login = login;
login.InlogLeerling();
}
I have already tried so many things.
You have two problems in your code.
You can´t call any private member from outside your class. So make your method public
your method expects a parameter of type MainPage. So you have to provide it, which is exactly what your error states:
public void LoginKlik(Login login)
{
this.login = login;
login.InlogLeerling(this);
}
Apart from those you shouldn´t expose a field publicily. Instead use a public property which you can modify within your class and read outside your class Login:
public MainPage MainPage { get; private set; }
You should study access modifier. With private, other classes could not access it. So you could change it to either internal or public. Here is reference
- https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/access-modifiers
internal void InlogLeerling(MainPage mainpage)
You will not be able to call the method because they are not in same class.
When you give an access modifier of privte, the accesses is possible only within the class.
If you would like to give more access there is:
protected - A protected member is accessible within its class and by derived class instances.
Internal- Internal types or members are accessible only within files in the same assembly.(i.e. the same compiled program)
public- . Public access is the most permissive access level. There are no restrictions
Therefor by using internal or public (depends on what you need in more large aspect) you will be able to access this method within other classes in your project
I have exception
class SyntaxError : Exception {
public SyntaxError(int l) {
line = l;
}
public int line;
}
I'm using unit tests to test class Parser which on specific input should throw exception above. I'm using code like this:
[TestMethod]
[ExpectedException(typeof(Parser.SyntaxError))]
public void eolSyntaxError()
{
parser.reader = new StringReader("; alfa\n; beta\n\n\n\na");
parser.eol();
}
Is there any smart simple way to check if SyntaxError.line == 1?
Best I come up with is:
[TestMethod]
public void eolSyntaxError()
{
try {
parser.reader = new StringReader("; alfa\n; beta\n\n\n\na");
parser.eol();
Assert.Fail();
} catch (SyntaxError e) {
Assert.AreEqual(1, e.line);
}
}
I don't like it very much, is there better way?
Consider using FluentAssertions. Your test will then look like this:
[TestMethod]
public void eolSyntaxError()
{
parser.reader = new StringReader("; alfa\n; beta\n\n\n\na");
Action parseEol = () => parser.eol();
parseEol
.ShouldThrow<SyntaxError>()
.And.line.Should().Be(1);
}
Otherwise, your approach is pretty much as good as it gets.
You could write a method similar to the one in NUnit
public T Throws<T>(Action code) where T : Exception
{
Exception coughtException = null;
try
{
code();
}
catch (Exception ex)
{
coughtException = ex;
}
Assert.IsNotNull(coughtException, "Test code didn't throw exception");
Assert.AreEqual(coughtException.GetType(), typeof(T), "Test code didn't throw same type exception");
return (T)coughtException;
}
And then you can use it in your test method
Parser.SyntaxError exception = Throws<Parser.SyntaxError>(() => parser.eol());
Assert.AreEqual(1, exception.line);
As per my comment, if the line at which you encounter the syntax error is relevant, then include it in your custom exception class, like so.
public class SyntaxError : Exception
{
public SyntaxError(int atLine)
{
AtLine = atLine;
}
public int AtLine { get; private set; }
}
Then it's easy to test.
EDIT - After having read the question (!) here's a simple additional Assert method which will tidy up your exception assertions.
public static class xAssert
{
public static TException Throws<TException>(Action a) where TException : Exception
{
try
{
a();
}
catch (Exception ex)
{
var throws = ex as TException;
if (throws != null)
return throws;
}
Assert.Fail();
return default(TException);
}
}
Usage as follows...
public class Subject
{
public void ThrowMyException(int someState)
{
throw new MyException(someState);
}
public void ThrowSomeOtherException()
{
throw new InvalidOperationException();
}
}
public class MyException : Exception
{
public int SomeState { get; private set; }
public MyException(int someState)
{
SomeState = someState;
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var subject = new Subject();
var exceptionThrown = xAssert.Throws<MyException>(() => { subject.ThrowMyException(123); });
Assert.AreEqual(123, exceptionThrown.SomeState);
}
}
I am not aware of an out of the box solution for this, but I have seen the concept of expectations which work like this:
[TestMethod]
public void EolSyntaxError()
{
Expectations.Expect<(SyntaxError>(
() =>
{
parser.reader = new StringReader("; alfa\n; beta\n\n\n\na");
parser.eol();
},
e =>
{
Assert.AreEqual(1, e.line);
});
}
Expectations needs to be implemented. I reckon there will be libraries out there which already do this. Anyhow, the Expect method in Expectations could look like this:
public static void Expect<TExpectedException>(
System.Action action,
System.Action<TExpectedException> assertion) where TExpectedException : Exception
{
if (action == null) { throw new ArgumentNullException("action"); }
try
{
action.Invoke();
Assert.Fail(string.Format("{0} expected to be thrown", typeof(TExpectedException).Name));
}
catch (TExpectedException e)
{
assertion.Invoke(e);
}
}
how can i, in my function start to fill the parameters for the class it is supposed to return, but if an exception occurs i'll return my error class instead?
public **** function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return articles;
}
catch (Exception e)
{
Errors Error = new Errors();
Error.exceptionmessage = e.Message;
Error.exceptionname = e.ToString();
Error.httpcode = 500;
return Error;
}
}
is this possible and a good thing to do? or should i just extend all return classes with my error class, even though i will return much info with allot of null values.
i would like to send as little data as possible and if my function fails i'll just send back the error.
UPDATE
sorry for not giving enough inforamtion about my situation this is a function that i want to use in a webservice
[OperationContract]
[WebGet(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
**** Function();
so i dont think i can just throw an exception. i would like to return a class of articles if all is well so i dont have to convert my data to JSON but if something goes wrong i would like to send http code 500 Internal Server Error to the client.
i have not yet read all answers but i think i'll have to include my error class in all my other return classes so the client can now when something went wrong?
UPDATE:
That gives more insight on what you want to do. Since you can't throw exceptions, you should have a base result class. I usually do this for WCF methods I call through javascript, since it can't handle the exceptions nicely.
So you'll want a base class like:
[DataContract]
public class AjaxResult
{
public static AjaxResult GetSuccessResult()
{
return new AjaxResult();
}
[DataMember]
public int Status { get; set; }
[DataMember]
public string Error { get; set; }
}
Then you can inherit this, adding any data you would want to return. This example returns a single product object and a list of validation errors.
[DataContract]
public class SingleProductResult : AjaxResult
{
[DataMember]
public Product Data { get; set; }
[DataMember]
public IList<int> ValidationErrors { get; set; }
}
You can also opt to create a generic wrapper so you don't have to write to much code in your methods. I usually put this in a base class and let all WCF services inherit from that class.
protected T PerformAjaxOperation<T>(Func<T> action) where T : AjaxResult, new()
{
try
{
return action();
}
catch (AccessDeniedException ade)
{
// -- user tried to perform an invalid action
return new T()
{
Status = AjaxErrorCodes.AccessDenied,
Error = ade.ToString()
};
}
catch (Exception ex)
{
return new T()
{
Error = ex.ToString(),
Status = 1
};
}
}
Then just use it like so:
public SingleProductResult GetProduct(int productId)
{
return PerformAjaxOperation(() =>
{
return retval = new SingleProductResult()
{
Data = ProductServiceInstance.GetProduct(productId)
};
});
}
public AjaxResult DeleteProduct(int productId)
{
return PerformAjaxOperation(() => {
ProductServiceInstance.DeleteProduct(productId);
return AjaxResult.GetSuccessResult();
});
}
So, if everything proceeds smoothly, error will be 0 and message will be null. If an exception is thrown, then it will be caught by the PerformAjaxOperation() function and stuffed inside the AjaxResult object (or a derivative of it) and return to the client.
Previous answer:
I don't think this is a good idea. What you can do is create a custom exception by creating a class that inherits from Exception and add properties there that you want to save. Then when an exception occurs, you just catch it and stuff it inside this new exception along with other details. Then throw this exception instead. You can then catch this exception in the higher levels and display the proper message.
an example:
public IList<Articles> GetArticles()
{
try
{
return GetSomeArticlesFromDatabase();
}
catch (Exception innerException)
{
throw new MyCustomException("some data", 500, innerException);
}
}
public class MyCustomException : Exception
{
public int HttpCode { get; set; }
public MyCustomException(string errorMessage, int httpCode, Exception innerException)
: base(errorMessage, innerException) {
HttpCode = httpCode;
}
}
public void EntryPoint()
{
try
{
DoSomething();
var result = GetArticles();
DoSomething();
DisplayResult(result);
}
catch (MyCustomException ex)
{
ReturnHttpError(ex.Message, ex.HttpCode);
}
}
I would honestly advise against doing what you suggest. Instead, either use an existing Exception type or create a new subclass of Exception and throw it. You can even retain the causing exception information in the new exception's InnerException if so desired.
If the situation does not warrant an exception, however (you have not given enough details about what you are doing), you can create a Result class that contains error/warning information. This kind of thing would be better suited for warnings, though. That is, it is not an error condition that prevents things from continuing (exception), but instead a message that the calling code could choose to ignore without drastic side-effects.
For example:
class Result<T>
{
public Result(T Value, Errors Errors = null)
{
this.Value = Value;
this.Errors = Errors;
}
public T Value {get; private set;}
public Errors Errors {get; private set;}
}
Usage (as per your example code):
public Result<Articles> function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return new Result(articles);
}
catch (Exception e)
{
Errors Error = new Errors();
Error.exceptionmessage = e.Message;
Error.exceptionname = e.ToString();
Error.httpcode = 500;
return new Result<Articles>(null, Error);
}
}
If class1 and class2 have a common base type or common interface, use that. But in this case, you could create a wrapper class to encapsulate both result types, like this:
class MethodResult<T>
{
public T Result { get; private set; }
public Errors Errors { get; private set; }
public MethodResult(T result) { this.Result = result; }
public MethodResult(Errors errors) { this.Errors = errors; }
}
public MethodResult<Articles> MyMethod()
{
try
{
...
return new MethodResult<Articles>(articles);
}
catch(Exception e)
{
...
return new MethodResult<Articles>(errors);
}
}
In light of additional information in the question, since this is a WCF service, you could throw a WebFaultException:
public Articles function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return articles;
}
catch (Exception e)
{
throw new WebFaultException(System.Net.HttpStatusCode.InternalServerError)
{
Message = e.Message
};
}
}
The ways that other answers have handled this involve technical methods of how to define the two classes, using interfaces and subclassing.
However, fundamentally you're actually solving the wrong problem. You will still need to write code in the caller that distinguishes between the two types of object, as well as documenting the way in which your function works.
Personally, I would create a new Exception class for the type of error you may be handling, and throw that instead, for example:
public class InvalidArticleException: Exception {
public string ExceptionMessage { get; set; }
public string ExceptionName { get; set; }
public int HttpCode { get; set; }
}
public **** function()
{
try
{
// DO STUFF
return articles;
}
catch (InvalidArgumentException e)
{
throw new InvalidArticleException() {
ExceptionMessage = e.Message,
ExceptionName = e.ToString(),
HttpCode = 500
}
}
catch (Exception ex) { // Not actually required; left in for future debugging
throw ex;
}
}
Callers would then be able to catch the exception and examine it for the error details, with code that is kept separated from that which processes the returned articles.
You can try out keyword,
public Articles function(out Error err)
{
Articles articles = null;
err = null;
try
{
articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
// Set your article values
}
catch (Exception e)
{
Errors ex = new Errors();
ex.exceptionmessage = e.Message;
ex.exceptionname = e.ToString();
ex.httpcode = 500;
err = ex;
}
return articles;
}
I'm not sure why would you want swallowing the exeptions, but if you do whatn this behgaviour make a return type common for both type. The both classes inherit from object so you can change the method signature to public object function()
I created a little class in order to create logs.
This class use streamwriter functions in order to do this.
I write a log, and after closed the log, i would like to re-open after, in order to append some datas.
I tried severals tips, and...i always have an exception who tell me " The file is used by another process".
Nevertheless, i use the close(), but, i always had this exception.
Here is my class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TEST
{
public class CLog
{
private StreamWriter myWriter;
public string Name
{
set { Name = value; }
get
{
FileInfo myFile = new FileInfo(CompleteFileName);
return myFile.Name;
}
}
public string Directory
{
set { Directory = value; }
get
{
FileInfo myFile = new FileInfo(CompleteFileName);
return myFile.Directory.ToString();
}
}
public string CompleteFileName { set; get; }
public CLog(string _CompleteFileName)
{
CompleteFileName = _CompleteFileName;
}
public bool CreateLog()
{
try
{
myWriter = new StreamWriter(CompleteFileName);
return true;
}
catch (Exception ex )
{
return false;
}
}
public bool AppendTextToFile(string strText)
{
try
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText(CompleteFileName))
{
sw.WriteLine(strText);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool WriteLine(string strLine)
{
try
{
myWriter.WriteLine(strLine);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool SaveFile()
{
try
{
myWriter.Close();
myWriter.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
Please look at the AppendTextToFile.
Here is the use :
monLog = new CLog("C:\\TEST.TXT");
if (monLog.CreateLog())
{
monLog.WriteLine("");
monLog.WriteLine("******");
monLog.WriteLine("Some data");
monLog.WriteLine("******");
monLog.SaveFile();
...
....
monLog.AppendTextToFile("** my AppendedData***);
monLog.SaveFile();
}
Anyone know why i have this exception and how solve it ?
Thanks a lot :)