SetLockoutEnabled on additional user in seed method not finding UserId - entity-framework

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);
}
}
}

Related

Unable to retrieve API keys for a Function App using ListWebAppFunctionKeysArgs

How can I retrieve API keys for a function app in Azure using ListWebAppFunctionKeysArgs?
I have the following method:
public static Output<Dictionary<string, string>?> Get(string resourceGroupName, FunctionApp functionApp)
{
var output =
Output.Tuple(functionApp.Name, functionApp.Name)
.Apply(async tuple => {
var current = Pulumi.Azure.Core.GetClientConfig.InvokeAsync().Result;
var subscriptionId = current.SubscriptionId;
var appName = tuple.Item1;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken.Value);
var url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{appName}/functions?api-version=2022-03-01";
var result = await httpClient.GetAsync(url);
if (!result.IsSuccessStatusCode) throw new Exception($"Error: Failed to retrive Azure function names from {appName}");
var json = await result.Content.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
var items = root.value.Select(async v => {
var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
Name = appName,
FunctionName = v.properties.name,
ResourceGroupName = resourceGroupName
});
return data.Properties;
});
var data = items.SelectMany(v => v.Result).ToList();
return new Dictionary<string, string>(data);
});
return output;
}
Here's the code that I'm struggling with:
var json = await result.Content.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
var items = root.value.Select(async v => {
var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
Name = appName,
FunctionName = v.properties.name,
ResourceGroupName = resourceGroupName
});
return data.Properties; // Property values are null
});
Here's the result:
In conclusion, how do I acquire API keys for a function app?

How to create enterprise in Android Management API without customer interaction for getting enterprise token?

