I am trying to write an application (simple form) that will consume(invoke) the web service (Service1.asmx) and display the results. Now, the web service has a method. Here is the code:
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public Customer getCustomer(String id)
{
Customer customer = new Customer();
customer.CustomerId = id;
customer.CustomerName = "ABC Warehouse";
customer.CustomerAddress = "123 Anywhere";
customer.CustomerCity = "Pittsburgh";
customer.CustomerState = "PA";
customer.CustomerZip = 10379;
customer.CustomerContact = "Dan Smith";
customer.CustomerPhone = "2484567890";
customer.CustomerCredit = "True";
return customer;
}
}
When I run the web service from its original project I am able to type text in the text box Example and click invoke to view the xml resultsExample. Now, the simple form I have in another project has a textbox (txt1), button (btn1), and label (lbl1). I successfully add the web service and all the functions and classes transfer. Now, what I want to happen is when you type something in the text box, click submit, and view the xml results in the label which will include the typed text from the text box, exactly like if I would of run the service on its own. Here is the code where I am having trouble:
public partial class _Default : System.Web.UI.Page
{
protected void btn1_Click(object sender, EventArgs e)
{
MyService.Service1 service = new MyService.Service1();
string message = service.getCustomer(string id);
ID = txt1.Text;
lbl1.Text = message;
}
}
Where am I going wrong? I am a beginner obviously, so all help would be appreciated.
p.s.: MyService is what I named the namespace when I added the web service
your code will not compile because getCustomer return Customer object.
protected void btn1_Click(object sender, EventArgs e)
{
MyService.Service1 service = new MyService.Service1();
MyService.Customer customer= service.getCustomer(string id);
ID = customer.CustomerId;
// here you can generate XML based on customer object if you really need to do so
lbl1.Text = GetCustomerXML(customer);// implement method to get XML
}
private string GetCustomerXML( MyService.Customer customer)
{
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyService.Customer));
StringWriter sw= new StringWriter();
XmlWriter writer = XmlWriter.Create(sw);
xsSubmit.Serialize(writer, customer);
return sw.ToString();
}
First of all in service method you need to define that response format data must be in XML format. and then in client use 'XmlNode' to get data from service.
I think this post will be usefull for you
Your error is to be thinking that you're going to get XML back. You're not. You're going to get a MyService.Customer back.
FYI, you should be using "Add Service Reference" to consume the .asmx service.
Related
I am testing a client application with a web reference to a web service; the web reference is called "PrinterStatus".
In this application I populate a dropdown list with list of available method names. I want to call the method user has selected and not sure how to set it up.
private void PopulateDropdown()
{
// web service URL
string url = "http://1.2.3.4/PS_WS/PrinterStatus.asmx?WSDL";
WebServiceInfo webServiceInfo = WebServiceInfo.OpenWsdl(new Uri(url));
foreach (WebMethodInfo method in webServiceInfo.WebMethods)
{
ListItem li = new ListItem(method.Name);
ddlMethods.Items.Add(li);
}
}
This populates the drop down list with list of available methods (the code for "WebServiceInfo" is at this link).
When user clicks "Submit", I want to be able to call:
PrinterStatus ps = new PrinterStatus();
string sResp = ps.<method_name_user_selected>();
Update
Following Xerillio's recommendation, I made the following changes to get this to work. In my test client app I have a dropdown populated with available method names (ddlMethods) and two textboxes for IP address and port number of printer whose status I am interested in (tbIP and tbPort) and a "submit" button. I have removed all validation stuff.
Also, the web reference created in client app is named "PrinterStatus". The methods in web service return a JSON object.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string sMethodName = ddlMethods.SelectedValue;
string sIPAddress = tbIP.Text.Trim();
string sPort = tbPort.Text.Trim();
int iPort = int.Parse(sPort);
PrinterStatus ps = new PrinterStatus();
Type thisType = ps.GetType();
MethodInfo theMethod = thisType.GetMethod(sMethodName);
string sResp = theMethod.Invoke(ps, new object[] {sIPAddress, iPort}) as string;
Response resp = JsonConvert.DeserializeObject<Response>(sResp);
I have been trying to return an ArrayList from a WebService and I am confused about how to get it going as I get an error message saying
"Cannot implicitly convert type 'object[]' to 'System.Collections.ArrayList'".
Here is the Code for the Web Service names DDRParserService.asmx .
public ArrayList PVTLog(string reqNo, string groupNo, string filePath)
{
ArrayList logData = new ArrayList();
//Calling the Parsing Logic file
logData = ParsePVTLog_Service(reqNo, groupNo, filePath);
// I get the ArrayList in logData and return it
return logData
}
The Code where I consume the Web Service:
private void btnParse_Click(object sender, EventArgs e)
{
string strFilePath = txtOpenFile.Text;
string serialNo = txtSerialNumber.Text;
string groupNo = txtGroupNumber.Text;
ArrayList data = new ArrayList();
if (txtOpenFile.Text != "")
{
DDRParsingService.DDRParserService client = new DDRParsingService.DDRParserService();
// Call the Web Service
data = client.PVTLog(serialNo, groupNo, strFilePath);
// I get the error : Cannot implicitly convert type 'object[]' to 'System.Collections.ArrayList'
}
}
It would be great if you can help me handle this issue and access the data in the ArrayList returned by the Web Service.
Thanks in Advance!
on your service reference click configure:
Select your expected collection type:
click OK, then update the service reference:
When calling the Web Service, all I had to do was declare the returned object from the Web Service as a new ArrayList.
In the above code that I have posted, I called the Web Service like this :
private void btnParse_Click(object sender, EventArgs e)
{
string strFilePath = txtOpenFile.Text;
string serialNo = txtSerialNumber.Text;
string groupNo = txtGroupNumber.Text;
ArrayList data = new ArrayList();
if (txtOpenFile.Text != "")
{
DDRParsingService.DDRParserService client = new DDRParsingService.DDRParserService();
// Call the Web Service
data = client.PVTLog(serialNo, groupNo, strFilePath);
// I get the error : Cannot implicitly convert type 'object[]' to 'System.Collections.ArrayList'
}
}
But all I had to do was this :
data = new ArrayList(client.PVTLog(serialNo, groupNo, strFilePath));
i.e. Declare the returned object[] from the Web Service as a new ArrayList!
I am trying to make sense of the dotMailer API for C#.
I have a class library where I intend to store the functionality that will consume the dotMailer API which references version 1.5 of the API. I also have a Service Reference set up from this WSDL
I was looking through the C# examples, but already I'm stumped! The following was pulled directly from here
Example of use in C#
/// <summary>
/// Adds a contact to an address book
/// </summary>
public void AddContactToAddressBook()
{
const string username = "apiuser-XXXXXXXXXXXX#apiconnector.com";
const string password = "password";
const int addressBookId = 1; // ID of the target address book
Console.WriteLine("AddContactToAddressBook");
Console.WriteLine("-----------------------");
// Get an instance to the web reference
com.apiconnector.API api = new com.apiconnector.API();
try
{
// we need a new contact
com.apiconnector.APIContact contact = new com.apiconnector.APIContact();
// populate the contact
contact.AudienceType = com.apiconnector.ContactAudienceTypes.B2B;
// populate the data fields
contact.DataFields = new com.apiconnector.ContactDataFields();
contact.DataFields.Keys = new string[3];
contact.DataFields.Values = new object[3];
contact.DataFields.Keys[0] = "FIRSTNAME";
contact.DataFields.Values[0] = "John";
contact.DataFields.Keys[1] = "LASTNAME";
contact.DataFields.Values[1] = "Smith";
contact.DataFields.Keys[2] = "POSTCODE";
contact.DataFields.Values[2] = "IP4 1XU";
// email address
contact.Email = "joe.smith#example.com";
contact.EmailType = com.apiconnector.ContactEmailTypes.PlainText;
contact.Notes = "This is a test only email";
contact.OptInType = com.apiconnector.ContactOptInTypes.Single;
// This method will create the contact required if it doesn't already exist within the dotMailer system,
// so we don't have to call CreateContact as a prerequisite.
//
// This method will also overwrite an existing contact, with the information provided here.
//
// This method will fail if you try to add a contact to the "Test" or "All Contacts" address books.
//
com.apiconnector.APIContact newContact = api.AddContactToAddressBook(username, password, contact, addressBookId);
// Did we get something back from the API ?
if (newContact != null)
{
Console.WriteLine("Contact added to address book {0} -> {1}", newContact.ID, addressBookId);
}
}
catch (SoapException ex) // catch any soap issues/errors from the web service
{
Console.WriteLine("Error -> {0}", ex.Message);
}
Console.WriteLine();
}
My problem is that the following line does not resolve.
com.apiconnector.API api = new com.apiconnector.API();
I have looked in namespace dotMailer.Sdk.com.apiconnector for API but it does not exist, so where is it?
Am I missing something?
Add the wsdl as a service reference. In the example below I've called it "ServiceReference1" (because that's the default and I was lazy). You then use the reference to the APISoapClient (I've called it Client) instead of "api" that you're having trouble declaring.
All compiles fine, I'm not going to execute it because I've no idea what shenanigans my random code snippet is going to cause for the server! Should point you in the right direction?
using WindowsFormsApplication1.ServiceReference1;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string username = "apiuser-XXXXXXXXXXXX#apiconnector.com";
const string password = "password";
const int addressBookId = 1; // ID of the target address book
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddContactToAddressBook();
}
private void AddContactToAddressBook()
{
using (ServiceReference1.APISoapClient Client = new ServiceReference1.APISoapClient())
{
APIContact Contact = new APIContact();
Contact.AudienceType = ContactAudienceTypes.B2B;
APIContact NewContact = Client.AddContactToAddressBook(username, password, Contact, addressBookId); // etc. etc.
}
}
}
}
I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
I want to create a Facebook IFRAME applicaton with asp.net. I just want to know should I need to host the application some where over internet? If yes, how could I test my application on localhost?
Update:
I just want a simple app for displaying a user name with "Hello." Can anyone show me the code for that with the complete web.config configuration?
I'm trying this code
using facebook.web;
namespace TestFbApplication
{
public partial class _Default:facebook.web.CanvasFBMLBasePage
{
facebook.Components.FacebookService _fbService = new facebook.Components.FacebookService();
private const string FACEBOOK_APPKEY = "66a8278bb94d969247a80815bab686e5"; // From the Facebook application page
private const string FACEBOOK_SECRET = "de76280e4ddaef72ac2166afe7ffb9d5"; // From the Facebook application page
protected void Page_PreInit(object sender, EventArgs e)
{
base.RequireLogin = false;
_fbService.IsDesktopApplication = false;
_fbService.ApplicationKey = FACEBOOK_APPKEY;
_fbService.Secret = FACEBOOK_SECRET;
_fbService.IsDesktopApplication = false;
_fbService.ConnectToFacebook();
abc.InnerText = _fbService.users.getInfo().ToString();
}
and it is throwing and Exception in the last line that that the object reference is not set.
You will need to host your production application somewhere, but you can test locally. If you set your Canvas URL to http://localhost:81 in Facebook, this should work. It did for me a couple of months ago, but they may have changed it since then.
this might be an interesting for you:
http://www.stevetrefethen.com/blog/DevelopingFacebookapplicationsinCwithASPNET.aspx