EntityManager persist expects parameter 1 to be an entity object, NULL given zend doctrine - zend-framework2

I have this addaction controller and i'm getting this exception error though user are getting added.
public function addAction() {
$requestObj = $this->getRequest();
$viewModelObj = new ViewModel();
$errorMsg = array();
$userObj = new Entity\User();
try {
$userRepo = $this->getDoctrineRepository('User');
if ($this->getRequest()->getQuery('id')) {
$userObj = $userRepo->findOneBy(array('id'=>$this->getRequest()->getQuery('id')));
}
if ($requestObj->isPost()) {
$postData = $requestObj->getPost()->getArrayCopy();
$currentUser = $this->getFromSession('user');
$error = false;
if (trim($requestObj->getPost('firstName')) == "") {
$errorMsg[] = "First name is required";
$error = true;
}
if ($this->getRequest()->getQuery('id')) {
if($userObj->getCellPhone() != $postData['cellPhone']) {
if($userRepo->findOneBy(array('cellPhone'=> $postData['cellPhone']))) {
$errorMsg[] = "Cell Phone is already exists.";
$error = true;
}
}
} else {
$existUserByEmailObj = $userRepo->findOneBy(array('email'=> $postData['email']));
$existUserByCellObj = $userRepo->findOneBy(array('cellPhone'=> $postData['cellPhone']));
if($existUserByEmailObj){
$errorMsg[] = "Email is already exists.";
$error = true;
}
if($existUserByCellObj){
$errorMsg[] = "Cell Phone is already exists.";
$error = true;
}
}
if ($userObj->getId() && trim($requestObj->getPost('password')) == "") {
$postData['password'] = $userObj->getPassword();
} else if (trim($requestObj->getPost('password')) == "") {
// user add
$errorMsg[] = "Password is required";
$error = true;
}
// in edit if password is empty then insert previous password
// populate object with form data
$hydratorObj = new Hydrator\ClassMethods();
$hydratorObj->hydrate($postData, $userObj);
if($error == false) {
$userObj->setUpdatedBy($currentUser->getId());
$eMObj = $this->getDoctrineEntityManager();
if ($userObj->getId()) {
//$userObj->setIsVerified(2);
$eMObj->merge($userObj);
} else {
$userObj->setCreatedDate(new \DateTime("now"));
$userObj->setCreatedBy($currentUser->getId());
//$userObj->setIsVerified(2);
$eMObj->persist($userObj);
}
$eMObj->flush();
// Set User Sms Number
$userSmsNumberRepo = $this->getDoctrineRepository('UserSmsNumber');
$userSmsNumberObj = $userSmsNumberRepo->findOneBy(array('user'=> $userObj->getId()));
if(!$userSmsNumberObj) {
$smsNumberRepo = $this->getDoctrineRepository('SmsNumber');
$smsNumberObj = $smsNumberRepo->findSmsNumber();
if ($smsNumberObj) {
$userSmsNumberObj = new Entity\UserSmsNumber();
$userSmsNumberObj->setUser($userObj);
$userSmsNumberObj->setSmsNumber($smsNumberObj);
$smsNumberObj->setNoOfAssignee((int)$smsNumberObj->getNoOfAssignee() + 1);
}
$eMObj->persist($userSmsNumberObj);
$eMObj->merge($smsNumberObj);
$eMObj->flush();
// Send Email Alert to Admin if last one SmsNumber is exists.
$lastSmsNumber = $smsNumberRepo->lastOneSmsNumber();
if($lastSmsNumber == 0 || $lastSmsNumber == 1) {
$settingObj = $this->getDoctrineRepository('Setting');
$adminEmail = $settingObj->findValueByFieldName('ADMIN_EMAIL');
$sendArr = array($adminEmail => 'Fence-alert');
$placeholderArr = array('NAME' => 'Admin', 'SMSNUMBER' => $smsNumberObj->getSmsNumber(), 'NOOFASSIGNEE' => (int)$smsNumberObj->getNoOfAssignee());
$sendMailObj = new SendEmail($this->serviceLocator);
$sendMailObj->send($sendArr, 'SMSNUMBER_ALERT', $placeholderArr, $toAdmin = TRUE);
}
}
$this->flashMessenger()->addMessage('User Saved Successfully!');
$this->redirect()->toUrl(BASE_URL.'/admin/user');
}
}
$form = new UserForm($this->getServiceLocator(), 'formUser');
$form->bind($userObj);
$form->get('password')->setAttribute('type', 'text');
$form->get('password')->setValue($userObj->getPassword());
$viewModelObj->setVariables(array(
'errorMsg' => $errorMsg,
'form' => $form,
'userObj' => $userObj
));
return $viewModelObj;
} catch(\Exception $e) {
print_r($e);
$this->flashMessenger()->addMessage('Exception Error: User not saved.');
return $this->redirect()->toUrl(BASE_URL.'/admin/user');
}
}
error:
Doctrine\ORM\ORMInvalidArgumentException Object ( [message:protected] => EntityManager#persist() expects parameter 1 to be an entity object, NULL given.
...............................................................................................................................................................................................................................................................................................

I checked the code and I think the problem could be this:
At the row number 82 you check if $userSmsNumberObj is an object.
If it's null you enter in the if statement
At row number 85 you check if $smsNumberObj is an object or null
In case $smsNumberObj is null you jump to row 92 without instantiate a new UserSmsNumber and you try to persist a null value
I think you have to check if $userSmsNumberObj is an object before try to persist at row 92.

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

asp.net mvc core A second operation was started on the context before the first operation is completed

I am using this code for authorization on controllers.
with [Authorize(Policy = "CustomRole")]
The thing happened that after 3 or 4 request it fails with
A second operation started on this context before a previous operation completed
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
public CMSContext _context = new CMSContext();
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRoleRequirement requirement)
{
var routeobj = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var c = routeobj.RouteData.Values.Values.ToList();
var keys = routeobj.RouteData.Values.Keys.ToList();
string area = "";
string id = "";
string controller = "";
string action = "";
string module = "";
foreach (var item in keys)
{
if (item=="area")
{
int indexs = keys.FindIndex(cc => cc == "area");
area = c[indexs].ToString();
}
else if (item == "id")
{
int indexs = keys.FindIndex(cc => cc == "id");
id = c[indexs].ToString();
}
else if (item == "controller")
{
int indexs = keys.FindIndex(cc => cc == "controller");
controller = c[indexs].ToString();
}
else if (item == "module")
{
int indexs = keys.FindIndex(cc => cc == "module");
module = c[indexs].ToString();
}
else if (item == "action")
{
int indexs = keys.FindIndex(cc => cc == "action");
action = c[indexs].ToString();
}
}
string modulelink = controller;
if (!string.IsNullOrEmpty(module))
{
modulelink = modulelink + "/" + module;
}
List<string> Roles = new List<string>();
int UserId = Auth.UserID;
string UserName = Auth.UserName;
if (UserName == "superadmin")
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
// apparently the error occurred here
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
if (moduleobj != null)
{ // 69 role is assessing news module
//60 role is accessing page module
var RolesModulesobj = _context.AppRolesModules.FirstOrDefault(q => q.ModuleId == moduleobj.ModuleId && q.RolesId == Auth.RoleId);
if (RolesModulesobj != null)
{
string permissionsobj = RolesModulesobj.Permissions;
List<string> PermissionsListobj = permissionsobj.Split(',').Select(x => x.Trim()).ToList();
var FindFullAccess = PermissionsListobj.FirstOrDefault(q => q.Contains("FullAccess:true"));
if (FindFullAccess != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
var abc = PermissionsListobj.FirstOrDefault(q => q.Contains(action + ":true"));
if (abc != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
context.Fail();
return Task.CompletedTask;
}
}
}
}
}
The error occurred at this line above
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
How can I make task wait before the second operation started in the method above?
You can't use a singleton DB context. You either create one each time you need one or you pool them.

