title: How to create multiple configuration in Zerotouch? Configuration need enrollment token. Do we need multiple enrollment tokens for creating config?
body: <p>Get Method of HardwarePolicy</p>
  <pre><code>    [HttpGet]
      [CustomAuthorization]
      public IActionResult PolicyManagement(string profileType)
      {
          try
          {
              #region ResellerServiceAccountEMMOAuthCred
              ServiceAccountCredential? credential;
              string fileName = &quot;service_account_key.json&quot;;
              string path = Path.Combine(this.Environment.WebRootPath, &quot;ZeroTouchCredJSON&quot;, 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 = &quot;&quot;;
              //fetch two profile types (Fully Manged &amp; Work)
              dto.ProfileTypeList = _iAdminMapper.GetProfileTypeList();
              //fetch LoggedIn user info
              var loggedInUserEmail = HttpContext.Session.GetString(&quot;LoggedInUserName&quot;);
              var loggedInUserId = HttpContext.Session.GetString(&quot;LoggedInUserId&quot;);
  
              //fetch enterprises based on loggedInUser
              var enterprisesRes = _iEmmMapper.GetEnterprises().Where(x =&gt; x.AdminIdentityId == loggedInUserId).FirstOrDefault();
  
              //get enterprise data based on loggedIn user google account
              var enterpriseDatax = _iEmmMapper.GetEnterprises().Where(x =&gt; 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(&quot;enterprises/{0}&quot;, enterpriseDatax.EnterpriseId);
  
                  //Fetch Current PolicyName
                  var myPolicyDatax = _iEmmMapper.GetCommonPolicies().Where(x =&gt; x.EnterpriseId == enterpriseDatax.EnterpriseId &amp;&amp; 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 =&gt; x.EnterpriseId == enterpriseDatax.EnterpriseId &amp;&amp; x.PolicyProfileType == profileType &amp;&amp; x.PolicyType == ResourceMsg.Default).FirstOrDefault();
                  if (policyData != null)
                  {
                      policyId = policyData.PolicyId;
  
                      //managedplaystore
                      List&lt;string&gt; featuresList = new()
                      {
                          ResourceMsg.PLAY_SEARCH
                      };
  
                      //create web token for managed Google Play web UI; need reseller creds to generated token
                      var ParentFrameUrl = _iConfiguration.GetValue&lt;string&gt;(&quot;AppSetting:ParentFrameUrl&quot;);
                      WebToken webTokenInfo = service.Enterprises.WebTokens.Create(new DemoWebToken()
                                              .SetParentFrameUrl(ParentFrameUrl)
                                              .SetEnabledFeatures(featuresList), enterpriseNameFormat)
                                              .Execute();
                      var webToken = webTokenInfo.Value;
                      TempData[&quot;WebToken&quot;] = webToken;
  
                      //hardwaresettings
                      var result = _iEmmMapper.GetCommonPolicies().Where(x =&gt; x.PolicyId == policyId &amp;&amp; x.PolicyType == ResourceMsg.Default).FirstOrDefault();
  
                      //applicationsettings | based on profileType
                      var resAppmodel = _iEmmMapper.GetApplicationPolicies().OrderByDescending(x =&gt; x.Id).FirstOrDefault(x =&gt; x.PolicyId == policyId);
  
                      //devicesettings
                      var resDevicemodel = _iEmmMapper.GetDevicePolicies().Where(x =&gt; x.EnterpriseId == enterpriseDatax.EnterpriseId &amp;&amp; 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 = &quot;&quot;,
                                  PackageName = resDevicemodel != null? resDevicemodel.PackageName: &quot;&quot;,
                                  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[&quot;PolicyApplied&quot;] = TempData[&quot;PolicyApplied&quot;];
                              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[&quot;PolicyApplied&quot;] = TempData[&quot;PolicyApplied&quot;];
              return View(dto);
          }
          catch (Exception ex)
          {
              _loggerManager.LogError($&quot;Something went wrong inside CommonPolicies get action: {ex.Message}&quot;);
              return View(new CommonPoliciesDto());
          }
      }
  </code></pre>
  <p>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;</p>
  <pre><code>            //fetch UserIdentityId
              var userLoggedId = _iEmmMapper.GetEnterprises().Where(x=&gt; x.EnterpriseId == commonPolicies.MyEnterpriseId).Select(x =&gt; x.AdminIdentityId).FirstOrDefault();
              if(userLoggedId != null)
              {
                  commonPolicies.UserIdentityId = userLoggedId;
              }
  
              #region ResellerServiceAccountEMMOAuthCred
              //read service a/c creds
              ServiceAccountCredential? credential;
              string fileName = &quot;service_account_key.json&quot;;
              string path = Path.Combine(this.Environment.WebRootPath, &quot;ZeroTouchCredJSON&quot;, 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(&quot;PackageName&quot;);
              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 &gt; 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 + &quot;_&quot;;
                          }
                          myPolicyId = myPolicyId.Remove(myPolicyId.Length - 1, 1);
                          //Console.WriteLine(myPolicyId);
                      }
                      else
                      {
                          myPolicyId = myPolicyName;
                          //Console.WriteLine(test);
                      }
                      #endregion
  
                      var entepriseParent = string.Format(&quot;enterprises/{0}&quot;, commonPolicies.MyEnterpriseId);
                      var policyName = string.Format(&quot;{0}/policies/{1}&quot;, 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 =&gt; x.PolicyName.ToUpper() == commonPolicies.PolicyName.ToUpper().Trim() &amp;&amp; x.PolicyId == myPolicyId &amp;&amp; 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[&quot;Failure&quot;] = ResourceMsg.PolicyNameAlreadyExist;
                              string msgErr = &quot;Error in &quot; + this.GetType().ToString();
                              _loggerManager.LogError($&quot;{msgErr}{ResourceMsg.PolicyNameAlreadyExist}&quot;);
                              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 = &quot;&quot;;
                              commonPolicies.PolicyName = commonPolicies.PolicyName;
                              commonPolicies.PolicyType = ResourceMsg.Custom;
  
                              //update into database
                              var result = _iAdminMapper.CreateUpdateHardwarePolicies(commonPolicies);
                              if (result == 0)
                              {
                                  TempData[&quot;MsgCmnPolicies&quot;] = ResourceMsg.PoliciesCreatedSuccessfully;
                              }
                              else
                              {
                                  //this msg need to be removed
                                  if (result == 1)
                                  {
                                      TempData[&quot;MsgCmnPolicies&quot;] = 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[&quot;MsgCmnPolicies&quot;] = ResourceMsg.PoliciesCreatedSuccessfully;
                          }
                          else
                          {
                              if (result == 1)
                              {
                                  TempData[&quot;MsgCmnPolicies&quot;] = ResourceMsg.PoliciesUpdatedSuccessfully;
                              }
                          }
                      }
                      else
                      {
                          TempData[&quot;Failure&quot;] = ResourceMsg.PolicyNameAlreadyExist;
                          string msgErr = &quot;Error in &quot; + this.GetType().ToString();
                          _loggerManager.LogError($&quot;{msgErr}{ResourceMsg.PolicyNameAlreadyExist}&quot;);
                      }
  
                  }
                  else
                  {
                      TempData[&quot;Failure&quot;] = ResourceMsg.TryAgainContactTechnicalTeam;
                      string msgErr = &quot;Error in &quot; + this.GetType().ToString();
                      _loggerManager.LogError($&quot;{msgErr}{ResourceMsg.EnterpriseIdIsMissing}&quot;);
                  }
              }
              else
              {
                  TempData[&quot;Failure&quot;] = ResourceMsg.RequiredFieldsAreEmpty;
                  string msgErr = &quot;Error in &quot; + this.GetType().ToString();
                  _loggerManager.LogError($&quot;{msgErr}{ResourceMsg.RequiredFieldsAreEmpty}&quot;);
              }
  
              CommonPoliciesDto dto = new();
              //fetch &amp; bind two profile types (Fully Manged &amp; Work) on view
              dto.ProfileTypeList = _iAdminMapper.GetProfileTypeList();
  
              var myEnterpriseName = _iEmmMapper.GetEnterprises().Where(x =&gt; x.EnterpriseId == commonPolicies.MyEnterpriseId).Select(x =&gt; 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[&quot;Failure&quot;] = ResourceMsg.PolicyNotFoundContactTechnicalTeam;
              string msgErr = &quot;Error in &quot; + this.GetType().ToString();
              _loggerManager.LogError($&quot;{msgErr}{gex.Message}&quot;);
              return View(new EnterpriseDto());
          }
          catch (Exception ex)
          {
              TempData[&quot;Failure&quot;] = ResourceMsg.TryAgainContactTechnicalTeam;
              string msgErr = &quot;Error in &quot; + this.GetType().ToString();
              _loggerManager.LogError($&quot;{ex.Message}&quot;);
              return View();
          }
      }
  </code></pre>