Error message when I use xx.Contains in C# - c#

I am trying the following code inside an ASP MVC Razor file:
var topic = ViewData["TopicID"];
var mustBeReplaced = string.Empty;
var topicValue = Model.Topic;
var replaceResult = string.Empty;
if (topic.Contains(topicValue)) {
mustBeReplaced = "value=\"" + topicValue + "\"";
replaceResult = mustBeReplaced + " selected=\"selected\"";
topic = topic.Replace(mustBeReplaced, replaceResult);
}
But I get an error message:
object' does not contain a definition for 'Contains' and the best extension method overload

var topic = ViewData["TopicID"];
Returns object. You need to cast to string.

Try this
var topic = (string)ViewData["TopicID"];
var mustBeReplaced = string.Empty;
var topicValue = "11111";
var replaceResult = string.Empty;
if (topic.Contains(topicValue))
{
mustBeReplaced = "value=\"" + topicValue + "\"";
replaceResult = mustBeReplaced + " selected=\"selected\"";
topic = topic.Replace(mustBeReplaced, replaceResult);
}

Related

how to get json result from payfort Apis in C#

The problem I am facing is that, payfort API should return me some json. But instead i get some html that has some hidden fields. and i see no error written inside there.
Here is my code
string access_code = string.Empty,
amount = string.Empty,
currency = string.Empty,
customer_email = string.Empty,
merchant_reference = string.Empty,
order_description = string.Empty,
language = string.Empty,
merchant_identifier = string.Empty,
signature = string.Empty,
command = string.Empty;
access_code = "X78979879h8h8h8";
amount = "1000";
command = "AUTHORIZATION";
currency = "AED";
customer_email = "zetawars#hotmail.com";
language = "en";
merchant_identifier = "RaskdQuCc";
merchant_reference = "ASASASASASADSS";
order_description = "Some order details";
signature = "";
string signature_string = "PASSaccess_code="+access_code+"amount="+amount+"command="+command+"currency="+currency+"customer_email"+customer_email+"language"+language+"merchant_identifier"+merchant_identifier+"merchant_reference"+merchant_reference+"order_description"+order_description+"PASS";
signature = getHashSha256(signature_string);
string url = "https://sbcheckout.payfort.com/FortAPI/paymentPage";
string param = "access_code" + access_code + "&amount=" + amount + "&currency=" + currency +
"&customer_email=" + customer_email + "&merchant_reference=" + merchant_reference +
"&order_description=" + order_description + "&language=" + language + "merchant_identifier="
+ merchant_identifier + "&signature=" + signature + "&command=" + command;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
//wc.Headers.Add("Content-Type", "application/json");
string HtmlResult = wc.UploadString(url, param);
}
Try adding values for below header
wc.Headers[HttpRequestHeader.Authorization]
wc.Headers[HttpRequestHeader.TenantId]
wc.Headers[HttpRequestHeader.Client-Type]
wc.Headers[HttpRequestHeader.Protocol]
Works for me!!
First Encode the response
string responseString = Encoding.UTF8.GetString(response);
Use HtmlDocument (HtmlAgilityPack)
var html = new HtmlDocument();
var tokenValue = "";
html.LoadHtml(responseString);
After Loading This into html you can query fields and values.
var tokenFormIdElement =
html.DocumentNode.SelectSingleNode("//input[#name='token']");
tokenValue = tokenFormIdElement.GetAttributeValue("value", "");

Pass parameter to a method and read the return value?

Having this code:
var code = "public class TestClass {" +
" public int HelloWorld(int num) {" +
" return 5 + num;" +
" }" +
"}";
var script = CSharpScript.Create(code);
var x = (await script.RunAsync()).ReturnValue;
How does one pass a value for the parameter, call the method and read the return value?
Continue with another code is the simplest.
var call = await script.ContinueWith<int>("new TestClass().HelloWorld(3)").RunAsync();
var x = call.ReturnValue;
By the way, CSharpScript is a scripting engine which does not require you having class and method like ordinary C# program. You can just use 5 + num as script content.
var code = "5 + num";
var numValue = 3;
var setParam = await CSharpScript.RunAsync("var num = " + numValue + ";");
var runCode = await setParam.ContinueWithAsync(code);
var x = runCode.ReturnValue;
For full example, take a look of RoslynScript/Script.cs

c# Retrieve multiple XML child nodes

