An error occured while connecting to CRM server within my plug-in - plugins

Please help me figure out how to get ride of this error:
An error occured while connecting to CRM server.
My code
namespace AutoCreateAccountAndContactFromLead
{
public class CreateAccountAndContact : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Extract the tracing service for use in debuuging sandboxed plug-ins
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParamaters collection contains all the data passed in the message request.
if(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameter
Entity lead = (Entity)context.InputParameters["Target"];
// If the entity's schema name is not "lead", then return. If it is, execute try block.
if (lead.LogicalName != "lead")
return;
try
{
// check plug-in is registerd in pre-operational stage.
if (context.Stage == 20)
{
// vars for create contact
var firstName = lead.Attributes["firstname"];
var lastName = lead.Attributes["lastname"];
var jobtitle = lead.Attributes["jobtitle"];
var emailaddress1 = lead.Attributes["emailaddress1"];
var mobilephone = lead.Attributes["mobilephone"];
var businessphone = lead.Attributes["telephone1"];
// vars for create account
var accountname = lead.Attributes["companyname"];
var websiteurl = lead.Attributes["websiteurl"];
var street1 = lead.Attributes["address1_line1"];
var street2 = lead.Attributes["address1_line2"];
var street3 = lead.Attributes["address1_line3"];
var city = lead.Attributes["address1_city"];
var stateprovice = lead.Attributes["address1_stateorprovince"];
var postalcode = lead.Attributes["address1_postalcode"];
var countryregion = lead.Attributes["address1_country"];
// create a contact entity
Entity contact = new Entity("contact");
contact["firstname"] = firstName;
contact["lastname"] = lastName;
contact["jobtitle"] = jobtitle;
contact["emailaddress1"] = emailaddress1;
contact["telephone1"] = businessphone;
contact["emailaddress1"] = emailaddress1;
contact["mobilephone"] = mobilephone;
// create an account entity
Entity account = new Entity("account");
account["name"] = accountname;
account["websiteurl"] = websiteurl;
account["address1_line1"] = street1;
account["address1_line2"] = street2;
account["address1_line3"] = street3;
account["address1_city"] = city;
account["address1_stateorprovince"] = stateprovice;
account["address1_postalcode"] = postalcode;
account["address1_country"] = countryregion;
// Obtain the orginxation service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
// contact and account
service.Create(contact);
service.Create(account);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occured while connecting to CRM server.", ex);
}
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
}
}

Related

OPC-DA AddGroup not working by using "TitaniumAS.Opc.Client" c# library

I'm getting a NULL reference error while adding the group. ie: in line -> opcDaGroup = server.AddGroup("Group");
Please help me out what's the issue and how to overcome the same.
whether this is the DCOM access issue.
Code:
public OpcDaGroup opcDaGroup;
private void StartConnection(string Cls_Id, string Machine_IpAddress)
{
try
{
log.Debug("START - Starting the connection");
Uri url = UrlBuilder.Build(Cls_Id, Machine_IpAddress);
server = new OpcDaServer(url);
server.Connect();
log.Debug("END - Starting the connection");
}
catch (Exception e)
{
log.Error("Could not connect to the OPC server for the IpAddress: {0}", e);
}
}
public OpcDaAdapterThreadImpl(string Cls_Id, string Machine_IpAddress, string name, ICollection<TagConfigurationModel> tags)
{
this.Cls_Id = Cls_Id;
this.Machine_IpAddress = Machine_IpAddress;
this.name = name;
this.AdapterReady = true;
Tags = tags;
var group = tags.GroupBy(c => new { ItemName = c.TagName }).Select(c => c.Key).Distinct();
grouptags = group.Select(c => new TagConfigurationModel { TagName = c.ItemName }).ToList();
opcTagItems = grouptags.Select(c => new OpcDaItemDefinition { ItemId = c.TagName, IsActive = true }).ToList();
// Connection Initializing
StartConnection(Cls_Id, Machine_IpAddress);
if (server.IsConnected)
{
// Add group to the server
opcDaGroup = server.AddGroup("Group");
opcDaGroup.IsActive = true;
// Add Items to group
opcDaGroup.AddItems(opcTagItems);
}
}

moq mongodb InsertOneAsync method

I am using Mongodb database with .net core. I just want to moq insert method that using mongodbContext. Here is what I am trying to do but it's not working:
public void InsertEventAsync_Test()
{
//Arrange
var eventRepository = EventRepository();
var pEvent = new PlanEvent
{
ID = "testEvent",
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
////Act
//mockEventContext.Setup(mr => mr.PlanEvent.InsertOne(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>()))
mockEventContext.Setup(s => s.PlanEvent.InsertOneAsync(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>())).Returns("sdad");
var result = eventRepository.InsertEventAsync(pEvent);
////Assert
result.Should().NotBeNull();
}
Below is the method that I need to Moq:
public EventRepository(IFMPContext eventContext)
{
_eventContext = eventContext;
}
public async Task<string> InsertEventAsync(Model.EventDataModel.PlanEvent eventobj)
{
eventobj._id = ObjectId.GenerateNewId();
eventobj.CreatedDateTime = DateTime.UtcNow.ToString();
try
{
_eventContext.PlanEvent.InsertOne(eventobj);
return eventobj.ID;
}
catch (Exception ex)
{
string x = ex.Message;
}
return "";
}
Assuming
public class EventRepository {
private readonly IFMPContext eventContext;
public EventRepository(IFMPContext eventContext) {
this.eventContext = eventContext;
}
public async Task<string> InsertEventAsync(Model.EventDataModel.PlanEvent eventobj) {
eventobj._id = ObjectId.GenerateNewId();
eventobj.CreatedDateTime = DateTime.UtcNow.ToString();
try {
await eventContext.PlanEvent.InsertOneAsync(eventobj);
return eventobj.ID;
} catch (Exception ex) {
string x = ex.Message;
}
return "";
}
}
You need to configure the test to support the async nature of the method under test
public async Task InsertEventAsync_Test()
{
//Arrange
var expected = "testEvent";
var pEvent = new PlanEvent {
ID = expected,
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
var mockEventContext = new Mock<IFMPContext>();
mockEventContext
.Setup(_ => _.PlanEvent.InsertOneAsync(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>()))
.ReturnsAsync(Task.FromResult((object)null));
var eventRepository = new EventRepository(mockEventContext.Object);
//Act
var actual = await eventRepository.InsertEventAsync(pEvent);
//Assert
actual.Should().NotBeNull()
actual.Should().Be(expected);
}
The test method definition needed to be updated to be asynchronous to allow the method under test to be awaited. The mock dependency also needed to be setup in such a way to allow the async flow to continue as expected when invoked.
#Nkosi Thanks a lot for your help. Finally i found the way. i was missing extra moq param It.IsAny<System.Threading.CancellationToken>() below is the working test
public void InsertEventAsync_Test()
{
//Arrange
var eventRepository = EventRepository();
var pEvent = new PlanEvent
{
ID = "testEvent",
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
////Act
mockEventContext.Setup(s => s.PlanEvent.InsertOne(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>(),It.IsAny<System.Threading.CancellationToken>()));
var result = eventRepository.InsertEventAsync(pEvent);
////Assert
result.Should().NotBeNull();
Assert.AreEqual(pEvent.ID, result);
}

ConfirmEmailAsync() method is not working

I am having issue in confirming new user email. the Confirm email link works for first 20 minutes , but after 50 minutes the link expires. I have set the token expiration time to 24 hours. Please help me in resolving this issue. I am stuck on it for last 2 days:(.My code is as follows:
I am setting the token lifetime in Create() method in ApplicationUserManager as following:
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"))
{
TokenLifespan = _settings.ConfirmationAndResetTokenExpirationTimeSpan
};
}
And then In AccountsController, the Create method for new user is geiven below. The SendEmailAsync method consist of email subject, email body, generated password and the callback uri.
[Authorize(Roles = Roles.Bam.Name.Admin)]
[HttpPost]
[Route(Routes.Accounts.Template.Create, Name = Routes.Accounts.Name.Create)]
public async Task<IHttpActionResult> Create(CreateUserBindingModel createUserBindingModel)
{
IHttpActionResult result;
var memberNameExists = UserManager.Users.Any(x => x.MemberName.ToLower() == createUserBindingModel.MemberName.ToLower());
if (!memberNameExists)
{
var applicationUser = new ApplicationUser
{
UserName = createUserBindingModel.Email,
Email = createUserBindingModel.Email,
FirstName = createUserBindingModel.FirstName,
LastName = createUserBindingModel.LastName,
Company = createUserBindingModel.Company,
Location = createUserBindingModel.Location,
PhoneNumber = createUserBindingModel.PhoneNumber,
MemberName = createUserBindingModel.MemberName,
LastLoginDate = SqlDateTime.MinValue.Value,
CreateDate = DateTime.Now,
CreatedBy = User.Identity.GetUserId(),
UpdateDate = DateTime.Now,
UpdatedBy = User.Identity.GetUserId(),
TwoFactorEnabled = createUserBindingModel.TwoFactorEnabled,
SecurityResetRequired = true,
PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToDouble(ConfigurationManager.AppSettings["PasswordExpirationDays"]))
};
if (!string.IsNullOrEmpty(createUserBindingModel.AvatarBase64))
{
var avatarBytes = Convert.FromBase64String(createUserBindingModel.AvatarBase64);
var resizedAvatarBytes = ImageResizer.ResizeImage(avatarBytes, _avatarWidth, _avatarHeight);
applicationUser.UserAvatar = new ApplicationUserAvatar
{
Avatar = resizedAvatarBytes
};
}
var generatedPassword = PasswordGenerator.GenerateStrongPassword(10, 10);
var identityResult = await UserManager.CreateAsync(applicationUser, generatedPassword);
if (identityResult.Succeeded)
{
await UserManager.AddToRolesAsync(applicationUser.Id, createUserBindingModel.Roles.ToArray());
var token = await UserManager.GenerateEmailConfirmationTokenAsync(applicationUser.Id);
var callbackUri = string.Format("{0}?userId={1}&token={2}", createUserBindingModel.EmailConfirmationCallbackUri, applicationUser.Id, HttpUtility.UrlEncode(token));
await UserManager.SendEmailAsync(applicationUser.Id, Email.Confirmation.Subject, string.Format(Email.Confirmation.Body, string.Format("{0} {1}", applicationUser.FirstName, applicationUser.LastName), callbackUri, generatedPassword, _settings.AccessTokenExpirationTimeSpan.TotalHours));
var userUrl = new Uri(Url.Link(Routes.Accounts.Name.Get, new { id = applicationUser.Id }));
var roles = await UserManager.GetRolesAsync(applicationUser.Id);
var contract = _accountsMapper.ToContract(applicationUser, roles);
result = Created(userUrl, contract);
}
else
{
result = GetErrorResult(identityResult);
}
}
else
{
ModelState.AddModelError(string.Empty, "Member Name already exists!");
result = BadRequest(ModelState);
}
return result;
}
Once the email is generated the UI has following JS angular code which gets executed and the provide the userid and token to service.
Angular JS code:
angular.module('confirmEmailModule').factory('confirmEmailFactory', function ($http) {
var factory = {};
factory.confirmEmail = function(userId, token) {
var encodedToken = encodeURIComponent(token);
var uri = '/identity/api/accounts/confirmemail?userId=' + userId + '&token=' + token;
return $http.post(uri);
}
return factory;
});
and the Service is :
[AllowAnonymous]
[HttpPost]
[Route(Routes.Accounts.Template.ConfirmEmail, Name = Routes.Accounts.Name.ConfirmEmail)]
public async Task<IHttpActionResult> ConfirmEmail([FromUri] string userId, [FromUri] string token)
{
//var decodedToken = HttpUtility.UrlDecode(token);
var identityResult = await UserManager.ConfirmEmailAsync(userId, token);
var result = identityResult.Succeeded ? StatusCode(HttpStatusCode.NoContent) : GetErrorResult(identityResult);
return result;
}
Please advice.
I found the solution to this issue. I am posting it if somebody faced the same issue. In my case the services and web API were on different servers. Different machine keys caused this issue. So I generated the machine key for my Web application and posted the same machine key in web.config file of Identity service. After that it worked. For more information on generating machine key, following link is helpful.
http://gunaatita.com/Blog/How-to-Generate-Machine-Key-using-IIS/1058
This is what worked for me. Hope it helps out;
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return RedirectToAction("employees", "home");
}
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"The User ID {userId} is invalid";
return View("NotFound");
}
var result = await userManager.ConfirmEmailAsync(user, Uri.EscapeDataString(token));
if (result != null)
{
user.EmailConfirmed = true;
await userManager.UpdateAsync(user);
return View();
}
}

