ASP.NET & Angular 7:POST a picture into database - asp.net-mvc

I'm trying to upload an image using an API but the same error shows every time:
"Error reading bytes. Unexpected token: StartObject. Path 'picture'"
the picture is declared as a byte[] in the ASP.NET entity
and I use the formdata to post the picture in angular
Angular code:
onFileChanged(event) {
this.selectedFile = event.target.files[0]
}
adduser() {
this.fd = new FormData();
this.fd.append('picture', this.selectedFile)
this.user.firstname = this.firstname;
this.user.lastname = this.lastname;
this.user.password = this.pass;
this.user.userName = this.email;
this.user.type = this.role;
this.user.picture = this.fd;
alert(this.user.picture)
this.auth.adduser(this.user).subscribe(Response => {
console.log(Response);
this.route.navigate(['login']);
}, error => {
console.log(error)
});
}
.Net code:
[HttpPost]
public async Task < Object > PostAdmin([FromBody] UserModel model) {
{
var profile = new Profile() {
UserName = model.UserName,
lastname = model.lastname,
address = model.address,
firstname = model.firstname,
picture = model.picture,
phone = model.phone,
university = model.university,
Type = model.Type
};
using(var stream = new MemoryStream()) {
profile.picture = stream.ToArray();
}
var user = await _userManager.FindByNameAsync(profile.UserName);
if (user != null) {
return Ok(new {
status = false
});
}
try {
var result = await _userManager.CreateAsync(profile, model.Password);
var role = await _userManager.AddToRoleAsync(profile, model.Type);
return Ok(result);
}
catch (Exception e) {
return BadRequest(new {
status = false, message = e.Message
});
}

Related

How to create multiple configuration in Zerotouch? Configuration need enrollment token. Do we need multiple enrollment tokens for creating config?

Get Method of HardwarePolicy
[HttpGet]
[CustomAuthorization]
public IActionResult PolicyManagement(string profileType)
{
try
{
#region ResellerServiceAccountEMMOAuthCred
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(AndroidManagementService.ScopeConstants.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
ViewBag.MyPolicyName = string.Empty;
dynamic? policyId = null;
CommonPoliciesDto dto = new();
CommonPoliciesDto cpDto = new();
bool jFlag = false;
dynamic enterpriseNameFormat = "";
//fetch two profile types (Fully Manged & Work)
dto.ProfileTypeList = _iAdminMapper.GetProfileTypeList();
//fetch LoggedIn user info
var loggedInUserEmail = HttpContext.Session.GetString("LoggedInUserName");
var loggedInUserId = HttpContext.Session.GetString("LoggedInUserId");
//fetch enterprises based on loggedInUser
var enterprisesRes = _iEmmMapper.GetEnterprises().Where(x => x.AdminIdentityId == loggedInUserId).FirstOrDefault();
//get enterprise data based on loggedIn user google account
var enterpriseDatax = _iEmmMapper.GetEnterprises().Where(x => x.CustomerGoogleAccountId == enterprisesRes.CustomerGoogleAccountId).FirstOrDefault();
if (enterpriseDatax != null)
{
//bind myEnterpriseId in view page
ViewBag.MyEnterpriseeId = enterpriseDatax.EnterpriseId;
//DeviceList
//dto.DeviceList = _iAdminMapper.GetDropDevicesList(enterpriseDatax.EnterpriseId);
enterpriseNameFormat = string.Format("enterprises/{0}", enterpriseDatax.EnterpriseId);
//Fetch Current PolicyName
var myPolicyDatax = _iEmmMapper.GetCommonPolicies().Where(x => x.EnterpriseId == enterpriseDatax.EnterpriseId && x.CustomStatus2 == true).FirstOrDefault();
if(myPolicyDatax != null)
{
ViewBag.MyPolicyName = myPolicyDatax.PolicyName;
}
else
{
ViewBag.MyPolicyName = ResourceMsg.DefaultPolicy;
}
//fetch policy info based on enterpriseId and profileType
var policyData = _iEmmMapper.GetCommonPolicies().Where(x => x.EnterpriseId == enterpriseDatax.EnterpriseId && x.PolicyProfileType == profileType && x.PolicyType == ResourceMsg.Default).FirstOrDefault();
if (policyData != null)
{
policyId = policyData.PolicyId;
//managedplaystore
List<string> featuresList = new()
{
ResourceMsg.PLAY_SEARCH
};
//create web token for managed Google Play web UI; need reseller creds to generated token
var ParentFrameUrl = _iConfiguration.GetValue<string>("AppSetting:ParentFrameUrl");
WebToken webTokenInfo = service.Enterprises.WebTokens.Create(new DemoWebToken()
.SetParentFrameUrl(ParentFrameUrl)
.SetEnabledFeatures(featuresList), enterpriseNameFormat)
.Execute();
var webToken = webTokenInfo.Value;
TempData["WebToken"] = webToken;
//hardwaresettings
var result = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyId == policyId && x.PolicyType == ResourceMsg.Default).FirstOrDefault();
//applicationsettings | based on profileType
var resAppmodel = _iEmmMapper.GetApplicationPolicies().OrderByDescending(x => x.Id).FirstOrDefault(x => x.PolicyId == policyId);
//devicesettings
var resDevicemodel = _iEmmMapper.GetDevicePolicies().Where(x => x.EnterpriseId == enterpriseDatax.EnterpriseId && x.IsActive).FirstOrDefault();
if (profileType != null)
{
//If Managed Profile then perform on all settings
if (profileType == ResourceMsg.FullyManged)
{
if (result != null)
{
}
if (resAppmodel != null)
{
}
if (resDevicemodel != null)
{
}
//prepare commonpolicies vmodel to send to view
dto = new()
{
EnterpriseName = enterpriseDatax.EnterpriseNameRequested,
//populate policyNameList
//EnterpriseList = _iEmmMapper.GetActiveEnterprisesDropList(),
//populate enterprise list
EnterpriseList = _iEmmMapper.GetActiveEnterprisesDropList(),
//common policies
ProfileTypeList = _iAdminMapper.GetProfileTypeList(),
ProfileType = profileType,
//bindMyEnterpriseId in view
MyEnterpriseId = enterpriseDatax.EnterpriseId,
//hardware settings
DupWifiConfigDisabled = cpDto.DupWifiConfigDisabled,
DupMobileNetworksConfigDisabled = cpDto.DupMobileNetworksConfigDisabled,
DupBluetoothDisabled = cpDto.DupBluetoothDisabled,
DupUsbFileTransferDisabled = cpDto.DupUsbFileTransferDisabled,
MaximumTimeToLock = cpDto.MaximumTimeToLock,
AdjustVolumeDisabled = result != null ? result.AdjustVolumeDisabled : false,
ScreenCaptureDisabled = result != null ? result.ScreenCaptureDisabled : false,
StatusBarDisabled = result != null ? result.StatusBarDisabled : false,
BluetoothContactSharingDisabled = result != null ? result.BluetoothContactSharingDisabled : false,
ShareLocationDisabled = result != null ? result.ShareLocationDisabled : false,
WifiConfigDisabled = result != null ? result.WifiConfigDisabled : false,
MobileNetworksConfigDisabled = result != null ? result.MobileNetworksConfigDisabled : false,
AutoDateAndTimeZone = result != null ? result.AutoDateAndTimeZone : ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED,
KeyguardDisabled = result != null ? result.KeyguardDisabled : false,
CameraDisabled = result != null ? result.CameraDisabled : false,
//app settings
ApplicationName = cpDto.ApplicationName ?? string.Empty,
AppPackageName = cpDto.AppPackageName ?? string.Empty,
DupInstallType = cpDto.DupInstallType,
DupDefaultPermissionPolicy = cpDto.DupDefaultPermissionPolicy,
PackageList = _iEmmMapper.GetApplicationsList(),
//device mode settings
KioskMode = cpDto.KioskMode,
AppPolicyName = "",
PackageName = resDevicemodel != null? resDevicemodel.PackageName: "",
PackageId = cpDto.PackageId,
DupLockPowerButton = cpDto.DupLockPowerButton,
StatusBar = cpDto.StatusBar,
DupDisableDeviceSettings = cpDto.DupDisableDeviceSettings,
SystemNavigation = cpDto.SystemNavigation != null ? cpDto.SystemNavigation : ResourceMsg.SYSTEM_NAVIGATION_UNSPECIFIED,
DupEnableSystemErrorWarnings = cpDto.DupEnableSystemErrorWarnings,
IsDeleted = resDevicemodel != null ? resDevicemodel.IsDeleted: true,
//fetch defaultConfiguration status to show createConfiguration button when status is true
IsDefaultConfigurationSet = enterpriseDatax.IsDefaultConfigurationSet,
DeviceList = _iAdminMapper.GetDropDevicesList(enterpriseDatax.EnterpriseId)
};
if (jFlag)
{
//when profile dropdown changed
return Json(dto);
}
// TempData["PolicyApplied"] = TempData["PolicyApplied"];
return View(dto);
}
//If work Profile then perform on hardware and apps settings
if (profileType == ResourceMsg.Work)
{
if (result != null)
{
}
if (resAppmodel != null)
{
}
//prepare commonpolicies vmodel to send to view
dto = new()
{
EnterpriseName = enterpriseDatax.EnterpriseNameRequested,
//hardware settings
DupWifiConfigDisabled = cpDto.DupWifiConfigDisabled,
DupMobileNetworksConfigDisabled = cpDto.DupMobileNetworksConfigDisabled,
DupBluetoothDisabled = cpDto.DupBluetoothDisabled,
DupUsbFileTransferDisabled = cpDto.DupUsbFileTransferDisabled,
MaximumTimeToLock = cpDto.MaximumTimeToLock,
AdjustVolumeDisabled = result != null ? result.AdjustVolumeDisabled : false,
ScreenCaptureDisabled = result != null ? result.ScreenCaptureDisabled : false,
StatusBarDisabled = result != null ? result.StatusBarDisabled : false,
BluetoothContactSharingDisabled = result != null ? result.BluetoothContactSharingDisabled : false,
ShareLocationDisabled = result != null ? result.ShareLocationDisabled : false,
WifiConfigDisabled = result != null ? result.WifiConfigDisabled : false,
MobileNetworksConfigDisabled = result != null ? result.MobileNetworksConfigDisabled : false,
AutoDateAndTimeZone = result != null ? result.AutoDateAndTimeZone : ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED,
KeyguardDisabled = result != null ? result.KeyguardDisabled : false,
CameraDisabled = result != null ? result.CameraDisabled : false,
//app settings
ApplicationName = cpDto.ApplicationName ?? string.Empty,
AppPackageName = cpDto.AppPackageName ?? string.Empty,
DupInstallType = cpDto.DupInstallType,
DupDefaultPermissionPolicy = cpDto.DupDefaultPermissionPolicy,
PackageList = _iEmmMapper.GetApplicationsList(),
//common policies
EnterpriseList = _iEmmMapper.GetActiveEnterprisesDropList(),
ProfileTypeList = _iEmmMapper.GetProfileTypeList(),
ProfileType = profileType,
//bindMyEnterpriseId in view
MyEnterpriseId = enterpriseDatax.EnterpriseId,
//fetch defaultConfiguration status to show createConfiguration button when status is true
IsDefaultConfigurationSet = enterpriseDatax.IsDefaultConfigurationSet,
DeviceList = _iAdminMapper.GetDropDevicesList(enterpriseDatax.EnterpriseId)
};
if (jFlag)
{
//when profile dropdown changed
return Json(dto);
}
return View(dto);
}
}
}
}
// TempData["PolicyApplied"] = TempData["PolicyApplied"];
return View(dto);
}
catch (Exception ex)
{
_loggerManager.LogError($"Something went wrong inside CommonPolicies get action: {ex.Message}");
return View(new CommonPoliciesDto());
}
}
Post Mehtod
[HttpPost]
[CustomAuthorization]
public IActionResult PolicyManagement(CommonPoliciesDto commonPolicies)
{
try
{
dynamic PolicyAge = string.Empty;
dynamic policyResponse = string.Empty;
string myPolicyId = string.Empty;
//bind myEnterpriseId in view page
ViewBag.MyEnterpriseeId = commonPolicies.MyEnterpriseId;
//fetch UserIdentityId
var userLoggedId = _iEmmMapper.GetEnterprises().Where(x=> x.EnterpriseId == commonPolicies.MyEnterpriseId).Select(x => x.AdminIdentityId).FirstOrDefault();
if(userLoggedId != null)
{
commonPolicies.UserIdentityId = userLoggedId;
}
#region ResellerServiceAccountEMMOAuthCred
//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(AndroidManagementService.ScopeConstants.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
ModelState.Remove("PackageName");
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(commonPolicies.MyEnterpriseId))
{
#region conditions
if (commonPolicies.AutoDateAndTimeZone == ResourceMsg.AUTO_DATEANDTIMEZONE_ENFORCED)
{
commonPolicies.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_ENFORCED;
}
else if (commonPolicies.AutoDateAndTimeZone == ResourceMsg.AUTO_DATEANDTIMEZONE_USERCHOICE)
{
commonPolicies.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_USERCHOICE;
}
else
{
commonPolicies.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED;
}
//
if (commonPolicies.WifiMoblieData == 1)
{
commonPolicies.WifiConfigDisabled = false;
commonPolicies.MobileNetworksConfigDisabled = true;
}
else if (commonPolicies.WifiMoblieData == 2)
{
commonPolicies.MobileNetworksConfigDisabled = false;
commonPolicies.WifiConfigDisabled = true;
}
else
{
commonPolicies.WifiConfigDisabled = false;
commonPolicies.MobileNetworksConfigDisabled = false;
}
//
if (commonPolicies.DupBluetoothDisabled == 1)
{
commonPolicies.BluetoothDisabled = false;
}
else
{
commonPolicies.BluetoothDisabled = true;
commonPolicies.BluetoothContactSharingDisabled = true;
}
if (commonPolicies.DupUsbFileTransferDisabled == 1)
{
commonPolicies.UsbFileTransferDisabled = false;
}
else
{
commonPolicies.UsbFileTransferDisabled = true;
}
if (commonPolicies.MaximumTimeToLock > 0)
{
commonPolicies.MaximumTimeToLock *= 60000;
}
#endregion
#region formingPolicyIdFromPolicyName
//form Policy Id
string myPolicyName = commonPolicies.PolicyName.Trim();
bool flag = false;
foreach (var data in myPolicyName.ToCharArray())
{
if (data == ' ')
{
flag = true;
}
}
if (flag)
{
string[] polArr = myPolicyName.Split(' ');
foreach (var datax in polArr)
{
myPolicyId += datax + "_";
}
myPolicyId = myPolicyId.Remove(myPolicyId.Length - 1, 1);
//Console.WriteLine(myPolicyId);
}
else
{
myPolicyId = myPolicyName;
//Console.WriteLine(test);
}
#endregion
var entepriseParent = string.Format("enterprises/{0}", commonPolicies.MyEnterpriseId);
var policyName = string.Format("{0}/policies/{1}", entepriseParent, myPolicyId);
//Check if policy exist on server or not
//If policy not exist on server then it thru 404 error
try
{
policyResponse = service.Enterprises.Policies.Get(policyName).Execute();
}
catch (GoogleApiException gex)
{
//thru 404 error as this is the new policy for the server
PolicyAge = ResourceMsg.New;
}
if (PolicyAge != ResourceMsg.New)
{
//Policy exist on server
PolicyAge = ResourceMsg.Existing;
}
//condition for add policy
if (commonPolicies.ActionType != ResourceMsg.update)
{
//check if the policyId exist in both database and active in server
var IsPolicyExistOnDB = _iEmmMapper.GetCommonPolicies().Where(x => x.PolicyName.ToUpper() == commonPolicies.PolicyName.ToUpper().Trim() && x.PolicyId == myPolicyId && x.EnterpriseId == commonPolicies.MyEnterpriseId).Any();
//If PolicyExistOnDb or PolicyIsNewToServer then only thru policy exist error
if(IsPolicyExistOnDB || PolicyAge == ResourceMsg.Existing)
{
//If Policy Exist on server then can't create a policy again with the same name
TempData["Failure"] = ResourceMsg.PolicyNameAlreadyExist;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ResourceMsg.PolicyNameAlreadyExist}");
return View(new EnterpriseDto());
}
else
{
//create a new policy in DB without policyId
//as PolicyId only generated by the server which need to be created during apply policy
//update data to common policies database table
commonPolicies.EnterpriseId = commonPolicies.MyEnterpriseId;
commonPolicies.PolicyId = "";
commonPolicies.PolicyName = commonPolicies.PolicyName;
commonPolicies.PolicyType = ResourceMsg.Custom;
//update into database
var result = _iAdminMapper.CreateUpdateHardwarePolicies(commonPolicies);
if (result == 0)
{
TempData["MsgCmnPolicies"] = ResourceMsg.PoliciesCreatedSuccessfully;
}
else
{
//this msg need to be removed
if (result == 1)
{
TempData["MsgCmnPolicies"] = ResourceMsg.PoliciesUpdatedSuccessfully;
}
}
}
}
else if (commonPolicies.ActionType == ResourceMsg.update)
{
//If the policy Exist on server then update the policy settings on server thru Policies.Patch endpoint
if(PolicyAge == ResourceMsg.Existing)
{
var newpolicyResponse = service.Enterprises.Policies.Patch(ConfigureCommonPolicies(commonPolicies), policyName).Execute();
commonPolicies.PolicyId = myPolicyId;
}
//update policy on local database
commonPolicies.EnterpriseId = commonPolicies.MyEnterpriseId;
commonPolicies.PolicyId = commonPolicies.PolicyId == null? string.Empty: commonPolicies.PolicyId;
commonPolicies.PolicyName = commonPolicies.PolicyName;
commonPolicies.PolicyType = ResourceMsg.Custom;
//update into database
var result = _iAdminMapper.CreateUpdateHardwarePolicies(commonPolicies);
if (result == 0)
{
TempData["MsgCmnPolicies"] = ResourceMsg.PoliciesCreatedSuccessfully;
}
else
{
if (result == 1)
{
TempData["MsgCmnPolicies"] = ResourceMsg.PoliciesUpdatedSuccessfully;
}
}
}
else
{
TempData["Failure"] = ResourceMsg.PolicyNameAlreadyExist;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ResourceMsg.PolicyNameAlreadyExist}");
}
}
else
{
TempData["Failure"] = ResourceMsg.TryAgainContactTechnicalTeam;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ResourceMsg.EnterpriseIdIsMissing}");
}
}
else
{
TempData["Failure"] = ResourceMsg.RequiredFieldsAreEmpty;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ResourceMsg.RequiredFieldsAreEmpty}");
}
CommonPoliciesDto dto = new();
//fetch & bind two profile types (Fully Manged & Work) on view
dto.ProfileTypeList = _iAdminMapper.GetProfileTypeList();
var myEnterpriseName = _iEmmMapper.GetEnterprises().Where(x => x.EnterpriseId == commonPolicies.MyEnterpriseId).Select(x => x.EnterpriseNameRequested).FirstOrDefault();
//DeviceList
dto.DeviceList = _iAdminMapper.GetDropDevicesList(commonPolicies.MyEnterpriseId);
dto.EnterpriseName = myEnterpriseName;
//pass the dto model to view
return View(dto);
}
catch (GoogleApiException gex)
{
TempData["Failure"] = ResourceMsg.PolicyNotFoundContactTechnicalTeam;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{gex.Message}");
return View(new EnterpriseDto());
}
catch (Exception ex)
{
TempData["Failure"] = ResourceMsg.TryAgainContactTechnicalTeam;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{ex.Message}");
return View();
}
}
Apply the policy
[HttpPost]
[CustomAuthorization]
/// <summary>
/// This method is used to apply hardware policy.
/// </summary>
/// <returns></returns>
public IActionResult ApplyHardwarePolicy(string rwId, string devarr)
{
try
{
#region ResellerServiceAccountEMMOAuthCred
//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(AndroidManagementService.ScopeConstants.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
string PolicyAge = string.Empty;
CommonPoliciesDto model = new();
string myPolicyId = string.Empty;
string[] devicesArr = devarr.Split('|');
devicesArr = devicesArr.SkipLast(1).ToArray();
//fetch policy information based on rowId
var policyInfo = _iEmmMapper.GetCommonPolicies().Where(x => x.Id == Convert.ToInt32(rwId)).FirstOrDefault();
if(policyInfo != null)
{
//initialize model to assign apps into it
model.ApplicationDtoList = new List<ApplicationsDto>();
var appModel = new ApplicationsDto();
//prepare the model from database response to apply the policy on server
#region conditions
if (policyInfo.AutoDateAndTimeZone == ResourceMsg.AUTO_DATEANDTIMEZONE_ENFORCED)
{
model.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_ENFORCED;
}
else if (policyInfo.AutoDateAndTimeZone == ResourceMsg.AUTO_DATEANDTIMEZONE_USERCHOICE)
{
model.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_USERCHOICE;
}
else
{
model.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED;
}
//
if (policyInfo.WifiConfigDisabled == false && policyInfo.MobileNetworksConfigDisabled == false)
{
model.WifiConfigDisabled = false;
model.MobileNetworksConfigDisabled = false;
}
if (policyInfo.WifiConfigDisabled == true)
{
model.WifiConfigDisabled = true;
model.MobileNetworksConfigDisabled = false;
}
else if (policyInfo.MobileNetworksConfigDisabled == true)
{
model.MobileNetworksConfigDisabled = true;
model.WifiConfigDisabled = false;
}
else
{
model.WifiConfigDisabled = false;
model.MobileNetworksConfigDisabled = false;
}
//
if (policyInfo.BluetoothDisabled == false)
{
model.BluetoothDisabled = false;
}
else
{
model.BluetoothDisabled = true;
model.BluetoothContactSharingDisabled = true;
}
//
if (policyInfo.UsbFileTransferDisabled == false)
{
model.UsbFileTransferDisabled = false;
}
else
{
model.UsbFileTransferDisabled = true;
}
//MaximumTimeToLock
model.MaximumTimeToLock = policyInfo.MaximumTimeToLock;
//adjustvolume
model.AdjustVolumeDisabled = policyInfo.AdjustVolumeDisabled;
//screencapture
model.ScreenCaptureDisabled = policyInfo.ScreenCaptureDisabled;
//statusbar
if(policyInfo.StatusBarDisabled == true)
{
model.StatusBarDisabled = true;
}
else
{
model.StatusBarDisabled = false;
}
//sharelocation
model.ShareLocationDisabled = policyInfo.ShareLocationDisabled;
//keyguard
model.KeyguardDisabled = policyInfo.KeyguardDisabled;
//camera
model.CameraDisabled = policyInfo.CameraDisabled;
#endregion
#region forming policyId from policyName
//form Policy Id
string myPolicyName = policyInfo.PolicyName.Trim();
bool flag = false;
foreach (var data in myPolicyName.ToCharArray())
{
if (data == ' ')
{
flag = true;
}
}
if (flag)
{
string[] polArr = myPolicyName.Split(' ');
foreach (var datax in polArr)
{
myPolicyId += datax + "_";
}
myPolicyId = myPolicyId.Remove(myPolicyId.Length - 1, 1);
//Console.WriteLine(myPolicyId);
}
else
{
myPolicyId = myPolicyName;
//Console.WriteLine(test);
}
#endregion
//Apply the selected policy on server
//check there is an active policy of the enterprise on server
var entepriseParent = string.Format("enterprises/{0}", policyInfo.EnterpriseId);
//var policyName = string.Format("{0}/policies/{1}", entepriseParent, myDefaumyPolicyIdltPolicyId);
var policyName = string.Format("{0}/policies/{1}", entepriseParent, myPolicyId);
//Check if policy exist on server or not
//If policy not exist on server then it thru 404 error
dynamic appList = string.Empty;
try
{
appList = service.Enterprises.Policies.Get(policyName).Execute();
}
catch (GoogleApiException gex)
{
//thru 404 error as this is the new policy for the server
PolicyAge = ResourceMsg.New;
}
//If policy is not the new policy then the existing policy
if (PolicyAge == string.Empty)
{
//If there no 404 exeception from server then the policy is the existing server policy
PolicyAge = ResourceMsg.Old;
}
//devicename
dynamic deviceNameAPI = string.Empty;
if (PolicyAge.Equals(ResourceMsg.New))
{
//create a new policy on the server with the formed policyId thru policies.patch endpoint
var newpolicyResponse = service.Enterprises.Policies.Patch(ConfigureCommonPolicies(model), policyName).Execute();
//loop thru each requested devices
foreach (var deviceId in devicesArr)
{
//form the deviceName API format
deviceNameAPI = string.Format("{0}/devices/{1}", entepriseParent, deviceId);
//Check device is exist on server or not
var deviceResponse = service.Enterprises.Devices.Get(deviceNameAPI).Execute();
//This device belongs to EMM Device; Full fledged path
//There is also Device class exist for Zerotouch device
Google.Apis.AndroidManagement.v1.Data.Device device = new Google.Apis.AndroidManagement.v1.Data.Device()
{
//Assign policyId to policyName
PolicyName = myPolicyId,
State = ResourceMsg.ACTIVE
};
//Apply the newly created policy on the requested devices thru device.patch endpont
var devicePatchResponse = service.Enterprises.Devices.Patch(device, deviceNameAPI).Execute();
}
//Update the local database with newly applied policy
}
else
{
if (PolicyAge.Equals(ResourceMsg.Old))
{
//No need to create a new policy on server
if (appList != null)
{
//set all hardware policies exist on server
//check if app list is null or not
if (appList.Applications != null)
{
//set all application policies exist from server
//fetching existing apps from the provided policy
foreach (var app in appList.Applications)
{
appModel = new ApplicationsDto()
{
PackageName = app.PackageName,
InstallType = app.InstallType,
DefaultPermissionPolicy = app.DefaultPermissionPolicy
};
model.ApplicationDtoList.Add(appModel);
}
}
}
//update the existing policy
var newpolicyResponse = service.Enterprises.Policies.Patch(ConfigureCommonPolicies(model), policyName).Execute();
//loop thru each requested devices
foreach (var deviceId in devicesArr)
{
//form the deviceName API format
deviceNameAPI = string.Format("{0}/devices/{1}", entepriseParent, deviceId);
//Check device is exist on server or not
var deviceResponse = service.Enterprises.Devices.Get(deviceNameAPI).Execute();
//This device belongs to EMM Device; Full fledged path
//There is also Device class exist for Zerotouch device
Google.Apis.AndroidManagement.v1.Data.Device device = new Google.Apis.AndroidManagement.v1.Data.Device()
{
//Assign policyId to policyName
PolicyName = myPolicyId,
State = ResourceMsg.ACTIVE
};
//Apply the newly created policy on the requested devices thru device.patch endpont
var devicePatchResponse = service.Enterprises.Devices.Patch(device, deviceNameAPI).Execute();
}
}
}
model.EnterpriseId = policyInfo.EnterpriseId;
model.PolicyName = policyInfo.PolicyName;
model.PolicyId = myPolicyId;
model.PolicyNameApiFormat = policyName;
model.Custom1 = DateTime.UtcNow.ToString();//PolicyAppliedDate
model.CustomStatus1 = true; //PolicyAppliedOnServerStatus
//model.CustomStatus2 = true; //IsThisCurrentPolicy
//update the policyInfo on local database
var result = _iAdminMapper.CreateUpdateHardwarePolicies(model);
if (result == 1)
{
//update the IsThisCurrentAppliedPolicy = customstatus2 to false for rest policies under the same policyId
//var res = _iAdminMapper.UpdateHardwarePoliciesStatus(model);
TempData["PolicyApplied"] = ResourceMsg.PoliciesAppliedSuccessfully;
}
else
{
TempData["PolicyApplied"] = ResourceMsg.ContactTechnicalTeam;
}
}
else
{
TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ResourceMsg.PolicyNotFound}");
return Json(new {success = false,message= ResourceMsg.ContactTechnicalTeam });
}
return Json(new { success = true, message = TempData["PolicyApplied"] });
}
catch (Exception ex)
{
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ex.Message}");
TempData["Failure"] = ResourceMsg.ContactTechnicalTeam;
return Json(new { success = false, message = ResourceMsg.ContactTechnicalTeam });
}
}
Method for Delete Policy
[HttpGet]
public IActionResult DeleteHardwarePolicy(string rwId)
{
try
{
if (rwId != null)
{
#region ResellerServiceAccountEMMOAuthCred
//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(AndroidManagementService.ScopeConstants.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
//Fetch enterpriseId based on deviceId where device is active
var policiesInfo = _iEmmMapper.GetCommonPolicies().Where(x => x.Id == Convert.ToInt32(rwId) && x.IsActive).FirstOrDefault();
if (policiesInfo != null)
{
//Fetch Default Policy
var defaultPolicyId = _iEmmMapper.GetCommonPolicies().Where(x => x.EnterpriseId == policiesInfo.EnterpriseId && x.PolicyProfileType == policiesInfo.PolicyProfileType && x.PolicyType == ResourceMsg.Default).Select(x=> x.PolicyId).FirstOrDefault();
//If policy is active policy for any devices then after deleting the sever will be updated with default policy
var entepriseParent = string.Format("enterprises/{0}", policiesInfo.EnterpriseId);
//Fetch DeviceList with ongoing deleted policy
//var DevicesList = service.Enterprises.Devices.List(entepriseParent);
var deviceList = _iEmmMapper.GetDevices().Where(x => x.PolicyId == policiesInfo.PolicyId && x.IsActive).ToList();
if(deviceList.Count > 0)
{
//apply all devices with default policy
foreach(var device in deviceList)
{
var deviceNameAPI = string.Format("{0}/devices/{1}", entepriseParent, device.DeviceId);
//Apply policy on device
Google.Apis.AndroidManagement.v1.Data.Device deviceBody = new Google.Apis.AndroidManagement.v1.Data.Device()
{
//Assign policyId to policyName
PolicyName = defaultPolicyId,
State = ResourceMsg.ACTIVE
};
//Apply the newly created policy on the requested devices thru device.patch endpont
var devicePatchResponse = service.Enterprises.Devices.Patch(deviceBody, deviceNameAPI).Execute();
}
}
//var policyName = string.Format("{0}/policies/{1}", entepriseParent, policiesInfo.PolicyId);
//var policyResponse = service.Enterprises.Policies.Get(policyName).Execute();
//if(policyResponse != null)
//{
// //If policy exist on server then set default hardware policy
// var appliedPolicyData = service.Enterprises.Policies.Patch(DefaultHardwarePolicies(policiesInfo.PolicyId), policyName).Execute();
//}
//soft delete policy from local database
var result = _iAdminMapper.SoftDeletePolicy(Convert.ToInt32(rwId));
if (result == 1)
{
TempData["MsgCmnPolicies"] = ResourceMsg.DeleteMsg;
return RedirectToAction("PolicyManagement", "Admin");
}
}
return RedirectToAction("PolicyManagement", "Admin");
}
return RedirectToAction("PolicyManagement", "Admin");
}
catch (Exception ex)
{
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ex.Message}");
return RedirectToAction("PolicyManagement", "Admin");
}
}
This method for get policy h/w policy
[HttpGet]
/// <summary>
/// This method is used to return hardware policies based on enterprise Id in json format.
/// </summary>
/// <param name="enterpriseId"></param>
/// <returns></returns>
public IActionResult GetjHardwarePolicies(string enterpriseId)
{
try
{
IList<CommonPoliciesDto> hardwarePoliciesList = new List<CommonPoliciesDto>();
List<SelectListItem> deviceDropList = new List<SelectListItem>();
SelectListItem hardwarePoliciy = new();
//fetch enterprise name
var enterpriseName = _iEmmMapper.GetEnterprises().Where(x=> x.EnterpriseId == enterpriseId).Select(x=> x.EnterpriseNameRequested).FirstOrDefault();
//fetch devices based on enterprise
var deviceList = _iEmmMapper.GetDevices().Where(x => x.EnterpriseId == enterpriseId && x.IsActive).ToList();
if(deviceList.Count > 0)
{
foreach(var device in deviceList)
{
hardwarePoliciy = new SelectListItem()
{
Text = device.Model,
Value = device.DeviceId
};
deviceDropList.Add(hardwarePoliciy);
};
}
if (enterpriseId != null)
{
//fetch list of custom hardware policies based on enterprise
var hardwarePoliciesListResponse = _iEmmMapper.GetCommonPolicies().Where(x => x.EnterpriseId.Equals(enterpriseId) && x.PolicyType == ResourceMsg.Custom && x.IsActive);
foreach (var policy in hardwarePoliciesListResponse)
{
policy.EnterpriseName = enterpriseName;
policy.DeviceList.AddRange(deviceDropList);
hardwarePoliciesList.Add(policy);
}
}
//List<SelectListItem> countries = this.Context.Customers.Where(x => x.Country != null)
//.Select(x => new SelectListItem
//{
// Text = x.Country,
// Value = x.Country
//}).Distinct().ToList();
return new JsonResult(hardwarePoliciesList);
}
catch (Exception ex)
{
string msgErr = "Error in " + this.GetType().ToString();
_loggerManager.LogError($"{msgErr}{ex.Message}");
return RedirectToAction("PolicyManagement", "Admin");
}
}
This method is used for edit policy
[HttpGet]
/// <summary>
/// This method used to Edit Hardware Setting modal by Id.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public JsonResult jEditHardwareSettings(int id)
{
CommonPoliciesDto commonModel = new() { Id = id };
var responseHardwareModel = _iEmmMapper.GetCommonPolicies().Where(x => x.Id == id).FirstOrDefault();
if (responseHardwareModel != null)
{
#region Hardware Settings from database
//PolicyName
commonModel.PolicyName = responseHardwareModel.PolicyName;
//ProfileType
commonModel.PolicyProfileType = responseHardwareModel.PolicyProfileType;
//Blutooth
if (responseHardwareModel.BluetoothDisabled == false)
{
commonModel.DupBluetoothDisabled = 1;
}
else
{
commonModel.DupBluetoothDisabled = 0;
}
//USB
if (responseHardwareModel.UsbFileTransferDisabled == false)
{
commonModel.DupUsbFileTransferDisabled = 1;
}
else
{
commonModel.DupUsbFileTransferDisabled = 0;
}
//Wifi
if (responseHardwareModel.WifiConfigDisabled == false)
{
//enabled
commonModel.DupWifiConfigDisabled = 1;
}
else
{
//disabled
commonModel.DupWifiConfigDisabled = 0;
}
//MobileData
if (responseHardwareModel.MobileNetworksConfigDisabled == false)
{
commonModel.DupMobileNetworksConfigDisabled = 1;
}
else
{
commonModel.DupMobileNetworksConfigDisabled = 0;
}
//ScreenLockTime
if (responseHardwareModel.MaximumTimeToLock > 0)
{
commonModel.MaximumTimeToLock = responseHardwareModel.MaximumTimeToLock / 60000;
}
//LockVolume
commonModel.AdjustVolumeDisabled = responseHardwareModel.AdjustVolumeDisabled;
//ManageTimeZone
if (responseHardwareModel.AutoDateAndTimeZone == ResourceMsg.AUTO_DATEANDTIMEZONE_ENFORCED)
{
commonModel.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_ENFORCED;
}
else if (responseHardwareModel.AutoDateAndTimeZone == ResourceMsg.AUTO_DATEANDTIMEZONE_USERCHOICE)
{
commonModel.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_USERCHOICE;
}
else
{
commonModel.AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED;
}
//ScreenCapture
commonModel.ScreenCaptureDisabled = responseHardwareModel.ScreenCaptureDisabled;
//StatusBar
commonModel.StatusBarDisabled = responseHardwareModel.StatusBarDisabled;
//BlutoothContactSharing
commonModel.BluetoothContactSharingDisabled = responseHardwareModel.BluetoothContactSharingDisabled;
//GPS
commonModel.ShareLocationDisabled = responseHardwareModel.ShareLocationDisabled;
//Keyguard
commonModel.KeyguardDisabled = responseHardwareModel.KeyguardDisabled;
//Camera
commonModel.CameraDisabled = responseHardwareModel.CameraDisabled;
#endregion
}
return Json(commonModel);
}