I've managed to link up a single XElement successfully into my program though I'm not having any luck with the other two I have in place, I've tried using;
IEnumerable query = from booking in doc.Descendants("Booking")
Though I've haven't had much luck placing the values into list box.
Here's the code for function:
private void btnimport_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.CheckFileExists = true;
open.InitialDirectory = "#C:\\";
open.Filter = "XML Files (*.xml)|*.xml|All Files(*.*)|*.*";
open.Multiselect = false;
if (open.ShowDialog() == DialogResult.OK)
{
try
{
XDocument doc = XDocument.Load(open.FileName);
//Grabs the customer elements
var query = from booking in doc.Descendants("Booking")
select new
{
//Customer Elements
CustomerId = booking.Element("CustomerId").Value,
Title = booking.Element("Title").Value,
Firstname = booking.Element("FirstName").Value,
Lastname = booking.Element("LastName").Value,
DateofBirth = booking.Element("DateofBirth").Value,
Email = booking.Element("Email").Value,
HouseNo = booking.Element("HouseNo").Value,
Street = booking.Element("Street").Value,
Postcode = booking.Element("Postcode").Value,
Town = booking.Element("Town").Value,
County = booking.Element("County").Value,
ContactNo = booking.Element("ContactNo").Value,
//Holiday Elements
HolidayId = booking.Element("HolidayId").Value,
HotelName = booking.Element("HotelName").Value,
Location = booking.Element("Location").Value,
BookFrom = booking.Element("BookFrom").Value,
BookTo = booking.Element("BookTo").Value,
CheckInTime = booking.Element("CheckInTime").Value,
CheckOutTime = booking.Element("CheckOutTime").Value,
NoOfRoomsBooked = booking.Element("NoOfRoomsBooked").Value,
RoomType = booking.Element("RoomType").Value,
RoomServices = booking.Element("RoomServices").Value,
Parking = booking.Element("Parking").Value,
Pet = booking.Element("Pet").Value,
//TravelInfo Elements
TravelInfoId = booking.Element("TravelInfoId").Value,
TravellingFrom = booking.Element("TravellingFrom").Value,
Destination = booking.Element("Destination").Value,
Fare = booking.Element("Fare").Value,
TravelInsurance = booking.Element("TravelInsurance").Value,
InFlightMeals = booking.Element("In-FlightMeals").Value,
LuggageAllowance = booking.Element("LuggageAllowance").Value,
ExtraLuggage = booking.Element("ExtraLuggage").Value,
CarHire = booking.Element("CarHire").Value,
ReturnTransfer = booking.Element("ReturnTransfer").Value,
};
//Inputs all of the values in bookings
foreach (var booking in query)
{
//Customer values
txtCustomerId.Text = txtCustomerId.Text + booking.CustomerId;
txttitle.Text = txttitle.Text + booking.Title;
txtfname.Text = txtfname.Text + booking.Firstname;
txtlname.Text = txtlname.Text + booking.Lastname;
txtdob.Text = txtdob.Text + booking.DateofBirth;
txtemail.Text = txtemail.Text + booking.Email;
txthouseno.Text = txthouseno.Text + booking.HouseNo;
txtstreet.Text = txtstreet.Text + booking.Street;
txtpostcode.Text = txtpostcode.Text + booking.Postcode;
txttown.Text = txttown.Text + booking.Town;
txtcounty.Text = txtcounty.Text + booking.County;
txtcontactno.Text = txtcontactno.Text + booking.ContactNo;
//Holiday Values
txtHolidayId.Text = txtHolidayId.Text + booking.HolidayId;
txthname.Text = txthname.Text + booking.HotelName;
txtl.Text = txtl.Text + booking.Location;
txtbf.Text = txtbf.Text + booking.BookFrom;
txtbt.Text = txtbt.Text + booking.BookTo;
txtcit.Text = txtcit.Text + booking.CheckInTime;
txtcot.Text = txtcot.Text + booking.CheckOutTime;
txtnorb.Text = txtnorb.Text + booking.NoOfRoomsBooked;
txtrt.Text = txtrt.Text + booking.RoomType;
txtrs.Text = txtrs.Text + booking.RoomServices;
txtpark.Text = txtpark.Text + booking.Parking;
txtpet.Text = txtpet.Text + booking.Pet;
//TravelInfo Values
txtTravelInfoId.Text = txtTravelInfoId.Text + booking.TravelInfoId;
txttf.Text = txttf.Text + booking.TravellingFrom;
txtd.Text = txtd.Text + booking.Destination;
txtf.Text = txtf.Text + booking.Fare;
txtti.Text = txtti.Text + booking.TravelInsurance;
txtifi.Text = txtifi.Text + booking.InFlightMeals;
txtla.Text = txtla.Text + booking.LuggageAllowance;
txtel.Text = txtel.Text + booking.ExtraLuggage;
txtch.Text = txtch.Text + booking.CarHire;
txtrtrans.Text = txtrtrans.Text + booking.ReturnTransfer;
}
MessageBox.Show("XML has been imported");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
If anyone knows where I've gone wrong or what I need to add / change please let me know :)
Many thanks,
10gez10
You have several problems:
Firstly, your data elements are not immediate children of the booking element, there are intermediate elements <Customer>, <Holiday> and <TravelInfo>. Thus you need to do something like
var query = from booking in doc.Descendants("Booking")
let customer = booking.Element("Customer")
let holiday = booking.Element("Holiday")
let travelInfo = booking.Element("TravelInfo")
select new
{
//Customer Elements
CustomerId = customer.Element("CustomerId").Value,
Title = customer.Element("Title").Value,
HolidayId = holiday.Element("HolidayId").Value,
TravelInfoId = travelInfo.Element("TravelInfoId").Value,
}
Secondly, several elements are misspelled:
CheckOutTime should be CheckoutTime
In-FlightMeals should be InFlightMeals.
CarHire should be CareHire (yes "CareHire" is what's in the XML.)
Thus, when you do (e.g.) Element("In-FlightMeals").Value, Element() is returning null so you get a null reference exception and your code is aborted.
Thirdly, the element BookTo is completely missing, so BookTo = holiday.Element("BookTo").Value generates a null reference exception.
More generally, I do not recommend this coding approach. If any of your XML elements are missing, your query will throw an exception because element.Element("name") will be null. What's worse, Visual Studio doesn't seem to report an accurate line number on which the null reference occurs, instead giving the line number of the select new statement. And (on my version at least), it's not possible to step into the constructor for an anonymous type either. This makes debugging well-nigh impossible.
Instead, skip the intermediate anonymous type and do things in a more direct, traditional manner:
foreach (var booking in doc.Descendants("Booking"))
{
var customer = booking.Element("Customer");
var holiday = booking.Element("Holiday");
var travelInfo = booking.Element("TravelInfo");
XElement element;
if (customer != null)
{
if ((element = customer.Element("CustomerId")) != null)
txtCustomerId.Text = txtCustomerId.Text + element.Value;
}
// And so on.
}

Adding double quotes to # string

As far as i understood, a string with an # in required a set of double quotes to insert the quote in to the string?
I have tried that principle and to no avail. The following line works, but if i were to replace those strings with parameter values then i cant seem to get the correct compilation value
var node = doc.SelectSingleNode(#"//node[#label = ""Chemist Name""]/node[#label = ""John,Smith""]");
my attempt (of which i have tried several versions and ended up here, where i have now givn up !)
var node = doc.SelectSingleNode(#"//node[#label = " + ""+parentID+"" + "]/node[#label = " + ""+ name +"" + "]");
can anyone help me please?
Use single quotes:
var node = doc.SelectSingleNode
(#"//node[#label = 'Chemist Name']/node[#label = 'John,Smith']");
var node = doc.SelectSingleNode(
string.format(#"//node[#label = '{0}']/node[#label = '{1}']"
, parentID, name));
You are missing another double quote to close the string being appended and also # before each string containing "".
Try this:
var node =
doc.SelectSingleNode(#"//node[#label = """ + parentID + #"""]/node[#label = """ + name + #"""]");
var node = doc.SelectSingleNode(string.format(#"//node[#label = ""{0}""]/node[#label = ""{1}""]", parentId, name));
Write an extension method to extend string:
public static string Quote(this string input)
{
return string.Format(#"""{0}""", input);
}
And then use it as follows:
var node = doc.SelectSingleNode(#"//node[#label = " + parentID.Quote() + "]/node[#label = " + name.Quote() + "]");
Or simply:
var node = doc.SelectSingleNode(string.Format(#"//node[#label = {0}"]/node[#label = {1}"]",parentID.Quote(), name.Quote());

client.get("me/statuses") returns empty "data" array using C# Facebook SDK 5.0.3

Using the C# Facebook SDK 5.0.3 everything works fine whit the client.Get("/me").
But when retrieving the status, I should get aan arraylist "data" with all the status messages according to the facebook Graph API, but instead my data array is empty and I get a 'Index out of bounds' exception.
Does anyone have an idea what my problem could be?
if (Request.Params["code"] != null)
{
var client = new FacebookClient(GetAccessToken());
dynamic me = client.Get("/me");
imgUser.ImageUrl = "https://graph.facebook.com/" + me.id + "/picture";
lblUsername.Text = me.name;
lblHometown.Text = me.hometown.name;
lblBirthday.Text = me.birthday;
lblCurrenttown.Text = me.location.name;
lblEmail.Text = me.email;
lblOpleidingen.Text = "";
lblOpleidingen.Text += me.education[1].type + ": " + me.education[1].school.name + ", " + me.education[1].year.name + "<br />"
+ me.education[0].type + ": " + me.education[0].school.name + ", " + me.education[0].year.name;
lblSex.Text = me.gender;
dynamic status = client.get("/me/statuses");
txtStatus.Text = status.data[0].message;
}
It requires the read_stream permission. Ensure you have it.
Your permission array should look like follows:
string[] extendedPermissions = new[] { "user_about_me", "read_stream" };
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
furthermore your second get() should be capitalized: Get()
dynamic status = client.get("/me/statuses");
dynamic status = client.Get("/me/statuses");

Categories