XML not being passed to WCF - c#

I'm running some local test on a API, for some reason the data XML data is not making it to the API. rData.labelDetail is submitted to the API as null.
It almost appears as though I'm using the incorrect ContentType but I've tried application/xml and text/xml with no success.
Request:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
public partial class TestAPI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://localhost:56146/Packages.svc/auth");
request.Method = "POST";
string postData = "<?xml version='1.0' encoding='UTF-8'?><RequestData xmlns='http://www.labels.com/label'><details>Test|Second Part</details></RequestData>";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
}
}
Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace XYZService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IPackages" in both code and config file together.
[ServiceContract]
public interface IPackages
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "auth")]
ResponseData Auth(RequestData rData);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace XYZService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Packages" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Packages.svc or Packages.svc.cs at the Solution Explorer and start debugging.
public class Packages : IPackages
{
#region
public ResponseData Auth(RequestData rData)
{
var data = rData.labelDetail.Split('|'); //Keep getting error here
var response = new ResponseData
{
Name = data[0],
PackageID = data[1]
};
return response;
}
#endregion
}
[DataContract(Namespace = "http://www.labels.com/label")]
public class RequestData
{
[DataMember]
public string labelDetail { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string PackageID { get; set; }
}
}

You have an element name mismatch. In your XML request, your root element RequestData has a nested element named details:
string postData = "<?xml version='1.0' encoding='UTF-8'?><RequestData xmlns='http://www.labels.com/label'><details>Test|Second Part</details></RequestData>";
But in your data contract, the corresponding property is named labelDetail:
[DataContract(Namespace = "http://www.labels.com/label")]
public class RequestData
{
[DataMember] // Notice that "Name" is not set
public string labelDetail { get; set; }
}
You need to make the names match, for instance by doing:
[DataMember(Name="details")]
public string labelDetail { get; set; }

Related

Creating a script component with error in SSIS

I am trying to get data from a IT ticketing system through API in SSIS using Script Component, very new to this:
I am just starting with 1 field called Supplier, for that i have so far written below scripts:
Script Component
Created a class called ResultAPI:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
public class ResultAPI
{
public string Supplier { get; set; }
}
}
Another class called GenericResponse:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
public class GenericResponse
{
public ResultAPI[] ListData { get; set; }
}
public class ResultGen
{
public GenericResponse Result { get; set; }
}
}
Main:
public override void CreateNewOutputRows()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://***************");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var cred = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "pwd")));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", cred);
string APIUrl = string.Format("https://**************");
var response = client.GetAsync(APIUrl).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<ResultAPI>(result);
APIResultsBuffer.AddRow();
//APIResultsBuffer.SupplierType = data.SupplierType;
APIResultsBuffer.Supplier = data.Supplier;
//APIResultsBuffer.nextpage = data.nextpage;
//APIResultsBuffer.previouspage = data.previouspage;
//APIResultsBuffer.recordcount = data.recordcount;
//APIResultsBuffer.HREF = data.HREF;
}
}
}
When I execute the package, i get the attached error:
Error
Not sure exactly where this error is.
Hoping to download this file in SQL Server table

HTTPWebRequest - GetResponse() - forcibly closed by the remote host in SSIS C# script

I have created a REST API solution in SSIS script component using C# which fetches the dataset record from Oracle, changes the recordset into JSON format and sends it over to REST Web API Endpoint. Now, when I run the code; it throws the error "Connection forcibly closed by the remote host" on the GetResponse() method. Please see below my code:
#endregion
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
#endregion
public class ScriptMain : UserComponent
{
String jsonStr = null;
int rowNumber = 0;
private static string _uploadUrl = "https://mycloud.integration.cloud.com:5501/STAGING_PUBLISH/1.0/create";
private dynamic _sfResult;
private static string output;
public override void PreExecute()
{
base.PreExecute();
/*
* Add your code here
*/
}
public override void PostExecute()
{
base.PostExecute();
CreateNewOutputRows();
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string jsonStr = #"{""DataIn"": { ""client_id"": ""100001""
, ""first_name"": ""Test""
, ""last_name"": ""User1""
, ""mobile_phone"": ""411111111""
, ""current_status"": ""Yes""},
""ExternalID"" : ""100001"",
""System"" : ""Import"" }";
//json
ProcessJson(jsonStr);
}
public void ProcessJson(String VarStr) {
if (VarStr.ToString() != "")
{
HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp(_uploadUrl);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
//var newStream = httpWebRequest.GetRequestStream();
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.Headers.Add("Authorization", "Basic " + "SVNUU1NJU0NSTUFkbWluc0B1bmlzYS5lZHUuYXU6WEJ1dk5iNVpIbg==");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonStr);
body = body + VarStr;
streamWriter.Flush();
}
//httpWebRequest.KeepAlive = false;
httpWebRequest.ServicePoint.ConnectionLimit = 1;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // <<------ FAILS HERE
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
public override void CreateNewOutputRows()
{
base.CreateNewOutputRows();
}
}
I would really appreciate if someone can help me with this. Thanks.

