How to get UserContactLists from constant contact using c# - c#

I am going to use Constant contact for email marketing. I am not getting how to get userContactList which are all there in my constant contact account.If anyone have any idea please help me.
Thanks in advance

Here is some code I wrote a while ago that returns the user list ID based on the name of an existing user list. its all C# and uses RESTSharp library which you can install inside your VS project using Nuget.
public static string GetContactListIDByListName(string listname)
{
feedData = string.Empty;
id = string.Empty;
name = string.Empty;
status = string.Empty;
modified_date = string.Empty;
created_date = string.Empty;
contact_count = 0;
Stream stream = null;
StreamReader streamReader = null;
var client = new RestClient(ccURL);
var request = new RestRequest("/v2/lists?modified_since=[DATE]&api_key=[API-KEY]", Method.GET);
request.AddHeader("Authorization", "Bearer [ACCESS-TOKEN]");
request.AddHeader("X-Originating-Ip", "[SERVER-IP]");
request.AddHeader("Accept", "application/json");
IRestResponse response = client.Execute(request);
feedData = response.Content;
// DESERIALIZE Mashery JSON Response
byte[] byteArray = Encoding.ASCII.GetBytes(feedData);
MemoryStream myStream = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Mashery.GetAllListsDef[]));
object result = serializer.ReadObject(myStream);
Mashery.GetAllListsDef[] jsonObj = result as Mashery.GetAllListsDef[];
foreach (Mashery.GetAllListsDef myResult in jsonObj)
{
if (myResult.name.ToUpper().Equals(listname.ToUpper()))
{
return myResult.id.ToString();
}
}
return "";
}
// JSON Definition For [GET All Lists] End Point Method
[Serializable, XmlRoot("GetAllListsDef"), DataContract(Name = "GetAllListsDef")]
public class GetAllListsDef
{
[XmlElement("id"), DataMember(Name = "id")]
public string id { get; set; }
[XmlElement("name"), DataMember(Name = "name")]
public string name { get; set; }
[XmlElement("status"), DataMember(Name = "status")]
public string status { get; set; }
[XmlElement("created_date"), DataMember(Name = "created_date")]
public string created_date { get; set; }
[XmlElement("modified_date"), DataMember(Name = "modified_date")]
public string modified_date { get; set; }
[XmlElement("contact_count"), DataMember(Name = "contact_count")]
public string contact_count { get; set; }
}

Related

Receive API Response in c#

im trying to get a this value that i send with JSON string POST, when i receive the response in postman, there's value like status, id, etc that i not POST, while i do understand get the value from JSON string,
i dont quite understand to get a receive API value like status and Name
what i do tried recently
public class Condition
{
public string status { get; set; }
public string name { get; set; }
public string positition { get; set; }
public int no_id { get; set; }
public string time_auth { get; set; }
public string account_type { get; set; }
}
for the method
public partial class ResponseJSON
{
public bool Result(string jsonData, string URL, out string status)
{
bool resultresponse = false;
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
var writer = new StreamWriter(request.GetRequestStream());
string wrote = jsonData;
writer.Write(wrote);
var httpResponse = (HttpWebResponse)request.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var result = streamReader.ReadToEnd();
dynamic R = JsonConvert.DeserializeObject<dynamic>(wrote);
status = R.auth_type;
return resultresponse;
}
}
and for the main
string jsonData = #"{
'auth_type':'7',
'staff_id':'1234567890',
'staff_pin': '1234'}";
dynamic data = JObject.Parse(jsonData);
string URL = "Link URL";
string status = string.Empty;
ResponseJSON responseJSON = new ResponseJSON();
responseJSON.Result(jsonData, URL, out status);
You might want to declare the same class "Condition" on your client side, so you can deserialize the response with Newtonsoft with something like this:
var conditionResponse = JsonConvert.DeserializeObject<Condition>(jsonData);

ASP DotNet Core MVC Reading API JsonSerializer start from another node