SetLockoutEnabled on additional user in seed method not finding UserId

I am trying to seed my database with the primary admin user (which when done on its own works fine) but when I attempt to add the first BP user then it is erroring out on the following line:
result = userManager.SetLockoutEnabled(bpc1.Id, false)
My question is, is it only possible to add the admin roles and not other roles?
with the error "UserId not Found" but if i check this on debug I can see that the bpc1 has an Id attached to it, my code is as follows:
public static void InitializeIdentityForEF(ApplicationDbContext db) {
//User Manager and Role Manager
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
//Admin User
const string name = "Admin#123456";
const string password = "Password!";
//BP Customers
const string bpc1_name = "bpc1";
const string bpc1_password = "Welcome2!";
const string bpc2_name = "bpc2";
const string bpc2_password = "Welcome2!";
const string bpc3_name = "bpc3";
const string bpc3_password = "Welcome2!";
//KP Customers
const string kpc1_name = "kpc1";
const string kpc1_password = "Welcome2!";
const string kpc2_name = "kpc2";
const string kpc2_password = "Welcome2!";
const string kpc3_name = "kpc3";
const string kpc3_password = "Welcome2!";
//Roles
const string roleName = "Admin";
const string roleName2 = "BP";
const string roleName3 = "KP";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null) {
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
//Create Role Billpay if it does not exist
var role2 = roleManager.FindByName(roleName2);
if (role2 == null) {
role2 = new IdentityRole(roleName2);
var roleresult2 = roleManager.Create(role2);
}
//Create Role Keypad if it does not exist
var role3 = roleManager.FindByName(roleName3);
if (role3 == null) {
role3 = new IdentityRole(roleName3);
var roleresult3 = roleManager.Create(role3);
}
//Create Admin user
var user = userManager.FindByName(name);
if (user == null) {
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
//Create Billpay Customer 1
var bpc1 = userManager.FindByName(bpc1_name);
if (bpc1 == null)
{
bpc1 = new ApplicationUser { UserName = bpc1_name, Email = bpc1_name };
var result = userManager.Create(user, bpc1_password);
result = userManager.SetLockoutEnabled(bpc1.Id, false);
}
//Create Billpay Customer 2
var bpc2 = userManager.FindByName(bpc2_name);
if (bpc2 == null)
{
bpc2 = new ApplicationUser { UserName = bpc2_name, Email = bpc2_name };
var result = userManager.Create(bpc2, bpc2_password);
result = userManager.SetLockoutEnabled(bpc2.Id, false);
}
//Create Billpay Customer 3
var bpc3 = userManager.FindByName(bpc3_name);
if (bpc3 == null)
{
bpc3 = new ApplicationUser { UserName = bpc3_name, Email = bpc3_name };
var result = userManager.Create(bpc3, bpc3_password);
result = userManager.SetLockoutEnabled(bpc3.Id, false);
}
//Create Keypad Customer 1
var kpc1 = userManager.FindByName(kpc1_name);
if (kpc1 == null)
{
kpc1 = new ApplicationUser { UserName = kpc1_name, Email = kpc1_name };
var result = userManager.Create(kpc1, kpc1_password);
result = userManager.SetLockoutEnabled(kpc1.Id, false);
}
//Create Keypad Customer 2
var kpc2 = userManager.FindByName(kpc2_name);
if (kpc2 == null)
{
kpc2 = new ApplicationUser { UserName = kpc2_name, Email = kpc2_name };
var result = userManager.Create(kpc2, kpc2_password);
result = userManager.SetLockoutEnabled(kpc2.Id, false);
}
//Create Keypad Customer 3
var kpc3 = userManager.FindByName(kpc3_name);
if (kpc3 == null)
{
kpc3 = new ApplicationUser { UserName = kpc3_name, Email = kpc3_name };
var result = userManager.Create(kpc3, kpc3_password);
result = userManager.SetLockoutEnabled(kpc3.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name)) {
var result = userManager.AddToRole(user.Id, role.Name);
}
// Add Billpay Customers to Role Billpay if not already added
var rolesForBillpayCustomer1 = userManager.GetRoles(bpc1.Id);
var rolesForBillpayCustomer2 = userManager.GetRoles(bpc2.Id);
var rolesForBillpayCustomer3 = userManager.GetRoles(bpc3.Id);
if (!rolesForBillpayCustomer1.Contains(role2.Name))
{
var result = userManager.AddToRole(bpc1.Id, role2.Name);
}
if (!rolesForBillpayCustomer2.Contains(role2.Name))
{
var result = userManager.AddToRole(bpc2.Id, role2.Name);
}
if (!rolesForBillpayCustomer3.Contains(role2.Name))
{
var result = userManager.AddToRole(bpc1.Id, role2.Name);
}
// Add Keypad Customers to Role Keypad if not already added
var rolesForKeypadCustomer1 = userManager.GetRoles(kpc1.Id);
var rolesForKeypadCustomer2 = userManager.GetRoles(kpc2.Id);
var rolesForKeypadCustomer3 = userManager.GetRoles(kpc3.Id);
if (!rolesForKeypadCustomer1.Contains(role2.Name))
{
var result = userManager.AddToRole(kpc1.Id, role3.Name);
}
if (!rolesForKeypadCustomer2.Contains(role2.Name))
{
var result = userManager.AddToRole(kpc2.Id, role3.Name);
}
if (!rolesForKeypadCustomer3.Contains(role2.Name))
{
var result = userManager.AddToRole(kpc3.Id, role3.Name);
}
}
}