This is controller code. Here I have provide how I'm creating enterprise. But currently I'm unable to create enterprise without enterprise token. Which I'm getting from customer, when customer registering thyself on play.google.com.
<!-- begin snippet: js hide: false console: true babel: false -->
using Google.Apis.Auth.AspNetCore3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.AndroidManagement.v1;
using Google.Apis.Services;
using Microsoft.AspNetCore.Mvc;
using Google.Apis.AndroidManagement.v1.Data;
using System.Security.Claims;
using Newtonsoft.Json;
using QRCoder;
using System.Drawing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
namespace xProducts_RETL.Web.Controllers
{
public class EmmController : Controller
{
private readonly ILoggerManager _loggerManager;
private readonly IEmmMapper _iEmmMapper;
private readonly IConfiguration _iConfiguration;
private SignInManager<IdentityUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IHostingEnvironment _environment;
private readonly UserManager<IdentityUser> _userManager;
//private static readonly string ProjectId = "xpdemo";
private static readonly string ProjectId = "xdemo";
private static readonly string PolicyId = Zoo_ManagedPolicy";
private static readonly string PolicyId2 = "Zoo_WorkPolicy";
private static readonly string PolicyId3 = "Zoo_ManagedPolicyx";
//private static readonly string COSU_APP_PACKAGE_NAME = "com.google.android.apps.work.clouddpc";
//private static readonly string TestEnterpriseName = "enterprises/xxxxj";
private static readonly string TestEnterpriseName = "enterprises/xxxx8";
private const string Package_Outlook = "com.microsoft.office.outlook";
public EmmController(ILoggerManager loggermanager, IEmmMapper iEmmMapper, IConfiguration iConfiguration, SignInManager<IdentityUser> signInManager, RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager,IHostingEnvironment environment)
{
_loggerManager = loggermanager;
_iEmmMapper = iEmmMapper;
_iConfiguration = iConfiguration;
_signInManager = signInManager;
_userManager = userManager;
_roleManager = roleManager;
_environment = environment;
}
[HttpGet]
public IActionResult CreateEnterprise(EnterpriseDto enterpriseDto, string x)
{
try
{
//bind dropdowns
enterpriseDto.EnterpriseList = _iEmmMapper.GetEnterpriseList();
enterpriseDto.CreatedEnterpriseList = _iEmmMapper.GetGooglePlaySignedupEnterpriseList();
//fetch superadmin info
var superadminData = _userManager.GetUsersInRoleAsync("SuperAdmin").Result;
var superadminId = superadminData[0].Id;
var enterpriseList = _iEmmMapper.GetEnterprises().Where(x => x.OwnerIdentityId == superadminId && x.EnrollmentToken != null && x.EnrollmentTokenWP != null).ToList();
foreach (var enterprise in enterpriseList)
{
enterpriseDto.EnterpriseId = enterprise.EnterpriseId;
}
//
return View(enterpriseDto);
}
catch (Exception ex)
{
_loggerManager.LogError($"Something went wrong inside CreateEnterprise get action: {ex.Message}");
return View(enterpriseDto);
}
}
[HttpPost]
public IActionResult CreateEnterprise(EnterpriseDto enterpriseObj)
{
//populate default dropdown values
EnterpriseDto enterpriseModel = new();
enterpriseModel.EnterpriseList = _iEmmMapper.GetEnterpriseList();
enterpriseModel.CreatedEnterpriseList = _iEmmMapper.GetEnterpriseList();
if (enterpriseObj.Id != 0 || enterpriseObj.Id2 != 0)
{
#region serviceAccountAuthenctiactionFlow
//read service a/c creds
ServiceAccountCredential? credential;
string fileName = "service_account_key.json";
string path = Path.Combine(this._environment.WebRootPath, "ZeroTouchCredJSON", fileName);
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped("https://www.googleapis.com/auth/androidmanagement")
.UnderlyingCredential as ServiceAccountCredential;
}
// Create a zero-touch enrollment API service endpoint.
var service = new AndroidManagementService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ResourceMsg.EMMAppName
});
#endregion
//create signup url
var signupData = service.SignupUrls.Create();
signupData.ProjectId = ProjectId;
signupData.CallbackUrl = _iConfiguration.GetValue<string>("AppSetting:CallBackURL");
var response = signupData.Execute();
if (response != null)
{
//create enterprise
var enterpriseData = service.Enterprises.Create(new Enterprise());
enterpriseData.ProjectId = ProjectId;
enterpriseData.SignupUrlName = response.Name;
enterpriseData.EnterpriseToken = "EAJmqckyhc_cep8KkQ-NDU3SG4uC7WfJk1oumRM9SqDPZ-jzMY6D-K-bbWaYHMDvMNsc-faLjwLdyF50yTZIKv_JK_vxEXxp2rPVKkDxzce8whACXz261yaM";
var enterpriseResponse = enterpriseData.Execute();
}
}
return View(enterpriseModel);
}
//[GoogleScopedAuthorize(AndroidManagementService.ScopeConstants.Androidmanagement)]
//[HttpPost]
//public async Task<IActionResult> CreateEnterprise([FromServices] IGoogleAuthProvider auth, EnterpriseDto enterpriseObj)
//{
// EnterpriseDto enterpriseModel = new();
// try
// {
// //bind dropdowns
// enterpriseModel.EnterpriseList = _iEmmMapper.GetEnterpriseList();
// enterpriseModel.CreatedEnterpriseList = _iEmmMapper.GetEnterpriseList();
// if (enterpriseObj.Id != 0 || enterpriseObj.Id2 != 0)
// {
// #region OAuthFlow
// // Check if the required scopes have been granted.
// if (await auth.RequireScopesAsync(AndroidManagementService.ScopeConstants.Androidmanagement) is IActionResult authResult)
// {
// return authResult;
// }
// //The required scopes have now been granted.
// GoogleCredential cred = await auth.GetCredentialAsync();
// var service = new AndroidManagementService(new BaseClientService.Initializer
// {
// HttpClientInitializer = cred.CreateScoped(AndroidManagementService.Scope.Androidmanagement),
// ApplicationName = ResourceMsg.EMMAppName
// });
// //Fetch client information from GCP
// dynamic name = "";
// dynamic email = "";
// if (User.Identity is ClaimsIdentity claimsIdentity)
// {
// var listk = claimsIdentity.Claims.Select(x => new { x.Type, x.Value }).ToList();
// name = listk[3].Value;
// email = User.FindFirstValue(ClaimTypes.Email);
// }
// //noob | superadmin
// if (email != "xy#gmail.com")
// {
// TempData["VerificationFailed"] = "You have logged in with a customer account. Please login with owner account to continue.";
// return View();
// }
// //var enterpriseRes = _iEmmMapper.GetEnterprises().Where(x=> x.ClientEmail == email);
// //if(enterpriseRes!= null)
// //{
// // TempData["MsgSignupFailed"] = "There is already an Enterprise exist. Please try with a different mail to add a new Enterprise.";
// // return View(enterpriseModel);
// //}
// #endregion
// //check userId existance
// string ownerUserId = "";
// var users = _userManager.Users.ToList();
// foreach (var user in users)
// {
// if (user.Email == "xx#yopmail.com")
// {
// ownerUserId = user.Id;
// break;
// }
// }
// //Enterprise Signup
// if (enterpriseObj.Id != 0 && enterpriseObj.ActionFlag == "Signup")
// {
// //create signup url
// var signupData = service.SignupUrls.Create();
// signupData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
// signupData.ProjectId = ProjectId;
// signupData.CallbackUrl = _iConfiguration.GetValue<string>("AppSetting:CallBackURL");
// //signupData.Service.
// var response = signupData.Execute();
// var ownerGoogleAccountId = User.FindFirstValue(ClaimTypes.Email);
// if (ownerGoogleAccountId != null && ownerUserId != null)
// {
// //assign client info to model
// enterpriseObj.ClientName = name;
// enterpriseObj.ClientEmail = email;
// //assign signup data to vmodel
// enterpriseObj.SignupUrlName = response.Name;
// enterpriseObj.SignupUrlURL = response.Url;
// enterpriseObj.OwnerIdentityId = ownerUserId;
// enterpriseObj.OwnerGoogleAccountId = ownerGoogleAccountId;
// //insert data into database
// var result = _iEmmMapper.CreateUpdateEnterprise(enterpriseObj);
// if (result == 1)
// {
// TempData["MsgSignupUrl"] = "Signup URL for the enterprise generated successfully.";
// return View(enterpriseModel);
// }
// }
// TempData["VerificationFailed"] = "Please login with current account details.";
// return View(enterpriseModel);
// }
// //Create Enterprise
// if (enterpriseObj.Id2 != 0 && enterpriseObj.ActionFlag == "Enterprise")
// {
// var response = _iEmmMapper.GetEnterprises().Where(x => x.Id == enterpriseObj.Id2).FirstOrDefault();
// if (response != null)
// {
// var enterpriseData = service.Enterprises.Create(new Enterprise());
// enterpriseData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
// enterpriseData.ProjectId = ProjectId;
// enterpriseData.SignupUrlName = response.SignupUrlName;
// enterpriseData.EnterpriseToken = response.EnterpriseToken;
// //enterprise generated
// var enterpriseResponse = enterpriseData.Execute();
// enterpriseModel.EnterpriseNameAPIFormat = enterpriseResponse.Name;
// var EnterpriseNameResponse = enterpriseResponse.Name;
// //enterpriseModel.EnterpriseToken = enterpriseData.EnterpriseToken;
// //fetch enterprise from db
// //var resultEnterprise = _iEmmMapper.GetEnterprises();
// //if (resultEnterprise != null)
// //{
// // foreach (var enterprise in resultEnterprise)
// // {
// //if (enterprise.ClientEmail == email)
// //{
// //prepare commonpolicies obj
// CommonPoliciesDto commonPolicies = new();
// //initialize model to assign apps into it
// commonPolicies.ApplicationDtoList = new List<ApplicationsDto>();
// var appModel = new ApplicationsDto();
// //enterprise Id >noob
// string[] enterpriseFullId = enterpriseResponse.Name.Split('/');
// string enterpriseId = enterpriseFullId[1];
// //create two different new policies
// string[] enterpriseArr = response.EnterpriseNameRequested.Split(' ');
// string enterpriseFirstName = enterpriseArr[0];
// string ManagedProfilePolicyName = enterpriseFirstName + "_FMDefaultPolicy";
// string WorkProfilePolicyName = enterpriseFirstName + "_WPDefaultPolicy";
// //var IsPolicyIdExist = _iEmmMapper.GetDevices().Where(x => x.PolicyId == PolicyId3 && x.EnterpriseId == enterpriseId).Any();//noob
// //if (IsPolicyIdExist)
// //{
// // SetDefaultPoliciesForExistingPolicy(TestEnterpriseName, PolicyId3);
// //}
// //else
// //{
// // //if policyId not assigned previously with any token
// // GenereateEnrollmentTokenForNewPolicy(TestEnterpriseName, PolicyId3);
// //}
// var IsManagedPolicyIdExist = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == ManagedProfilePolicyName && x.EnterpriseId == enterpriseId).Any();//noob
// if (!IsManagedPolicyIdExist)
// {
// //if policyId not assigned previously with any token
// GenereateEnrollmentTokenForNewPolicy(EnterpriseNameResponse, ManagedProfilePolicyName, ResourceMsg.FullyManged);
// }
// var IsWorkPolicyIdExist = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == WorkProfilePolicyName && x.EnterpriseId == enterpriseId).Any();//noob
// if (!IsWorkPolicyIdExist)
// {
// //if policyId not assigned previously with any token
// GenereateEnrollmentTokenForNewPolicy(EnterpriseNameResponse, WorkProfilePolicyName, ResourceMsg.Work);
// }
// #region localFunctionToGenerateTokenThruEnterpriseIdAndPolicyId
// void GenereateEnrollmentTokenForNewPolicy(string enterpriseNameAPIFormat, string myPolicyId, string policyProfileType)
// {
// //forming policy name
// string policyName = enterpriseNameAPIFormat + ResourceMsg.POLICIES_FORMAT + myPolicyId;
// //set a default hardware policy to newly registered device
// var appliedPolicyData = service.Enterprises.Policies.Patch(DefaultHardwarePolicies(myPolicyId), policyName).Execute();
// if (appliedPolicyData != null)//noob
// {
// enterpriseModel.PolicyName = policyName;
// //Create Default Policy in Database
// CommonPoliciesDto commonPoliciesModel = new()
// {
// UserIdentityId = ownerUserId,
// EnterpriseId = enterpriseId,
// PolicyId = myPolicyId,
// PolicyName = policyName,
// PolicyType = "Default",
// PolicyProfileType = policyProfileType,
// PolicyNameApiFormat = policyName,
// //
// MaximumTimeToLock = 0,
// StatusBarDisabled = false,
// KeyguardDisabled = false,
// WifiConfigDisabled = false,
// MobileNetworksConfigDisabled = false,
// BluetoothDisabled = true,
// BluetoothContactSharingDisabled = true,
// UsbFileTransferDisabled = true,
// AdjustVolumeDisabled = true,
// ScreenCaptureDisabled = true,
// ShareLocationDisabled = true,
// AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED,
// CameraDisabled = true
// };
// var result = _iEmmMapper.CreateUpdateCommonPolicies(commonPoliciesModel);
// if (result == 0)
// {
// //TempData["MsgCmnPolicies"] = ResourceMsg.PoliciesCreatedSuccessfully;
// }
// var rtrvPolicy6 = _iEmmMapper.GetCommonPolicies().ToList();
// var rtrvPolicy = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == myPolicyId).FirstOrDefault();
// if (rtrvPolicy != null)
// {
// if (rtrvPolicy.PolicyProfileType == ResourceMsg.FullyManged)
// {
// //create enrollmentToken for Fully Managed Device with a policy name & assign created user
// //removed to setup KIOSK mode -> .SetUser(user.AccountIdentifier)
// EnrollmentToken token = new DemoEnrollmentToken().SetPolicyName(myPolicyId).SetDuration(ResourceMsg.ThirtyDaysInSecond).SetAllowPersonalUsage(ResourceMsg.PERSONAL_USAGE_DISALLOWED);
// var tokenResponse = service.Enterprises.EnrollmentTokens.Create(token, enterpriseNameAPIFormat).Execute();
// var eToken = tokenResponse.Value;
// enterpriseModel.EnrollmentToken = eToken;
// }
// else
// {
// if (rtrvPolicy.PolicyProfileType == ResourceMsg.Work)
// {
// //User setup [can't be use in KIOSK mode setup or only work for work profile]
// var user = new User
// {
// AccountIdentifier = Guid.NewGuid().ToString()
// };
// //create enrollmentToken for work profile Device with a policy name & assign created user
// EnrollmentToken token2 = new DemoEnrollmentToken().SetPolicyName(myPolicyId).SetUser(user.AccountIdentifier).SetDuration(ResourceMsg.ThirtyDaysInSecond).SetAllowPersonalUsage(ResourceMsg.PERSONAL_USAGE_ALLOWED);
// var tokenResponse2 = service.Enterprises.EnrollmentTokens.Create(token2, enterpriseNameAPIFormat).Execute();
// var eToken2 = tokenResponse2.Value;
// enterpriseModel.EnrollmentTokenWP = eToken2;
// }
// }
// }
// else
// {
// _loggerManager.LogError($"There is an error occured in GenereateEnrollmentTokenForNewPolicy local function. {ResourceMsg.InvalidPolicy}");
// TempData["Failure"] = ResourceMsg.InvalidPolicy;
// }
// }
// }
// #endregion
// enterpriseModel.Id = enterpriseObj.Id2;
// enterpriseModel.EnterpriseId = enterpriseId;
// if (enterpriseModel.Id != 0 && enterpriseModel.EnterpriseId != null)
// {
// //update data into database
// var entResponse = _iEmmMapper.CreateUpdateEnterprise(enterpriseModel);
// if (entResponse == 1)
// {
// TempData["MsgEnterprise"] = ResourceMsg.EnterpriseCreatedSuccessfully;
// }
// }
// //}
// // }
// //}
// }
// else
// {
// TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
// }
// }
// }
// return View(enterpriseModel);
// }
// catch (Google.GoogleApiException gex)
// {
// string msgErr = "Error in " + this.GetType().ToString();
// _loggerManager.LogError($"{msgErr}{gex.Message}");
// TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
// return View(enterpriseModel);
// }
// catch (Exception ex)
// {
// string msgErr = "Error in " + this.GetType().ToString();
// _loggerManager.LogError($"{msgErr}{ex.Message}");
// TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
// return View(enterpriseModel);
// }
//}
I'm facing this issue from a long time. Please share your feedback and help on this. Any help is appreciable.
There are two ways to create an enterprise:
Customer-managed enterprise: This is the recommended way to create an enterprise. This is the one you are using in your code and it requires an enterprise token.
EMM-managed enterprise: This is not the preferred method to create an enterprise, but it is still possible to create and manage an EMM-managed enterprise using this method. EMM managed enterprises can be created programmatically without customer intervention.
This guide covers how to create EMM-managed enterprises. With this method, EMMs have full control over an enterprise’s lifecycle.
Note: In the future, it would not be possible to create any EMM-managed enterprises using the enterprises.create method.
I suggest reviewing the process of creating a Customer-managed Enterprise by having the Enterprise IT admin complete the sign-up flow, as this is the preferred method.

