I'm attempting to move from using VB WPF to C# WPF, What I have attempted so far is using an online converter because of the amount of code I have. The problem being that I have come into some troubles understanding some errors presented and being a beginner in C# I'm a little lost.
The code below is what I'm currently using with standard VB WPF and work perfectly fine and a copy of what the c# converter changes it into. (Note I have added Bing Maps WPF Reference to both VB and C#)
Private Sub Aberdeen() Handles BTNCounty.Click
If TXTCounty.Text = "Aberdeen" Then
Dim CountyLocation(2) As Microsoft.Maps.MapControl.WPF.Location
CountyLocation(0) = New Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584)
CountyLocation(1) = New Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584)
CountyLocation(2) = New Microsoft.Maps.MapControl.WPF.Location(57.124838, -2.0991633)
Dim names = New String() {"Aberdeen Central", "Aberdeen Lochnagar", "Aberdeen Kincorth"}
For index = 0 To CountyLocation.Length - 1
Dim Pin = New Microsoft.Maps.MapControl.WPF.Pushpin()
Dim CoordinateTip = New ToolTip()
CoordinateTip.Content = names(index)
Pin.Location = CountyLocation(index)
Pin.ToolTip = CoordinateTip
BingMap.Children.Add(Pin)
Next
End If
End Sub
Below is the example of the converted code into c#
private void Aberdeen()
{
if (TXTCounty.Text == "Aberdeen") {
Microsoft.Maps.MapControl.WPF.Location[] CountyLocation = new Microsoft.Maps.MapControl.WPF.Location[3];
CountyLocation(0) = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation(1) = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation(2) = new Microsoft.Maps.MapControl.WPF.Location(57.124838, -2.0991633);
dynamic names = new string[] {
"Aberdeen Central",
"Aberdeen Lochnagar",
"\tAberdeen Kincorth"
};
for (index = 0; index <= CountyLocation.Length - 1; index++) {
dynamic Pin = new Microsoft.Maps.MapControl.WPF.Pushpin();
dynamic CoordinateTip = new ToolTip();
CoordinateTip.Content = names(index);
Pin.Location = CountyLocation(index);
Pin.ToolTip = CoordinateTip;
BingMap.Children.Add(Pin);
}
}
}
I recieve 3 errors which I was wondering if you could tell me what they mean and how to resolve the issue?
CountyLocation is a variable but used like a method?
2 The name index does not exist in the current context?
3 System.Windows.FrameworkElement.ToolTip is a property but is used like a type?
Any help would be much appreciated as this very much foreign territory for me.
Please see the answers inline.
The main issue is that the converter has converted all your type inference calls (Dim variable = ...) to dynamics, which is incorrect. You should use var for type inference.
private void Aberdeen()
{
if (TXTCounty.Text == "Aberdeen") {
Microsoft.Maps.MapControl.WPF.Location[] CountyLocation = new Microsoft.Maps.MapControl.WPF.Location[3];
// Error 1: Setting array variables is done using square brackets, otherwise it's considered a method invocation
CountyLocation[0] = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation[1] = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation[2] = new Microsoft.Maps.MapControl.WPF.Location(57.124838, -2.0991633);
// extra: you don't need dynamic here, just var will do
var names = new string[] {
"Aberdeen Central",
"Aberdeen Lochnagar",
"\tAberdeen Kincorth"
};
// Error 2: you need to declare the index variable (added var)
for (var index = 0; index <= CountyLocation.Length - 1; index++) {
// Error 3: don't need dynamic here
var Pin = new Microsoft.Maps.MapControl.WPF.Pushpin();
// don't need dynamic here
var CoordinateTip = new ToolTip();
// Same as error 1: Array access is done with square brackets
CoordinateTip.Content = names[index];
// Same as error 1: Array access is done with square brackets
Pin.Location = CountyLocation[index];
Pin.ToolTip = CoordinateTip;
BingMap.Children.Add(Pin);
}
}
}
Related
I've tried add new encounter but it shows "System.NullReferenceException: 'Object reference not set to an instance of an object'". Heare is my code:
private static void AddEncounter()
{
var encount = new Encounter();
encount.Identifier.Add(new Identifier
{
Use = (Identifier.IdentifierUse?)1,
System = "http://www.amc.nl/zorgportal/identifiers/visits",
Value = "tek001"
}) ;
encount.Class = new Coding("http://terminology.hl7.org/CodeSystem/v3-ActCode", "SS", "Lưu trú ngắn hạn");
encount.Status = 0;
encount.Priority = new CodeableConcept("http://terminology.hl7.org/CodeSystem/v3-ActPriority", "R", "routine");
encount.Subject = new ResourceReference("Patient/a07b880381ec44ad8f80743f396c8011/_history/1", "Lâm");
encount.Length.Value = 120;
encount.Length.Unit = "min";
encount.Length.System = "http://unitsofmeasure.org";
encount.Length.Code = "min";
encount.ReasonCode.Add(new CodeableConcept("http://snomed.info/sct", "184004", "Rối loạn nhịp tim rút"));
encount.Hospitalization.PreAdmissionIdentifier.Use = (Identifier.IdentifierUse?)1;
encount.Hospitalization.PreAdmissionIdentifier.System = "http://www.amc.nl/zorgportal/identifiers/pre-admissions";
encount.Hospitalization.PreAdmissionIdentifier.Value = "1598753";
encount.Hospitalization.AdmitSource = new CodeableConcept("http://terminology.hl7.org/CodeSystem/admit-source", "outp", "Khoa ngoại trú");
encount.Hospitalization.DischargeDisposition = new CodeableConcept("http://terminology.hl7.org/CodeSystem/discharge-disposition", "hosp", "Bệnh nhân đã được xuất viện và chăm sóc giảm nhẹ");
Console.WriteLine("Successful");
Console.ReadLine();
}
How can i add an exactly?
Just like you do with creating the Identifier for the Identifier field and the other complex objects for the Class, Priority and Subject fields, you will need to create a Duration for the Length field:
encount.Length = new Duration();
encount.Length.Value = 120;
// etc.
You will have to do this for all of the complex objects you use in your code, so also for the Hospitalization field and the PreAdmissionIdentifier:
encount.Hospitalization = new Encounter.HospitalizationComponent();
encount.Hospitalization.PreAdmissionIdentifier = new Identifier();
// etc.
Another change I would like to advice, is to make use of the values provided in the enum for the identifier use, to make your code more readable and your intention clear:
encount.Hospitalization.PreAdmissionIdentifier.Use = Identifier.IdentifierUse.Official;
It's difficult to say for certain without seeing the entire class but System.NullReferenceException is thrown when trying to access something that has not been instantiated.
encount.Hospitalization is likely a reference to another class which must first be instantiated. Try first creating and instance before accessing (example below).
encount.Length = new Length();
encount.Hospitalization = new Hospitalization();
Note: I'm guessing the class names (Length and Hospitalization) so you may need to adjust for your code. The main idea is that you must create the class (new ...()) before utilizing\accessing.
I am trying to create an array of 20 candidates from my Candidate class. So far, this is what I have:
Candidate candidate0 = new Candidate();
Candidate candidate1 = new Candidate();
Candidate candidate2 = new Candidate();
Candidate candidate3 = new Candidate();
...
Candidate candidate19 = new Candidate();
Candidate[] candidates = new Candidate[20];
candidates[0] = candidate0;
candidates[1] = candidate1;
candidates[2] = candidate2;
candidates[3] = candidate3;
...
candidates[19] = candidate19;
I know this is not the correct or 'best' way to do this. What would be the best way?
What you need is a for loop :
int candidateLength = 20 ;
Candidate[] candidates = new Candidate[candidateLength ];
for(int i=0 ; i<candidates.Length ; i++)
{
candidates[i] = new Candidate();
}
Adam - you'd be subjectively better off using a list for this along the lines of:
List<Candidate> canditateList = new List<Candidate>();
// MaxLength is a const defined somewhere earlier perhaps
for(int i=0 ;i<MaxLength;i++){
canditateList.Add(new Candidate(){... properties here});
}
// etc, etc.
You could then factor this out to an array if required using:
var candidateArray = canditateList.ToArray();
Just my initial thoughts, tho you may of course have a good reason for wishing to use an array from the start, my premise is that I would go with a list and party on that for various extracted flavours.
Guys I am working with an API integration project in vb.net. Result from API is returned in XML format and I have been provided with some some of the classes which help me to navigate through xml. It's one of the class is WSGetFareQuoteRequest which has many properties. And one of its properties is Result which is defined in the integration document as:
Response Description
Structure of WSGetFareQuoteResponse is as follows:
Field Name DataType Remarks
Result* WSResult This result will
comprise of the new
fare(if any of the
component of fare
gets updated),
otherwise it will
remain the same.
Status WSStatus It will be having the
status or error
information.
When I asked API team regarding the initialisation of this result property of this object they provided me c# code as shown below :
WSGetFareQuoteRequest wsFareQuoteRequest = new WSGetFareQuoteRequest();
WSGetFareQuoteResponse wsFareQuoteResponse = new WSGetFareQuoteResponse();
int nor = 1;
if (searchResponse.Result != null && searchResponse.Result.Length 0 &&
objResult[i].IsLcc)
{
wsFareQuoteRequest.Result = new WSResult[nor];
wsFareQuoteRequest.Result[0] = new WSResult();
wsFareQuoteRequest.Result[0] = objResult[i];
wsFareQuoteRequest.SessionId = searchResponse.SessionId;
wsFareQuoteResponse = bApi.GetFareQuote(wsFareQuoteRequest);
Now my question is that I am doing the project in vb.net.I tried its vb.net equivalent it is showing me error at first line of object creation of Result property.I tried its vb.net equivalent as:
wsFareQuoteRequest.Result = New WSResult(nor)
'Only above line is creating error as Too many arguments to Pub Sub New'
wsFareQuoteRequest.Result(0) = New WSResult()
wsFareQuoteRequest.Result(0) = searchresponse.Result(i)
wsFareQuoteRequest.SessionId = searchresponse.SessionId
wsFareQuoteResponse = bapi.GetFareQuote(wsFareQuoteRequest)
Arrays in Visual Basic > Creating an Array
cargoWeights = New Double(10) {}
atmospherePressures = New Short(2, 2, 4, 10) {}
inquiriesByYearMonthDay = New Byte(20)()() {}
and in your case it would be:
wsFareQuoteRequest.Result = New WSResult(nor) {}
you are missing the {} at the end.
I am trying to create a list via array like this:
private Application[] GetApps()
{
DataSet ds = new Dataset();
string query = "query";
ds = GetData(query);
var appList = new Application[ds.Tables[0].Rows.Count];
for(var i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
DataRow item = ds.Tables[0].Rows[i];
appList[i].Name = item["Name"].ToString();
appList[i].Confidentiality = int.Parse(item["Conf"].ToString());
appList[i].Id = item["ID"].ToString();
}
return appList;
}
I keep getting an object null error and I know I have to be missing something completely obvious that I'm just not seeing. Do I need to declare the new array in some other way?
When you create appList, you are only creating the array itself. .NET does not automatically populate the array with Application objects for you to manipulate. You need to create a new Application object, and set the properties on that object, then you can assign the object to the array.
There are multiple Application classes withing the .NET framework, none of which seem to match your code, so the below example will simply assume that Application is a custom type of your own design.
for(var i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow item = ds.Tables[0].Rows[i];
Appliction app = new Application();
app.Name = item["Name"].ToString();
app.Confidentiality = int.Parse(item["Conf"].ToString());
app.Id = item["ID"].ToString();
appList[i] = app
}
As an aside, note that you can replace i <= x - 1 with i < x and the behavior is exactly the same.
Finally, you should introduce checks for all of your accessors if there is a chance that they could return null. For example, if item["Name"] returns null, then calling item["Name"].ToString() is equivelant to calling null.ToString(), which will also result in a NullReferenceException.
I am using the PayPal sandbox in ASP.Net C# 4.0. I added the following web reference:
https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
If i have 1 item (gimme 2 t-shirts please) i can pass it to the PayPal object and complete my transactions with no problems whatsoever:
var item = new PayPalAPIHelper.PayPalWS.PaymentDetailsItemType
{
Quantity = 2, //etc...etc
};
var paymentDetails = new PayPalAPIHelper.PayPalWS.PaymentDetailsType();
paymentDetails.PaymentDetailsItem = new PaymentDetailsItemType[]{item};
Now my dilemma is when a customer wants different items (1 t-shirt, 1 pair of pants). Now i need multiple PaymentDetailsItemType objects to pass to the paymentDetails object. I tried this:
//now i have an array of different items
var items = new PayPalAPIHelper.PayPalWS.PaymentDetailsItemType[3];
items[0].Description = "T-shirt";
items[1].Description = "Jeans";
paymentDetails.PaymentDetailsItem = new PaymentDetailsItemType[]{items};
I get this error:
Cannot implicitly convert type 'PayPalAPIHelper.PayPalWS.PaymentDetailsItemType[]'
to 'PayPalAPIHelper.PayPalWS.PaymentDetailsItemType'
I can do this and it compiles:
paymentDetails.PaymentDetailsItem = new PaymentDetailsItemType[]{items[0],items[1]};
But when I run it, i get Data type '' mismatch in element 'Quantity' when i call the PayPal service:
PayPalAPIHelper.PayPalWS.PaymentDetailsType paymentDetails = new PayPalAPIHelper.PayPalWS.PaymentDetailsType();
paymentDetails.PaymentDetailsItem = new PayPalAPIHelper.PayPalWS.PaymentDetailsItemType[] { items[0],items[1] };
reqDetails.PaymentDetails = new PayPalAPIHelper.PayPalWS.PaymentDetailsType[] { paymentDetails };
PayPalAPIHelper.PayPalWS.SetExpressCheckoutReq req = new PayPalAPIHelper.PayPalWS.SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new PayPalAPIHelper.PayPalWS.SetExpressCheckoutRequestType()
{
Version = Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
// query PayPal and get token
//error occurs here
PayPalAPIHelper.PayPalWS.SetExpressCheckoutResponseType resp = BuildPayPalWebservice().SetExpressCheckout(req); //this is where the error occurs
How do i pass multiple types to the PayPal API web service so the user can order different items? Thanks in advance
First, you already have an array, so it makes no sense to create a new one just for the sake of assignment into paymentDetails.PaymentDetailsItem:
var items = new PayPalAPIHelper.PayPalWS.PaymentDetailsItemType[3];
…
paymentDetails.PaymentDetailsItem = items; // this is wrong: new PaymentDetailsItemType[]{items};
By writing new PaymentDetailsItemType[]{items} you create a new array and try to initialize its first item (of type PaymentDetailsItemType) with the contents of another array items (of type PaymentDetailsItemType[] — hence incompatible).
Second, make sure you fill all required properties for all items in the array. Most likely, in your example of one t-shirt and one jeans you should do:
items[0].Description = "T-shirt";
items[0].Quantity = 1;
items[1].Description = "Jeans";
items[1].Quantity = 1;