I'm trying to convert following vb set/get function to c#. It is used through an ActiveX page like :
Item.CtxString(document.getElementById("setvar").value+"1")=document.getElementById("setval").value;
or :
Item.CtxString("var1") = "var";
The following code is used in VB.NET :
Public Property CtxString(ByVal strItemType As String) As String
Get
Try
Return myContext.ContextString(strItemType)
Catch ex As Exception
Return ""
End Try
End Get
Set(ByVal value As String)
Try
myContext.ContextString(strItemType) = value
Catch ex As Exception
End Try
End Set
End Property
Public Sub SetCtxString(ByVal strItemType As String, ByVal value As String)
Try
myContext.ContextString(strItemType) = value
Catch ex As Exception
End Try
End Sub
I'm trying to convert this from VB to C#, with following function :
public string CtxString
{
get
{
return ctxString;
}
set
{
ctxString = value;
}
}
public void SetCtxString(string value)
{
this.ctxString = value;
}
ContextString is a function used in c++, which needs to be converted to c# aswell..
STDMETHODIMP CContextATL::get_ContextString(BSTR strItemType, BSTR *pVal)
{
try
{
_bstr_t strItem(strItemType, true);
_bstr_t strTemp;
char szBuffer[2048] = {0};
CContextItem *pItem = _Module.GetContextItemFromEnvironment(m_strEnv, (char *)strItem);
if(pItem != NULL)
{
strTemp = pItem->GetContextStringValue().c_str();
*pVal = ::SysAllocString(static_cast<const wchar_t*>(strTemp));
sprintf( szBuffer, "ContextString Key = '%s' Value = '%s' read by Client %s with name = %s in Environment %s\r\n", (char *)strItem, (char *)strTemp, m_strId.c_str(), m_strClientName.c_str(), m_strEnv.c_str());
}
else
{
sprintf( szBuffer, "ContextString Key = '%s' not found while reading by Client %s with name = %s in Environment %s\r\n", (char *)strItem, m_strId.c_str(), m_strClientName.c_str(), m_strEnv.c_str());
}
_Module.WriteDebugString(szBuffer);
}
catch(_com_error & e)
{
ATLTRACE("CContextATL::get_ContextString exception : %s\n", e.ErrorMessage());
}
return S_OK;
}
Anyone who could help me out to convert the following function from VB.NET to c#?
The VB property is a "parameterized property" - this is not available in C#, so you would convert this to 2 separate methods:
public string get_CtxString(string strItemType)
{
try
{
return myContext.ContextString(strItemType);
}
catch (Exception ex)
{
return "";
}
}
public void set_CtxString(string strItemType, string value)
{
try
{
myContext.ContextString(strItemType) = value;
}
catch (Exception ex)
{
}
}
Your original 'set' method is now redundant:
public void SetCtxString(string strItemType, string value)
{
try
{
myContext.ContextString(strItemType) = value;
}
catch (Exception ex)
{
}
}
How about this? C# can overload bracket operator.
I have no idea what's ContextString is, however, if ContextString is a Dictionary or the type uses brackets to get value, you can do it like this:
public string this[string strItemType]
{
get
{
try
{
return myContext.ContextString[strItemType];
}
catch (Exception ex)
{
return "";
}
}
set
{
try
{
myContext.ContextString[strItemType] = value;
}
catch (Exception ex) { }
}
}
Related
This code works by taking a function as a parameter and using try-catch to log the result of the function.
When I change the functionDecorator here, I want the changes to be applied automatically to functionDecorator<T> or functionDecorator<T1, T2> without copying the entire code as it is now
These functions that do almost the same thing Is there a way to manage each other's behavior in one place, including even try-catch statements?
public void funtionDecorator(Func<bool> Func, string successText = "success", string failText = "fail", string errorText = "error")
{
try
{
if (Func())
{
txtStatusBar.Text = successText;
}
else
{
txtStatusBar.Text = failText;
}
}
catch(Exception ex)
{
txtStatusBar.Text = errorText + Func.Method.Name + ex.ToString();
}
}
// ex : funtionDecorator<DataTable>(useDataFuntion, dt);
public void funtionDecorator<T>(Func<T, bool> Func, T type, string successText = "success", string failText = "fail", string errorText = "error")
{
try
{
if (Func(type))
{
txtStatusBar.Text = successText;
}
else
{
txtStatusBar.Text = failText;
}
}
catch (Exception ex)
{
txtStatusBar.Text = errorText + Func.Method.Name + ex.ToString();
}
}
// ex : funtionDecorator<DataTable, Double>(useDataFuntion, dt, value);
public void funtionDecorator<T1, T2>(Func<T1, T2, bool> Func, T1 type1, T2 type2, string successText = "success", string failText = "fail", string errorText = "error")
{
try
{
if (Func(type1, type2))
{
txtStatusBar.Text = successText;
}
else
{
txtStatusBar.Text = failText;
}
}
catch (Exception ex)
{
txtStatusBar.Text = errorText + Func.Method.Name + ex.ToString();
}
}
I tried to handle it dynamically using dynamic, but the function type was not converted to dynamic, so I couldn't find a way.
This is my code.
public static String telegramsetime(String str, String str2)
{
try
{
string text = telegramsettime(str, str2);
return text;
}
catch (Exception th)
{
return th.ToString();
}
}
The "telegramsettime" is a function which is inside a file named "libjnitg.so".How can i run this function properly?
Is it possible to return a List OR an int in a method?
Something like:
if it succeeded: return List
if it failed: return int (that gives an error number) or string with error message.
(failed as in no exceptions but the values are incorrect, like PointF.X = below 0 or Lowest value is over 10).
Now I'm doing it like this:
public List<PointF> GetContourInfoFromFile(string a_file)
{
ListContourPoints.Clear();
List<string> textLines = new List<string>();
bool inEntitiesPart = false;
bool inContourPart = false;
try
{
foreach (string str in File.ReadAllLines(a_file))
{
textLines.Add(str);//Set complete file in array
}
for (int i = 0; i < textLines.Count; i++)
{
//read complete file and get information and set them in ListContourPoints
}
//Check Coordinate values
for (int i = 0; i < ListContourPoints.Count; i++)
{
//Coordinates are below -1!
if (ListContourPoints[i].X < -1 || ListContourPoints[i].Y < -1)
{
ListContourPoints.Clear();
break;
}
//Lowest X coordinate is not below 10!
if (mostLowestXContour(ListContourPoints) > 10)
{
ListContourPoints.Clear();
break;
}
//Lowest Y coordinate is not below 10!
if (mostLowestYContour(ListContourPoints) > 10)
{
ListContourPoints.Clear();
break;
}
}
}
catch (Exception E)
{
string Error = E.Message;
ListContourPoints.Clear();
}
return ListContourPoints;
}
When I do it like this, I know there is something wrong with te values.. but not specifically what.
So how can I solve this? If it's not possible with returning a list OR string/int, what's the best solution?
You can
Solution 1:
throw exception if error, and in your code above do a try catch
Delete the part catch in your function, and when you call you function do it in try catch like this:
try
{
List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
string Error = E.Message;
}
Solution 2:
return an object with Listresult and error as property
Instead of returning a number, you can throw an exception from the catch block so that it can be caught by the outer exception handler.
Here's a sample:
public void MainMethod()
{
try
{
var myList = SomeMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // prints out "SomeMethod failed."
}
}
public List<object> SomeMethod()
{
try
{
int i = 1 + 1;
// Some process that may throw an exception
List<object> list = new List<object>();
list.Add(1);
list.Add(i);
return list;
}
catch (Exception ex)
{
Exception newEx = new Exception("SomeMethod failed.");
throw newEx;
}
}
you could create a wrapper class which holds either the value or the errorcode. Example:
public class Holder<T>
{
private Holder(T value)
{
WasSuccessful = true;
Value = value;
}
private Holder(int errorCode)
{
WasSuccessful = false;
ErrorCode = errorCode;
}
public bool WasSuccessful { get; }
public T Value { get; }
public int ErrorCode { get; }
public static Holder<T> Success(T value)
{
return new Holder<T>(value);
}
public static Holder<T> Fail(int errorCode)
{
return new Holder<T>(errorCode);
}
}
Usage:
public Holder<PointF> MyFunc()
{
try
{
//
return Holder<PointF>.Success(new PointF());
}
catch
{
return Holder<PointF>.Fail(101);
}
}
one solution would be to return object
public object GetContourInfoFromFile(string a_file)
{
}
and in the method where you call this try to cast to both int and list and see which one succeeds.
a more elaborate solution would be to have a class
public class YourClassName{
public List<PointF> YourList {get; set;} //for success
public int YourVariable {get; set} // for failure
public string YourMEssage {get; set} // for failure
}
and return that one
public YourClassName GetContourInfoFromFile(string a_file)
{
}
I am writing to seek help with regards to implementing a return statement for my test method. I am currently getting a null response from my test() method, but I would like to know, how can I catch the error from my "IsValidEmailDomain" method in my "test" method:
public static bool IsValidEmailDomain(MailAddress address)
{
if (address == null) return false;
var response = DnsClient.Default.Resolve(address.Host, RecordType.Mx);
try
{
if (response == null || response.AnswerRecords == null) return false;
}
catch (FormatException ex)
{
ex.ToString();
throw ex;
//return false;
}
return response.AnswerRecords.OfType<MxRecord>().Any();
}
public static bool IsValidEmailDomain(string address)
{
if (string.IsNullOrWhiteSpace(address)) return false;
MailAddress theAddress;
try
{
theAddress = new MailAddress(address);
}
catch (FormatException)
{
return false;
}
return IsValidEmailDomain(theAddress);
}
public static string test()
{
string mail = "########";
if (IsValidEmailDomain(mail))
{
return mail;
}
else
{
///How to return error from IsValidEmailDomain() method.
}
}
Any hint or suggestion would be most appreciated.
public static string test()
{
string mail = "########";
bool? answer;
Exception ex;
try
{
answer = IsValidEmailDomain(mail);
}
catch(Exception e)
{
ex = e;
}
if (answer)
{
return mail;
}
else
{
// here you can check to see if the answer is null or if you actually got an exception
}
}
There are a couple of ways to do this.
Use an out parameter.
Throw an exception if there was an issue. (Defeats the purpose of bool)
I usually go with a combination when I come across something like this.
public bool IsValidEmailDomain(string email)
{
return IsValidEmailDomain(email, false);
}
public bool IsValidEmailDomain(string email, bool throwErrorIfInvalid)
{
string invalidMessage;
var valid = ValidateEmailDomain(email, out invalidMessage);
if(valid)
return true;
if (throwErrorIfInvalid)
throw new Exception(invalidMessage);
return false;
}
public bool ValidateEmailDomain(string email, out string invalidMessage)
{
invalidMessage= null;
if (....) // Whatever your logic is.
return true;
invalidMessage= "Invalid due to ....";
return false;
}
I am in the process of converting code from VB to C# from an old system that used a base classes for web forms to inherit classes from. My hope is to build a new login for our new extranet that functions like the old system, I may have missed a step but here is the block I tried to convert.
public bool CheckAD()
{
string fncADStatus = "Failure";
string fncSuccess = "Success";
string fncFailure = "Failure";
fncADStatus = Convert.ToString(Session["SessionADStatus"]);
try
{
if (fncADStatus == fncSuccess)
{
return true;
}
}
catch
{
if (fncADStatus == fncFailure)
{
return false;
}
if (Session["SessionADStatus"] == null)
{
return false;
}
}
}
And I get the following error "not all code path return a value" but I don't quite understand why.
it give you the error because you have not mentioned the else statment; nothing will be returned if condition fall in else. do the following will not give you the errro.
public bool CheckAD() {
string fncADStatus = "Failure";
string fncSuccess = "Success";
string fncFailure = "Failure";
fncADStatus = Convert.ToString(Session["SessionADStatus"]);
try
{
Boolean output = false;
if (fncADStatus == fncSuccess)
{
output = true;
}
return output;
}
catch
{
Boolean output = true;
if (fncADStatus == fncFailure)
{
output = false;
}
if (Session["SessionADStatus"] == null)
{
output = false;
}
return output;
}
}
Not all the code paths in the catch block return a result. Usually, you would write something like this
public bool CheckAD()
{
try {...}
catch
{
if (fncADStatus == fncFailure)
{
logger.Debug("One");
}
if (Session["SessionADStatus"] == null)
{
logger.Debug("Two");
}
return false; // <<<<< This bit is missing in your case
}
}