MS Graph SendMail with attachment

I have problem to send an email with attachment.
Without attachment it works.
If I use the same function and add an attachment to the message I get the following error message:
Code: ErrorRequiredPropertyMissing Message: Required property is missing. ClientRequestId: 2af....
I am using MS Graph v4.0.30319
What am I doing wrong
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#mail.com"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\me\Desktop\Test.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
//ODataType = "#microsoft.graph.fileAttachment",
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#MailNo2.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
// -- If I comment this out I can send the mail without error but without attachment----
message.Attachments.Add(attachment);
message.HasAttachments = true;
//-----------------------------------------------------------------
var request = graphClient.Me.SendMail(message, true);
// Messages[message.Id].Send();// SendMail(message, null);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
The below code works perfectly fine for me
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\Shiva\Desktop\sample.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
message.HasAttachments = true;
message.Attachments.Add(attachment);
var request = graphClient.Me.SendMail(message, true);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
You need to make sure that you have the PDF file path correctly specified and the fromSender variable will obviously be yours as you are calling me/sendMail. If you want to send mail from other user's mailbox then you need to have client credential flow setup so that it can give you an App-only token which should have required permissions and you need to change the call something like this var request = graphClient.Users["userid/UPN"].SendMail(message, true);.
I have just updated the MS Graph preview version from
4.0.0-preview.1
to
4.0.0-preview.2
Now everything works as expected
I think it was a bug in preview.1