I am having trouble deserializing a json api.
This is my api endpoint: https://www.googleapis.com/books/v1/volumes?q=harry+potter
The problem I have is: The JSON value could not be converted to System.Collections.Generic.IEnumerable at LineNumber: 0 | BytePositionInLine:1
failing at: Books = await JsonSerializer.DeserializeAsync<IEnumerable<Book>>(responseStream);
I think the reason is it is starting the parsing from the root, where it is receiving an object.
Is there a way to skip the "kind" and "totalItems" node and start directly from the "items" node?
public async Task<IActionResult> Index()
{
var message = new HttpRequestMessage();
message.Method = HttpMethod.Get;
message.RequestUri = new Uri(URL);
message.Headers.Add("Accept", "application/json");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(message);
if (response.IsSuccessStatusCode)
{
using var responseStream = await response.Content.ReadAsStreamAsync();
Books = await JsonSerializer.DeserializeAsync<IEnumerable<Book>>(responseStream);
}
else
{
GetBooksError = true;
Books = Array.Empty<Book>();
}
return View(Books);
}
Model Class:
public class Book
{
[Display(Name = "ID")]
public string id { get; set; }
[Display(Name = "Title")]
public string title { get; set; }
[Display(Name = "Authors")]
public string[] authors { get; set; }
[Display(Name = "Publisher")]
public string publisher { get; set; }
[Display(Name = "Published Date")]
public string publishedDate { get; set; }
[Display(Name = "Description")]
public string description { get; set; }
[Display(Name = "ISBN 10")]
public string ISBN_10 { get; set; }
[Display(Name = "Image")]
public string smallThumbnail { get; set; }
}
I found a way to do this using JsonDocument. Its not very elegant because you are basically parsing the json twice but it should work.
var responseStream = await response.Content.ReadAsStreamAsync();
// Parse the result of the query to a JsonDocument
var document = JsonDocument.Parse(responseStream);
// Access the "items" collection in the JsonDocument
var booksElement = document.RootElement.GetProperty("items");
// Get the raw Json text of the collection and parse it to IEnumerable<Book>
// The JsonSerializerOptions make sure to ignore case sensitivity
Books = JsonSerializer.Deserialize<IEnumerable<Book>>(booksElement.GetRawText(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
I used the answer to this question to create this solution.

How to write json format in C# string?

How i cab write a json format in C# string:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string strNJson = #"{to:'topics/extrafx',notification:{title:{0},text:{1},sound: 'default'}}";
strNJson = string.Format(strNJson, not_title, not_body);
streamWriter.Write(strNJson);
streamWriter.Flush();
}
Please advice?
Json is the text serialisation of an object. So you simply have to create an object with those property and serialise it. To assit in creating the class that represent your object you can simply paste a Valid Json to Json 2 C#.
public class Notification
{
public string title { get; set; }
public string text { get; set; }
public string sound { get; set; }
}
public class RootObject
{
public string to { get; set; }
public Notification notification { get; set; }
}
And use it like :
var item = new RootObject {
to = "topics/extrafx",
notification = new Notification {
title = variableFoo,
text = variableBar,
sound = "default"
}
};
var result = JsonConvert.SerializeObject(item);
Try this version:
string not_title, not_body;
not_title = "title";
not_body = "body";
string strNJson = #"{{'to':'topics/extrafx','notification':{{'title':'{0}','text':'{1}','sound': 'default'}}}}";
strNJson = string.Format(strNJson, not_title, not_body);
private const string DATA = #"{
""uuid"": ""27c0f81c-23bc-4878-a6a5-49da58cd30dr"",
""status"": ""Work"",
""job_address"": ""Somewhere"",
""job_description"": ""Just a Test API CALL, John Mckinley's Job""}";
"" Calling the Data to this one
content = new StringContent(DATA, Encoding.UTF8, "application/json");
You can try this.

Streaming Api consumption

I have an api http://oversea-download.hikvision.com/uploadfile/Leaflet/ISAPI/HIKVISION%20ISAPI_2.0-IPMD%20Service.pdf I want to receive which uses a HTTP get and wants connection keep-alive.
Once connected it sends XML responses which I want to deserialise. I've created a class to represent the data structure, but I'm not sure how to continually update a list or similar as and when the data is sent back, for example the response (from wireshark) looks like:
I'm not concerned with the parsing of data and updating the list, more how I can keep listening on a socket and see that its XML data and needs to be serialised.. without processing the stream into a buffer and looking for delimiters?
So far the code I had been unsuccessfully playing with looks like:
public static async Task NewTask()
{
var client = new RestClient("http://192.168.0.152:80/");
client.Authenticator = new HttpBasicAuthenticator("admin", "ThePassword");
client.Encoding = Encoding.UTF8;
var request = new RestRequest("ISAPI/Event/notification/alertStream", Method.GET);
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Type", "application/xml");
IRestResponse<EventNotificationAlert> response2 = client.Execute<EventNotificationAlert>(request);
var name = response2.Data.eventType;
Console.WriteLine(name);
//var asyncHandle = client.ExecuteAsync<EventNotificationAlert>(request, response => {
// Console.WriteLine(response.Data.eventDescription);
//});
}
and the class:
public class EventNotificationAlert
{
public string version { get; set; }
public string ipAddress { get; set; }
public string portNo { get; set; }
public string protocol { get; set; }
public string macAddress { get; set; }
public string channelID { get; set; }
public string dateTime { get; set; }
public string activePostCount { get; set; }
public string eventType { get; set; }
public string eventState { get; set; }
public string eventDescription { get; set; }
}
disregard my comment, can't format it.. this kind of works.. but given I get boundary and content-type text I've got crude processing in...
var messageBuffer = string.Empty;
var request = WebRequest.Create("http://192.168.0.152:80/ISAPI/Event/notification/alertStream");
request.Credentials = new NetworkCredential("admin", "ThePassword");
request.BeginGetResponse(ar =>
{
var req = (WebRequest)ar.AsyncState;
// TODO: Add exception handling: EndGetResponse could throw
using (var response = req.EndGetResponse(ar))
using (var reader = new StreamReader(response.GetResponseStream()))
{
// This loop goes as long as the api is streaming
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line == xmlEndStr)
{
messageBuffer += line;
GotMessage(messageBuffer);
messageBuffer = string.Empty;
}
else if (line.StartsWith("<"))
{
messageBuffer += line;
}
}
}
}, request);
static void GotMessage(string msg)
{
var mySerializer = new XmlSerializer(typeof(EventNotificationAlert));
var stringReader = new StringReader(msg);
var eventAlert = (EventNotificationAlert)mySerializer.Deserialize(stringReader);
Console.WriteLine($"DateTime: {eventAlert.dateTime} Channel: {eventAlert.channelID} Type: {eventAlert.eventType} Description: {eventAlert.eventDescription}");
}
Happy to hear of better ways (as you can tell I'm not great with c#!)

c# JSON Post Issue

I can't work this one out. If I use NewtonSoft to serialize the object to JSON before a HTTP Post, I receive a 400 from the REST Service. If I just post the JSON as a string, in the below code as "jsonx" it works. However, if I compare the strings "json" and "jsonx" they're the same.
public async Task<String> TransferAsync(String fromAddress, Int64 amount, String toAddress, String assetId)
{
Models.CoinPrism.TransferRequest request = new CoinPrism.TransferRequest()
{
fees = 1000,
from = fromAddress,
};
request.to[0] = new CoinPrism.Transfer()
{
address = toAddress,
amount = amount,
asset_id = assetId
};
String json = Newtonsoft.Json.JsonConvert.SerializeObject(request);
String jsonX = "{ \"fees\": 1000, \"from\": \"1zLkEoZF7Zdoso57h9si5fKxrKopnGSDn\", \"to\": [ { \"address\": \"akSjSW57xhGp86K6JFXXroACfRCw7SPv637\", \"amount\": \"10\", \"asset_id\": \"AHthB6AQHaSS9VffkfMqTKTxVV43Dgst36\" } ]}";
Uri baseAddress = new Uri("https://api.coinprism.com/");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
using (var content = new StringContent(jsonX, System.Text.Encoding.Default, "application/json"))
{
using (var response = await httpClient.PostAsync("v1/sendasset?format=json", content))
{
string responseData = await response.Content.ReadAsStringAsync();
return responseData;
}
}
}
}
Models
public class TransferRequest
{
public Int64 fees { get; set; }
public String from { get; set; }
public Transfer[] to { get; set; }
public TransferRequest(Int32 n = 1)
{
this.to = new Transfer[n];
}
public TransferRequest(Transfer transfer)
{
this.to = new Transfer[1];
this.to[0] = transfer;
}
}
public class Transfer
{
public String address { get; set; }
public Int64 amount { get; set; }
public String asset_id { get; set; }
}
The reason of the error is that they are identical strings but with different encoding.
You are sending the wrong encoding for the string.
1- After serializing, convert the string to ANSI encoding (for example)
2- using (var content = new StringContent(jsonX, System.Text.Encoding.ANSI, "application/json)

Categories

Resources