GET, POST to a rest api

Hi i have a Api that i want to use to collect data from a backend that spits out json i need to get this via C# Application and it's http functionalities. My question is should i use a rest api and setup an async thread that downloads the data and then use the data as i want to from there or should i somehow use something close to a Web Api i have an authentication that is required to exist in a header. This has given me some hedaches because i keep on being split by what to use for what. I mean i need to do a Httprequest with a header. this i later on need to use for posting to another database. but the user of the program should not have to see the data itself. i have two examples that i have done but i don't know with what i should continue? this is my two examples in code...
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace Plugin
{
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class Api
{
private HttpVerb HttpMethod { get; set; }
public Api()
{}
public string startDownload()
{
return (Download("sending token"));
}
private string Download(string token)
{
string strResponseValue = string.Empty;
string finnishedOutput = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Url");
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = HttpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
strResponseValue = reader.ReadToEnd();
}
return strResponseValue;
}
catch (WebException e)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if ((int)httpResponse.StatusCode == 401)
{}
int errorCodeInt;
string errorCode;
errorCodeInt = (int)httpResponse.StatusCode;
errorCode = errorCodeInt.ToString();
return errorCode;
}
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestAPi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Api.InitializeClient("");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestAPi
{
public class Api
{
private static HttpClient ApiClient { get; set;}
private string url { get; set;}
public static void InitializeClient(string token)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("your url");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Bearer Authentication"));
}
public async Task<Data> LoadData()
{
url = ApiClient.BaseAddress.ToString();
using (HttpResponseMessage response = await ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
Data data = await response.Content.ReadAsAsync<data>();
return data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}

Post a message to slack from c# application

I am trying to post a message on the #general channel and this worked when was doing it through a console app but Now I am using MVC and the message doesn't seem to get posted. Also, earlier I was using the webhook URL and now I am using the access token that I have.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SlackClient.Controllers
{
public class SlackClient
{
private readonly Uri _uri;
private readonly Encoding _encoding = new UTF8Encoding();
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
//Post a message using simple strings
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
//Post a message using a Payload object
public void PostMessage(Payload payload)
{
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
}
}
}
//This class serializes into the Json payload required by Slack Incoming WebHooks
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
}
And the other class is SlackClientTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SlackClient.Controllers
{
public class SlackClientTest
{
void TestPostMessage()
{
string urlWithAccessToken = "https://srishti2604.slack.com/services/hooks/incoming-webhook?token=my-tokenHere.";
SlackClient client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "Mr. Torgue",
text: "THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLYMOWWWWWWWW!",
channel: "#general");
}
}
}
Could someone tell me what might me wrong?
My console app looks like this
SlackClient.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SlackProject1
{
public class SlackCient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient();
public SlackCient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}
public async Task<HttpResponseMessage> SendMessageAsync(string message,
string channel = null, string username = null)
{
var payload = new
{
text = message,
channel,
username,
};
var serializedPayload = JsonConvert.SerializeObject(payload);
var response = await _httpClient.PostAsync(_webhookUrl,
new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
}
}
And the Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackProject1
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}
private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://hooks.slack.com/services/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");
var slackClient = new SlackCient(webhookUrl);
while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var response = await slackClient.SendMessageAsync(message);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
}
}
}
}

Unity3D Multiplayer logins

So I have this c# script that looks just like this
using UnityEngine;
using System.Collections;
using System.Net;
using WebRequest;
using System.IO;
using System.Runtime;
using System.Runtime.Remoting;
public class Login_Button : MonoBehaviour {
// Use this for initialization
void Start () {
}
public static string UserName;
public static string Password;
// Update is called once per frame
void Update () {
}
public void UserInput (string UserInput)
{
UserName = UserInput;
}
public void PassInput (string PassInput)
{
Password = PassInput;
}
public void UserName_Checked(string Menu_MultiLobby)
{
string ActiveCheck = "*************/api.php" + UserName + "&p=" + Password;
WebRequest request = WebRequest.Create(ActiveCheck);
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string Active = reader.ReadToEnd();
reader.Close();
response.Close();
if (Active == "accepted")
{
Application.LoadLevel(Menu_MultiLobby);
}
else if (Active == "wrong")
{
}
}
}
In Unity3D I'm getting this error.
Assets/Login_Button.cs(4,7): error CSO246: The type of namespace name 'WebRequest' could not be found.
I was using MonoDevelop and I put the .dll into the references. Do I need to put it somewhere else? Also in case your wondering this is made so it will use the php to connect to a mySQL and check if account exists.
The WebRequest class is in the System.Net namespace, not the WebRequest namespace (that does not exist). Specify
using System.Net;
instead of
using WebRequest;
Better yet, simply remove using WebRequest, since System.Net is already in your namespaces list.

Categories