Error while running unit test on ASP.Net MVC registraton code which uses ASP.Net Identity

I am new to ASP.Net MVC and Identity.
I have following unit test method.
[TestMethod]
public void SignUp()
{
try
{
var dummyUser = new ApplicationUser() { UserName = "xyz", Email = "xyz#gmail.com" };
ViewModels.RegisterViewModel rvm = new ViewModels.RegisterViewModel { Name = "abc", Email = "abc#yahoo.com", Password = "123456" };
var store = new Mock<IUserStore<ApplicationUser>>();
store.As<IUserPasswordStore<ApplicationUser>>()
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new ApplicationUser() { Id = "id" });
store.Setup(x => x.CreateAsync(dummyUser)).Returns(Task.FromResult(IdentityResult.Success));
store.As<IUserRoleStore<ApplicationUser>>().Setup(x => x.AddToRoleAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).Returns(Task.FromResult(IdentityResult.Success));
store.As<IUserRoleStore<ApplicationUser>>().Setup(x => x.IsInRoleAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(true);
store.As<IRoleStore<IdentityRole>>().Setup(x => x.CreateAsync(new IdentityRole("I"))).Returns(Task.FromResult(IdentityResult.Success));
//var roleStore = new Mock<IRoleStore<IdentityRole>>();
//roleStore.As<IRoleStore<IdentityRole>>();
//roleStore.Setup(x => x.CreateAsync(new IdentityRole("I"))).Returns(Task.FromResult(IdentityResult.Success));
//var testRoleManager = new ApplicationRoleManager(roleStore.Object);
//to register usertokenprovider as it is needed to send confirmation email
var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
var testUserManager = new ApplicationUserManager(store.Object);
testUserManager.UserTokenProvider =new DataProtectorTokenProvider<ApplicationUser>(provider.Create("ASP.NET Identity"));
// mocking IAuthenticationManager
var mockAuthenticationManager = new Mock<IAuthenticationManager>();
mockAuthenticationManager.Setup(am => am.SignOut());
mockAuthenticationManager.Setup(am => am.SignIn());
//mocking Context
var routes = new System.Web.Routing.RouteCollection();
ProChartSiteMVC.RouteConfig.RegisterRoutes(routes);
var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost:1431/a", UriKind.Absolute));
request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
response.Setup(x => x.ApplyAppPathModifier("/post1")).Returns("http://localhost:1431/post1");
var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
var testSignInManager = new ApplicationSignInManager(testUserManager,mockAuthenticationManager.Object);
BussinessLayer bussinessLayer = new BussinessLayer(db);
AccountController controller = new AccountController(testUserManager,testSignInManager, bussinessLayer);
var UrlHelperMock = new Mock<UrlHelper>();
controller.Url = UrlHelperMock.Object;
controller.ControllerContext = new ControllerContext(context.Object, new System.Web.Routing.RouteData(), controller);
var result = controller.SignUp(rvm) as Task<ActionResult>;
var viewresult = result.Result;
Assert.IsNotNull(result);
}
catch (Exception ex) { string str = ex.ToString(); }
}
Original SignUp method which works fine when I run it debug mode but gives error if executed from unit test.
[HttpPost]
public async Task<ActionResult> SignUp(RegisterViewModel rvm)
{
if (ModelState.IsValid)
{
var appUser = new ApplicationUser();
appUser.UserName = bLayer.GenerateInvestarID(rvm.Email);
appUser.Email = rvm.Email;
appUser.Name = rvm.Name;
appUser.LockoutEnabled = true;
appUser.InstituteCode = "10";
try
{
var result = await UserManager.CreateAsync(appUser, rvm.Password);
if (result.Succeeded)
{
IdentityResult addResult = await UserManager.AddToRoleAsync(appUser.Id, "I");
await SignInManager.SignInAsync(appUser, isPersistent: false, rememberBrowser: false);
string code = await UserManager.GenerateEmailConfirmationTokenAsync(appUser.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = appUser.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(appUser.Id, "Confirm your account", "Please confirm your account by clicking here");
return RedirectToAction("Thankyou");
}
else
{
AddErrors(result);
return PartialView("_PartialSignUp", rvm);
}
}
catch(Exception ex)
{
ModelState.AddModelError("CredentialError", ex.Message);
return PartialView("_PartialSignUp", rvm);
}
}
else
{
ModelState.AddModelError("CredentialError", "Invalid Details");
return PartialView("_PartialSignUp", rvm);
}
}
I get following error while IdentityResult addResult = await UserManager.AddToRoleAsync(appUser.Id, "I") is executed from above code through unit test.
System.NullReferenceException was caught
_HResult=-2147467261
_message=Object reference not set to an instance of an object.
HResult=-2147467261
IsTransient=false
Message=Object reference not set to an instance of an object.
Source=Microsoft.AspNet.Identity.Core
StackTrace:
at Microsoft.AspNet.Identity.UserManager`2.<AddToRoleAsync>d__83.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at SiteMVC.Controllers.AccountController.<SignUp>d__0.MoveNext()
What is going wrong here which causes above error.
To me it looks like you need to Setup result for IUserStore.GetRolesAsync method.
UserManager.AddToRoleAsync method calls IUserStore.GetRolesAsync and calls 'Contains' method on the returned collection of the roles.
Since there is no result is setup for this method in unit test it returns null as the default which caused this exception to happen.
Following is the code I have setup the result for IUserStore.GetRolesAsync to return empty list of roles.
[TestMethod]
public void SignUp()
{
try
{
var dummyUser = new ApplicationUser() { UserName = "xyz", Email = "xyz#gmail.com" };
ViewModels.RegisterViewModel rvm = new ViewModels.RegisterViewModel { Name = "abc", Email = "abc#yahoo.com", Password = "123456" };
var store = new Mock<IUserStore<ApplicationUser>>();
var roles = new List<string>(); // Populate this list as per your need.
store.As<IUserPasswordStore<ApplicationUser>>()
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new ApplicationUser() { Id = "id" });
store.Setup(x => x.CreateAsync(dummyUser)).Returns(Task.FromResult(IdentityResult.Success));
//Setting up the result for GetRoleAsync method to return roles collection.
store.As<IUserRoleStore<ApplicationUser>>().Setup(x => x.GetRolesAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(roles);
//Rest of the unit test code
}
catch (Exception ex) { string str = ex.ToString(); }
}

add role in database in asp mvc identity

i need to when user regiter add in tabel AspNetRole add user id and role id .
but when i create a user show me this error .
how can i insert role in database ?
/*************************************************************************************************/
identityconfig :
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
public static class SecurityRole
{
public const string Admin = "admin";
public const string Accounting = "accounting";
}
StartupAuth :
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
AccountController :
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase IamgeProfile)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Username, Email = model.Email };
user.Name = model.Name;
user.Family = model.Family;
user.Address = model.Address;
user.BankName = model.BankName;
user.City = model.City;
user.Ostan = model.Ostan;
user.PhoneNumber = model.PhoneNumber;
user.HomeNumber = model.HomeNumber;
user.ShabaNo = model.ShabaNo;
user.PostaCode = model.PostaCode;
user.NationalCode = model.NationalCode;
if (IamgeProfile != null)
{
IamgeProfile = Request.Files[0];
var ext = System.IO.Path.GetExtension(IamgeProfile.FileName);
if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
{
string filename = model.Name + model.Family + model.NationalCode + ext;
IamgeProfile.SaveAs(Server.MapPath(#"~/Images/UserImageProfile/" + filename));
user.IamgeProfile = filename;
}
}
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
await UserManager.AddToRoleAsync(user.Id, role: SecurityRole.Accounting);
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: link");
ViewBag.Link = callbackUrl;
return View("DisplayEmail");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
To add a role into AspNetRoles you can do this in your Seed() or other startup method:
if (!context.Roles.Any(r => r.Name == "Admin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "Admin" };
manager.Create(role);
}
https://msdn.microsoft.com/en-us/library/dn613057(v=vs.108).aspx

MVC 5.1 identity 2 add new Role to myself need to log out

When I add new Role to my own account I have to log out and log back in so this role will start working. Is there a way to re-load roles on the fly (after adding/deleting) ?
I'm using Individual Accounts stored in Ms SQL Server 2012 in MVC 5.1.2 and Identity v. 2.0.0
Below is controller code:
// GET: /Users/Edit/1
public async Task<ActionResult> Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
var userRoles = await UserManager.GetRolesAsync(user.Id);
return View(new EditUserViewModel()
{
Id = user.Id,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
CustomerID = user.CustomerID,
siteID = user.SiteID,
RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
}),
SitesList = db.sites.ToList().Select(y=> new SelectListItem()
{
Selected= user.SiteID==y.siteID,
Text = y.siteCode,
Value= y.siteID.ToString()
})
});
}
//
// POST: /Users/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Email,Id,FirstName,LastName,CustomerID,siteID")] EditUserViewModel editUser, params string[] selectedRole)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(editUser.Id);
if (user == null)
{
return HttpNotFound();
}
user.UserName = editUser.Email;
user.Email = editUser.Email;
user.FirstName = editUser.FirstName;
user.LastName = editUser.LastName;
user.CustomerID = editUser.CustomerID;
user.SiteID = editUser.siteID;
var userRoles = await UserManager.GetRolesAsync(user.Id);
selectedRole = selectedRole ?? new string[] { };
var result = await UserManager.AddUserToRolesAsync(user.Id, selectedRole.Except(userRoles).ToList<string>());
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
result = await UserManager.RemoveUserFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToList<string>());
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
editUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
//Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
});
ModelState.AddModelError("", "Something failed.");
return View(editUser);
}

Resources