How do I add a salesforce community user using the API? - c#

I've downloaded the API WSDL and added it to my C# project and have many successful integrations running throught it both bringing down and upserting data. I'm having a lot of trouble with creating community user accounts for our learning management system though.
I can't tell if I need to supply an account, or a contact, or a user type, and no matter what I try I end up with an error that doesn't lead me to a logical fix.
I think i'm closest with the below configuration, which is giving me this error: "You can't create a contact for this user because the org doesn't have the necessary permissions. Contact Salesforce Customer Support for help."
This is my C# code I'm trying to create a User account with:
public UpsertResponse UpsertLearningUser()
{
SFProd.User U = new SFProd.User();
U.Id = UserID;
U.Username = UserName;
U.Alias = TechCode;
U.CommunityNickname = FirstName + "." + LastName;
U.FirstName = FirstName;
U.LastName = LastName;
U.MiddleName = MiddleName;
U.Title = Title;
U.Department = Department;
U.Division = Division;
U.IsActive = Active;
U.IsActiveSpecified = true;
U.UserPermissionsChatterAnswersUser = true;
U.UserPermissionsChatterAnswersUserSpecified = true;
//U.UserPermissionsMobileUser = true;
//U.UserPermissionsMobileUserSpecified = true;
U.Phone = Phone;
U.EmployeeNumber = ADPNumber;
U.NS_Internal_ID__c = NSEmployeeID.ToString();
U.Employee_ID__c = double.Parse(EmployeeID.ToString());
U.Employee_ID__cSpecified = true;
U.Zone__c = Department;
U.Region__c = Division;
U.Certification_Level__c = CertificationLevel;
if (CertificationLevelDate != DateTime.Parse("1/1/1900"))
{
U.Certification_Level_Date__c = CertificationLevelDate;
U.Certification_Level_Date__cSpecified = true;
}
U.Country = Country;
U.State = State;
U.City = City;
U.PostalCode = PostalCode;
U.Street = Street;
U.Email = Email;
U.TimeZoneSidKey = "America/Chicago";
U.EmailEncodingKey = "ISO-8859-1";
U.ProfileId = "00ef10000016tfvAAA";
U.LanguageLocaleKey = "en_US";
U.ContactId = ContactID;
List<SFProd.sObject> Objs = new List<SFProd.sObject>();
Objs.Add(U);
return new UpsertResponse(SFConnection.RunUpsert("Username", Objs)[0], UserID);
}
Has anyone else done this sucessfully? or have any idea what I'm doing wrong?

There is a special function for creating external users. Try a variation of the CreateExternalUser() function: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_sites.htm

Related

NullReferenceException When Using VerifyHashedPassword in asp.net core