opcua session was closed by client

I have written the attached OpcUaConnector class for opc-ua connection related activities.
But it is not handling session. For example:
In opc ua configuration disabled the endpoint
In kepserver configuration did runtime > reinitializing
The windows service is throwing:
Source : system.Reactive.Core
InnerException : The session was closed by client
and stopping the windows service, as this error goes unhandled.
Can some one suggest how to handle session in opc-ua?
public class OpcUaConnector
{
private static SimplerAES simplerAES = new SimplerAES();
private DataContainer dataCointainer = null;
private UaTcpSessionChannel channel;
private string opcServerName = string.Empty;
private string opcUserId = string.Empty;
private string opcPassword = string.Empty;
private static ILog LogOpcStore;
private static System.IDisposable token;
private static uint id;
public OpcConnector(ILog Log)
{
IntializeLogOpcStore(Log);
}
private static void IntializeLogOpcStore(ILog Log)
{
LogOpcStore = Log;
}
public async Task OpenOpcConnection()
{
try
{
if ((!string.IsNullOrEmpty(this.opcServerName) & (this.opcServerName != AppMain.MyAppSettings.OpcServer)) ||
(!string.IsNullOrEmpty(this.opcUserId) & (this.opcUserId != AppMain.MyAppSettings.OpcUserId)) ||
(!string.IsNullOrEmpty(this.opcPassword) & (this.opcPassword != AppMain.MyAppSettings.OpcPassword)))
{
await channel.CloseAsync();
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
if (channel==null || (channel != null && (channel.State == CommunicationState.Closed || channel.State == CommunicationState.Faulted)))
{
var appDescription = new ApplicationDescription()
{
ApplicationName = "MyAppName",
ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:MyAppName",
ApplicationType = ApplicationType.Client,
};
//application data won't be deleted when uninstall
var certificateStore = new DirectoryStore(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyAppName", "pki"),
true, true
);
//if the Ethernet cable unplugs or the Wifi drops out,
//you have some timeouts that can keep the session open for a while.
//There is a SessionTimeout (default of 2 min).
this.channel = new UaTcpSessionChannel(
appDescription,
certificateStore,
SignInOpc,
AppMain.MyAppSettings.OpcServer,
null,
options: new UaTcpSessionChannelOptions { SessionTimeout = 120000 });
await channel.OpenAsync();
//LogOpcStore.Info(String.Format("Opc connection sucessful"));
}
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.HResult + " " + ex.Message, "C052");
throw serviceException;
}
}
private static async Task RecursivelyFindNode(UaTcpSessionChannel channel, NodeId nodeid)
{
BrowseRequest browseRequest = new BrowseRequest
{
NodesToBrowse = new BrowseDescription[] { new BrowseDescription { NodeId = nodeid, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } },
};
BrowseResponse browseResponse = await channel.BrowseAsync(browseRequest);
foreach (var rd1 in browseResponse.Results[0].References ?? new ReferenceDescription[0])
{
uint chid = AppMain.MyTagDatabase.GetClientHandleByTag(rd1.DisplayName.ToString());
if (chid > 0)
{
AppMain.MyTagDatabase.UpdateNodeByClientHandle(chid, rd1.NodeId.ToString());
}
await RecursivelyFindNode(channel, ExpandedNodeId.ToNodeId(rd1.NodeId, channel.NamespaceUris));
}
}
public async Task CreateSubscription(DataContainer dc)
{
double curReadingValue;
try
{
dataCointainer = dc;
await RecursivelyFindNode(channel, NodeId.Parse(ObjectIds.RootFolder));
if (AppMain.MyTagDatabase.GetCntTagsNotInOpcServer() == AppMain.MyTagDatabase.GetTagCount())
{
//no need to create subscription
return;
}
//subscription timeout that is the product of PublishingInterval * LifetimeCount:
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest);
id = subscriptionResponse.SubscriptionId;
var itemsToCreate = new MonitoredItemCreateRequest[AppMain.MyTagDatabase.GetTagHavingNodeCount()];
int i = 0;
foreach (var item in AppMain.MyTagDatabase.GetMyTagDatabase())
{
var itemKey = item.Key;
var itemValue = item.Value;
itemsToCreate[i] = new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse(itemValue.NodeId), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = itemKey, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } };
i++;
}
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = itemsToCreate,
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
}
catch (Exception ex)
{
//If the interruption lasts longer than these timeouts then the SessionChannel and Subscriptions will need to be recreated.
channel = null;
FatalServiceException fatalserviceException = new FatalServiceException(ex.Message, "C052");
throw fatalserviceException;
}
}
public async Task DeleteSubscription()
{
try
{
var request = new DeleteSubscriptionsRequest
{
SubscriptionIds = new uint[] { id }
};
await channel.DeleteSubscriptionsAsync(request);
token.Dispose();
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.Message, "C052");
throw serviceException;
}
}
private static async Task<IUserIdentity> SignInOpc(EndpointDescription endpoint)
{
IUserIdentity userIdentity = null;
if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
{
userIdentity = new AnonymousIdentity();
}
else if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
{
var userName = AppMain.MyAppSettings.OpcUserId;
var password = simplerAES.Decrypt(AppMain.MyAppSettings.OpcPassword);
userIdentity = new UserNameIdentity(userName, password);
}
return userIdentity;
}
private void AddDataPointToContainer(int dataType, string source, DateTime SourceTimestampUTC, double value)
{
ConditionValue conditionValue = new ConditionValue();
long timestamp = AppMain.ServerSyncTimeStore.ConvertDateTimeToTimeStampUTC(SourceTimestampUTC);
conditionValue.dataType = dataType;
conditionValue.source = source;
conditionValue.timestamp = timestamp;
conditionValue.SourceTimestampUTC = SourceTimestampUTC;
conditionValue.LocalTime = SourceTimestampUTC.ToLocalTime();
conditionValue.value = value;
//LogOpcStore.Info(String.Format("TagName : {0} SourceTimestampUTC : {1} timestamp : {2} LocalTime : {3} curReadingValue : {4}", source, SourceTimestampUTC, timestamp, SourceTimestampUTC.ToLocalTime(), value));
dataCointainer.AddDataPoint(conditionValue);
}
}
I see you are using the project https://github.com/convertersystems/opc-ua-client.
When a server closes the session and socket (as happens when you reinitialize Kepware) the client receives immediate notification that causes the client channel to fault. A faulted channel cannot be reopened, it should be aborted and a new channel should be created.
I made this standalone test, to show that you may have to catch an exception and recreate the channel and subscription. The point of this test is to subscribe to the CurrentTime node and collect 60 datachanges. The test should last a minute. If you re-init the Kepware server in the middle of the test, the code catches the exception and recreates the channel and subscription.
[TestMethod]
public async Task OpcConnectorTest()
{
var count = 0;
UaTcpSessionChannel channel = null;
while (count < 60)
{
try
{
channel = new UaTcpSessionChannel(
this.localDescription,
this.certificateStore,
new AnonymousIdentity(),
EndpointUrl,
SecurityPolicyUris.None,
loggerFactory: this.loggerFactory);
await channel.OpenAsync();
// create the keep alive subscription.
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false);
var id = subscriptionResponse.SubscriptionId;
var token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
Console.WriteLine($"sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}");
count++;
}
}
});
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = new MonitoredItemCreateRequest[]
{
new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse("i=2258"), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = 12345, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } }
},
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
while (channel.State == CommunicationState.Opened && count < 60)
{
await Task.Delay(1000);
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.GetType()}. {ex.Message}");
}
}
if (channel != null)
{
Console.WriteLine($"Closing session '{channel.SessionId}'.");
await channel.CloseAsync();
}
}
I know this is an old post, but I stumbled upon this problem as well. For those interested:
The problem is related to the subscription(s).
When the following code is run:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
Observable.subscribe() takes multiple arguments. You should include what to do in case of an error. For example:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(
pr => { code to run normally... },
ex => { Log.Info(ex.Message); },
() => { }
);
See http://reactivex.io/documentation/operators/subscribe.html for more information.

