I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.
Any sample code would be greatly appreciated!
Link to API: http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf
I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:
using System.Net;
using System.Text;
using System;
namespace RightNowSample
{
class Program
{
static void Main(string[] args)
{
string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php";
WebClient webClient = new WebClient();
string requestXml =
#"<connector>
<function name=""ans_get"">
<parameter name=""args"" type=""pair"">
<pair name=""id"" type=""integer"">33</pair>
<pair name=""sub_tbl"" type='pair'>
<pair name=""tbl_id"" type=""integer"">164</pair>
</pair>
</parameter>
</function>
</connector>";
string secString = "";
string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes);
string responseData = Encoding.UTF8.GetString(responseDataBytes);
Console.WriteLine(responseData);
}
}
}
I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.
This will Create a Contact in Right now
class Program
{
private RightNowSyncPortClient _Service;
public Program()
{
_Service = new RightNowSyncPortClient();
_Service.ClientCredentials.UserName.UserName = "Rightnow UID";
_Service.ClientCredentials.UserName.Password = "Right now password";
}
private Contact Contactinfo()
{
Contact newContact = new Contact();
PersonName personName = new PersonName();
personName.First = "conatctname";
personName.Last = "conatctlastname";
newContact.Name = personName;
Email[] emailArray = new Email[1];
emailArray[0] = new Email();
emailArray[0].action = ActionEnum.add;
emailArray[0].actionSpecified = true;
emailArray[0].Address = "mail#mail.com";
NamedID addressType = new NamedID();
ID addressTypeID = new ID();
addressTypeID.id = 1;
addressType.ID = addressTypeID;
addressType.ID.idSpecified = true;
emailArray[0].AddressType = addressType;
emailArray[0].Invalid = false;
emailArray[0].InvalidSpecified = true;
newContact.Emails = emailArray;
return newContact;
}
public long CreateContact()
{
Contact newContact = Contactinfo();
//Set the application ID in the client info header
ClientInfoHeader clientInfoHeader = new ClientInfoHeader();
clientInfoHeader.AppID = ".NET Getting Started";
//Set the create processing options, allow external events and rules to execute
CreateProcessingOptions createProcessingOptions = new CreateProcessingOptions();
createProcessingOptions.SuppressExternalEvents = false;
createProcessingOptions.SuppressRules = false;
RNObject[] createObjects = new RNObject[] { newContact };
//Invoke the create operation on the RightNow server
RNObject[] createResults = _Service.Create(clientInfoHeader, createObjects, createProcessingOptions);
//We only created a single contact, this will be at index 0 of the results
newContact = createResults[0] as Contact;
return newContact.ID.id;
}
static void Main(string[] args)
{
Program RBSP = new Program();
try
{
long newContactID = RBSP.CreateContact();
System.Console.WriteLine("New Contact Created with ID: " + newContactID);
}
catch (FaultException ex)
{
Console.WriteLine(ex.Code);
Console.WriteLine(ex.Message);
}
System.Console.Read();
}
}
Related
I need to get (not download) the content from 10.000~ manifest files within a project in Azure DevOps, but I don't manage to achieve this. I have found several ways to retrieve the content from one file at a time, but in this context, it is neither an efficient nor sustainable solution. I have managed to retrieve all files of a particular file type by checking if the file path ends with the name of the file, then using the TfvcHttpClientBase.GetItemsBatch method. However, this method does not return the item's content.
Program.cs
using Microsoft.TeamFoundation.SourceControl.WebApi;
AzureRest azureRest = new AzureRest();
var tfvcItems = azureRest.GetTfvcItems();
List<TfvcItemDescriptor> itemDescriptorsList = new List<TfvcItemDescriptor>();
foreach(var item in tfvcItems)
{
//Example manifest file .NET
if (item.Path.EndsWith("packages.config"))
{
var itemDescriptor = new TfvcItemDescriptor()
{
Path = item.Path,
RecursionLevel = VersionControlRecursionType.None,
Version = "",
VersionOption = TfvcVersionOption.None,
VersionType = TfvcVersionType.Latest
};
itemDescriptorsList.Add(itemDescriptor);
}
}
TfvcItemDescriptor[] itemDescriptorsArray = itemDescriptorsList.ToArray();
var itemBatch = azureRest.GetTfvcItemsBatch(itemDescriptorsArray);
foreach(var itemList in itemBatch)
{
foreach(var itemListList in itemList)
{
Console.WriteLine("Content: " + itemListList.Content); //empty/null
Console.WriteLine("ContentMetadata: " + itemListList.ContentMetadata); //not empty/null
}
}
AzureRest.cs
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
public class AzureRest
{
const string ORG_URL = "https://org/url/url";
const string PROJECT = "Project";
const string PAT = "PersonalAccessToken";
private string GetTokenConfig()
{
return PAT;
}
private string GetProjectNameConfig()
{
return PROJECT;
}
private VssConnection Authenticate()
{
string token = GetTokenConfig();
string projectName = GetProjectNameConfig();
var credentials = new VssBasicCredential(string.Empty, token);
var connection = new VssConnection(new Uri(ORG_URL), credentials);
return connection;
}
public List<TfvcItem> GetTfvcItems()
{
var connection = Authenticate();
using (TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>())
{
var tfvcItems = tfvcClient.GetItemsAsync(scopePath: "/Path", recursionLevel: VersionControlRecursionType.Full, true).Result;
return tfvcItems;
}
}
public List<List<TfvcItem>> GetTfvcItemsBatch(TfvcItemDescriptor[] itemDescriptors)
{
TfvcItemRequestData requestData = new TfvcItemRequestData()
{
IncludeContentMetadata = true,
IncludeLinks = true,
ItemDescriptors = itemDescriptors
};
var connection = Authenticate();
using (TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>())
{
var tfvcItems = tfvcClient.GetItemsBatchAsync(requestData).Result;
return tfvcItems;
}
}
}
}
For reference:
I have tested the codes you shared and when debugging at "itemDescriptorsList" and have found that there is no content specified in it, so that's why you cannot get the txt content.
You should first check and add the content property into the "itemDescriptorsList".
I wish to automate the transfer of ether to a list of people.
Assume the list is in a csv.
I wrote some code to automate the process.
class Program
{
int nonce = 0;
static void Main(string[] args)
{
var account = SetupAccount();
var recipients = ReadCsv();
var web3Init = GetConnection();
nonce = web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(account.Address).Result;
//var recipients = new List<Records>() { new Records() { Value = 10000000000000000, Address = "0x5CC494843e3f4AC175A5e730c300b011FAbF2cEa" } };
foreach (var recipient in recipients)
{
try
{
var web3 = GetConnection();
var receipt = SendEther(account, recipient, web3).Result;
}
catch (System.Exception)
{
MessageBox.Show("Failed");
}
Thread.Sleep(30000);
}
}
private static async Task<TransactionReceipt> SendEther(Account account, Records recipient, Web3 web3)
{
var transactionPolling = web3.TransactionManager.TransactionReceiptService;
//var currentBalance = await web3.Eth.GetBalance.SendRequestAsync(account.Address);
//assumed client is mining already
//when sending a transaction using an Account, a raw transaction is signed and send using the private key
return await transactionPolling.SendRequestAndWaitForReceiptAsync(() =>
{
var transactionInput = new TransactionInput
{
From = account.Address,
//Gas = new HexBigInteger(25000),
GasPrice = new HexBigInteger(10 ^ 10),
To = recipient.Address,
Value = new HexBigInteger(new BigInteger(recipient.Value)),
Nonce = nonce
};
var txSigned = new Nethereum.Signer.TransactionSigner();
var signedTx = txSigned.SignTransaction(account.PrivateKey, transactionInput.To, transactionInput.Value, transactionInput.Nonce);
var transaction = new Nethereum.RPC.Eth.Transactions.EthSendRawTransaction(web3.Client);
nonce++;
return transaction.SendRequestAsync(signedTx);
});
}
private static Web3 GetConnection()
{
return new Web3("https://mainnet.infura.io");
}
private static Account SetupAccount()
{
var password = "#Password";
var accountFilePath = #"filePath";
return Account.LoadFromKeyStoreFile(accountFilePath, password);
}
private static List<Records> ReadCsv()
{
string filePath = #"C:\Users\Potti\source\repos\ConversionFiles\XrcfRecipients.csv";
if (File.Exists(filePath))
{
using (StreamReader stream = new StreamReader(filePath))
{
CsvReader reader = new CsvReader(stream, new Configuration
{
TrimOptions = TrimOptions.Trim,
HasHeaderRecord = true,
HeaderValidated = null
});
reader.Configuration.RegisterClassMap<RecordMapper>();
return reader.GetRecords<Records>().ToList();
}
}
else
{
return null;
}
}
}
class Records
{
public string Address { get; set; }
public decimal Value { get; set; }
}
sealed class RecordMapper : ClassMap<Records>
{
public RecordMapper()
{
Map(x => x.Address).Name("Address");
Map(x => x.Value).Name("Value");
}
}
How do i modify the process to execute all the transactions at once instead of waiting for each to complete? (Fire and forget)
Also, are there any security considerations of doing this?
What you are currently doing is waiting for each transaction to be mined. What you can do is the following:
var account = new Account("privateKey"); // or load it from your keystore file as you are doing.
var web3 = new Web3(account, "https://mainnet.infura.io");
First create a web3 instance using the same Account object, because we are using an account with a private key, Nethereum will sign your transactions offline before sending them.
Now using the TransactionManager, you can then send a transaction per each recepient
var transactionHashes = new List<string>();
foreach(var recepient in recepients){
var transactionInput = new TransactionInput
{
From = account.Address,
GasPrice = Web3.Convert.ToWei(1.5, UnitConversion.EthUnit.Gwei);,
To = recipient.Address,
Value = new HexBigInteger(new BigInteger(recipient.Value)),
};
var transactionHash = web3.Eth.TransactionManager.SendTransactionAsync(transactionInput);
transanctionHashes.Add(transactionHash);
}
Note that when Nethereum uses the same instance of an Account and TransactionManager (or Web3 in this scenario) it creates a default NonceMemoryService, so you don't need to keep track of your nonces (Transaction number), to sign the transaction.
Also I have done a conversion for the GasPrice from Gwei to Wei, as an example of Unit conversions, I assume that you already have converted to Wei the Ether amounts you are going to send.
Finally, another note, to further simplify this, there is an upcoming EtherTransferService which allows you to input Ether amounts and Gwei price amounts to avoid doing conversions. Also the gas price will be calculated for you, if not passed any parameter.
web3.Eth.GetEtherTransferService().TransferEtherAsync("toAddress", EtherAmount);
I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}
I am using the below code to create a instance in the hp cloud(or any openstack). I am having issues with determining the base url.There could be other errors and i would appreciate anybody seeing them also. So do i find out the base url. I had a look through the hp docs but to no avail ?! Also i am unsure of how to obtain the image id, i presume the flavor is 'small' etc?
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
namespace Openstack2
{
class Program
{
static void Main(string[] args)
{
Uri baseUrl = new Uri("https://horizon.hpcloud.com/auth/login/");
CloudIdentity cloudId = new CloudIdentity()
{
Username = "#####",
Password = "####"
};
CloudIdentityProvider cip = new CloudIdentityProvider(cloudId, baseUrl);
UserAccess ua = cip.Authenticate(cloudId);
CloudServersProvider provider = new CloudServersProvider(cloudId);
Metadata metaData = new Metadata(); // Add some metadata just because we can
metaData.Add("Description", "Example 4 - Getting Started");
string serverName = "Server a14";
string imageId = "###";
string flavorId = "standard.xsmall";
NewServer newServer = provider.CreateServer(serverName, imageId, flavorId,DiskConfiguration.Manual, metaData);
}
}
}
The above code is based on the rackspace sdk to connect to the hp cloud, so that could be an issue. But i also used the following code based on the other .net openstack api.:
var identityUrl = "https://horizon.hpcloud.com/auth/login/";
var imageUrl = "http://server:9292";
var username = "####";
var password = "###";
var cloudId = new CloudIdentity() { Username = username, Password = password };
var cloudIdProvider = new CloudIdentityProvider(new Uri(identityUrl));
cloudIdProvider.Authenticate(cloudId);
var cloudServersProvider = new CloudServersProvider(cloudId, cloudIdProvider);
var newServer = cloudServersProvider.CreateServer("Team 101 Server a14", "Team 101 Server a14", "standard.xsmall");
Still will not connect to my hp openstack. I think i will half to ditch c# and maybe go with powershell or nova.
i am using HP Cloud and this is how i get the baseUrl:
...
using HPCloud.Common;
using HPCloud.Objects;
using HPCloud.Objects.Utility;
using HPCloud.Objects.DataAccess;
using HPCloud.Objects.Domain;
using HPCloud.Objects.Domain.Compute;
using HPCloud.Objects.Domain.Admin;
session = Session.CreateSession("accessKey", "secretKey", "tennantID");
private Session session = null;
public static string GenerateUrl(Session session, string bucket_name, string key)
{
string baseUrl = session.Context.ServiceCatalog.GetService(HPCloud.Objects.Domain.Admin.Services.ObjectStorage).Url;
return baseUrl + "/" + bucket_name + "/" + key;
}
You will need to get accesskey, secretkey, and tennantID from your cloud admin page.
You may need to add HPCloud-API and BouncyCastle from Nuget.
so now you can use the following to drop a file in your cloud bucket:
public static bool PutFile(Session session, string bucket_name, string file_path, out string key)
{
if (!File.Exists(file_path))
{
throw new FileNotFoundException(file_path);
}
bool success = false;
key = System.IO.Path.GetFileName(file_path);
try
{
var soRepo = session.Factory.CreateStorageObjectRepository();
string fullUrl = GenerateUrl(session, bucket_name, key);
soRepo.Copy(file_path, fullUrl, false);
success = true;
}
catch
{
success = false;
key = string.Empty;
}
return success;
}
I'm trying to get the following to work on my machine but I get an error (Cannot create an instance of the abstract class or interface 'System.ServiceModel.Channels.MessageHeader')
using System;
using System.IO;
using System.Reflection;
namespace com.companyname.business
{
/// <summary>
/// Summary description for SessionCreateRQClient.
/// </summary>
class SessionCreateRQClient
{
/// <summary>
/// The main entry point.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
// Set user information, including security credentials and the IPCC.
string username = "user";
string password = "password";
string ipcc = "IPCC";
string domain = "DEFAULT";
string temp = Environment.GetEnvironmentVariable("tmp"); // Get temp directory
string PropsFileName = temp + "/session.properties"; // Define dir and file name
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header and provide the conversation ID.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = "TestSession"; // Set the ConversationId
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
//Add the value for eb:CPAId, which is the IPCC.
//Add the value for the action code of this Web service, SessionCreateRQ.
msgHeader.CPAId = ipcc;
msgHeader.Action = "SessionCreateRQ";
Service service = new Service();
service.Value = "SessionCreate";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security security = new Security();
SecurityUsernameToken securityUserToken = new SecurityUsernameToken();
securityUserToken.Username = username;
securityUserToken.Password = password;
securityUserToken.Organization = ipcc;
securityUserToken.Domain = domain;
security.UsernameToken = securityUserToken;
SessionCreateRQ req = new SessionCreateRQ();
SessionCreateRQPOS pos = new SessionCreateRQPOS();
SessionCreateRQPOSSource source = new SessionCreateRQPOSSource();
source.PseudoCityCode = ipcc;
pos.Source = source;
req.POS = pos;
SessionCreateRQService serviceObj = new SessionCreateRQService();
serviceObj.MessageHeaderValue = msgHeader;
serviceObj.SecurityValue = security;
SessionCreateRS resp = serviceObj.SessionCreateRQ(req); // Send the request
if (resp.Errors != null && resp.Errors.Error != null)
{
Console.WriteLine("Error : " + resp.Errors.Error.ErrorInfo.Message);
}
else
{
msgHeader = serviceObj.MessageHeaderValue;
security = serviceObj.SecurityValue;
Console.WriteLine("**********************************************");
Console.WriteLine("Response of SessionCreateRQ service");
Console.WriteLine("BinarySecurityToken returned : " + security.BinarySecurityToken);
Console.WriteLine("**********************************************");
string ConvIdLine = "convid="+msgHeader.ConversationId; // ConversationId to a string
string TokenLine = "securitytoken="+security.BinarySecurityToken; // BinarySecurityToken to a string
string ipccLine = "ipcc="+ipcc; // IPCC to a string
File.Delete(PropsFileName); // Clean up
TextWriter tw = new StreamWriter(PropsFileName); // Create & open the file
tw.WriteLine(DateTime.Now); // Write the date for reference
tw.WriteLine(TokenLine); // Write the BinarySecurityToken
tw.WriteLine(ConvIdLine); // Write the ConversationId
tw.WriteLine(ipccLine); // Write the IPCC
tw.Close();
//Console.Read();
}
}
catch(Exception e)
{
Console.WriteLine("Exception Message : " + e.Message );
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
Console.Read();
}
}
}
}
I have added the reference System.ServiceModel and the lines:
using System.ServiceModel;
using System.ServiceModel.Channels;
but I continue to get that error when trying to compile --
Cannot create an instance of the abstract class or interface 'System.ServiceModel.Channels.MessageHeader'
I am using Microsoft Visual Studio 2008
Version 9.0.21022.8 RTM
Microsoft .NET Framework
Version 3.5 SP1
Professional Edition
Is there another reference I have to add? Or a dll to move over?
I wonder was the code above written for Framework 2.0 only?
Thanks for your help.
The error message is correct, you cannot create an instance of that class, it is declared abstract.
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messageheader.aspx
See if the static method MessageHeader.CreateHeader will work for you. Note there is several overloads, so pick the best one for you.