I am using a service reference which connects to internet and I want to show message in a message box if ever the connection fails. How will I call message box in the member function of the class which has void return type? This is the member function of the class:
public void ReverseGeocodePoint()
{
try{
string results = "";
string key = "abc";
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set the credentials using a valid Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = key;
// Set the point to use to find a matching address
GeocodeService.Location point = new GeocodeService.Location();
point.Latitude = latitude;
point.Longitude = longitude;
reverseGeocodeRequest.Location = point;
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
//This will connect to the server
GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = geocodeResponse.Results[0].DisplayName;
else
results = "No Results found";
address = results;
}} catch{ //here I want to show a msgbox but the problem is, this is not the form class}
Don't catch the exception in that class if there's nothing you can do about it there. Just let it bubble up and catch it where you can do something about it:
public class MyForm : Form
{
public void SomeMethod()
{
try
{
var sc = new ServiceClass();
sc.ReverseGeocodePoint();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
In ReverseGeocodePoint(), remove the try/catch statements.
Related
I use a VPN class in my program. But when I try to connect, it cause the following error:
the system could not find the phone book entry for this connection
Here is the connect method:
public void VPN_Connect(string VPN_Name, string VPN_ID, string VPN_PW)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Network\Connections\Pbk\rasphone.pbk";
AllUsersPhoneBook = new RasPhoneBook();
AllUsersPhoneBook.Open(path);
if (AllUsersPhoneBook.Entries.Contains(EntryName))
{
AllUsersPhoneBook.Entries[EntryName].PhoneNumber = VPN_Name;
AllUsersPhoneBook.Entries[EntryName].Update();
}
else
{
RasEntry entry = RasEntry.CreateVpnEntry(EntryName, VPN_Name, RasVpnStrategy.Default,
RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
entry.EncryptionType = RasEncryptionType.None;
AllUsersPhoneBook.Entries.Add(entry);
}
Dialer = new RasDialer();
Dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
this.Dialer.EntryName = EntryName;
this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.Dialer.Credentials = new NetworkCredential(VPN_ID, VPN_PW);
this.handle = this.Dialer.DialAsync();
VPN_Status = (int)status.Defalut;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
How can I solve this problem?
I'm also using windows 10 with latest update and DotRas last version.
I managed to add a contact but when I try and add an invoice I get an error message 'A validation exception occurred'. I would appreciate suggestions as to what is causing this error.
private void button1_Click(object sender, EventArgs e)
{
try
{
/// first create an instance of the Xero API
var api = new Xero.Api.Example.Applications.Private.Core(false);
Contact newContact = new Contact();
newContact.Name = "Orac";
Invoice newInvoice = new Invoice();
newInvoice.Contact = new Contact();
newInvoice.Contact = newContact;
newInvoice.Date = System.DateTime.Now;
newInvoice.DueDate = System.DateTime.Now.AddMonths(1);
newInvoice.Status = Xero.Api.Core.Model.Status.InvoiceStatus.Authorised;
newInvoice.Type = Xero.Api.Core.Model.Types.InvoiceType.AccountsReceivable;
List<LineItem> lines = new List<LineItem>();
LineItem li = new LineItem();
li.LineAmount = Convert.ToDecimal("200.00");
li.Quantity = Convert.ToDecimal("1.0000");
li.ItemCode = "100";
li.Description = "Webdev inv test";
li.AccountCode = "200";
li.UnitAmount = Convert.ToDecimal("50.00");
lines.Add(li);
newInvoice.LineItems = lines;
// call the API to create the contact
api.Invoices.Create(newInvoice);
//api.Contacts.Create(newContact);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Retain the result of your creation request - e.g.
var result = api.Invoices.Create(newInvoice);
...and examine the Errors and Warnings properties of the result to determine what's wrong with your request.
The type of exception thrown is a ValidationException. Either catch that type specifically or cast your caught generic Exception, and inspect the ValidationErrors property
I have two reliable queues and they are being accessed by two guest executables and each of them access their own. Sometimes the function I use to access them doesn't update the reliable queue object in the function and the wrong request is sent to the wrong guest executable.
What happens is that the clientId is passed by the guest executable to this function in the Get request. Let us say that there are two clientId(s) called T1 and T2.
What happens is that the guest executable (client) T2 at times gets the request that was meant for T1. Even though I tried line by line debugging the parameters passed to this function are correct.
Here is my API's POST that is passed a json to be added to the queue for the clients to receive from the GET
[HttpPost("MarketInfo")]
public JObject GetMarketInfo([FromBody] JObject jObject)
{
List<JToken> clients = jObject.GetValue("clients").ToList();
string json;
JObject response = new JObject();
JArray jsonArray = new JArray();
try
{
foreach (JToken client in clients)
{
var id = Guid.NewGuid();
json = "{'name':'MarketInfo','id':'" + id.ToString() + "','mtClientId':'" + terminal["name"].ToString() + "','parameters':{'symbol':'" + terminal["symbol"].ToString() + "','property':24}}";
bool result = _requestsCollectionHandler.CreateRequestForClient(JObject.Parse(json));
JObject clientResponse = new JObject();
if (result==true)
{
clientResponse["name"] = client["name"].ToString();
clientResponse["guid"] = id.ToString();
jsonArray.Add(clientResponse);
}
else
{
clientResponse["name"] = terminal.Children()["name"].ToString();
clientResponse["guid"] = "ERROR";
jsonArray.Add(terminalResponse);
}
}
response["clients"] = jsonArray;
return response;
}
catch (Exception e)
{
Debug.Write(e.Message);
return null;
}
}
This is the json that we pass to this API
{"clients":[{"name":"T1","symbol":"SomeInfo"},{"name":"T2","symbol":"SomeInfo"}]}
The problem is always with the clients object that is passed first.
Before I explain further let me also share the code for the client's HttpGet
[HttpGet("{clientId}")]
public string Get([FromRoute] string clientId)
{
try
{
string request = _requestsCollectionHandler.GetRequestJsonFromQueue(clientId);
return request;
}
catch(Exception e)
{
return e.Message;
}
}
This is the function that creates an object that is to be added by another function in the reliable queue
public bool CreateRequestForClient(JObject jObject)
{
try
{
this._jObject = new JObject(jObject);
CreateKey();
AddToRequestToQueueAsync();
return true;
}
catch (Exception e)
{
Debug.Write(e.Message);
_exceptionMessage = e.Message;
return false;
}
}
private void CreateKey()
{
dynamic data = JObject.Parse(_jObject.ToString(Newtonsoft.Json.Formatting.None));
string name = data.name;
string id = data.id;
string clientId = data.clientId;
_key.id = id;
_key.name = name;
_key.clientId = clientId;
//key.timestamp = GetTimestamp();
_key.timestamp = GetTimestamp();
_key.requestJson = _jObject.ToString(Newtonsoft.Json.Formatting.None);
}
_key is a private variable in class a custom class
This is the function in my class of request handler that adds the requests to the queue
private void AddToRequestToQueueAsync()
{
var transaction = this._stateManager.CreateTransaction();
CancellationToken cancellationToken
= new CancellationToken(false);
try
{
string queue = _key.clientId;
IReliableConcurrentQueue<TerminalResponseKey> reliableQueue =
_stateManager.GetOrAddAsync<IReliableConcurrentQueue<TerminalResponseKey>>(queue).Result;
transaction = this._stateManager.CreateTransaction();
if (reliableQueue!=null)
{
long count = reliableQueue.Count;
reliableQueue.EnqueueAsync(transaction, _key);
count = reliableQueue.Count;
transaction.CommitAsync().Wait();
}
else
{
transaction.Abort();
}
}
catch
{
transaction.Abort();
throw;
}
}
This is function that is used by the client
public string GetRequestJsonFromQueue(string clientId)
{
string queue = clientId;
try
{
IReliableConcurrentQueue<TerminalResponseKey> reliableQueue =
this._stateManager.GetOrAddAsync<IReliableConcurrentQueue<TerminalResponseKey>>(queue).Result;
if(reliableQueue != null)
{
ConditionalValue<TerminalResponseKey> key =
reliableQueue.TryDequeueAsync(transaction).Result;
if(key.HasValue)
{
string request = key.Value.requestJson;
transaction.CommitAsync().Wait();
return request;
}
}
else
{
transaction.Abort();
}
return "NO QUEUE";
}
catch (Exception e)
{
Debug.WriteLine(e);
transaction.Abort();
return e.InnerException.Message;
}
}
As far as I have found out I think my problem is in this function above. Because I don't know how the client T2 or client T1 gets another client's queue because the parameters determining the queue are their IDs and are totally unique.
These Ids are also passed correctly to this:
IReliableConcurrentQueue<TerminalResponseKey> reliableQueue =
this._stateManager.GetOrAddAsync<IReliableConcurrentQueue<TerminalResponseKey>>(queue).Result;
As you can see that we have queue=clientId
I have tried adding proper timespans but it was of no use as there is no exception thrown for OperationTimedOut. Furthermore since I am new to ServiceFabric I maybe totally doing anything wrong.
PS: Sorry for maybe a lot of jumbled up and confused code and question AND SOME OF THE INFORMATION IS OBFUSCATED DUE TO CONFIDENTIALITY BUT NOTHING OBSTRUCTING THE UNDERSTANDING OF THIS IS HIDDEN (I Hope not an issue)
I hope this is not an issue maybe an error I am overlooking at my side
When you put the request in the queue, in AddToRequestToQueueAsync(), the name of the queue is set from _key.terminalId (and I don't see where you assign it), but when you read from it, in GetRequestJsonFromQueue(), the clientId
is used as the queue name.
I am using active directory and want a list of all users, basically in dotnet core. But I am receiving an exception:
Search result reference received, and referral following is off
Below is my code.
LdapSearchResults lsc = lc.Search("DC = xyz, DC = local", LdapConnection.SCOPE_ONE , "(|(objectClass = person)(objectClass = user))", null, false);
Necromancing - just in case the links go dark.
To fix it in your application, set ReferralFollowing to true.
if you get the message
Search result reference received, and referral following is off
, add
Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
cons.ReferralFollowing = true;
lc.Constraints = cons;
to your code.
Example:
public static void GetUsers()
{
System.Collections.Generic.List<ARSoft.Tools.Net.Dns.SrvRecord> lsLdap = GetLdap();
ARSoft.Tools.Net.Dns.SrvRecord ldap = lsLdap[0];
string[] attrs = new string[] { "cn", "distinguishedName", "sAMAccountName", "userPrincipalName", "displayName", "givenName", "sn", "mail", "mailNickname", "memberOf", "homeDirectory", "msExchUserCulture" };
// CN = Common Name
// OU = Organizational Unit
// DC = Domain Component
string searchBase = "DC=cor,DC=local";
string searchFilter = "(&(objectClass=user)(objectCategory=person))";
string ldapHost = MySamples.TestSettings.ldapHost;
int ldapPort = MySamples.TestSettings.ldapPort;//System.Convert.ToInt32(args[1]);
string loginDN = MySamples.TestSettings.loginDN; // args[2];
string password = MySamples.TestSettings.password; // args[3];
Novell.Directory.Ldap.LdapConnection lc = new Novell.Directory.Ldap.LdapConnection();
int ldapVersion = Novell.Directory.Ldap.LdapConnection.Ldap_V3;
try
{
// connect to the server
lc.Connect(ldap.Target.ToString(), ldap.Port);
// bind to the server
lc.Bind(ldapVersion, loginDN, password);
Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
cons.ReferralFollowing = true;
lc.Constraints = cons;
// To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE(default) to disable referrals.
Novell.Directory.Ldap.LdapSearchResults lsc = lc.Search(searchBase,
Novell.Directory.Ldap.LdapConnection.SCOPE_SUB,
searchFilter,
attrs,
false,
(Novell.Directory.Ldap.LdapSearchConstraints)null);
while (lsc.HasMore())
{
Novell.Directory.Ldap.LdapEntry nextEntry = null;
try
{
nextEntry = lsc.Next();
}
catch (Novell.Directory.Ldap.LdapReferralException eR)
{
// https://stackoverflow.com/questions/46052873/ldap-referal-error
// The response you received means that the directory you are requesting does not contain the data you look for,
// but they are in another directory, and in the response there is the information about the "referral" directory
// on which you need to rebind to "redo" the search.This principle in LDAP are the referral.
// https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html
// To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE (default) to disable referrals.
// are you sure your bind user meaning
// auth.impl.ldap.userid=CN=DotCMSUser,OU=Service Accounts,DC=mycompany,DC=intranet
// auth.impl.ldap.password = mypassword123
// has permissions to the user that is logging in and its groups?
System.Diagnostics.Debug.WriteLine(eR.LdapErrorMessage);
}
catch (Novell.Directory.Ldap.LdapException e)
{
// WARNING: Here catches only LDAP-Exception, no other types...
System.Console.WriteLine("Error: " + e.LdapErrorMessage);
// Exception is thrown, go for next entry
continue;
}
var atCN = nextEntry.getAttribute("cn");
var atUN = nextEntry.getAttribute("sAMAccountName");
var atDN = nextEntry.getAttribute("distinguishedName");
var atDIN = nextEntry.getAttribute("displayName");
if (atCN != null)
System.Console.WriteLine(atCN.StringValue);
if (atUN != null)
System.Console.WriteLine(atUN.StringValue);
if (atDN != null)
System.Console.WriteLine(atDN.StringValue);
if (atDIN != null)
System.Console.WriteLine(atDIN.StringValue);
System.Console.WriteLine("\n" + nextEntry.DN);
Novell.Directory.Ldap.LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
while (ienum.MoveNext())
{
Novell.Directory.Ldap.LdapAttribute attribute = (Novell.Directory.Ldap.LdapAttribute)ienum.Current;
string attributeName = attribute.Name;
string attributeVal = attribute.StringValue;
System.Console.WriteLine(attributeName + "value:" + attributeVal);
}
}
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
finally
{
// disconnect with the server
lc.Disconnect();
}
}
You have to activate the behaviour which will follow the referral returned by the directory.
The response you received means that the directory you are requesting does not contain the data you look for, but they are in another directory, and in the response there is the information about the "referral" directory on which you need to rebind to "redo" the search. This principle in LDAP are the referral.
I don't know how to do it in C#, but maybe have a look at :
https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html
I have the following Payments code.
var service = new StripeChargeService(newgenSecretKey);
try
{
var result = service.Create(newCharge);
if (result.Paid)
{
lab.Text = "It worked";
CartOrders.UpdateTransactionID(result.Id, OrderID, "Express Checkout");
Response.Redirect("PgeCustSuccess.aspx?OrderID=" + OrderID);
}
}
catch (StripeException stripeException)
{
Debug.WriteLine(stripeException.Message);
stripe.Text = stripeException.Message;
//CartOrders.UpdateTransactionID(result.FailureMessage, OrderID, "Express Checkout");
}
I would like to log the commented out value in the catch block(result.FailureMessage).I am trying to catch the Stripe Errors if thrown and logging it into my database. The problem I am facing is that I cannot get the result.FailureMessage to work in the catch block. I understand that a global var cannot be declared and must only be used locally.
Here are a few thing that I tried.
Declared the result outside the try block but did not succeed because var should be initialised with a type and it is of type stripe
var service = new StripeChargeService(newgenSecretKey);
var result = new { };
try
{
//did not work
result = service.Create(newCharge);
if (result.Paid)
{
Any Ideas ?
You could do:
var service = new StripeChargeService(newgenSecretKey);
Stripe result;
try
{
result = service.Create(newCharge);
if (result.Paid)
{
Try moving result up out of the try, or:
var service = new StripeChargeService(newgenSecretKey);
var result;
try
{
result = service.Create(newCharge);
if (result.Paid)
{
lab.Text = "It worked";
CartOrders.UpdateTransactionID(result.Id, OrderID, "Express Checkout");
Response.Redirect("PgeCustSuccess.aspx?OrderID=" + OrderID);
}
}
catch (StripeException stripeException)
{
Debug.WriteLine(stripeException.Message);
stripe.Text = stripeException.Message;
//CartOrders.UpdateTransactionID(result.FailureMessage, OrderID, "Express Checkout");
}
Note that your result.FailureMessage may throw an Exception if result is never populated; you could use an if statement or try-catch to prevent against this.