Entity Framework not saving to the database

I have a challenge that I am trying to update a record from database But it is not saving to the database, and not showing any errors, it is giving a message that it has updated the record but there are no changes to the database. My code is as below. Any suggestions
dbEntities context = new dbEntities();
var query = context.ConsultantsProfiles.SingleOrDefault(c => c.Username == username);
if (query != null)
{
query.Summary = txtSummary.Text;
query.CareerTitle = txtTitle.Text;
query.ConsultantType = cbType.Text;
query.Username = username;
query.FirstName = txtFirstname.Text;
query.LastName = txtLastName.Text;
query.Email = txtEmail.Text;
query.DateofBirth = Convert.ToDateTime(dptDateofBirth.Value);
query.PhoneNumber = txtPhoneNumber.Text;
query.Website = txtWebsite.Text;
query.Town = txtTown.Text;
query.Country = txtCountry.Text;
if (FileUpload1.HasFile)
{
//image upload
HttpPostedFile postedFile = FileUpload1.PostedFile;
// HttpPostedFile postedFile = uploadControl.UploadedFiles[i];
Stream stream = postedFile.InputStream;
BinaryReader reader = new BinaryReader(stream);
byte[] imgByte = reader.ReadBytes((int)stream.Length);
int imglength = FileUpload1.PostedFile.ContentLength;
query.ProfilePhoto = imgByte;
}
context.ConsultantsProfiles.Attach(query);
context.Entry(query).State = EntityState.Modified;
context.SaveChanges();
}
Response.Write("<script language=javascript>alert('Notification: The Profile Has been Updated');</script>");
}
dbEntities context = new dbEntities();
var consultantProfile = new ConsultantProfile
{
Summary = txtSummary.Text;
CareerTitle = txtTitle.Text;
ConsultantType = cbType.Text;
Username = username;
FirstName = txtFirstname.Text;
LastName = txtLastName.Text;
Email = txtEmail.Text;
DateofBirth = Convert.ToDateTime(dptDateofBirth.Value);
PhoneNumber = txtPhoneNumber.Text;
Website = txtWebsite.Text;
Town = txtTown.Text;
Country = txtCountry.Text;
}
if (FileUpload1.HasFile)
{
//image upload
HttpPostedFile postedFile = FileUpload1.PostedFile;
// HttpPostedFile postedFile = uploadControl.UploadedFiles[i];
Stream stream = postedFile.InputStream;
BinaryReader reader = new BinaryReader(stream);
byte[] imgByte = reader.ReadBytes((int)stream.Length);
int imglength = FileUpload1.PostedFile.ContentLength;
consultantProfile.ProfilePhoto = imgByte;
}
context.Entry(ConsultantsProfiles).State = EntityState.Modified;
context.SaveChanges();

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();
}
}