asp.net-MVC Unexplained Production Exception

After moving my application to production, I get the regular Object reference not set to an instance of an object. exception logged in my event viewer.
This exception occurs intermittently few times a day, the problem is that I cannot put my hand on the problem, the logged exception details are not helpful, as there are no code line numbers included in the stack trace.
The Exception occurs on an action in my home controller which is the entry point action for each user arriving at the web site.
Can anyone help me reason with the below trace:
ERROR => Object reference not set to an instance of an object.
(XXX.XXX.Web.Controllers.HomeController.Index)
(
<>c__DisplayClass2b.<BeginInvokeAction>b__1c =>
<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32 =>
<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f =>
AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d =>
WrappedAsyncResult`2.CallEndDelegate =>
AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39 =>
ControllerActionInvoker.InvokeActionMethod =>
ReflectedActionDescriptor.Execute =>
<no type>.lambda_method => HomeController.Index )
System.NullReferenceException: Object reference not set to an instance of an object.
at XXXX.XXXX.Web.Controllers.HomeController.Index()
Code:
[SSOAuthorize]
public ActionResult Index()
{
try
{
ViewBag.ShowXXXAccountPrompt = false;
ViewBag.IsErrored = "false";
#region "Session Check"
if (_webHttpContext == null)
{
return RedirectToAction("signout", "Federation");
}
if (_webHttpContext.Session == null)
{
return RedirectToAction("signout", "Federation");
}
if (_webHttpContext.Session.PortalUser == null)
{
return RedirectToAction("signout", "Federation");
}
#endregion
if (_webHttpContext.Session.PortalUser != null)
{
if (!string.IsNullOrEmpty(_webHttpContext.Session.PortalUser.UserName))
{
var user = _usersManagementService.GetUserByUsername(_webHttpContext.Session.PortalUser.UserName);
var latestsubline = _subscriptionLineService.GetLatestLineByUserName(_webHttpContext.Session.PortalUser.UserName);
var isDualAccount = latestsubline == null ? false : latestsubline.Action == (int)Entities.SubscriptionLineAction.Activate? latestsubline.IsDualAccount : false;
isDualAccount = isDualAccount == null ? false : isDualAccount;
if(user == null)
{
//whenever there is no account Just Create it, the subscriptionLines table is irrelevant
_usersManagementService.CreateUser(_webHttpContext.Session.PortalUser.UserName, isDualAccount);
}
if (user.Status == AccountStatus.Inactive)
{
//Account Re-Activation Logic
if (_usersManagementService.CreateAccountHistory(user))
{
user.FirstLogonOn = DateTime.Now;
user.DeactivatedOn = null;
user.Status = AccountStatus.Active;
user.IsDualAccount = isDualAccount;
_usersManagementService.UpdateAccount(user);
#region "Check XXX Dual Account"
try
{
if (_webHttpContext.Session.MultipleAccountDialogueInformed == false)
{
_webHttpContext.Session.MultipleAccountDialogueInformed = true;
if (user.IsDualAccount == true)
{
ViewBag.ShowXXXAccountPrompt = true;
}
else
{
ViewBag.ShowXXXAccountPrompt = false;
}
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, "XXX Account Service _ " + ex.Message, ex);
}
#endregion
}
else
{
ViewBag.IsErrored = "true";
return View(_webHttpContext.Account);
}
}
else
{
#region "Check XXX Dual Account"
try
{
if (_webHttpContext.Session.MultipleAccountDialogueInformed == false)
{
_webHttpContext.Session.MultipleAccountDialogueInformed = true;
if (user.IsDualAccount == true)
{
ViewBag.ShowXXXAccountPrompt = true;
}
else
{
ViewBag.ShowXXXAccountPrompt = false;
}
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, "XXX Account Service _ " + ex.Message, ex);
}
#endregion
}
_webHttpContext.BrowserDetails.OperatingSystem = Entities.OperatingSystem.MacinXXXh;
_webHttpContext.Session.PortalUser.Id = user.Id;
if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.Windows)
{
ViewBag.ProductType = "ZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(0);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionNT);
ViewBag.ProductId = (int)ProductType.ComputerProtectionNT;
}
else if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.MacinXXXh)
{
ViewBag.ProductType = "MacZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(1);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionOSX);
ViewBag.ProductId = (int)ProductType.ComputerProtectionOSX;
}
else if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.Other)
{
ViewBag.ProductType = "AndroidZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(2);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionAndroid);
ViewBag.ProductId = (int)ProductType.ComputerProtectionAndroid;
}
ViewBag.ZZZInstallUrl = PortalConfig.ZZZInstallUrl;
ViewBag.ScInstallUrl = PortalConfig.SafeCentralInstallUrl;
ViewBag.MacZZZInstallUrl = PortalConfig.MacZZZInstallUrl;
ViewBag.TTTTEmail = _webHttpContext.Session.PortalUser.UserName;
}
else // if primary username coming back from sso is empty
{
return RedirectToAction("signout", "Federation");
}
}
else // if the portal user is null
{
return RedirectToAction("signout", "Federation");
}
}
catch (Exception ex)
{
ViewBag.IsErrored = "true";
_logger.Log(LogLevel.Error, ex.Message, ex);
}
return View(_webHttpContext.Account);
}

Laravel Auth::atempt keeps failing

I am using this code to authenticate user with Facebook and laravel-oauth2 package. But my Auth::atempt keeps failing.(Ecos FLAG) Can someone help me see the problem ? Here is my controller function and code for my route:
Route::get('oauth/{provider}', 'HomeController#provide');
public function provide($provider)
{
$init_p = $provider;
$provider = OAuth2::provider($provider, array(
'id' => 'MY ID',
'secret' => 'MY SECRET',
));
if ( ! isset($_GET['code']))
{
return $provider->authorize();
}
else
{
try
{
$params = $provider->access($_GET['code']);
$token = new Token_Access(array(
'access_token' => $params->access_token
));
$provided_user = $provider->get_user_info($token);
if($init_p == 'facebook')
{
if (User::whereFacebookUid($provided_user['uid'])->first())
{
if(Auth::check())
{
return Redirect::to('/testovi');
}
else
{
if (Auth::attempt(array('password' => $provided_user['uid'])))
{
return Redirect::to('/testovi');
}
else
{
echo("FLAG");
}
}
}
else
{
$user = new User;
$user->name = $provided_user['name'];
$user->email = $provided_user['email'];
$user->password = $provided_user['uid'];
$user->facebook_uid = $provided_user['uid'];
$user->save();
Auth::login($user);
return Redirect::to('testovi');
}
}
}
catch (OAuth2_Exception $e)
{
show_error('That didnt work: '.$e);
}
}
}
Solution was to HASH uid befor saving id to db. Details from:
Details
$user = new User;
$user->username = $provided_user['name'];
$user->email = $provided_user['email'];
$user->password = Hash::make($provided_user['uid']);
$user->facebook_uid = $provided_user['uid'];
$user->save();
Auth::login($user);
return Redirect::to('testovi');

Zend framework $form->isValid($formData) Return invalid and I dont know why

I have a 2-steps-form (Fancy Name), but, when I submit this form, the validation return false all time, I debugged it and I receive all the parameters I want, but for some reason the isValid is false and get some error in the RadioButton element, this is the code:
This is the forms/Users.php
public function signup()
{
$contryModel = new Application_Model_Country();
$countries = $contryModel->getCountries();
foreach ($countries as $array)
{
if(isset($array['id_country'])){
$countryArr[$array['id_country']] = $array['country'];
}
}
array_unshift($countryArr, '-- Select Your Country --');
$name = new Zend_Form_Element_Text('Name');
$name->setLabel('Name')
->setRequired(true)
->addValidator('NotEmpty');
$lastname = new Zend_Form_Element_Text('LastName');
$lastname->setLabel('Last Name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('Email');
$email->setLabel('Email')
->setRequired(true)
->addValidator('NotEmpty');
$website = new Zend_Form_Element_Text('Website');
$website->setLabel('Website')
->setRequired(true)
->addValidator('NotEmpty');
$country = new Zend_Form_Element_Select('Country');
$country->setLabel('Country')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions($countryArr);
$city = new Zend_Form_Element_Select('City');
$city->setLabel('City')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions(array('-- Select Your City --'))
->setRegisterInArrayValidator(false)
->setAttrib('disabled',true);
$password = new Zend_Form_Element_Password('Password');
$password->setLabel('Password')
->setRequired(true)
->addValidator('NotEmpty');
$rpassword = new Zend_Form_Element_Password('RepeatPassword');
$rpassword->setLabel('Repeat Password')
->setRequired(true)
->addValidator('NotEmpty');
$why = new Zend_Form_Element_Textarea('Why');
$why->setRequired(true)
->addValidator('NotEmpty')
->setAttrib('cols', '50')
->setAttrib('rows', '4');
$job = new Zend_Form_Element_Text('Job');
$job->setLabel("Job")
->setRequired(true)
->addValidator('NotEmpty');
$boxes = new Application_Model_Colors();
$res = $boxes->getColors();
foreach($res as $colors){
$colorArr[$colors['id']]['color'] = $colors['color'];
$colorArr[$colors['id']]['overColor'] = $colors['overColor'];
}
$color = new Zend_Form_Element_Radio('color');
$color->setLabel('Color')
->addMultiOptions($colorArr)
->addValidator('NotEmpty');
$save = new Zend_Form_Element_Submit('Submit');
$save->setLabel('Save');
$this->addElements(array($name, $lastname, $email, $website, $password, $rpassword, $job, $country, $city, $color, $why, $save));
}
*This is a part of the view * where I format the Radios
<?php
foreach($this->form->color->options as $key=>$colors){
echo "<label><input type='radio' value='$key' name='color'><div class='registrationBoxes' style='background-color:#".$colors['color']."' data-color='".$colors['color']."' data-overColor='".$colors['overColor']."' value='".$colors['color']."'></div></label>";
}
?>
And here is the Controller
public function indexAction()
{
$form = new Application_Form_Users();
$form->signup();
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
if($form->isValid($formData))
{
$formData = $this->getRequest()->getPost();
$name = $formData['Name'];
$lastName = $formData['LastName'];
$email = $formData['Email'];
$website = $formData['Website'];
$password = $formData['Password'];
$rpassword = $formData['RepeatPassword'];
$job = $formData['Job'];
$country = $formData['Country'];
$city = $formData['City'];
$color = $formData['color'];
$why = $formData['Why'];
$date_create = date('Y-m-d H:i:s');
$position = new Application_Model_Country();
$latLong = $position->getLatLong($city);
if($password == $rpassword){
$data = array( 'name'=>$name,
'last_name'=>$lastName,
'email'=>$email,
'website'=>$website,
'password'=>md5($password),
'date_create'=>$date_create,
'job'=>$job,
'country'=>$country,
'city'=>$city,
'color'=>$color,
'why'=>$why,
'latitude'=>$latLong['latitude'],
'longitude'=>$latLong['longitude']
);
$add = new Application_Model_Users();
$res = $add->insertUser($data);
if($res){
$this->view->message = "Registration Successfuly.";
$this->_redirect("/contact");
}else{
$this->view->errorMessage = "We have a problem with your registration, please try again later.";
}
}else{
$this->view->errorMessage = "Password and confirm password don't match.";
$form->populate($formData);
}
} else {
$this->view->errorMessage = "There is an error on your registration, all fields are requried";
$form->populate($formData);
}
}
}
a die(var_dump()) return this:
array(12) {
["Name"]=>
string(9) "Some name"
["LastName"]=>
string(13) "Some lastName"
["Email"]=>
string(21) "Someemail#hotmail.com"
["Password"]=>
string(5) "Some "
["RepeatPassword"]=>
string(5) "Some "
["Website"]=>
string(12) "Some website"
["Job"]=>
string(8) "Some job"
["Country"]=>
string(1) "7"
["City"]=>
string(3) "434"
["color"]=>
string(1) "3"
["Why"]=>
string(10) "Emotional!"
["Submit"]=>
string(4) "Save"
}
As you can see, all the parameters are coming and with value, but for no reason the isValid is returning false, some idea guys?
Thanks.-
EDIT
This is a part of the Zend/form.php code required by Tonunu
public function __construct ($options = null)
{
if (is_array($options)) {
$this->setOptions($options);
} elseif ($options instanceof Zend_Config) {
$this->setConfig($options);
}
// Extensions...
$this->init();
$this->loadDefaultDecorators();
}
public function __clone ()
{
$elements = array();
foreach ($this->getElements() as $name => $element) {
$elements[] = clone $element;
}
$this->setElements($elements);
$subForms = array();
foreach ($this->getSubForms() as $name => $subForm) {
$subForms[$name] = clone $subForm;
}
$this->setSubForms($subForms);
$displayGroups = array();
foreach ($this->_displayGroups as $group) {
$clone = clone $group;
$elements = array();
foreach ($clone->getElements() as $name => $e) {
$elements[] = $this->getElement($name);
}
$clone->setElements($elements);
$displayGroups[] = $clone;
}
$this->setDisplayGroups($displayGroups);
}
public function setOptions (array $options)
{
if (isset($options['prefixPath'])) {
$this->addPrefixPaths($options['prefixPath']);
unset($options['prefixPath']);
}
if (isset($options['elementPrefixPath'])) {
$this->addElementPrefixPaths($options['elementPrefixPath']);
unset($options['elementPrefixPath']);
}
if (isset($options['displayGroupPrefixPath'])) {
$this->addDisplayGroupPrefixPaths(
$options['displayGroupPrefixPath']);
unset($options['displayGroupPrefixPath']);
}
if (isset($options['elementDecorators'])) {
$this->_elementDecorators = $options['elementDecorators'];
unset($options['elementDecorators']);
}
if (isset($options['elements'])) {
$this->setElements($options['elements']);
unset($options['elements']);
}
if (isset($options['defaultDisplayGroupClass'])) {
$this->setDefaultDisplayGroupClass(
$options['defaultDisplayGroupClass']);
unset($options['defaultDisplayGroupClass']);
}
if (isset($options['displayGroupDecorators'])) {
$displayGroupDecorators = $options['displayGroupDecorators'];
unset($options['displayGroupDecorators']);
}
if (isset($options['elementsBelongTo'])) {
$elementsBelongTo = $options['elementsBelongTo'];
unset($options['elementsBelongTo']);
}
if (isset($options['attribs'])) {
$this->addAttribs($options['attribs']);
unset($options['attribs']);
}
$forbidden = array('Options', 'Config', 'PluginLoader', 'SubForms',
'View', 'Translator', 'Attrib', 'Default');
foreach ($options as $key => $value) {
$normalized = ucfirst($key);
if (in_array($normalized, $forbidden)) {
continue;
}
$method = 'set' . $normalized;
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->setAttrib($key, $value);
}
}
if (isset($displayGroupDecorators)) {
$this->setDisplayGroupDecorators($displayGroupDecorators);
}
if (isset($elementsBelongTo)) {
$this->setElementsBelongTo($elementsBelongTo);
}
return $this;
}
In order to check if your form is valid, you have to put your data into it, using this method !
$form->setData($formData)
and then you can ask for validation
$form->isValid()
So what you need is :
$formData = $this->getRequest()->getPost();
$form->setData($formData);
if($form->isValid()){
//Blablablabla
}

Resources