Here's what happen i am working on login controller where i need to verify user input password with password hash that is in the database. When i'm trying to verify the correct password it is returning NullReferenceException: Object reference not set to an instance of an object. But when i debug it, the line with this code :
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
is skipped and does not executed but when i return the value of verified.toString() directly after calling above line of code, it is printing a "Success" string. But when it is failed to verify, the code just work properly. Here's the full code :
public dbSearchResponse dbSearch(string username, string password, ADResponse ldapResult)
{
LoginResponse finalResult = new LoginResponse();
TableSystemUser resultData = new TableSystemUser();
PasswordHasher<OldLoginParamModel> hasher = new PasswordHasher<OldLoginParamModel>(
new OptionsWrapper<PasswordHasherOptions>(
new PasswordHasherOptions()
{
CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
}));
OldLoginParamModel inputModel = new OldLoginParamModel();
inputModel.grant_type = "password";
inputModel.password = password;
inputModel.username = username;
string hashedPassword = hasher.HashPassword(inputModel, inputModel.password);
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableSystemUser>(
"SELECT id, email, emailconfirmed, passwordhash, phonenumber, username, fullname, dateofbirth, gender, COALESCE(usercredit.saldo, 0) as saldo, pricing.psc, pricing.psm, pricing.plc, pricing.plm, pricing.csc, pricing.csm, pricing.clc, pricing.clm, pricing.ssc, pricing.ssm, pricing.slc, pricing.slm FROM systemuser LEFT OUTER JOIN usercredit ON systemuser.id = usercredit.systemuserid INNER JOIN userpricing ON UUID(systemuser.id) = userpricing.systemuserid INNER JOIN pricing ON userpricing.pricingid = pricing.pricingid WHERE systemuser.email= '" + username + "' and systemuser.emailconfirmed = true;"
);
resultData = value.First();
}
catch (Exception e)
{
//Failed response
dbSearchResponse dbRespNRErr = new dbSearchResponse();
dbRespNRErr.loginResponse = null;
dbRespNRErr.userid = null;
dbRespNRErr.response = "Email not registered.";
return dbRespNRErr;
}
}
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
/*But when return the verified.toString() value here, it is returning "Success"
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = verified.toString();
return dbRespErr; */
if (verified.toString() == "Success")
{
finalResult.FullName = resultData.fullname;
finalResult.Gender = resultData.gender;
//11/26/1998 12:00:00 AM
finalResult.DateOfBirth = resultData.dateofbirth.ToString("MM/dd/yyyy HH:mm:ss tt");
finalResult.Phone = resultData.phonenumber;
finalResult.Email = resultData.email;
finalResult.UserName = resultData.username;
finalResult.PLC = resultData.plc.ToString();
finalResult.PLM = resultData.plm.ToString();
finalResult.PSC = resultData.psc.ToString();
finalResult.PSM = resultData.psm.ToString();
finalResult.SLC = resultData.slc.ToString();
finalResult.SLM = resultData.slm.ToString();
finalResult.SSC = resultData.ssc.ToString();
finalResult.SSM = resultData.ssm.ToString();
finalResult.CLC = resultData.clc.ToString();
finalResult.CLM = resultData.clm.ToString();
finalResult.CSC = resultData.csc.ToString();
finalResult.CSM = resultData.csm.ToString();
finalResult.PayLater = ldapResult.memberof;
finalResult.Credit = resultData.saldo.ToString();
dbSearchResponse dbResp = new dbSearchResponse();
dbResp.loginResponse = finalResult;
dbResp.userid = resultData.id;
dbResp.response = "success";
return dbResp;
}
//Failed response
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = "The user name or password is incorrect.";
return dbRespErr;
}
Anyone know what happen and how to solve it? Thanks
After i do some detailed run check, i notice that the null part of the code is,
finalResult.PayLater = ldapResult.memberof;
But i don't understand why is the error response given suggest that the null was this line of code
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
so in that case, i thanks to everyone who have responded to my question.

paypal sandbox test account in windows form application in C# for POS credit card swipe