IPP Create Customers Never Appears in QBD

I am trying to add a customer and an invoice to QuickBooks, but neither appear. QuickBooks responds with this XML:
http://pastebin.com/PLsFbA6N
My code for adding customers and invoices appears to work and I see no errors:
public Customer BuildCustomerAddRq(JMAOrder _Order)
{
// Construct subordinate required records
//BuildStandardTermsAddRq("Web Order");
// build the main customer record
Customer QBCustomerAdd = new Customer();
var Customer = _Order.BillingAddress;
var Billing = _Order.BillingAddress;
PhysicalAddress phy = new PhysicalAddress();
// if the setting is that all orders go under the same customer ID, then push
// the address lines down one and store the customer name on address line 1.
if (_qboSettings.CustomerID == "SingleName")
{
QBCustomerAdd.DBAName = "Web Store";
QBCustomerAdd.Email = new EmailAddress[] { new EmailAddress() { Address = "info#webstore.com", Tag = new string[] { "Business" } } };
QBCustomerAdd.GivenName = "Web";
QBCustomerAdd.Active = true;
QBCustomerAdd.FamilyName = "Store";
phy.Line1 = "Web Store";
phy.Line2 = "";
phy.Tag = new string[] { "Billing" };
}
else
{
//QBCustomerAdd.DBAName = GetCustId(_Order);
QBCustomerAdd.Email = new EmailAddress[] { new EmailAddress() { Address = Customer.Email, Tag = new string[] { "Business" } } };
QBCustomerAdd.GivenName = Customer.FirstName;
QBCustomerAdd.Active = true;
QBCustomerAdd.FamilyName = Customer.LastName;
if (!String.IsNullOrEmpty(Customer.PhoneNumber))
{
QBCustomerAdd.Phone = new TelephoneNumber[] { new TelephoneNumber() { FreeFormNumber = Customer.PhoneNumber, Tag = new string[] { "Business" } } };
}
phy.Line1 = Billing.Address1;
if (!String.IsNullOrEmpty(Billing.Address2))
{
phy.Line2 = Billing.Address2;
}
phy.City = Billing.City;
if (Billing.RegionName != null)
{
phy.CountrySubDivisionCode = Billing.RegionName;
}
phy.PostalCode = Billing.PostalCode;
phy.Country = Billing.CountryName;
phy.Tag = new string[] { "Billing" };
}
// build add request and exit
QBCustomerAdd.Address = new PhysicalAddress[] { phy };
try
{
Customer cu = dataServices.Add(QBCustomerAdd);
return cu;
}
catch (Exception ex)
{
ErrorMessageDataSource.Insert(new ErrorMessage(MessageSeverity.Error, "QBO", String.Format("Error adding customer : {0}", ex.ToString())));
Customer ct = new Customer();
return ct;
}
When I run Intuit Sync Manager, I see no new customer or invoice. Is it possible to add new customers to QuickBooks?
It appears that the customer entered QuickBooks in error state. I needed to add the QBCustomerAdd.Name field.
CustomerQuery cq = new CustomerQuery();
cq.ErroredObjectsOnly = true;
var bList = cq.ExecuteQuery<Customer>(dataServices.ServiceContext);