Devexpress MVC datacontext - asp.net-mvc

I have a problem with the system for ordering products.
Scenario:
Two separate browsers
Two separate accounts (after logging in a separate session id)
when clicked, grouped, and enabled in the connect string MultipleActiveResultSets = true.
Users click at the same time (each has different filters set, grouping), but when the second user clicks on, the user gets the result of the first user query (different parameters)
Update
[C#]
PartialViewResult AdvancedCustomBindingCore(GridViewModel viewModel)
{
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKar(_Session));///////////////////-------------------ustawiamy do modelu zrodlo danych .....
if (Session["fulltextsearch"] == null)
{
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKar(_Session));
Session["fulltextsearch"] = null;
}
else
{
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKarFullTextSearch(_Session));
}
viewModel.ProcessCustomBinding(
GridViewCustomBindingHandlers.GetDataRowCountAdvanced,
GridViewCustomBindingHandlers.GetDataAdvanced,
GridViewCustomBindingHandlers.GetSummaryValuesAdvanced,
GridViewCustomBindingHandlers.GetGroupingInfoAdvanced,
GridViewCustomBindingHandlers.GetUniqueHeaderFilterValuesAdvanced
);
return PartialView("GridViewMgKarPartial", viewModel);
}
static GridViewModel CreateGridViewModelWithSummary()
{
var viewModel = new GridViewModel();///////////////////-------------------ustawiamy kolumny ze zrodla danych.....
viewModel.KeyFieldName = "SymKar;LogoP;JM;SymWL";
viewModel.Columns.Add("SymKar");
viewModel.Columns.Add("SymKarObcy");
viewModel.Columns.Add("OpiKar");
viewModel.Columns.Add("L_OpiKar_EN");
viewModel.Columns.Add("JM");
//////////////Jezeli ma byc niewidoczna to w cshtml tez sie musi zgadzac....czyli nie dodajemy
viewModel.Columns.Add("CenaNetto");
//////////////Jezeli ma byc niewidoczna to w cshtml tez sie musi zgadzac....czyli nie dodajemy
viewModel.Columns.Add("IloscPAL");
viewModel.Columns.Add("StanDys");
viewModel.Columns.Add("GruKar");
viewModel.Columns.Add("Waga");
viewModel.Columns.Add("LogoP");
viewModel.Columns.Add("RodzajHandlowy");
viewModel.Pager.PageSize = 20;
//viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Size", SummaryType = SummaryItemType.Sum });
//viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Subject", SummaryType = SummaryItemType.Count });
//viewModel.GroupSummary.Add(new GridViewSummaryItemState() { FieldName = string.Empty, SummaryType = SummaryItemType.Count });
return viewModel;
}
#endregion CustomBindingRoute_Settings
#region CustomBindingRoute_General
public ActionResult GridViewMgKarPartial(string selectedValues)//------------------------------------------------Ustawiamy nazwe dla View ktory powstal...........
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
Session[_SessionSelected] = selectedValues;
GridViewModel viewModel = GridViewExtension.GetViewModel(str_GridViewName);
if (viewModel == null)
viewModel = CreateGridViewModelWithSummary();
string _FilterExpression = "";
int FILTER_UserID = usr.users_ID;
if (Session["myGridStatefiltrKM"] != null)
{
var userFiltersList = iMagoDataProvider.wusr_f_GetUserFiters(FILTER_UserID, "GridView_mpid_" + menu_pozycje_ID).Where(x => x.wusr_GrdFiltMenForSessionidId == Convert.ToInt32(Session["myGridStatefiltrKM"])).ToList().OrderByDescending(m => m.DomyslnyFiltr).ThenByDescending(m => m.DateCreated);
foreach (var item in userFiltersList)
{
_FilterExpression = item.FilterExpression.ToString();
}
}
if (_FilterExpression != "")
viewModel.FilterExpression = _FilterExpression;//"StartsWith([SymKar], 'aa')";
return AdvancedCustomBindingCore(viewModel);
}
// Paging
public ActionResult AdvancedCustomBindingPagingAction(GridViewPagerState pager)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyPagingState(pager);
string _FilterExpression = "";
try
{
db.wusr_p_GetGridFilterMenuForUsers(_Session, menu_pozycje_ID, str_GridViewName, ref _FilterExpression);//Pamietaj o wpisaniu prawidlowej nazwy dla grida(unikatowego w obrebie menu)
}
catch (Exception e)
{
return ExceptionHandle(e);
}
if (_FilterExpression != "")
{
viewModel.FilterExpression = _FilterExpression;//"StartsWith([SymKar], 'aa')";
}
if (Session["fulltextsearch"] == null)
{
//var model = iMagoDataProvider.Get_f_ListaZgloszen(userSessionid, 1);
Session["fulltextsearch"] = null;
return AdvancedCustomBindingCore(viewModel);
// return PartialView("Lista", model);
}
else
{
if (Session["filtr"] != null)
{
viewModel.FilterExpression = Session["filtr"].ToString();
}
var model = Session["fulltextsearch"];
return AdvancedCustomBindingCore(viewModel);
}
// return AdvancedCustomBindingCore(viewModel);
}
// Filtering
public ActionResult AdvancedCustomBindingFilteringAction(GridViewFilteringState filteringState)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyFilteringState(filteringState);
//Zapamietujemy filtry - na okres sessji ... pozniej odczytujemy ogolne tak by przy nowej sesji zawsze byly domyslne
int FILTER_UserID = usr.users_ID;
string _FilterExpression = "";
if (Session["myGridStatefiltrKM"] != null)
{
var userFiltersList = iMagoDataProvider.wusr_f_GetUserFiters(FILTER_UserID, "GridView_mpid_" + menu_pozycje_ID).Where(x => x.wusr_GrdFiltMenForSessionidId == Convert.ToInt32(Session["myGridStatefiltrKM"])).ToList().OrderByDescending(m => m.DomyslnyFiltr).ThenByDescending(m => m.DateCreated);
foreach (var item in userFiltersList)
{
_FilterExpression = item.FilterExpression.ToString();
}
}
return AdvancedCustomBindingCore(viewModel);
}
// Sorting
public ActionResult AdvancedCustomBindingSortingAction(GridViewColumnState column, bool reset)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplySortingState(column, reset);
return AdvancedCustomBindingCore(viewModel);
}
// Grouping
public ActionResult AdvancedCustomBindingGroupingAction(GridViewColumnState column)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyGroupingState(column);
return AdvancedCustomBindingCore(viewModel);
}
Partial View
[HTML]
#{
SortedList<string, IMago.Models.model_Uprawnienia> rights = ViewBag.Rights;
}
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "GridView_mgKar";
settings.CallbackRouteValues = new { Controller = "KartotekaMaterialowa", Action = "GridViewMgKarPartial" };
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Filtr"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Filtering,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingFilteringAction" }
);
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Group"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Grouping,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingGroupingAction" }
);
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.KeyFieldName = "SymKar;LogoP;JM;SymWL";
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = false;
settings.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;
settings.Settings.ShowFooter = true;
settings.SettingsSearchPanel.Visible = false;
settings.Settings.ShowFilterRowMenuLikeItem = true;
settings.Settings.ShowHeaderFilterButton = true;
settings.EnableRowsCache = false;
settings.Styles.AlternatingRow.Enabled = DefaultBoolean.True;
settings.Styles.AlternatingRow.BackColor = System.Drawing.Color.White;
settings.Styles.Row.BackColor = System.Drawing.Color.WhiteSmoke;
settings.Styles.FocusedRow.CssClass = "EmptyFocusedRow";
settings.Styles.RowHotTrack.CssClass = "RowHover";
settings.Styles.Cell.Wrap = DefaultBoolean.False;
settings.Styles.Cell.Font.Size = FontUnit.Smaller;
settings.Styles.Header.Font.Size = FontUnit.XSmall;
settings.Styles.Header.Font.Bold = true;
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymKar"))
settings.Columns.Add(c =>
{
c.FieldName = "SymKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKar").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_Nag_Kol_pd_isstandard")) //Przy ZPW
settings.Columns.Add(column =>
{
column.FieldName = "pd_isstandard";
column.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolpd_isstandard").ToUpper();
column.Width = 20;
column.HeaderStyle.Wrap = DefaultBoolean.True;
column.ColumnType = MVCxGridViewColumnType.CheckBox;
column.ReadOnly = true;
//column.PropertiesEdit.DisplayFormatString = "c";
column.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymKarObcy"))
settings.Columns.Add(c =>
{
c.FieldName = "SymKarObcy";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKarObcy").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_OpiKar"))
settings.Columns.Add(c =>
{
c.FieldName = "OpiKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolOpikar").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_L_OpiKar_EN"))
settings.Columns.Add(c =>
{
c.FieldName = "L_OpiKar_EN";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolOpikarEn").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_JM"))
settings.Columns.Add(c =>
{
c.FieldName = "JM";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolJM").ToUpper();
c.Width = 50;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_CenaNetto"))
settings.Columns.Add(c =>
{
c.FieldName = "CenaNetto";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolCenaNetto").ToUpper();
c.PropertiesEdit.DisplayFormatString = PageHelper.N2_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymWL"))
settings.Columns.Add(c =>
{
c.FieldName = "SymWL";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymWL").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_IloscPAL"))
settings.Columns.Add(c =>
{
c.FieldName = "IloscPAL";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolIloscCalopaletowa").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N0_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_StanDys"))
settings.Columns.Add(c =>
{
c.FieldName = "StanDys";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolStanWolny").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N0_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_GruKar"))
settings.Columns.Add(c =>
{
c.FieldName = "GruKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKarGrup").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_Waga"))
settings.Columns.Add(c =>
{
c.FieldName = "Waga";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolWaga").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_LogoP"))
settings.Columns.Add(c =>
{
c.FieldName = "LogoP";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolLogoP").ToUpper();
// c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_RodzajHandlowy"))
settings.Columns.Add(c =>
{
c.FieldName = "RodzajHandlowy";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolRodzajHandlowy").ToUpper();
// c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Sort"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Sorting,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingSortingAction" }
);
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Paging,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingPagingAction" }
);
settings.EnableCallbackAnimation = false;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowSelectCheckbox = true;
settings.CommandColumn.Width = Unit.Pixel(65);
settings.SettingsBehavior.ConfirmDelete = true;
settings.SettingsBehavior.AllowFocusedRow = true;
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
settings.ClientSideEvents.EndCallback = "OnEndCallback";
settings.CustomJSProperties = (sender, e) =>
{
e.Properties["cpFilterExpression"] = (sender as MVCxGridView).FilterExpression;
MVCxGridView g = sender as MVCxGridView;
Dictionary<int, object> dict = new Dictionary<int, object>();
int startIndex = g.PageIndex * g.SettingsPager.PageSize;
int endIndex = startIndex + g.SettingsPager.PageSize;
int kluczpomocny = 0;
for (int i = startIndex; i < endIndex; i++)
{
string klucz = g.GetRowValues(i, "SymKar") + "|" + g.GetRowValues(i, "LogoP") + "|" + g.GetRowValues(i, "JM") + "|" + g.GetRowValues(i, "SymWL");
dict[kluczpomocny] = klucz + "<|>" + g.GetRowValues(i, "LogoP") + "<|>" + g.GetRowValues(i, "JM") + "<|>" + g.GetRowValues(i, "SymWL") + "<|>" + g.GetRowValues(i, "CenaNetto")+"<|>"+ g.GetRowValues(i, "SymKar");
kluczpomocny++;
}
e.Properties["cpData"]=dict;
};
}).BindToCustomData(Model).GetHtml()

official reply from DevExpress:
"Thank you for the sample project and database backup. I was able to reproduce both issues on my side. I also analyzed how your data layer works when this behavior is reproducible and now I see what causes the issue: you are placing an IQueriable model instance in a static field which is shared among different requests.
As far as I understand, you used the code for the helper class from our Custom Data Binding (Advanced) demo. In this demo, the data source can't be different: a query is always executed on the non-parameterized Emails data set. That's why we put it in a static property.
In your case, the static Model property will not work correctly for multiple concurrent requests. On each request, you are changing an IQueriable instance to a user-specific parameterized query. Due to the fact that an IQueriable instance uses the lazy-loading feature, a query is only executed when the ToList method is invoked (it is done internally in the GridView extension code). That's why you may encounter a situation when the following scenario occurs: you set a model for Grid1 and start building a database query in the GetDataAdvanced method, but at that time, Grid2 set its own model. Thus, substituting the model (the parameterized query to a stored procedure) of the first SQL query built by Grid1.
To fix this issue, I suggest that you make the GridViewCustomBindingHandlers class non-static and create an instance of this class for each controller. This will resolve the issue with the same data for two different users. Make sure that the 'MultipleActiveResultSets' parameter in the connection string is set to 'True'. I demonstrated the implementation of this approach in the updated sample project in the attachment.
Regarding the code in our demo: I described why we implemented it in this way above. However, our implementation in the demo made you implement your own data layer incorrectly. As we try to show the best practices in our demos, the fact that our implementation caused confusion did not go unnoticed. I passed the information regarding your scenario to the team for discussion. This will help us implement better demos/examples in the future or update the existing ones."

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

Value cannot be null. Parameter name DropdownList in ASP. NET CORE

I have a problem in mi code, when show the error message appears the message of the title
This is the code of my form Register
<div class="form-group col-md-6">
#if (!Model.MODEL_PACIENTE.PAC_ID.Equals(0))
{
<label>Comuna:</label>
#Html.DropDownList("MODEL_PACIENTE.PAC_COMUNA", new SelectList(Model.MODEL_PACIENTE.Comuna_Lista, "Text", "Text"),
new { #class = "form-control" })
}
else
{
<label>Comuna:</label>
#Html.DropDownList("MODEL_PACIENTE.PAC_COMUNA", new SelectList(Model.MODEL_PACIENTE.Comuna_Lista, "Text", "Text"),
"ESCOGA UNA COMUNA", new { #class = "form-control" }) // HERE IS THE ERROR WHEN MY DNI IS REGISTER IN THE BD }
<span asp-validation-for="MODEL_PACIENTE.PAC_COMUNA" class="text-danger"></span>
</div>
Code of my class GetOdontologo
public List<SelectListItem> GetOdontologo(ApplicationDbContext context)
{
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
context.TBL_ODONTOLOGO.ToList().ForEach(item =>
{
selectListItems.Add(new SelectListItem
{
Value = item.ODONT_ID.ToString(),
// Text = item.ODONT_CODIGO
Text = item.ODONT_CODIGO + '-' + item.ODONT_APELLIDO + ' ' + item.ODONT_NOMBRE
});
});
}
catch (Exception ex)
{
Console.WriteLine($"Error: '{ex}'");
}
return selectListItems;
}
This is the class GetComuna
public List<SelectListItem> GetComuna(ApplicationDbContext context)
{
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
context.TBL_PROVINCIA.ToList().ForEach(item =>
{
selectListItems.Add(new SelectListItem
{
Value = item.PROV_ID.ToString(),
Text = item.PROV_NOMBRE
});
});
}
catch (Exception ex)
{
Console.WriteLine($"Error: '{ex}'");
}
return selectListItems;
}
And this the code of my method "onget"
public void OnGet(int idActPac)
{
_DataPac2 = null;
if(idActPac.Equals(0))
{
_DataPac2 = null;
}
if (_dataInput != null || _DataPac1 != null || _DataPac2 != null)
{
if (_dataInput != null)
{
MODEL_PACIENTE = _dataInput;
MODEL_PACIENTE.AvatarImage = null;
}
else
{
if (_DataPac1 != null || _DataPac2 != null)
{
if (_DataPac2 != null)
_DataPac1 = _DataPac2;
MODEL_PACIENTE = new PACIENTE
{
PAC_ID = _DataPac1.PAC_ID,
PAC_NOMBRE = _DataPac1.PAC_NOMBRE,
PAC_APELLIDO = _DataPac1.PAC_APELLIDO,
PAC_CODIGO = _DataPac1.PAC_CODIGO,
PAC_EDAD = _DataPac1.PAC_EDAD,
PAC_COD_ODONT = _DataPac1.PAC_COD_ODONT,
PAC_COMUNA = _DataPac1.PAC_COMUNA,
PAC_CORREO = _DataPac1.PAC_CORREO,
PAC_DIRECCION = _DataPac1.PAC_DIRECCION,
PAC_OBSERVACIONES = _DataPac1.PAC_OBSERVACIONES,
PAC_OTRAS_COMUNAS = _DataPac1.PAC_OTRAS_COMUNAS,
PAC_CONVENIO = _DataPac1.PAC_CONVENIO,
PAC_PREVISIONES = _DataPac1.PAC_PREVISIONES,
PAC_REPRESENTANTE = _DataPac1.PAC_REPRESENTANTE,
PAC_RUT = _DataPac1.PAC_RUT,
PAC_SEXO = _DataPac1.PAC_SEXO,
PAC_TELEFONO = _DataPac1.PAC_TELEFONO,
PAC_FECHA_NAC = _DataPac1.PAC_FECHA_NAC,
PAC_FEC_ACT = _DataPac1.PAC_FEC_ACT,
PAC_FEC_REG = _DataPac1.PAC_FEC_REG,
PAC_IMAGEN = _DataPac1.PAC_IMAGEN,
//AL USAR EL METODO ACTUALIZAR AL CARGAR LOS DATOS EN LOS INPUT NO OLVIDAR QUE SE DEBE CARGAR
//NUEVAMENTE LOS DropDownList LLAMANDOLO NUEVAMENTE AL FINAL COMO SE VE EN EL CODIGO A CONTINUACION
Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
Odontologo_Lista = _lOdontologo.GetOdontologo(_context)
};
if (_dataInput != null)
{
MODEL_PACIENTE.ErrorMessage = _dataInput.ErrorMessage;
}
}
}
}
else
{
var Cod_Pac = 0;
String TempCodPac = null;
var Ultimo_Paciente = (from t in _context.TBL_PACIENTE
orderby t.PAC_CODIGO
select t).LastOrDefault();
if (Ultimo_Paciente != null)
{
Cod_Pac = (Ultimo_Paciente.PAC_CODIGO != null) ?
Convert.ToInt32(Ultimo_Paciente.PAC_CODIGO) + 1 :
1;
if (Cod_Pac < 10)
{
TempCodPac = String.Concat("0000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 10 && Cod_Pac <= 11)
{
TempCodPac = String.Concat("000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 10 && Cod_Pac < 100)
{
TempCodPac = String.Concat("000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 100 && Cod_Pac <=101)
{
TempCodPac = String.Concat("00", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 100 && Cod_Pac < 1000)
{
TempCodPac = String.Concat("00", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 1000 && Cod_Pac <= 1001)
{
TempCodPac = String.Concat("0", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 1000 && Cod_Pac <= 9999)
{
TempCodPac = String.Concat("0", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 9999 && Cod_Pac < 99999)
{
TempCodPac = String.Concat("", Convert.ToString(Cod_Pac));
}
}
MODEL_PACIENTE = new PACIENTE
{
PAC_CODIGO = TempCodPac,
Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
Odontologo_Lista = _lOdontologo.GetOdontologo(_context),
PAC_COD_ODONT = "00000"
};
}
_DataPac2 = _DataPac1;
_DataPac1 = null;
}
The code of my method Save_Patient
private async Task<bool> Guardar_Paciente_Async()
{
_dataInput = MODEL_PACIENTE;
var valor = false;
if (ModelState.IsValid)
{
var PacLista = _context.TBL_PACIENTE.Where(u => u.PAC_RUT.Equals(MODEL_PACIENTE.PAC_RUT)).ToList();
if (PacLista.Count.Equals(0))
{
var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var imagenByte = await _lCargarImagen.ByteAvatarImageAsync(MODEL_PACIENTE.AvatarImage, _environment, "images/user_icon.png");
string TmpCodPac = _dataInput.PAC_COD_ODONT;
String vfCodPac = TmpCodPac.Substring(0, 4);
var Nuevo_Paciente = new MODELO_PACIENTE
{
PAC_CODIGO = _dataInput.PAC_CODIGO,
PAC_NOMBRE = _dataInput.PAC_NOMBRE.ToUpper(),
PAC_APELLIDO = _dataInput.PAC_APELLIDO.ToUpper(),
PAC_SEXO = _dataInput.PAC_SEXO,
PAC_RUT = _dataInput.PAC_RUT,
PAC_FECHA_NAC = _dataInput.PAC_FECHA_NAC,
PAC_EDAD = _dataInput.PAC_EDAD,
PAC_REPRESENTANTE = _dataInput.PAC_REPRESENTANTE?.ToUpper(),
PAC_DIRECCION = _dataInput.PAC_DIRECCION?.ToUpper(),
PAC_COMUNA = _dataInput.PAC_COMUNA?.ToUpper(),
PAC_OTRAS_COMUNAS = _dataInput.PAC_OTRAS_COMUNAS?.ToUpper(),
PAC_TELEFONO = _dataInput.PAC_TELEFONO,
PAC_CORREO = _dataInput.PAC_CORREO,
PAC_CONVENIO = _dataInput.PAC_CONVENIO?.ToUpper(),
PAC_PREVISIONES = _dataInput.PAC_PREVISIONES?.ToUpper(),
PAC_OBSERVACIONES = _dataInput.PAC_OBSERVACIONES?.ToUpper(),
PAC_COD_ODONT = vfCodPac,
PAC_IMAGEN = imagenByte,
PAC_FEC_REG = DateTime.Now,
PAC_FEC_ACT = DateTime.Now
};
await _context.AddAsync(Nuevo_Paciente);
_context.SaveChanges();
transaction.Commit();
_dataInput = null;
valor = true;
}
catch (Exception ex)
{
_dataInput.ErrorMessage = ex.Message;
transaction.Rollback();
valor = false;
}
}
});
}
else
{
_dataInput.ErrorMessage = $"El RUT {MODEL_PACIENTE.PAC_RUT} ya se encuentra Registrado";
// It should show this error in the respective "input", but the error message you see below in the image appears
}
}
else
{
foreach (var modelState in ModelState.Values)
{
foreach (var error in modelState.Errors)
{
_dataInput.ErrorMessage += error.ErrorMessage;
}
}
valor = false;
}
return valor;
}
If I debug, when I start it loads the 2 records from the dentist table, but when I put the existing ID at the time of appearing the error message appears what is seen in the image and when trying to load the list again it comes out null
After checking the ID error, the "Odontologia Lista" method returns null and the title error appears
where is the problem ?, I appreciate your help or guide to solve this problem.
You can try to check the following code:
MODEL_PACIENTE = new PACIENTE
{
PAC_CODIGO = TempCodPac,
//Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
//Odontologo_Lista = _lOdontologo.GetOdontologo(_context),
PAC_COD_ODONT = "00000"
};
Odontologo_Lista = _lOdontologo.GetOdontologo(_context), is commented.If _dataInput == null && _DataPac1 == null && _DataPac2 == null,the Odontologo_Lista will not be set,and you will get the error Value cannot be null.

Using the generic type 'PagedList.StaticPagedList<T>' requires 1 type arguments

I am working on user roles using Asp.net MVC. I am stuck while working on Admin section. I have mentioned one question above and the second question is similar which is Using the generic type 'System.Collections.Generic.List' requires 1 type arguments
Here is my code.
public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
{
try
{
int intPage = 1;
int intPageSize = 5;
int intTotalPageCount = 0;
if (searchStringUserNameOrEmail != null)
{
intPage = 1;
}
else
{
if (currentFilter != null)
{
searchStringUserNameOrEmail = currentFilter;
intPage = page ?? 1;
}
else
{
searchStringUserNameOrEmail = "";
intPage = page ?? 1;
}
}
ViewBag.CurrentFilter = searchStringUserNameOrEmail;
List col_UserDTO = new List();
int intSkip = (intPage - 1) * intPageSize;
intTotalPageCount = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.Count();
var result = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.OrderBy(x => x.UserName)
.Skip(intSkip)
.Take(intPageSize)
.ToList();
foreach (var item in result)
{
ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
objUserDTO.UserName = item.UserName;
objUserDTO.Email = item.Email;
objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
col_UserDTO.Add(objUserDTO);
}
// Set the number of pages
// Error appears here
var _UserDTOAsIPagedList =
new StaticPagedList
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
return View(_UserDTOAsIPagedList);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
List col_UserDTO = new List(); // Error appears here
return View(col_UserDTO.ToPagedList(1, 25));
}
}
#endregion
`
StaticPagedList is generic. You need to supply the type of collection(for col_UserDTO), in your case List:
var _UserDTOAsIPagedList =
new StaticPagedList<List<ExpandedUserDTO>>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
See http://www.programering.com/a/MTN2gDNwATM.html
You may need to change List col_UserDTO references to List<ExpandedUserDTO> col_UserDTO
Use this instead
var _UserDTOAsIPagedList =
new StaticPagedList<ExpandedUserDTO>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);

how to use CRUD operation in MVC using class library and Entityframework

My Controller in which there are different actions for different views
// GET: Employee
public ActionResult Index)
{
List<EmployeeViewModel> Employees = null;
Employees = _DaoEmployee.FindAll();
ViewData["model"] = Employees;
return View(Employees);
}
public ActionResult Details(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
employee emp = _DaoEmployee.ViewEmployee(id);
return View(emp);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
return View();
}
// POST: Employee
[HttpPost]
// public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
// public ActionResult Create(employee emp, HttpPostedFileBase file)
public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
{
string path = null;
emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.createddate = DateTime.Now;
emp.updatedby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.updateddate = DateTime.Now;
int empid = _DaoEmployee.AddEmployee(emp);
if (empid == -1)
{
return HttpNotFound();
}
if (empid >= 1)
{
//Insert User
// string image = System.IO.Path.GetFileName(file.FileName);
if (file != null)
{
var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
path = Server.MapPath("~/Content/images/" + newPath);
file.SaveAs(path);
}
string sub = "Your Password";
cms_user u = new cms_user();
u.user_name = emp.emp_name;
u.user_image = path;
u.user_email = emp.email;
u.user_password = RandomPassword.CreatePassword();
u.entity_id = empid;
u.entity_type = "Employee";
u.user_description = emp.comment;
var pass = "Your Password is " + u.user_password;
bool result = _DaoUser.AddUser(u);
if (result == true)
{
emp_performance ep = new emp_performance();
var designation = _DaoEmployee.GetEmployeeDesignationName(emp.desig_id);
ep.emp_perf_des = "Start Working As " + designation;
ep.emp_perf_date = DateTime.Now;
ep.emp_id = empid;
bool res = _DaoEmployee.AddEmployeePerformance(ep);
if (res == true)
{
await Email.sendEmail(u.user_name, u.user_email, pass, sub);
TempData["add"] = emp.emp_name + " is Added and Email Sent Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
TempData["add"] = emp.emp_name + " is Added Succesfully But Email Not Sent !!!";
return RedirectToAction("Index", "Employee");
}
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
//Get
[HttpGet]
public ActionResult Edit(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
employee emp = _DaoEmployee.FindEmployee(id);
if (emp != null)
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
return View(emp);
}
else
return HttpNotFound();
}
// POST: Employee
[HttpPost]
public ActionResult Edit(employee emp)
{
var id = emp.emp_id;
emp.email = "example#gmail.com";
emp.updatedby = emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.updateddate = DateTime.Now;
bool result = _DaoEmployee.EditEmployee(emp);
if (result == true)
{
TempData["update"] = emp.emp_name + " is Updated Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
TempData["error"] = "Error !!! Employee is not Updated";
return View();
}
}
// DELETE: Employee
public ActionResult Delete(int id)
{
var name = _db.employees.FirstOrDefault(q => q.emp_id == id).emp_name;
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
else
{
if (id != 0)
{
bool result = _DaoEmployee.DeleteEmployee(id);
if (result == true)
{
TempData["delete"] = name + " is Deleted Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
}
}
TempData["error"] = "Error !!! User is not Deleted";
return RedirectToAction("Index", "Employee");
}
//protected override void Dispose(bool disposing)
//{
// if (disposing)
// {
// _db.Dispose();
// }
// base.Dispose(disposing);
//}
public ActionResult Profile()
{
if (!Sessions.IsEmployeeLoggedIn())
{
return View();
}
int user_id = Convert.ToInt32(Sessions.GetSession()[0]);
int id = Convert.ToInt32(Sessions.GetSession()[5]);
ViewBag.user_password = _db.cms_user.FirstOrDefault(q => q.user_id == user_id).user_password;
cms_user user = _DaoUser.FindUser(id);
//Get employee perfomance history from tbl performance
List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
ViewData["JoBHistory"] = emp_his;
//Attendance Of Employee
List<attendance> att = _DaoAttendance.FindById(id);
ViewData["attendance"] = att;
//Projects on which employee working
List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
ViewData["projteam"] = team;
//Get Employee Designation from tbl emp
int designation = _DaoEmployee.GetEmployeeDesignation(id);
ViewBag.EmployeeDesignation = _DaoEmployee.GetEmployeeDesignationName(designation);
employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
return View(emp);
}
public ActionResult Dashboard()
{
if (!Sessions.IsAdminLoggedIn())
{
return View();
}
ViewBag.image = Sessions.GetSession()[2];
int id = Convert.ToInt32(Sessions.GetSession()[5]);
employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
return View(emp);
}
public ActionResult ViewAttendance(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
List<attendance> att = _DaoAttendance.FindById(id);
if (att != null)
{
return View(att);
}
else
return HttpNotFound();
}
public ActionResult ViewProjects(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
ViewData["projteam"] = team;
if (team != null)
{
return View();
}
else
return HttpNotFound();
return View();
}
public ActionResult JobHistory(int id)
{
List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
ViewData["model"] = emp_his;
return View(emp_his);
}
public ActionResult AddDesignation()
{
string desg = Request.Form["emp_desg"];
bool result = _DaoEmployee.AddDesignation(desg);
if (result == true)
{
return RedirectToAction("Dashboard", "Employee");
}
else
return HttpNotFound();
}
public ActionResult DesignationList(int Id)
{
if (Id == 1)
{
IEnumerable<emp_status> status = _db.emp_status.ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
status,
"emp_status_id",
"emp_status_name"), JsonRequestBehavior.AllowGet
);
return View(status);
}
if (Id == 2)
{
IEnumerable<designation> status = _db.designations.ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
status,
"desg_id",
"desg_name"), JsonRequestBehavior.AllowGet
);
return View(status);
}
return View("Index");
}
[HttpPost]
public ActionResult MarkAttendance(attendance att)
{
att.Date = DateTime.Now;
int Id = Convert.ToInt32(Sessions.GetSession()[5]);
att.emp_id = Id;
bool result = _DaoAttendance.AddEmployeeAttendance(att);
if (result == true)
{
return RedirectToAction("Profile", "Employee");
}
else
{
return RedirectToAction("Profile", "Employee");
}
}
public ActionResult EditUser(cms_user user, HttpPostedFileBase file)
{
string path = Sessions.GetSession()[3];
if (file != null)
{
var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
path = Server.MapPath("~/Content/images/" + newPath);
file.SaveAs(path);
}
user.user_image = path;
user.user_id = Convert.ToInt32(Sessions.GetSession()[0]);
user.entity_id = Convert.ToInt32(Sessions.GetSession()[5]);
user.entity_type = Sessions.GetSession()[4];
//user.user_description = Request.Form["user_description"];
bool result = _DaoUser.EditUser(user);
if (result == true)
{
return RedirectToAction("Profile", "Employee");
}
else
{
return RedirectToAction("Profile", "Employee");
}
}
public ActionResult AddPerformance(emp_performance ep)
{
var name = _db.employees.FirstOrDefault(q => q.emp_id == ep.emp_id).emp_name;
ep.emp_perf_date = DateTime.Now;
bool result = _DaoEmployee.AddEmployeePerformance(ep);
if (result == true)
{
TempData["add"] = "Perfomnace of " + name + " Added Successfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
TempData["error"] = "Error !!! Employee Performance is not Added";
return RedirectToAction("Index", "Employee");
}
}
}
Class Libraray Class
public class DaoEmployee
{
CmsdbEntities _db = new CmsdbEntities();
public List<EntityFramework.employee> FindAllEmployee()
{
try
{
var records = from r in _db.employees
select r;
return records.ToList();
}
catch (Exception ex)
{
return new List<EntityFramework.employee>();
}
}
public List<EmployeeViewModel> FindAll()
{
try
{
// Should be check by directly assigning
// the List<employeeV> or IEnumerable<employeeV>
var records = (from r in _db.employees
select new
{
r.emp_id,
r.emp_name,
r.emp_contactno,
r.emp_dob,
r.emp_salary,
r.emp_joindate,
r.emp_address,
emp_designation = _db.designations.FirstOrDefault(q => q.desg_id == r.desig_id).desg_name,
emp_status = _db.emp_status.FirstOrDefault(q => q.emp_status_id == r.emp_status_id).emp_status_name,
createdbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.createdby).user_name,
r.createddate,
updateddbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.updatedby).user_name,
r.updateddate
}).ToList();
List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
foreach (var record in records)
{
EmployeeViewModel employee = new EmployeeViewModel();
employee.emp_id = record.emp_id;
employee.emp_name = record.emp_name;
employee.emp_contactno = record.emp_contactno;
employee.emp_dob = record.emp_dob;
employee.emp_salary = record.emp_salary;
employee.emp_joindate = record.emp_joindate;
employee.emp_address = record.emp_address;
employee.emp_designation = record.emp_designation;
employee.emp_status = record.emp_status;
employee.createdbyName = record.createdbyName;
employee.createddate = record.createddate;
employee.updatedbyName = record.updateddbyName;
employee.updateddate = record.updateddate;
employees.Add(employee);
}
return employees;
}
catch (Exception ex)
{
return new List<EmployeeViewModel>();
}
}
public List<ProjectViewModel> FindProjectsByStatus(int j)
{
throw new NotImplementedException();
}
public bool CheckEmployeePerformance(int empid, int projid)
{
try
{
var record = from r in _db.emp_performance
where r.emp_id == empid && r.proj_id == projid
select r;
if (record != null)
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
public object GetEmployeeDesignationName(int? desig_id)
{
return _db.designations.FirstOrDefault(a => a.desg_id == desig_id).desg_name;
}
public employee FindEmployee(int id)
{
return _db.employees.Find(id);
}
public bool EditEmployee(employee emp)
{
try
{
_db.Entry(emp).State = EntityState.Modified;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public int AddEmployee(employee emp)
{
try
{
_db.Entry(emp).State = EntityState.Added;
_db.SaveChanges();
return emp.emp_id;
}
catch (Exception ex)
{
return -1;
}
}
public employee ViewEmployee(int id)
{
return _db.employees.Find(id);
}
public bool DeleteEmployee(int id)
{
try
{
employee emp = _db.employees.Find(id);
_db.employees.Remove(emp);
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool AddEmployeePerformance(emp_performance ep)
{
try
{
_db.Entry(ep).State = EntityState.Added;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public List<emp_performance> FindHistory(int id)
{
try
{
var records = from r in _db.emp_performance
where r.emp_id == id
select r;
return records.ToList();
}
catch (Exception ex)
{
return new List<emp_performance>();
}
}
public bool AddDesignation(string desg)
{
designation d = new designation();
d.desg_name = desg;
try
{
_db.Entry(d).State = EntityState.Added;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public dynamic GetEmployeeDesignation(int id)
{
int? desig = _db.employees.FirstOrDefault(u => u.emp_id == id).desig_id;
return desig;
}
public dynamic GetEmployeeDesignationName(int designation)
{
string desig = _db.designations.Where(u => u.desg_id == designation).FirstOrDefault().desg_name;
return desig;
}
}
What is the benefits of using class library classes, Can anyone explain?

Dev Express Mvc Editing GridViewSetting error?

my code is too long so sorry :)
#model IEnumerable<Osos11.Models.Customers>
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvEditing";
settings.KeyFieldName = "sno";
settings.CallbackRouteValues = new { Controller = "Customer", Action = "EditingPartial" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Columns.Add(column =>
{
column.Caption = "#";
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("Edit", "EditingEdit", new { sno = DataBinder.Eval(c.DataItem, "sno") }) + " " +
Html.ActionLink("Delete", "EditingDelete", new { sno = DataBinder.Eval(c.DataItem, "sno") },
new { onclick = "return confirm('Do you really want to delete this record?')" })
);
});
column.SetHeaderTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("New", "EditingEdit", new { sno = -1 }).ToHtmlString()
);
});
column.Settings.AllowDragDrop = DefaultBoolean.False;
column.Settings.AllowSort = DefaultBoolean.False;
column.Width = 70;
});
settings.Columns.Add("Name");
//settings.Columns.Add(column =>
//{
// column.FieldName = "CategoryID";
// column.Caption = "Category";
// column.ColumnType = MVCxGridViewColumnType.ComboBox;
// var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
// comboBoxProperties.DataSource = NorthwindDataProvider.GetCategories();
// comboBoxProperties.TextField = "CategoryName";
// comboBoxProperties.ValueField = "CategoryID";
// comboBoxProperties.ValueType = typeof(int);
//});
settings.Columns.Add("CustomerNumber");
//settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
//settings.Columns.Add("UnitsInStock");
//settings.Columns.Add("Discontinued", MVCxGridViewColumnType.CheckBox);
settings.ClientLayout = (s, e) =>
{
if (e.LayoutMode == ClientLayoutMode.Loading)
{
if (Session["GridState"] != null)
e.LayoutData = (string)Session["GridState"];
}
else
Session["GridState"] = e.LayoutData;
};
settings.PreRender = (s, e) =>
{
if (ViewData["VisibleID"] == null) return;
ASPxGridView grid = (ASPxGridView)s;
grid.MakeRowVisible(ViewData["VisibleID"]);
};
}).Bind(Model).GetHtml()
I got this error
Compiler Error Message: CS1660: Cannot convert lambda expression to type 'DevExpress.Web.Mvc.GridViewSettings' because it is not a delegate type
It seems that this issue is caused by the fact that any expression in the GridView's definition is not valid.
As a result, the entire GridView's definition (lambda expression) cannot be recognized by the View Engine.

Resources