I create sample a windows form application.
I download pay pal sdk in visual studio.
I create paypal sandbox test account
whre to add the credential details?
where we put app id:
Sandbox test AppID:
APP-80W284485P519543T
I have copy some code for winform app while click a button that is.
Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
sdkConfig.Add("mode", "sandbox");
accessToken = new OAuthTokenCredential("AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd", "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX", sdkConfig).GetAccessToken();
HttpContext CurrContext = HttpContext.Current;
APIContext apiContext = new APIContext(accessToken);
Item item = new Item();
item.name = _ItemDescription;
item.currency = "USD";
item.price = _Amount;
item.quantity = "1";
item.sku = _UPC;
List<Item> itms = new List<Item>();
itms.Add(item);
ItemList itemList = new ItemList();
itemList.items = itms;
Address billingAddress = new Address();
billingAddress.city = "Chennai";
billingAddress.country_code = "US";
billingAddress.line1 = "11/12";
billingAddress.line2 = "Andavar nager main street";
billingAddress.postal_code = "600089";
billingAddress.state = "Tamil nadu";
CreditCard crdtCard = new CreditCard();
crdtCard.billing_address = billingAddress;
crdtCard.cvv2 = 2222;
crdtCard.expire_month = 4;
crdtCard.expire_year = 2020;
crdtCard.first_name = "Arul";
crdtCard.last_name = "Murugan";
crdtCard.number = "4032039053301695";
crdtCard.type = "visa";
Details details = new Details();
details.tax = "0";
details.shipping = "0";
details.subtotal = _Amount;
Amount amont = new Amount();
amont.currency = "USD";
amont.total = _Amount;
amont.details = details;
Transaction tran = new Transaction();
tran.amount = amont;
tran.description = _ItemDescription;
tran.item_list = itemList;
List<Transaction> transactions = new List<Transaction>();
transactions.Add(tran);
FundingInstrument fundInstrument = new FundingInstrument();
fundInstrument.credit_card = crdtCard;
List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
fundingInstrumentList.Add(fundInstrument);
PayerInfo pi = new PayerInfo();
pi.email = "sysumurugan-facilitator#gmail.com";
pi.first_name = "Arul";
pi.last_name = "Murugan";
Payer payr = new Payer();
payr.funding_instruments = fundingInstrumentList;
payr.payment_method = "credit_card";
payr.payer_info = pi;
pi.shipping_address = new ShippingAddress
{
city = "San Mateo",
country_code = "US",
line1 = "SO TEST",
line2 = "",
postal_code = "94002",
state = "CA",
};
Payment paymnt = new Payment();
paymnt.intent = "sale";
paymnt.payer = payr;
paymnt.transactions = transactions;
try
{
Payment createdPayment = paymnt.Create(apiContext);
CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));
}
catch (PayPal.Exception.PayPalException ex)
{
if (ex.InnerException is PayPal.Exception.ConnectionException)
{
CurrContext.Response.Write(((PayPal.Exception.ConnectionException)ex.InnerException).Response);
}
else
{
CurrContext.Response.Write(ex.Message);
}
}
catch (Exception es)
{
MessageBox.Show( es.ToString());
}
CurrContext.Items.Add("RequestJson", JObject.Parse(paymnt.ConvertToJson()).ToString(Formatting.Indented));
my reference link is
http://pastebin.com/H7VuPQs4
Parsing a PayPal REST Credit Card Transaction Response (JSON),
C# PayPal REST API Checkout with Credit Card
please explian to me any other way for credit card transaction for POS(Point Of Sale) through win form application.
The PayPal .NET SDK is meant for server applications (e.g. ASP.NET) where application credentials are stored in a secure manner. Using the SDK directly from a WinForms application running on a POS system presents a security risk because your merchant account credentials are not stored in a secure manner. Ideally, the POS system should be communicating back to a secure server somewhere that performs the processing.
With that said, this use case is what PayPal Here is designed for.

ASP.NET PayPal Parallel Payments

I am needing some assistance with paypal Parallel payments C# I have tried the Classic API and the REST API that paypal has. I am running into cycles and don't know what else to do, I have tried to get chained payments working and I have google'd and there is a huge lack of support so Im now trying Parallel. Let you know i get an 500 internal Server error..
ReceiverList receiverList = new ReceiverList();
receiverList.receiver = new List<Receiver>();
Receiver secondaryReceiver = new Receiver((decimal?)2.00);
secondaryReceiver.email = "xxxxxxxxx#gmail.com";
secondaryReceiver.primary = false;
secondaryReceiver.paymentType = "GOODS";
receiverList.receiver.Add(secondaryReceiver);
Receiver primaryReceiver = new Receiver((decimal?)10.00);
primaryReceiver.email = "xxxxxxxxxxxxxxxxxx-facilitator#gmail.com ";
primaryReceiver.primary = true;
primaryReceiver.paymentType = "GOODS";
primaryReceiver.invoiceId = "123456789";
receiverList.receiver.Add(primaryReceiver);
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
string actionType = "Pay";
string returnUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?success=true";
string cancelUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true";
string currencyCode = "USD";
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";
payRequest.feesPayer = "PRIMARYRECEIVER";
payRequest.trackingId = "123456789";
Dictionary<string, string> paypalConfig = new Dictionary<string, string>();
paypalConfig.Add("account1.apiUsername", "xxxxxxxxxxxxxxx-facilitator_api1.gmail.com");
paypalConfig.Add("account1.apiPassword", "xxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.apiSignature", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.applicationId", "APP-80W284485P519543T");
paypalConfig.Add("IPNEndpoint", "https://www.paypal.com/cgi-bin/webscr");
paypalConfig.Add("url", "https://www.paypal.com/webscr&cmd=_express-checkout&token=");
paypalConfig.Add("endpoint", "https://api-3t.paypal.com/2.0/");
paypalConfig.Add("mode", "sandbox");
PayPal.AdaptivePayments.AdaptivePaymentsService service = new PayPal.AdaptivePayments.AdaptivePaymentsService(paypalConfig);
PayResponse response = service.Pay(payRequest);
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" + response.payKey;
}
Now as for the web.config I dont know exactly how to do it or really what to do. i Have found a few things but need of help.
Thanks

Dynamics 2011: Setting Owner of Activity record

I am trying create Activity record in Dynamics 2011 with owner name set as "test_user". Instead below code is taking credential which is used to access Dynamics API. Is there any way to impersonate "test_user" user without passing his password? Thank you.
string TargetCrmService = ConfigurationManager.AppSettings["TargetCrmService"];
string UserName = ConfigurationManager.AppSettings["UserName"];
string Domain = ConfigurationManager.AppSettings["Domain"];
string Password = ConfigurationManager.AppSettings["Password"];
Uri organizationUri = new Uri("http://CRMDEV/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = Domain + "\\" + UserName;
credentials.UserName.Password = Password;
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
var _userId = (from u in orgProxy.CreateQuery<SystemUser>()
where u.FullName == "Kevin Cook"
select u.SystemUserId.Value).FirstOrDefault();
IOrganizationService _service = (IOrganizationService)orgProxy;
_service.CallerId = _userId;
try
{
//Entity activity = new Entity("activitypointer");
Entity activity = new Entity("appointment");
activity["subject"] = "Test Meeting 1";
activity["description"] = "Test Description";
activity["scheduledstart"] = DateTime.Now;
activity["scheduledend"] = DateTime.Now.AddMinutes(30);
activity["createdbyname"] = "test_user";
activity["modifiedbyname"] = "test_user";
activity["createdbyname"] = "test_user";
activity["owneridname"] = "test_user";
Guid id = _service.Create(activity);
Console.WriteLine("id: " + id);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
Modified Code
Based on example on http://msdn.microsoft.com/en-us/library/gg309629.aspx
var _userId = (from u in orgProxy.CreateQuery<SystemUser>()
where u.FullName == "Kevin Cook"
select u.SystemUserId.Value).FirstOrDefault();
You have two methods of setting the owenr id of an entity in CRM.
Use the AssignRequest to update the record after it is created.
Use impersonation with the OrganizationServiceProxy, CallerId to use the particular user you'd like to be the owner when it's created. You don't need their password to do impersonation, just their CRM SystemUserId

How to get EmailId from outlook in C#

I need to get the emailid's from outlook in my C# application to send mail. I have userId or FirstName and LastName. Please suggest me a suitable method.
Thanks
public string GetEmaiId(string userId)
{
string email = string.Empty;
DirectorySearcher objsearch = new DirectorySearcher();
string strrootdse = objsearch.SearchRoot.Path;
DirectoryEntry objdirentry = new DirectoryEntry(strrootdse);
objsearch.Filter = "(& (cn=" + userId + ")(objectClass=user))";
objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
objsearch.PropertiesToLoad.Add("cn");
objsearch.PropertyNamesOnly = true;
objsearch.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
objsearch.Sort.PropertyName = "cn";
SearchResultCollection colresults = objsearch.FindAll();
foreach (SearchResult objresult in colresults)
{
email = objresult.GetDirectoryEntry().Properties["mail"].Value.ToString();
}
objsearch.Dispose();
return email;
}

Categories

Resources