public static void CleanSourceDatabase() { EclipseDatabase source = new EclipseDatabase(); BOALedgerDatabase destination = new BOALedgerDatabase(); MappingManager manager = new MappingManager(source, destination); ValidationManager validationManager = new ValidationManager(); validationManager.Validate<OrphanRecordValidation>(manager, source, destination); }
private void Form1_Load(object sender, EventArgs e) { Service1Client client = new Service1Client(); List<ProductDTO> products = client.GetProducts().ToList(); List<ProductDTO> validProducts = new List<ProductDTO>(); ValidationManager validation = new ValidationManager(); foreach (ProductDTO pr in products) { if (validation.IsValid<ProductDTO>(pr)) validProducts.Add(pr); } listBox1.DisplayMember = "ProductName"; listBox1.ValueMember = "Id"; listBox1.DataSource = validProducts; }
public void UISettingsInit() { if (ValidationManager.CheckClientInstallationPath(Settings.ClientInstallationPath)) { ValheimPlusInstalledClient = ValidationManager.CheckInstallationStatus(Settings.ClientInstallationPath); if (ValheimPlusInstalledClient) { clientInstalledLabel.Content = String.Format("ValheimPlus {0} installed on client", Settings.ValheimPlusGameClientVersion); clientInstalledLabel.Foreground = Brushes.Green; installClientButton.Content = "Reinstall ValheimPlus on client"; var modActive = File.Exists(String.Format("{0}winhttp.dll", Settings.ClientInstallationPath)); if (modActive) { enableDisableValheimPlusGameClientButton.Content = "Disable ValheimPlus"; enableDisableValheimPlusGameClientButton.Style = Application.Current.TryFindResource("MaterialDesignOutlinedButton") as Style; } else { enableDisableValheimPlusGameClientButton.Content = "Enable ValheimPlus"; enableDisableValheimPlusGameClientButton.Style = Application.Current.TryFindResource("MaterialDesignRaisedButton") as Style; } installClientButton.Visibility = Visibility.Visible; manageClientButton.Visibility = Visibility.Visible; installClientUpdateButton.Visibility = Visibility.Visible; checkClientUpdatesButtons.Visibility = Visibility.Visible; enableDisableValheimPlusGameClientButton.Visibility = Visibility.Visible; setClientPathButton.Visibility = Visibility.Hidden; } else { clientInstalledLabel.Content = "ValheimPlus not installed on client"; clientInstalledLabel.Foreground = Brushes.Red; manageClientButton.Visibility = Visibility.Hidden; installClientUpdateButton.Visibility = Visibility.Hidden; checkClientUpdatesButtons.Visibility = Visibility.Hidden; enableDisableValheimPlusGameClientButton.Visibility = Visibility.Hidden; setClientPathButton.Visibility = Visibility.Hidden; } } else { clientInstalledLabel.Content = "Valheim installation not found, select installation path by locating and choosing 'valheim.exe'"; clientInstalledLabel.Foreground = Brushes.Red; manageClientButton.Visibility = Visibility.Hidden; installClientUpdateButton.Visibility = Visibility.Hidden; checkClientUpdatesButtons.Visibility = Visibility.Hidden; enableDisableValheimPlusGameClientButton.Visibility = Visibility.Hidden; installClientButton.Visibility = Visibility.Hidden; setClientPathButton.Margin = new Thickness(16, 78, 0, 0); } if (ValidationManager.CheckServerInstallationPath(Settings.ServerInstallationPath)) { ValheimPlusInstalledServer = ValidationManager.CheckInstallationStatus(Settings.ServerInstallationPath); if (ValheimPlusInstalledServer) { serverInstalledLabel.Content = String.Format("ValheimPlus {0} installed on server", Settings.ValheimPlusServerClientVersion); serverInstalledLabel.Foreground = Brushes.Green; installServerButton.Content = "Reinstall ValheimPlus on server"; installServerButton.Visibility = Visibility.Visible; manageServerButton.Visibility = Visibility.Visible; installServerUpdateButton.Visibility = Visibility.Visible; checkServerUpdatesButton.Visibility = Visibility.Visible; setServerPathButton.Visibility = Visibility.Hidden; } else { serverInstalledLabel.Content = "ValheimPlus not installed on server"; serverInstalledLabel.Foreground = Brushes.Red; manageServerButton.Visibility = Visibility.Hidden; installServerUpdateButton.Visibility = Visibility.Hidden; checkServerUpdatesButton.Visibility = Visibility.Hidden; } } else { serverInstalledLabel.Content = "Valheim installation not found, select installation path by locating and choosing 'valheim__server.exe'"; serverInstalledLabel.Foreground = Brushes.Red; manageServerButton.Visibility = Visibility.Hidden; installServerUpdateButton.Visibility = Visibility.Hidden; checkServerUpdatesButton.Visibility = Visibility.Hidden; installServerButton.Visibility = Visibility.Hidden; setServerPathButton.Margin = new Thickness(16, 85, 0, 0); } }
public void ProcessRequest(HttpContext context) { // Negotiate with the request limiter (if enabled) if (_requestLimiter != null) { if (!_requestLimiter.ClientLimitOK(context.Request)) { // Deny request // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html context.Response.AppendHeader("Retry-After", _requestLimiter.LimiterTimeSpan.ToString()); throw new HttpException(429, "429 - Too many requests in too short timeframe. Please try again later."); } } // Enable CORS and preflight requests for saved queries // Preflight requests should also be allowed in the API (SSDHandler). if (Settings.Current.Features.SavedQuery.EnableCORS) { // Enable CORS (Cross-Origin-Resource-Sharing) context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); // Handle Preflight requests if (context.Request.HttpMethod == "OPTIONS") { context.Response.AppendHeader("Access-Control-Allow-Methods", "GET"); return; } } string queryName; var routeData = context.Items["RouteData"] as RouteData; if (routeData.Values["QueryName"] != null) { queryName = ValidationManager.GetValue(routeData.Values["QueryName"].ToString()); } else { //No query supplied goto error page. //TODO just to shut the compiler up queryName = ""; //TODO redirect throw new Exception("No query supplied"); } // ----- Handle changed output format ----- _format = GetChangedOutputFormat(routeData); // ----- Handle changed language ----- HandleChangedLanguage(); //Load saved query PCAxis.Query.SavedQuery sq = null; PXModel model = null; bool safe = true; try { if (PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.File) { string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/queries/"); if (!queryName.ToLower().EndsWith(".pxsq")) { queryName = queryName + ".pxsq"; } string[] allfiles = Directory.GetFiles(path, queryName, SearchOption.AllDirectories); if (allfiles.Length == 0) { throw new HttpException(404, "HTTP/1.1 404 Not Found "); } queryName = allfiles[0]; } //Check if the database is active. //It should not be possible to run a saved query if the database is not active sq = PCAxis.Query.SavedQueryManager.Current.Load(queryName); IEnumerable <string> db; TableSource src = sq.Sources[0]; if (src.Type.ToLower() == "cnmm") { db = PXWeb.Settings.Current.General.Databases.CnmmDatabases; } else { db = PXWeb.Settings.Current.General.Databases.PxDatabases; } bool activeDatabase = false; foreach (var item in db) { if (item.ToLower() == src.DatabaseId.ToLower()) { activeDatabase = true; break; } } if (!activeDatabase) { throw new SystemException(); } //Validate that the user has the rights to access the table string tableName = QueryHelper.GetTableName(src); //if (!AuthorizationUtil.IsAuthorized(src.DatabaseId, null, src.Source)) if (!AuthorizationUtil.IsAuthorized(src.DatabaseId, null, tableName)) //TODO: Should be dbid, menu and selection. Only works for SCB right now... (2018-11-14) { List <LinkManager.LinkItem> linkItems = new List <LinkManager.LinkItem>(); linkItems.Add(new LinkManager.LinkItem() { Key = PxUrl.LANGUAGE_KEY, Value = src.Language }); linkItems.Add(new LinkManager.LinkItem() { Key = PxUrl.DB_KEY, Value = src.DatabaseId }); linkItems.Add(new LinkManager.LinkItem() { Key = "msg", Value = "UnauthorizedTable" }); string url = LinkManager.CreateLink("~/Menu.aspx", linkItems.ToArray()); HttpContext.Current.Response.Redirect(url, false); HttpContext.Current.ApplicationInstance.CompleteRequest(); return; } if (string.IsNullOrWhiteSpace(_format)) { //Output format is not changed - use output format in the saved query _format = sq.Output.Type; } // "Pre-flight" request from MS Office application var userAgent = context.Request.Headers["User-Agent"]; //if (userAgent.ToLower().Contains("ms-office") && sq.Output.Type == PxUrl.VIEW_TABLE_IDENTIFIER) if (userAgent != null && userAgent.ToLower().Contains("ms-office")) { context.Response.Write("<html><body>ms office return</body></html>"); HttpContext.Current.ApplicationInstance.CompleteRequest(); //context.Response.End(); return; } //We need to store to be able to run workflow due to variables are referenced with name and not ids _originaleSavedQuerylanguage = sq.Sources[0].Language; // Check from saved query output type is on screen. If so createCopy shall be true, else false bool createCopy = CreateCopyOfCachedPaxiom(_format); // Create cache key string cacheKey = ""; if (_language != null) { cacheKey = string.Format("{0}_{1}", queryName, _language); } else { cacheKey = string.Format("{0}_{1}", queryName, _originaleSavedQuerylanguage); } // Handle redirects to the selection page in a special way. The model object will only contain metadata and no data if (_format.Equals(PxUrl.PAGE_SELECT)) { cacheKey = string.Format("{0}_{1}", cacheKey, PxUrl.PAGE_SELECT); } // Try to get model from cache model = PXWeb.Management.SavedQueryPaxiomCache.Current.Fetch(cacheKey, createCopy); PaxiomManager.QueryModel = PXWeb.Management.SavedQueryPaxiomCache.Current.FetchQueryModel(cacheKey, createCopy); if (model == null || PaxiomManager.QueryModel == null) { DateTime timeStamp = DateTime.Now; // Model not found in cache - load it manually model = LoadData(sq); //Check if we need to change langauge to be able to run workflow due to variables are referenced with name and not ids if (!string.IsNullOrEmpty(_language) && _language != _originaleSavedQuerylanguage) { model.Meta.SetLanguage(_originaleSavedQuerylanguage); } // No need to run workflow if we are redirecting to the selection page if (!_format.Equals(PxUrl.PAGE_SELECT)) { model = QueryHelper.RunWorkflow(sq, model); } //Set back to requested langauge after workflow operations if (!string.IsNullOrEmpty(_language) && _language != _originaleSavedQuerylanguage) { if (model.Meta.HasLanguage(_language)) { model.Meta.SetLanguage(_language); } } // Store model in cache PXWeb.Management.SavedQueryPaxiomCache.Current.Store(cacheKey, model, timeStamp); PXWeb.Management.SavedQueryPaxiomCache.Current.StoreQueryModel(cacheKey, PaxiomManager.QueryModel, timeStamp); } if (!sq.Safe) { safe = !CheckForUnsafeOperations(sq.Workflow); } } catch (Exception ex) { if ((PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.File && System.IO.File.Exists(queryName)) || (PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.Database)) { PCAxis.Query.SavedQueryManager.Current.MarkAsFailed(queryName); } throw new HttpException(404, "HTTP/1.1 404 Not Found"); //throw ex; } sq.LoadedQueryName = queryName; PCAxis.Query.SavedQueryManager.Current.MarkAsRunned(queryName); // Tell the selection page that it sholud clear the PxModel if (_format.Equals(PxUrl.PAGE_SELECT)) { HttpContext.Current.Session.Add("SelectionClearPxModel", true); } ViewSerializerCreator.GetSerializer(_format).Render(_format, sq, model, safe); }
public GrammarCompiler(ITokenizer tokenizer, IMorphAnalizer morph, IEnumerable <IExtension> extensions) { _condMan = new ConditionManager(); _valMan = new ValidationManager(); _variablesProcessor = new VariablesProcessor(tokenizer, morph, extensions); }
public static DataAccessResponseType CreateImageGroup(Account account, string imageGroupTypeNameKey, string imageGroupName) { var response = new DataAccessResponseType(); #region Validate Input #region Validate Image Group Name: ValidationResponseType ojectNameValidationResponse = ValidationManager.IsValidImageGroupName(imageGroupName); if (!ojectNameValidationResponse.isValid) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = ojectNameValidationResponse.validationMessage }); } #endregion if (String.IsNullOrEmpty(imageGroupTypeNameKey)) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "imageGroupTypeNameKey cannot be empty" }); } if (String.IsNullOrEmpty(imageGroupName)) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "imageGroupName cannot be empty" }); } #endregion #region Validate Plan Restrictions if (GetCustomImageGroupCount(account.AccountNameKey) >= account.PaymentPlan.MaxImageGroups) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "You have reached your account restriction of " + account.PaymentPlan.MaxImageGroups + " custom image groups" }); } #endregion //CREATE NAME KEY var imageGroupNameKey = Sahara.Core.Common.Methods.ObjectNames.ConvertToObjectNameKey(imageGroupName); #region Validate GroupType Exists var imageGroupTypes = GetImageFormatGroupTypes(); bool typeExists = false; foreach (ImageFormatGroupTypeModel type in imageGroupTypes) { if (type.ImageFormatGroupTypeNameKey == imageGroupTypeNameKey) { typeExists = true; } } if (!typeExists) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Format group type '" + imageGroupTypeNameKey + "' does not exists!" }); } #endregion #region Validate GroupName is unique to this type var imageFormats = GetImageFormats(account.AccountNameKey, imageGroupTypeNameKey); bool nameUniqueInType = true; foreach (ImageFormatGroupModel group in imageFormats) { if (group.ImageFormatGroupTypeNameKey == imageGroupTypeNameKey && group.ImageFormatGroupNameKey == imageGroupNameKey) { nameUniqueInType = false; } } if (!nameUniqueInType) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Group name '" + imageGroupNameKey + "' is not unique to the '" + imageGroupTypeNameKey + "' type!" }); } #endregion #region Create Model & ID var imageGroup = new ImageFormatGroupModel { ImageFormatGroupTypeNameKey = imageGroupTypeNameKey, ImageFormatGroupID = Guid.NewGuid(), ImageFormatGroupName = imageGroupName, ImageFormatGroupNameKey = imageGroupNameKey }; imageGroup.ImageFormatGroupID = Guid.NewGuid(); #endregion //INSERT response = Sql.Statements.InsertStatements.InsertImageGroup(account.SqlPartition, account.SchemaName, imageGroup); //, account.PaymentPlan.MaxImageGroups); //CLear Cache if (response.isSuccess) { Caching.InvalidateImageFormatCaches(account.AccountNameKey); } return(response); }
///// <summary> ///// 提交商检 ///// </summary> ///// <param name="sender"></param> ///// <param name="e"></param> //private void ToInspection_Click(object sender, System.Windows.RoutedEventArgs e) //{ // facades.ToInspection(vm.ProductSysNo.Value, (args) => // { // if (args) // { // CPApplication.Current.CurrentPage.Context.Window.Alert("提交商检成功!"); // CPApplication.Current.CurrentPage.Context.Window.Alert("Reload!"); // } // else // { // CPApplication.Current.CurrentPage.Context.Window.Alert("提交商检失败!"); // } // }); //} ///// <summary> ///// 提交报关 ///// </summary> ///// <param name="sender"></param> ///// <param name="e"></param> //private void ToCustoms_Click(object sender, System.Windows.RoutedEventArgs e) //{ // facades.ToCustoms(vm.ProductSysNo.Value, (args) => // { // if (args) // { // CPApplication.Current.CurrentPage.Context.Window.Alert("提交报关成功!"); // CPApplication.Current.CurrentPage.Context.Window.Alert("Reload!"); // } // else // { // CPApplication.Current.CurrentPage.Context.Window.Alert("提交报关失败!"); // } // }); //} //private void Audit_Click(object sender, System.Windows.RoutedEventArgs e) //{ // UCEntryStatusOperation addNews = new UCEntryStatusOperation(EntryStatusOperation.Audit, vm.ProductSysNo.Value); // addNews.dialog = MyWindow.ShowDialog("备案审核", addNews, (obj, args) => // { // if (args.DialogResult == DialogResultType.OK) // { // CPApplication.Current.CurrentPage.Context.Window.Alert("Reload!"); // } // }); //} //private void Inspection_Click(object sender, System.Windows.RoutedEventArgs e) //{ // UCEntryStatusOperation addNews = new UCEntryStatusOperation(EntryStatusOperation.Inspection, vm.ProductSysNo.Value); // addNews.dialog = MyWindow.ShowDialog("备案商检", addNews, (obj, args) => // { // if (args.DialogResult == DialogResultType.OK) // { // CPApplication.Current.CurrentPage.Context.Window.Alert("Reload!"); // } // }); //} //private void Customs_Click(object sender, System.Windows.RoutedEventArgs e) //{ // UCEntryStatusOperation addNews = new UCEntryStatusOperation(EntryStatusOperation.Customs, vm.ProductSysNo.Value); // addNews.dialog = MyWindow.ShowDialog("备案报关", addNews, (obj, args) => // { // if (args.DialogResult == DialogResultType.OK) // { // CPApplication.Current.CurrentPage.Context.Window.Alert("Reload!"); // } // }); //} public void Save() { ValidationManager.Validate(LayoutRootEntryInfo); Regex RtaxQty = new Regex(@"^\d{1,10}(\.\d{0,10})?$"); if (!string.IsNullOrEmpty(vm.TaxQty)) { if ((!RtaxQty.IsMatch(vm.TaxQty)) || vm.TaxQty.Trim().Length > 10) { CPApplication.Current.CurrentPage.Context.Window.Alert(string.Format("计税单位数量({0})输入错误!", vm.TaxQty)); return; } } if (!string.IsNullOrEmpty(vm.ApplyQty)) { int tempApplyQty = 0; if (!int.TryParse(vm.ApplyQty, out tempApplyQty) || vm.ApplyQty.Trim().Length > 10) { CPApplication.Current.CurrentPage.Context.Window.Alert(string.Format("申报数量({0})输入错误!", vm.ApplyQty)); return; } } Regex r1 = new Regex(@"^\d{1,8}(\.\d{1,2})?$"); if (!string.IsNullOrEmpty(vm.SuttleWeight)) { if (!r1.IsMatch(vm.SuttleWeight)) { CPApplication.Current.CurrentPage.Context.Window.Alert(string.Format("净重({0})输入错误!", vm.SuttleWeight)); return; } } if (!string.IsNullOrEmpty(vm.GrossWeight)) { if (!r1.IsMatch(vm.GrossWeight)) { CPApplication.Current.CurrentPage.Context.Window.Alert(string.Format("毛重({0})输入错误!", vm.GrossWeight)); return; } } Regex r2 = new Regex(@"^0\.[0-9]{0,2}$"); if (!string.IsNullOrEmpty(vm.TariffRate)) { if (!r2.IsMatch(vm.TariffRate)) { CPApplication.Current.CurrentPage.Context.Window.Alert(string.Format("税率({0})输入错误!", vm.TariffRate)); return; } } if (vm.ProductTradeType == TradeType.FTA) { if (string.IsNullOrWhiteSpace(vm.Note)) { CPApplication.Current.CurrentPage.Context.Window.Alert("自贸商品必填其他备注!"); return; } if (!vm.NeedValid.HasValue) { CPApplication.Current.CurrentPage.Context.Window.Alert("自贸商品必选商品需效期!"); return; } if (!vm.NeedLabel.HasValue) { CPApplication.Current.CurrentPage.Context.Window.Alert("自贸商品必选需粘贴中文标签!"); return; } } facades.Update(vm, (args) => { if (args) { CPApplication.Current.CurrentPage.Context.Window.Alert("更新成功!"); } else { CPApplication.Current.CurrentPage.Context.Window.Alert("更新失败!"); } }); }
public WorkItemManager(IDataProvider dataProvider, IDescriptorProvider descriptorProvider) { DataProvider = dataProvider; DescriptorManager = new DescriptorManager(descriptorProvider); ValidationManager = new ValidationManager(this, DescriptorManager); }
public void Test_RemovingSpecialCharacters() { string strToValidate = ValidationManager.OnlyStringsLettersDigitsSpaces("text'{/"); Assert.True(strToValidate == "text"); }
internal void ValidateDefinition(Activity root, bool isNewType, ITypeProvider typeProvider) { if (!this.validateOnCreate) { return; } ValidationErrorCollection errors = new ValidationErrorCollection(); // For validation purposes, create a type provider in the type case if the // host did not push one. if (typeProvider == null) { typeProvider = WorkflowRuntime.CreateTypeProvider(root); } // Validate that we are purely XAML. if (!isNewType) { if (!string.IsNullOrEmpty(root.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)) { errors.Add(new ValidationError(ExecutionStringManager.XomlWorkflowHasClassName, ErrorNumbers.Error_XomlWorkflowHasClassName)); } Queue compositeActivities = new Queue(); compositeActivities.Enqueue(root); while (compositeActivities.Count > 0) { Activity activity = compositeActivities.Dequeue() as Activity; if (activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) != null) { errors.Add(new ValidationError(ExecutionStringManager.XomlWorkflowHasCode, ErrorNumbers.Error_XomlWorkflowHasCode)); } CompositeActivity compositeActivity = activity as CompositeActivity; if (compositeActivity != null) { foreach (Activity childActivity in compositeActivity.EnabledActivities) { compositeActivities.Enqueue(childActivity); } } } } ServiceContainer serviceContainer = new ServiceContainer(); serviceContainer.AddService(typeof(ITypeProvider), typeProvider); ValidationManager validationManager = new ValidationManager(serviceContainer); using (WorkflowCompilationContext.CreateScope(validationManager)) { foreach (Validator validator in validationManager.GetValidators(root.GetType())) { foreach (ValidationError error in validator.Validate(validationManager, root)) { if (!error.UserData.Contains(typeof(Activity))) { error.UserData[typeof(Activity)] = root; } errors.Add(error); } } } if (errors.HasErrors) { throw new WorkflowValidationFailedException(ExecutionStringManager.WorkflowValidationFailure, errors); } }
private void btnSave_Click(object sender, RoutedEventArgs e) { #region [验证] if (!ValidationManager.Validate(this)) { return; } if (this.newVM.ConsignSettlementItemInfoList.Where(x => x.SettleSysNo != -1).Count() <= 0) { Window.Alert("请先选择结算商品!"); return; } #endregion //保存操作: Window.Confirm(ResConsignNew.ConfirmMsg_Save, (obj, args) => { if (args.DialogResult == DialogResultType.OK) { //去除已经删除的Item(SysNo=-1) newVM.ConsignSettlementItemInfoList = (from tItem in newVM.ConsignSettlementItemInfoList where tItem.SettleSysNo != -1 select tItem).ToList(); ConsignSettlementInfo info = EntityConverter <ConsignSettlementInfoVM, ConsignSettlementInfo> .Convert(newVM, (s, t) => { decimal usingReturnPoint = 0m; t.EIMSInfo = new ConsignSettlementEIMSInfo(); if (decimal.TryParse("", out usingReturnPoint)) { t.EIMSInfo.UsingReturnPoint = usingReturnPoint; } else { t.EIMSInfo.UsingReturnPoint = null; } t.SourceStockInfo = new BizEntity.Inventory.StockInfo() { SysNo = s.StockSysNo, }; t.PMInfo = new BizEntity.IM.ProductManagerInfo() { SysNo = Convert.ToInt32(s.PMSysNo), }; t.SettleUser = new BizEntity.Common.UserInfo() { SysNo = s.SettleUserSysNo, }; }); info.ConsignSettlementItemInfoList.ForEach(x => { x.ConsignToAccLogInfo.Cost = !x.ConsignToAccLogInfo.Cost.HasValue ? 0m : x.ConsignToAccLogInfo.Cost; }); //保存PM高级权限,用于业务端验证 info.IsManagerPM = AuthMgr.HasFunctionAbsolute(AuthKeyConst.PO_SeniorPM_Query); //代销商品规则检测 info.ConsignSettlementItemInfoList.ForEach(item => { if (item.SettleType == SettleType.O) { if (item.SettleRuleSysNo.HasValue && item.Cost != item.SettlePrice) { item.SettleRuleSysNo = null; item.SettleRuleName = null; } } }); //转租赁 info.LeaseType = this.newVM.LeaseType; serviceFacade.CreateConsignSettlement(info, (obj2, args2) => { if (args2.FaultsHandle()) { return; } Window.Alert(ResConsignNew.InfoMsg_Title, ResConsignNew.InfoMsg_CreateSuccess, MessageType.Information, (obj3, args3) => { if (args3.DialogResult == DialogResultType.Cancel) { Window.Close(); } }); }); } }); }
public static void Main() { Console.WriteLine("Program Working\n"); #region Manager instantiation var campaignManager = new CampaignManager(); var saleManager = new SaleManager(campaignManager); var gamerManager = new GamerManager(saleManager); var gameManager = new GameManager(); var validationManager = new ValidationManager(); #endregion #region Campaign insantiation var lowCampaign = new Campaign { Id = 1, Discount = 10, Title = "%10 discount!" }; var midCampaign = new Campaign { Id = 2, Discount = 20, Title = "%20 discount!" }; var highCampaign = new Campaign { Id = 3, Discount = 20, Title = "%30 discount!" }; #endregion campaignManager.NewCampaign(lowCampaign); campaignManager.NewCampaign(midCampaign); campaignManager.NewCampaign(highCampaign); #region Game insantiation var cod4 = new Game { Id = 1, Name = "Call Of Duty 4", Price = 100 }; var codBlackOps = new Game { Id = 2, Name = "Call Of Duty Black Ops", Price = 200 }; var gta5 = new Game { Id = 3, Name = "GTA 5", Price = 2000 }; #endregion gameManager.AddGame(gta5); gameManager.AddGame(cod4); gameManager.AddGame(codBlackOps); #region Gamer instantiation var poorGamer = new Gamer { Id = 1, Name = "Ibrahim", Surname = "Yargici", IdentityNumber = "12345678910", BirthDate = new DateTime(2020, 5, 01), BoughtGames = new List <Game>(), Budget = 100, UsedCampaigns = new List <Campaign> { midCampaign } }; var richGamer = new Gamer { Id = 2, Name = "Basar", Surname = "Yargici", IdentityNumber = "00012345670", BirthDate = new DateTime(2000, 11, 01), BoughtGames = new List <Game> { gta5 }, Budget = 400, UsedCampaigns = new List <Campaign> { lowCampaign, midCampaign, highCampaign } }; var hackerGamer = new Gamer { Id = 3, Name = "hacker", Surname = "gamer", IdentityNumber = "null", Budget = 9999999999999999, BirthDate = new DateTime(1111, 01, 01), BoughtGames = new List <Game> { gta5, cod4 }, UsedCampaigns = new List <Campaign>() }; #endregion // Add gamers gamerManager.NewGamer(poorGamer); gamerManager.NewGamer(richGamer); gamerManager.NewGamer(hackerGamer); // Is gamer valid // Console.WriteLine(validationManager.IsGamerValid(richGamer)); // Print all gamers // gamerManager.AllGamers(); // All games // gameManager.AllGames(); // All games that hackerGamer has // gamerManager.AllGameNames(hackerGamer); // All conditions on buying games // gamerManager.BuyGame(richGamer, codBlackOps); // // gamerManager.BuyGame(poorGamer, cod4); // // gamerManager.BuyGame(hackerGamer, codBlackOps); // // gamerManager.AllGamers(); // Delete gamer // gamerManager.DeleteGamer(hackerGamer); // Update gamer // gamerManager.UpdateGamer(hackerGamer); }
public GamerManager() { gamers = new List <Gamer>(); validationManager = new ValidationManager(); }
/// <inheritdoc /> public void CreateValidators(ClientValidatorProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } IStringLocalizer stringLocalizer = null; if (_options.Value.DataAnnotationLocalizerProvider != null && _stringLocalizerFactory != null) { // This will pass first non-null type (either containerType or modelType) to delegate. // Pass the root model type(container type) if it is non null, else pass the model type. stringLocalizer = _options.Value.DataAnnotationLocalizerProvider( context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType, _stringLocalizerFactory); } var hasRequiredAttribute = false; var metadata = context.ModelMetadata; var isPropertyValidation = metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName); var rules = ValidationManager.GetValidationRules(metadata.ContainerType, metadata.PropertyName); if (rules == null) { return; } foreach (var rule in rules) { var validationAttribute = rule.CreateValidationAttribute(); if (validationAttribute == null) { continue; } var validatorItem = new ClientValidatorItem(validationAttribute); if (validatorItem.Validator != null) { // Check if a required attribute is already cached. hasRequiredAttribute |= validatorItem.Validator is RequiredAttributeAdapter; continue; } hasRequiredAttribute |= validationAttribute is RequiredAttribute; var adapter = _validationAttributeAdapterProvider.GetAttributeAdapter(validationAttribute, stringLocalizer); if (adapter != null) { validatorItem.Validator = adapter; validatorItem.IsReusable = true; } context.Results.Add(validatorItem); } if (!hasRequiredAttribute && context.ModelMetadata.IsRequired) { // Add a default '[Required]' validator for generating HTML if necessary. context.Results.Add(new ClientValidatorItem { Validator = _validationAttributeAdapterProvider.GetAttributeAdapter( new RequiredAttribute(), stringLocalizer), IsReusable = true }); } }
private void btnSave_Click(object sender, RoutedEventArgs e) { //输入验证不通过,则直接返回 if (!ValidationManager.Validate(this)) { return; } var facade = new ECCategoryFacade(CPApplication.Current.CurrentPage); if (_currentVM.Level == ECCategoryLevel.Category3) { if (_currentVM.Name.Length < 1 || _currentVM.Name.Length > 10) { CurrentWindow.Alert("三级类别最少1个字,最多10个字"); return; } } else if (_currentVM.Level == ECCategoryLevel.Category2) { if (_currentVM.Name.Length < 1 || _currentVM.Name.Length > 15) { CurrentWindow.Alert("二级类别最少1个字,最多不能超过15个字"); return; } } else { if (_currentVM.Name.Length > 15) { CurrentWindow.Alert("名称字数长度超范围,一级类别不可大于15个字"); return; } } if (_isEditing) { //编辑 facade.Update(_currentVM, (s, args) => { if (args.FaultsHandle()) { return; } CurrentWindow.Alert(ResECCategory.Info_EditSuccess); OnEditCompleted(_currentVM); }); } else { //新建 facade.Create(_currentVM, (s, args) => { if (args.FaultsHandle()) { return; } CurrentWindow.Alert(ResECCategory.Info_AddSuccess); _currentVM = args.Result.Convert <ECCategory, ECCategoryVM>(); _currentVM.ChannelID = args.Result.WebChannel == null ? "1" : args.Result.WebChannel.ChannelID; OnAddCompleted(_currentVM); OnCancelClick(); }); } }
// Kiem tra valid cho mot instance public static bool IsValid(object instance) { ValidationManager vm = new ValidationManager(instance); return(vm.IsValid()); }
/// <summary> /// 发送订单拦截邮件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSendSOInterceptEmail_Click(object sender, RoutedEventArgs e) { SOInterceptInfoVM orderEmailInfoVM = new SOInterceptInfoVM(); SOInterceptInfoVM financeEmailInfoVM = new SOInterceptInfoVM(); orderEmailInfoVM.EmailAddress = this.txtEmailAddresse.Text; orderEmailInfoVM.CCEmailAddress = this.txtCCEmailAddress.Text; financeEmailInfoVM.FinanceEmailAddress = this.txtFinanceEmailAddress.Text; financeEmailInfoVM.FinanceCCEmailAddress = this.txtFinanceCCEmailAddress.Text; if (CurrentSOVM.InvoiceInfoVM.IsVAT == true) { if (string.IsNullOrEmpty(orderEmailInfoVM.EmailAddress) || string.IsNullOrEmpty(orderEmailInfoVM.CCEmailAddress) || string.IsNullOrEmpty(financeEmailInfoVM.FinanceEmailAddress) || string.IsNullOrEmpty(financeEmailInfoVM.FinanceCCEmailAddress) ) { CPApplication.Current.CurrentPage.Context.Window.Alert(ResSOIntercept.Info_SaveSOIntercept_Input_Error, MessageType.Error); } else { ValidationManager.Validate(this.gdOrderEmailInfo); if (orderEmailInfoVM.HasValidationErrors && orderEmailInfoVM.ValidationErrors.Count > 0) { return; } ValidationManager.Validate(this.gdFinanceEmailInfo); if (financeEmailInfoVM.HasValidationErrors && financeEmailInfoVM.ValidationErrors.Count > 0) { return; } SOInterceptInfoVM soInterceptInfoVM = new SOInterceptInfoVM(); soInterceptInfoVM.EmailAddress = orderEmailInfoVM.EmailAddress; soInterceptInfoVM.CCEmailAddress = orderEmailInfoVM.CCEmailAddress; soInterceptInfoVM.FinanceEmailAddress = financeEmailInfoVM.FinanceEmailAddress; soInterceptInfoVM.FinanceCCEmailAddress = financeEmailInfoVM.FinanceCCEmailAddress; CurrentSOVM.SOInterceptInfoVMList.Add(soInterceptInfoVM); #region 发送订单拦截邮件 SendEmailReq reqSOOrderIntercep = new SendEmailReq(); reqSOOrderIntercep.soInfo = SOFacade.ConvertTOSOInfoFromSOVM(CurrentSOVM); reqSOOrderIntercep.Language = CPApplication.Current.LanguageCode; new SOInterceptFacade().SendSOOrderInterceptEmail(reqSOOrderIntercep, (obj, args) => { if (!args.FaultsHandle()) { CloseDialog(new ResultEventArgs { DialogResult = DialogResultType.OK, }); } }); #endregion #region 发送增票拦截邮件 SendEmailReq reqSOFinanceIntercep = new SendEmailReq(); reqSOFinanceIntercep.soInfo = SOFacade.ConvertTOSOInfoFromSOVM(CurrentSOVM); reqSOFinanceIntercep.Language = CPApplication.Current.LanguageCode; new SOInterceptFacade().SendSOFinanceInterceptEmail(reqSOFinanceIntercep, (obj, args) => { if (!args.FaultsHandle()) { CPApplication.Current.CurrentPage.Context.Window.Alert(ResSOIntercept.Info_SendEmail_Sucessful, MessageType.Information); CloseDialog(new ResultEventArgs { DialogResult = DialogResultType.OK, }); } }); #endregion } } else { if (string.IsNullOrEmpty(orderEmailInfoVM.EmailAddress) || string.IsNullOrEmpty(orderEmailInfoVM.CCEmailAddress)) { CPApplication.Current.CurrentPage.Context.Window.Alert(ResSOIntercept.Info_SaveSOIntercept_Input_Error, MessageType.Error); } else { ValidationManager.Validate(this.gdOrderEmailInfo); if (orderEmailInfoVM.HasValidationErrors && orderEmailInfoVM.ValidationErrors.Count > 0) { return; } SOInterceptInfoVM soInterceptInfoVM = new SOInterceptInfoVM(); soInterceptInfoVM.EmailAddress = orderEmailInfoVM.EmailAddress; soInterceptInfoVM.CCEmailAddress = orderEmailInfoVM.CCEmailAddress; CurrentSOVM.SOInterceptInfoVMList.Add(soInterceptInfoVM); #region 发送订单拦截邮件 SendEmailReq reqSOOrderIntercep = new SendEmailReq(); reqSOOrderIntercep.soInfo = SOFacade.ConvertTOSOInfoFromSOVM(CurrentSOVM); reqSOOrderIntercep.Language = CPApplication.Current.LanguageCode; new SOInterceptFacade().SendSOOrderInterceptEmail(reqSOOrderIntercep, (obj, args) => { if (!args.FaultsHandle()) { CPApplication.Current.CurrentPage.Context.Window.Alert(ResSOIntercept.Info_SendEmail_Sucessful, MessageType.Information); CloseDialog(new ResultEventArgs { DialogResult = DialogResultType.OK, }); } }); #endregion } } }
private void btnUpdate_Click(object sender, RoutedEventArgs e) { //保存更新操作 : if (!ValidationManager.Validate(this)) { return; } List <string> checkPricesList = new List <string>(); string pricesCheckAlertString = string.Empty; string oldPriceNullString = string.Empty; if (string.IsNullOrEmpty(editVM.OldSettlePrice)) { oldPriceNullString += ResSettledProductsRuleQuery.InfoMsg_SettleRule_OldSettlePriceNullAlert + Environment.NewLine; } if (!string.IsNullOrEmpty(editVM.OldSettlePrice) && Convert.ToDecimal(editVM.OldSettlePrice) <= 0) { checkPricesList.Add(ResSettledProductsRuleQuery.InfoMsg_SettleRule_OldSettlePrice); } if (!string.IsNullOrEmpty(editVM.NewSettlePrice) && Convert.ToDecimal(editVM.NewSettlePrice) <= 0) { checkPricesList.Add(ResSettledProductsRuleQuery.InfoMsg_SettleRule_NewSettlePrice); } if (checkPricesList.Count > 0) { pricesCheckAlertString += string.Join(ResSettledProductsRuleQuery.Label_And, checkPricesList); } if (!string.IsNullOrEmpty(pricesCheckAlertString) || !string.IsNullOrEmpty(oldPriceNullString)) { string confirmStr = string.Empty; if (!string.IsNullOrEmpty(pricesCheckAlertString)) { confirmStr += string.Format(ResSettledProductsRuleQuery.InfoMsg_SettleRule_ContinueAlert, pricesCheckAlertString) + Environment.NewLine; } if (!string.IsNullOrEmpty(oldPriceNullString)) { confirmStr += oldPriceNullString + Environment.NewLine; } CurrentWindow.Confirm(confirmStr, (obj, args) => { if (args.DialogResult == DialogResultType.OK) { ConsignSettlementRulesInfo info = EntityConverter <ConsignSettlementRulesInfoVM, ConsignSettlementRulesInfo> .Convert(editVM); //结束时间换算到当天的23:59:59.997 //数据库最大保存到 .997 info.EndDate = info.EndDate.Value.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(997); serviceFacade.UpdateConsignSettleRule(info, (obj2, args2) => { if (args2.FaultsHandle()) { return; } CurrentWindow.Alert(ResSettledProductsRuleQuery.InfoMsg_SettleRule_Title, ResSettledProductsRuleQuery.InfoMsg_SettleRule_OprSuc, MessageType.Information, (obj3, args3) => { if (args3.DialogResult == DialogResultType.Cancel) { Dialog.ResultArgs.DialogResult = DialogResultType.OK; Dialog.ResultArgs.Data = editVM; Dialog.Close(true); } }); }); } }); } else { ConsignSettlementRulesInfo info = EntityConverter <ConsignSettlementRulesInfoVM, ConsignSettlementRulesInfo> .Convert(editVM); //结束时间换算到当天的23:59:59.997 //数据库最大保存到 .997 info.EndDate = info.EndDate.Value.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(997); serviceFacade.UpdateConsignSettleRule(info, (obj2, args2) => { if (args2.FaultsHandle()) { return; } CurrentWindow.Alert(ResSettledProductsRuleQuery.InfoMsg_SettleRule_Title, ResSettledProductsRuleQuery.InfoMsg_SettleRule_OprSuc, MessageType.Information, (obj3, args3) => { if (args3.DialogResult == DialogResultType.Cancel) { Dialog.ResultArgs.DialogResult = DialogResultType.OK; Dialog.ResultArgs.Data = editVM; Dialog.Close(true); } }); }); } }
private void btnSaveGiftSetting_Click(object sender, RoutedEventArgs e) { SaleGiftInfoViewModel vm = this.DataContext as SaleGiftInfoViewModel; if (vm.GiftComboType == SaleGiftGiftItemType.GiftPool) { foreach (SaleGift_GiftItemViewModel giftitem in vm.GiftItemList) { giftitem.Count = "0"; if (string.IsNullOrEmpty(giftitem.PlusPrice)) { giftitem.PlusPrice = giftitem.CurrentPrice.GetValueOrDefault().ToString("f2"); } } int count = 0; int.TryParse(vm.ItemGiftCount, out count); if (string.IsNullOrEmpty(vm.ItemGiftCount) || count < 1) { tbItemGiftCount.Validation("赠品池任选总数量不能为空并且必须为大于0的整数!", vm, this.gridGiftType); return; } else { tbItemGiftCount.ClearValidationError(); } } else { tbItemGiftCount.ClearValidationError(); } List <SaleGift_GiftItemViewModel> list = dgGiftProduct.ItemsSource as List <SaleGift_GiftItemViewModel>; if (list == null || list.Count == 0) { CurrentWindow.Alert("请至少设置1个赠品!"); return; } if (vm.GiftComboType.Value == SaleGiftGiftItemType.AssignGift) { foreach (SaleGift_GiftItemViewModel item in list) { if (string.IsNullOrEmpty(item.Count) || item.Count.Equals("0")) { CurrentWindow.Alert("赠品数量必须大于0!"); return; } } } ValidationManager.Validate(this.dgGiftProduct); foreach (SaleGift_GiftItemViewModel rowVM in list) { if (rowVM.HasValidationErrors) { return; } } SaleGiftFacade facade = new SaleGiftFacade(CPApplication.Current.CurrentPage); if (vm.IsAccess) //有高级权限 { facade.CheckGiftStockResult(vm, (obj, arg) => { if (arg.FaultsHandle()) { return; } if (arg.Result.Length > 0) { CPApplication.Current.CurrentPage.Context.Window.Confirm(arg.Result + ";是否继续保存?", (objs, args) => { if (args.DialogResult == Newegg.Oversea.Silverlight.Controls.Components.DialogResultType.OK) { facade.SetSaleGiftGiftItemRules(vm, (o, a) => { if (a.FaultsHandle()) { return; } CurrentWindow.Alert("赠品规则保存成功!"); }); } }); } else { facade.SetSaleGiftGiftItemRules(vm, (o, a) => { if (a.FaultsHandle()) { return; } CurrentWindow.Alert("赠品规则保存成功!"); }); } }); } else { facade.SetSaleGiftGiftItemRules(vm, (o, a) => { if (a.FaultsHandle()) { return; } CurrentWindow.Alert("赠品规则保存成功!"); }); } }
public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection errors = base.Validate(manager, obj); WebServiceFaultActivity activity = obj as WebServiceFaultActivity; if (activity == null) { throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(WebServiceFaultActivity).FullName }), "obj"); } if (!Helpers.IsActivityLocked(activity)) { List <ParameterInfo> list; List <ParameterInfo> list2; WebServiceInputActivity activity2 = null; if (string.IsNullOrEmpty(activity.InputActivityName)) { errors.Add(ValidationError.GetNotSetValidationError("InputActivityName")); return(errors); } ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider)); if (service == null) { throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName })); } bool flag = false; foreach (Activity activity3 in WebServiceActivityHelpers.GetPreceedingActivities(activity)) { if (((activity3 is WebServiceFaultActivity) && (string.Compare(((WebServiceFaultActivity)activity3).InputActivityName, activity.InputActivityName, StringComparison.Ordinal) == 0)) || ((activity3 is WebServiceOutputActivity) && (string.Compare(((WebServiceOutputActivity)activity3).InputActivityName, activity.InputActivityName, StringComparison.Ordinal) == 0))) { if (activity3 is WebServiceFaultActivity) { errors.Add(new ValidationError(SR.GetString("Error_DuplicateWebServiceFaultFound", new object[] { activity3.Name, activity.InputActivityName }), 0x574)); return(errors); } errors.Add(new ValidationError(SR.GetString("Error_DuplicateWebServiceResponseFound", new object[] { activity3.Name, activity.InputActivityName }), 0x56a)); return(errors); } } foreach (Activity activity4 in WebServiceActivityHelpers.GetPreceedingActivities(activity)) { if (string.Compare(activity4.QualifiedName, activity.InputActivityName, StringComparison.OrdinalIgnoreCase) == 0) { if (activity4 is WebServiceInputActivity) { activity2 = activity4 as WebServiceInputActivity; flag = true; break; } flag = false; errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotValid", new object[] { activity.InputActivityName }), 0x564)); return(errors); } } if (!flag) { errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotFound", new object[] { activity.InputActivityName }), 0x55e)); return(errors); } Type interfaceType = null; if (activity2.InterfaceType != null) { interfaceType = service.GetType(activity2.InterfaceType.AssemblyQualifiedName); } if (interfaceType == null) { errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotConfigured", new object[] { activity2.Name }), 0x566)); return(errors); } if (string.IsNullOrEmpty(activity2.MethodName)) { errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotConfigured", new object[] { activity2.Name }), 0x566)); return(errors); } MethodInfo interfaceMethod = Helpers.GetInterfaceMethod(interfaceType, activity2.MethodName); if (interfaceMethod == null) { errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotConfigured", new object[] { activity2.Name }), 0x566)); return(errors); } WebServiceActivityHelpers.GetParameterInfo(interfaceMethod, out list, out list2); if (list2.Count == 0) { errors.Add(new ValidationError(SR.GetString("Error_WebServiceFaultNotNeeded"), 0x57a)); return(errors); } } return(errors); }
public void CreateValidators(ModelValidatorProviderContext context) { IStringLocalizer stringLocalizer = null; if (_stringLocalizerFactory != null && _options.Value.DataAnnotationLocalizerProvider != null) { stringLocalizer = _options.Value.DataAnnotationLocalizerProvider( context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType, _stringLocalizerFactory); } var metadata = context.ModelMetadata; var isPropertyValidation = metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName); var rules = ValidationManager.GetValidationRules(metadata.ContainerType, metadata.PropertyName); if (rules == null) { return; } foreach (var rule in rules) { var validationAttribute = rule.CreateValidationAttribute(); if (validationAttribute == null) { continue; } var validatorItem = new ValidatorItem(validationAttribute); if (validatorItem.Validator != null) { continue; } var attribute = validatorItem.ValidatorMetadata as ValidationAttribute; if (attribute == null) { continue; } var validator = new CustomDataAnnotationsModelValidator( _validationAttributeAdapterProvider, attribute, stringLocalizer); validatorItem.Validator = validator; validatorItem.IsReusable = true; // Inserts validators based on whether or not they are 'required'. We want to run // 'required' validators first so that we get the best possible error message. if (attribute is RequiredAttribute) { context.Results.Remove(validatorItem); context.Results.Insert(0, validatorItem); } context.Results.Add(validatorItem); } // Produce a validator if the type supports IValidatableObject if (typeof(IValidatableObject).IsAssignableFrom(context.ModelMetadata.ModelType)) { context.Results.Add(new ValidatorItem { Validator = new CustomValidatableObjectAdapter(), IsReusable = true }); } }
private void continueButton_Click(object sender, EventArgs e) { if (_sender == generalTabPage) { if (!ValidationManager.Validate(generalPanel)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!_generalTabPassed) { _projectConfiguration = ProjectConfiguration.Load().ToList(); if (_projectConfiguration != null) { if (_projectConfiguration.Any(item => item.Name == nameTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "The project is already existing.", $"The project \"{nameTextBox.Text}\" is already existing.", PopupButtons.Ok); return; } } else { _projectConfiguration = new List<ProjectConfiguration>(); } } if (!Uri.IsWellFormedUriString(updateUrlTextBox.Text, UriKind.Absolute)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid adress.", "The given Update-URL is invalid.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(localPathTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } try { Path.GetFullPath(localPathTextBox.Text); } catch { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } _sender = httpAuthenticationTabPage; backButton.Enabled = true; informationCategoriesTabControl.SelectedTab = httpAuthenticationTabPage; } else if (_sender == httpAuthenticationTabPage) { if (httpAuthenticationCheckBox.Checked && !ValidationManager.Validate(httpAuthenticationPanel)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } _sender = ftpTabPage; informationCategoriesTabControl.SelectedTab = ftpTabPage; } else if (_sender == ftpTabPage) { if (!ValidationManager.Validate(ftpPanel) || string.IsNullOrEmpty(ftpPasswordTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } _ftp.Host = ftpHostTextBox.Text; _ftp.Port = int.Parse(ftpPortTextBox.Text); _ftp.Username = ftpUserTextBox.Text; _ftp.Directory = ftpDirectoryTextBox.Text; var ftpPassword = new SecureString(); foreach (var c in ftpPasswordTextBox.Text) { ftpPassword.AppendChar(c); } _ftp.Password = ftpPassword; // Same instance that FtpManager will automatically dispose _ftp.UsePassiveMode = ftpModeComboBox.SelectedIndex == 0; _ftp.Protocol = (FtpsSecurityProtocol) ftpProtocolComboBox.SelectedIndex; _ftp.NetworkVersion = (NetworkVersion) ipVersionComboBox.SelectedIndex; if (!backButton.Enabled) // If the back-button was disabled, enabled it again backButton.Enabled = true; _sender = statisticsServerTabPage; informationCategoriesTabControl.SelectedTab = statisticsServerTabPage; } else if (_sender == statisticsServerTabPage) { if (useStatisticsServerRadioButton.Checked) { if (SqlDatabaseName == null || string.IsNullOrWhiteSpace(sqlPasswordTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } } _sender = proxyTabPage; informationCategoriesTabControl.SelectedTab = proxyTabPage; } else if (_sender == proxyTabPage) { if (useProxyRadioButton.Checked && !ValidationManager.ValidateAndIgnore(proxyTabPage, new[] {proxyUserTextBox, proxyPasswordTextBox})) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } try { using (File.Create(localPathTextBox.Text)) { } _projectFileCreated = true; } catch (IOException ex) { Popup.ShowPopup(this, SystemIcons.Error, "Failed to create project file.", ex, PopupButtons.Ok); Close(); } var usePassive = ftpModeComboBox.SelectedIndex == 0; WebProxy proxy = null; string proxyUsername = null; string proxyPassword = null; if (!string.IsNullOrEmpty(proxyHostTextBox.Text)) { proxy = new WebProxy(proxyHostTextBox.Text); if (!string.IsNullOrEmpty(proxyUserTextBox.Text) && !string.IsNullOrEmpty(proxyPasswordTextBox.Text)) { proxyUsername = proxyUserTextBox.Text; if (!saveCredentialsCheckBox.Checked) proxyPassword = Convert.ToBase64String(AesManager.Encrypt(proxyPasswordTextBox.Text, ftpPasswordTextBox.Text, ftpUserTextBox.Text)); else proxyPassword = Convert.ToBase64String(AesManager.Encrypt(proxyPasswordTextBox.Text, Program.AesKeyPassword, Program.AesIvPassword)); } } string sqlPassword = null; if (useStatisticsServerRadioButton.Checked) { if (!saveCredentialsCheckBox.Checked) sqlPassword = Convert.ToBase64String(AesManager.Encrypt(sqlPasswordTextBox.Text, ftpPasswordTextBox.Text, ftpUserTextBox.Text)); else sqlPassword = Convert.ToBase64String(AesManager.Encrypt(sqlPasswordTextBox.Text, Program.AesKeyPassword, Program.AesIvPassword)); } Settings.Default.ApplicationID += 1; Settings.Default.Save(); Settings.Default.Reload(); string ftpPassword; if (!saveCredentialsCheckBox.Checked) ftpPassword = Convert.ToBase64String(AesManager.Encrypt(ftpPasswordTextBox.Text, ftpPasswordTextBox.Text, ftpUserTextBox.Text)); else ftpPassword = Convert.ToBase64String(AesManager.Encrypt(ftpPasswordTextBox.Text, Program.AesKeyPassword, Program.AesIvPassword)); // Create a new package... var project = new UpdateProject { Path = localPathTextBox.Text, Name = nameTextBox.Text, Guid = Guid.NewGuid().ToString(), ApplicationId = Settings.Default.ApplicationID, UpdateUrl = updateUrlTextBox.Text, Packages = null, SaveCredentials = saveCredentialsCheckBox.Checked, HttpAuthenticationCredentials = httpAuthenticationCheckBox.Checked ? new NetworkCredential(httpAuthenticationUserTextBox.Text, httpAuthenticationPasswordTextBox.Text) : null, FtpHost = ftpHostTextBox.Text, FtpPort = int.Parse(ftpPortTextBox.Text), FtpUsername = ftpUserTextBox.Text, FtpPassword = ftpPassword, FtpDirectory = ftpDirectoryTextBox.Text, FtpProtocol = ftpProtocolComboBox.SelectedIndex, FtpUsePassiveMode = usePassive, FtpTransferAssemblyFilePath = _ftpAssemblyPath, FtpNetworkVersion = (NetworkVersion) ipVersionComboBox.SelectedIndex, Proxy = proxy, ProxyUsername = proxyUsername, ProxyPassword = proxyPassword, UseStatistics = useStatisticsServerRadioButton.Checked, SqlDatabaseName = SqlDatabaseName, SqlWebUrl = SqlWebUrl, SqlUsername = SqlUsername, SqlPassword = sqlPassword, PrivateKey = PrivateKey, PublicKey = PublicKey, Log = null }; try { UpdateProject.SaveProject(localPathTextBox.Text, project); // ... and save it } catch (IOException ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while saving the project file.", ex, PopupButtons.Ok); _mustClose = true; Reset(); } try { var projectDirectoryPath = Path.Combine(Program.Path, "Projects", nameTextBox.Text); Directory.CreateDirectory(projectDirectoryPath); } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while creating the project'S directory.", ex, PopupButtons.Ok); _mustClose = true; Reset(); } try { _projectConfiguration.Add(new ProjectConfiguration(nameTextBox.Text, localPathTextBox.Text)); File.WriteAllText(Program.ProjectsConfigFilePath, Serializer.Serialize(_projectConfiguration)); _projectConfigurationEdited = true; } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while editing the project confiuration file. Please choose another name for the project.", ex, PopupButtons.Ok); _mustClose = true; Reset(); } if (useStatisticsServerRadioButton.Checked) { var phpFilePath = Path.Combine(Program.Path, "Projects", nameTextBox.Text, "statistics.php"); try { File.WriteAllBytes(phpFilePath, Resources.statistics); var phpFileContent = File.ReadAllText(phpFilePath); phpFileContent = phpFileContent.Replace("_DBURL", SqlWebUrl); phpFileContent = phpFileContent.Replace("_DBUSER", SqlUsername); phpFileContent = phpFileContent.Replace("_DBNAME", SqlDatabaseName); phpFileContent = phpFileContent.Replace("_DBPASS", sqlPasswordTextBox.Text); File.WriteAllText(phpFilePath, phpFileContent); _phpFileCreated = true; } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Failed to initialize the project-files.", ex, PopupButtons.Ok); _mustClose = true; Reset(); } } _generalTabPassed = true; InitializeProject(); } }
public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); WebServiceOutputActivity webServiceResponse = obj as WebServiceOutputActivity; if (webServiceResponse == null) { throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(WebServiceOutputActivity).FullName), "obj"); } if (Helpers.IsActivityLocked(webServiceResponse)) { return(validationErrors); } WebServiceInputActivity webServiceReceive = null; if (String.IsNullOrEmpty(webServiceResponse.InputActivityName)) { validationErrors.Add(ValidationError.GetNotSetValidationError("InputActivityName")); } else { ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider)); if (typeProvider == null) { throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName)); } bool foundMatchingReceive = false; foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(webServiceResponse)) { if ((activity is WebServiceOutputActivity && String.Compare(((WebServiceOutputActivity)activity).InputActivityName, webServiceResponse.InputActivityName, StringComparison.Ordinal) == 0) || (activity is WebServiceFaultActivity && String.Compare(((WebServiceFaultActivity)activity).InputActivityName, webServiceResponse.InputActivityName, StringComparison.Ordinal) == 0)) { if (activity is WebServiceOutputActivity) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_DuplicateWebServiceResponseFound, activity.QualifiedName, webServiceResponse.InputActivityName), ErrorNumbers.Error_DuplicateWebServiceResponseFound)); } else { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_DuplicateWebServiceFaultFound, activity.QualifiedName, webServiceResponse.InputActivityName), ErrorNumbers.Error_DuplicateWebServiceFaultFound)); } return(validationErrors); } } foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(webServiceResponse)) { if (String.Compare(activity.QualifiedName, webServiceResponse.InputActivityName, StringComparison.Ordinal) == 0) { if (activity is WebServiceInputActivity) { webServiceReceive = activity as WebServiceInputActivity; foundMatchingReceive = true; } else { foundMatchingReceive = false; validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotValid, webServiceResponse.InputActivityName), ErrorNumbers.Error_WebServiceReceiveNotValid)); return(validationErrors); } break; } } if (!foundMatchingReceive) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotFound, webServiceResponse.InputActivityName), ErrorNumbers.Error_WebServiceReceiveNotFound)); return(validationErrors); } else { Type interfaceType = null; if (webServiceReceive.InterfaceType != null) { interfaceType = typeProvider.GetType(webServiceReceive.InterfaceType.AssemblyQualifiedName); } if (interfaceType == null) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured)); } else { // Validate method if (String.IsNullOrEmpty(webServiceReceive.MethodName)) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured)); } else { MethodInfo methodInfo = Helpers.GetInterfaceMethod(interfaceType, webServiceReceive.MethodName); if (methodInfo == null) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured)); } else { ValidationErrorCollection parameterTypeErrors = WebServiceActivityHelpers.ValidateParameterTypes(methodInfo); if (parameterTypeErrors.Count > 0) { foreach (ValidationError parameterTypeError in parameterTypeErrors) { parameterTypeError.PropertyName = "InputActivityName"; } validationErrors.AddRange(parameterTypeErrors); } else { List <ParameterInfo> inputParameters, outParameters; WebServiceActivityHelpers.GetParameterInfo(methodInfo, out inputParameters, out outParameters); if (outParameters.Count == 0) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceResponseNotNeeded), ErrorNumbers.Error_WebServiceResponseNotNeeded)); } else { // Check to see if all output parameters have a valid bindings. foreach (ParameterInfo paramInfo in outParameters) { string paramName = paramInfo.Name; Type paramType = paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType; if (paramInfo.Position == -1) { paramName = "(ReturnValue)"; } object paramValue = null; if (webServiceResponse.ParameterBindings.Contains(paramName)) { if (webServiceResponse.ParameterBindings[paramName].IsBindingSet(WorkflowParameterBinding.ValueProperty)) { paramValue = webServiceResponse.ParameterBindings[paramName].GetBinding(WorkflowParameterBinding.ValueProperty); } else { paramValue = webServiceResponse.ParameterBindings[paramName].GetValue(WorkflowParameterBinding.ValueProperty); } } if (!paramType.IsPublic || !paramType.IsSerializable) { ValidationError validationError = new ValidationError(SR.GetString(SR.Error_TypeNotPublicSerializable, paramName, paramType.FullName), ErrorNumbers.Error_TypeNotPublicSerializable); validationError.PropertyName = (String.Compare(paramName, "(ReturnValue)", StringComparison.Ordinal) == 0) ? paramName : ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName); validationErrors.Add(validationError); } else if (!webServiceResponse.ParameterBindings.Contains(paramName) || paramValue == null) { ValidationError validationError = ValidationError.GetNotSetValidationError(paramName); validationError.PropertyName = (String.Compare(paramName, "(ReturnValue)", StringComparison.Ordinal) == 0) ? paramName : ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName); validationErrors.Add(validationError); } else { AccessTypes access = AccessTypes.Read; if (paramInfo.IsOut || paramInfo.IsRetval || paramInfo.Position == -1) { access = AccessTypes.Write; } ValidationErrorCollection variableErrors = ValidationHelpers.ValidateProperty(manager, webServiceResponse, paramValue, new PropertyValidationContext(webServiceResponse.ParameterBindings[paramName], null, paramName), new BindValidationContext(paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType, access)); foreach (ValidationError variableError in variableErrors) { if (String.Compare(paramName, "(ReturnValue)", StringComparison.Ordinal) != 0) { variableError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName); } } validationErrors.AddRange(variableErrors); } } if (webServiceResponse.ParameterBindings.Count > outParameters.Count) { validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_AdditionalBindingsFound), ErrorNumbers.Warning_AdditionalBindingsFound, true)); } } } } } } } } return(validationErrors); }
private void ButtonSave_Click(object sender, RoutedEventArgs e) { //_viewModel.GroupBuyingTypeSysNo = (int)cmbGroupBuyingCategoryType.SelectedValue; _viewModel.GroupBuyingTypeSysNo = 0; if (ValidationManager.Validate(Grid) && ValidationManager.Validate(gridPrice)) { if (_viewModel.BeginDate == null) { //Window.Alert("开始日期不能为空"); Window.Alert(ResGroupBuyingMaintain.Info_StartDateNotNull); return; } if (_viewModel.EndDate == null) { //Window.Alert("结束日期不能为空"); Window.Alert(ResGroupBuyingMaintain.Info_EndDateNotNull); return; } if (_viewModel.CategoryType == GroupBuyingCategoryType.Virtual && string.IsNullOrEmpty(_viewModel.CouponValidDate)) { //Window.Alert("虚拟团购有效日期不能为空"); Window.Alert(ResGroupBuyingMaintain.Info_ActiveDateNotNull); return; } if (_viewModel.GroupBuyingTypeSysNo != 6) { if (string.IsNullOrWhiteSpace(_viewModel.ProductID) || _viewModel.ProductSysNo == null) { Window.Alert(ResGroupBuyingMaintain.Msg_IsProductNull); return; } int _sysNoTmp = -1; if (!int.TryParse(_viewModel.ProductSysNo.ToString(), out _sysNoTmp)) { Window.Alert(ResGroupBuyingMaintain.Msg_IsProductSysNoFormatError); return; } } if (this._viewModel.CategoryType == GroupBuyingCategoryType.Virtual) { if (this._viewModel.GroupBuyingVendorSysNo == null) { //Window.Alert("请选择商家!", MessageType.Warning); Window.Alert(ResGroupBuyingMaintain.Info_SelectMerchant, MessageType.Warning); return; } if (this._viewModel.VendorStoreList.Where(prop => prop.IsChecked).Count() == 0) { //Window.Alert("请选择门店!", MessageType.Warning); Window.Alert(ResGroupBuyingMaintain.Info_SelectShop, MessageType.Warning); return; } } if (_viewModel.GroupBuyingTypeSysNo != 6) { _Facade.LoadMarginRateInfo(_viewModel, (obj0, args0) => { if (args0.FaultsHandle()) { return; } UCGroupBuySaveInfo saveInfoView = new UCGroupBuySaveInfo(); saveInfoView.MsgListVM = args0.Result; saveInfoView.vm = _viewModel; saveInfoView.Dialog = Window.ShowDialog(ResGroupBuyingMaintain.Msg_MakeSure, saveInfoView, (o, arg) => { if (arg.DialogResult == DialogResultType.OK) { SaveAction(); } }); }); } else { SaveAction(); } } }
private void continueButton_Click(object sender, EventArgs e) { backButton.Enabled = true; if (_sender == optionTabPage) { if (importProjectRadioButton.Checked) { wizardTabControl.SelectedTab = importTabPage; _sender = importTabPage; } else if (shareProjectRadioButton.Checked) { wizardTabControl.SelectedTab = shareTabPage; _sender = shareTabPage; } } else if (_sender == importTabPage) { if (!ValidationManager.Validate(importTabPage)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(projectToImportTextBox.Text) || !File.Exists(projectToImportTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } wizardTabControl.SelectedTab = importTabPage1; _sender = importTabPage1; } else if (_sender == importTabPage1) { if (!ValidationManager.Validate(importTabPage1)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (_projectConfigurations.Any(item => item.Name == projectNameTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Project already existing.", $"A project with the name \"{projectNameTextBox.Text}\" does already exist.", PopupButtons.Ok); return; } try { string folderPath = Path.Combine(Program.Path, "ImpProj"); string statisticsFilePath = Path.Combine(folderPath, "statistics.php"); string projectFilePath = Path.Combine(folderPath, $"{projectNameTextBox.Text}.nupdproj"); Directory.CreateDirectory(folderPath); var updateProject = UpdateProject.LoadProject(projectFilePath); if (updateProject.UseStatistics) { Popup.ShowPopup(this, SystemIcons.Warning, "Incompatible project.", "This project cannot be imported because the support for projects using statistics is currently missing. It will be available in the next version(s) of nUpdate Administration.", PopupButtons.Ok); Directory.Delete(folderPath); return; } //if (updateProject.ConfigVersion != "3b2") //{ // Popup.ShowPopup(this, SystemIcons.Warning, "Incompatible project.", "This project is not compatible to this version of nUpdate Administration. Please download the newest version of nUpdate Administration and then export the project again.", PopupButtons.Ok); // Directory.Delete(folderPath); // return; //} updateProject.Path = projectFilePathTextBox.Text; //if (updateProject.UseStatistics) //{ // var statisticsServers = Serializer.Deserialize<List<StatisticsServer>>(Path.Combine(Program.Path, "statservers.json")); // if (!statisticsServers.Any(item => item.WebUrl == updateProject.SqlWebUrl && item.DatabaseName == updateProject.SqlDatabaseName && item.Username == updateProject.SqlUsername)) // { // if (Popup.ShowPopup(this, SystemIcons.Information, "New statistics server found.", "This project uses a statistics server that isn't currently available on this computer. Should nUpdate Administration add this server to your list?", PopupButtons.YesNo) == DialogResult.Yes) // { // statisticsServers.Add(new StatisticsServer(updateProject.SqlWebUrl, updateProject.SqlDatabaseName, updateProject.SqlUsername)); // File.WriteAllText(Path.Combine(Program.Path, "statservers.json"), Serializer.Serialize(statisticsServers)); // } // } //} UpdateProject.SaveProject(updateProject.Path, updateProject); string projectPath = Path.Combine(Program.Path, "Projects", projectNameTextBox.Text); if (!Directory.Exists(projectPath)) { Directory.CreateDirectory(projectPath); } using (var zip = new ZipFile(projectToImportTextBox.Text)) { zip.ExtractAll(folderPath); } if (File.Exists(statisticsFilePath)) { File.Move(statisticsFilePath, Path.Combine(projectPath, "statistics.php")); } File.Move(projectFilePath, projectFilePathTextBox.Text); foreach (var versionDirectory in new DirectoryInfo(folderPath).GetDirectories()) { Directory.Move(versionDirectory.FullName, Path.Combine(projectPath, versionDirectory.Name)); } Directory.Delete(folderPath); _projectConfigurations.Add(new ProjectConfiguration(projectNameTextBox.Text, projectFilePathTextBox.Text)); File.WriteAllText(Program.ProjectsConfigFilePath, Serializer.Serialize(_projectConfigurations)); } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while importing the project.", ex, PopupButtons.Ok); return; } Close(); } else if (_sender == shareTabPage) { wizardTabControl.SelectedTab = shareTabPage1; _sender = shareTabPage1; } else if (_sender == shareTabPage1) { if (!ValidationManager.Validate(shareTabPage1)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(projectOutputPathTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } try { string projectPath = Path.Combine(Program.Path, "Projects", projectsListBox.SelectedItem.ToString()); using (var zip = new ZipFile()) { string statisticsFilePath = Path.Combine(projectPath, "statistics.php"); if (File.Exists(statisticsFilePath)) { zip.AddFile(statisticsFilePath, "/"); } zip.AddFile( _projectConfigurations.First(item => item.Name == projectsListBox.SelectedItem.ToString()) .Path, "/"); foreach ( var versionDirectory in new DirectoryInfo(projectPath).GetDirectories() .Where(item => UpdateVersion.IsValid(item.Name))) { zip.AddDirectoryByName(versionDirectory.Name); zip.AddDirectory(versionDirectory.FullName, versionDirectory.Name); } zip.Save(projectOutputPathTextBox.Text); } } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while sharing the project.", ex, PopupButtons.Ok); return; } Close(); } }
public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { #region validate Activity if (manager == null) { throw new ArgumentNullException("manager"); } if (obj == null) { throw new ArgumentNullException("obj"); } ValidationErrorCollection collection = base.Validate(manager, obj); if (collection.HasErrors) { return(collection); } ReturnActivity activity = obj as ReturnActivity; collection.Clear(); if (activity == null) { throw new NullReferenceException("activity"); } if (activity.Parent != null) { //int lastIndex = activity.Parent.Activities.Count - 1; //if (activity.Parent.Activities[lastIndex].QualifiedName != activity.QualifiedName) //{ // collection.Add(new ValidationError("Activity must be at last position).", 0)); // return collection; //} } #endregion #region validate Properties (In Order) try { if (activity.Parent != null) { if (string.IsNullOrEmpty(activity.ConnectorActivityName)) { collection.Add(ValidationError.GetNotSetValidationError("ConnectorActivityName")); return(collection); } if (activity.ConnectorActivityName != "(None)") { Activity connector = Helpers.GetRootActivity(activity).GetActivityByName(activity.ConnectorActivityName, false) as Activity; if (connector != null) { string methodname = connector.GetType().InvokeMember("MethodName", BindingFlags.ExactBinding | BindingFlags.GetProperty | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance, null, connector, new object[0], CultureInfo.InvariantCulture) as string; if (string.IsNullOrEmpty(methodname)) { activity.ConnectorActivityName = default(string); collection.Add(new ValidationError("Missing corresponding ConnectorActivity (MethodName)", 0)); return(collection); } Type type = connector.GetType().InvokeMember("Type", BindingFlags.ExactBinding | BindingFlags.GetProperty | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance, null, connector, new object[0], CultureInfo.InvariantCulture) as Type; if (type == null) { collection.Add(new ValidationError("Missing corresponding ConnectorActivity (Type)", 0)); return(collection); } } else { activity.ConnectorActivityName = default(string); collection.Add(new ValidationError("Missing corresponding ConnectorActivity", 0)); return(collection); } } } } catch (Exception ex) { Trace.WriteLine(ex); } #endregion return(collection); }
public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); WebServiceFaultActivity webServiceFault = obj as WebServiceFaultActivity; if (webServiceFault == null) { throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(WebServiceFaultActivity).FullName), "obj"); } if (Helpers.IsActivityLocked(webServiceFault)) { return(validationErrors); } WebServiceInputActivity webServiceReceive = null; if (String.IsNullOrEmpty(webServiceFault.InputActivityName)) { validationErrors.Add(ValidationError.GetNotSetValidationError("InputActivityName")); } else { ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider)); if (typeProvider == null) { throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName)); } bool foundMatchingReceive = false; foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(webServiceFault)) { if ((activity is WebServiceFaultActivity && String.Compare(((WebServiceFaultActivity)activity).InputActivityName, webServiceFault.InputActivityName, StringComparison.Ordinal) == 0) || (activity is WebServiceOutputActivity && String.Compare(((WebServiceOutputActivity)activity).InputActivityName, webServiceFault.InputActivityName, StringComparison.Ordinal) == 0)) { if (activity is WebServiceFaultActivity) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_DuplicateWebServiceFaultFound, activity.Name, webServiceFault.InputActivityName), ErrorNumbers.Error_DuplicateWebServiceFaultFound)); } else { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_DuplicateWebServiceResponseFound, activity.Name, webServiceFault.InputActivityName), ErrorNumbers.Error_DuplicateWebServiceResponseFound)); } return(validationErrors); } } foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(webServiceFault)) { if (String.Compare(activity.QualifiedName, webServiceFault.InputActivityName, StringComparison.OrdinalIgnoreCase) == 0) { if (activity is WebServiceInputActivity) { webServiceReceive = activity as WebServiceInputActivity; foundMatchingReceive = true; } else { foundMatchingReceive = false; validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotValid, webServiceFault.InputActivityName), ErrorNumbers.Error_WebServiceReceiveNotValid)); return(validationErrors); } break; } } if (!foundMatchingReceive) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotFound, webServiceFault.InputActivityName), ErrorNumbers.Error_WebServiceReceiveNotFound)); return(validationErrors); } Type interfaceType = null; if (webServiceReceive.InterfaceType != null) { interfaceType = typeProvider.GetType(webServiceReceive.InterfaceType.AssemblyQualifiedName); } if (interfaceType == null) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured)); return(validationErrors); } // Validate method if (String.IsNullOrEmpty(webServiceReceive.MethodName)) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured)); return(validationErrors); } MethodInfo methodInfo = Helpers.GetInterfaceMethod(interfaceType, webServiceReceive.MethodName); if (methodInfo == null) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured)); return(validationErrors); } List <ParameterInfo> inputParameters, outParameters; WebServiceActivityHelpers.GetParameterInfo(methodInfo, out inputParameters, out outParameters); if (outParameters.Count == 0) { validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceFaultNotNeeded), ErrorNumbers.Error_WebServiceFaultNotNeeded)); return(validationErrors); } } return(validationErrors); }
private void btnSave_Click(object sender, RoutedEventArgs e) { if (!ValidationManager.Validate(this.LayoutRoot)) { return; } CategoryKeywords item = EntityConvertorExtensions.ConvertVM <CategoryKeywordsVM, CategoryKeywords>(VM, (v, t) => { t.CommonKeywords = new BizEntity.LanguageContent(ECCentral.Portal.Basic.ConstValue.BizLanguageCode, v.CommonKeywords); }); if (VM.SysNo.HasValue)//更新 { facade.UpdateCommonKeyWords(item, (obj, args) => { if (args.FaultsHandle()) { return; } CPApplication.Current.CurrentPage.Context.Window.Alert(ResKeywords.Information_UpdateSuccessful, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Information); }); } else { item.CompanyCode = Newegg.Oversea.Silverlight.ControlPanel.Core.CPApplication.Current.CompanyCode; facade.CheckCategoryKeywordsC3SysNo(item, (obj, args) => { if (args.FaultsHandle()) { return; } if (args.Result) { CPApplication.Current.CurrentPage.Context.Window.Confirm(ResKeywords.Information_BUpdateCommonKeywords, (obj2, args2) => { if (args2.DialogResult == Newegg.Oversea.Silverlight.Controls.Components.DialogResultType.OK) { facade.AddCommonKeyWords(item, (obj1, args1) => { if (args1.FaultsHandle()) { return; } CPApplication.Current.CurrentPage.Context.Window.Alert(ResKeywords.Information_CreateSuccessful, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Information); }); } }); } else { facade.AddCommonKeyWords(item, (obj1, args1) => { if (args1.FaultsHandle()) { return; } CPApplication.Current.CurrentPage.Context.Window.Alert(ResKeywords.Information_CreateSuccessful, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Information); }); } }); } }
private void btnAddTemplate_Click(object sender, RoutedEventArgs e) { if (!ValidationManager.Validate(this)) { return; } CommissionRuleTemplateInfo info = new CommissionRuleTemplateInfo(); RefreshVendorSaleRuleList(); vm.SaleRuleEntity.StagedSaleRuleItems = this.ucSaleStageSettings.VendorStageSaleSettingsList; vm.SaleRuleEntity.MinCommissionAmt = string.IsNullOrEmpty(vm.GuaranteedAmt) ? (decimal?)null : decimal.Parse(vm.GuaranteedAmt); if (SysNo == 0) { info.C3SysNos = new List <CommissionRuleTemplateInfo.CategoryReq>(); foreach (var c1 in this.tvCategory.TreeNode.SonNodes) { foreach (var c2 in c1.SonNodes) { foreach (var c3 in c2.SonNodes) { if (c3.IsSelected) { info.C3SysNos.Add(new CommissionRuleTemplateInfo.CategoryReq() { C1 = c1.Value - 3000000, C2 = c2.Value - 4000000, C3 = c3.Value }); } } } } info.BrandSysNos = new List <int>(); foreach (var b in this.tvBrand.TreeNode.SonNodes) { if (b.IsSelected) { info.BrandSysNos.Add(b.Value); } } if (info.C3SysNos.Count == 0) { MessageBox.Show("请选择一个类别"); return; } if (info.BrandSysNos.Count == 0) { MessageBox.Show("请选择一个类别"); return; } info.Status = CommissionRuleStatus.Active; } else { info.C3SysNos = new List <CommissionRuleTemplateInfo.CategoryReq>(); info.C3SysNos.Add(new CommissionRuleTemplateInfo.CategoryReq() { C1 = EditInfo.C1SysNo.Value, C2 = EditInfo.C2SysNo.Value, C3 = EditInfo.C3SysNo.Value }); info.BrandSysNos = new List <int>(); info.BrandSysNos.Add(EditInfo.BrandSysNo.Value); info.Status = EditInfo.Status; } info.SaleRuleEntity = EntityConverter <VendorStagedSaleRuleEntityVM, VendorStagedSaleRuleEntity> .Convert(vm.SaleRuleEntity); info.RentFee = string.IsNullOrEmpty(vm.RentFee) ? (decimal?)null : decimal.Parse(vm.RentFee); info.OrderCommissionAmt = string.IsNullOrEmpty(vm.OrderCommissionAmt) ? (decimal?)null : decimal.Parse(vm.OrderCommissionAmt); info.DeliveryFee = string.IsNullOrEmpty(vm.DeliveryFee) ? (decimal?)null : decimal.Parse(vm.DeliveryFee); if ((info.OrderCommissionAmt == 0 || info.OrderCommissionAmt == null) && (info.SaleRuleEntity == null || info.SaleRuleEntity.StagedSaleRuleItems == null || info.SaleRuleEntity.StagedSaleRuleItems.Count == 0)) { MessageBox.Show("请至少设置一个销售提成或订单提成规则!"); return; } if (info.SaleRuleEntity != null && info.SaleRuleEntity.StagedSaleRuleItems != null && info.SaleRuleEntity.StagedSaleRuleItems.Count > 0) { info.SaleRuleEntity.StagedSaleRuleItems[info.SaleRuleEntity.StagedSaleRuleItems.Count - 1].EndAmt = 99999999; } vendorFacade.UpdateCommissionRuleTemplate(info, (o, args) => { if (args.FaultsHandle()) { return; } MessageBox.Show("操作成功!"); this.Dialog.ResultArgs.DialogResult = DialogResultType.OK; this.Dialog.Close(true); }); }
public static DataAccessResponseType CreateImageFormat(Account account, string imageGroupTypeNameKey, string imageGroupNameKey, string imageFormatName, int width, int height, bool listing, bool gallery) { var response = new DataAccessResponseType(); #region Validate Plan Restrictions if (GetCustomImageFormatCount(account.AccountNameKey) >= account.PaymentPlan.MaxImageFormats) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "You have reached your account restriction of " + account.PaymentPlan.MaxImageFormats + " custom image formats" }); } if (gallery && GetCustomImageGalleryCount(account.AccountNameKey) >= account.PaymentPlan.MaxImageGalleries) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "You have reached your account restriction of " + account.PaymentPlan.MaxImageGalleries + " custom image galleries" }); } #endregion #region Validate Platform Restrictions if (listing) { if (GetCustomImageFormatsAsListingCount(account.AccountNameKey) >= Settings.Objects.Limitations.MaximumImageFormatsAsListings) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "You have reached the platform restriction of " + Settings.Objects.Limitations.MaximumImageFormatsAsListings + " listing images per inventory" }); } } #endregion #region Validate Input if (String.IsNullOrEmpty(imageGroupTypeNameKey)) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "imageGroupTypeNameKey cannot be empty" }); } if (String.IsNullOrEmpty(imageGroupNameKey)) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "imageGroupNameKey cannot be empty" }); } if (String.IsNullOrEmpty(imageFormatName)) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "imageFormatName cannot be empty" }); } if (listing && gallery) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Image format cannot be both a Listing and a Gallery" }); } if (height < 1) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Image height must be taller than 1px" }); } if (width < 0) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Image width must be a positive number" }); } //if (width < 1) //<-- 0 now means that this is a VARIABLE WIDTH image //{ //return new DataAccessResponseType { isSuccess = false, ErrorMessage = "Image width must be wider than 1px" }; //} if (height > 4000) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Image height cannot be taller than 4,000px" }); } if (width > 4000) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Image width cannot be wider than 4,000px" }); } #endregion #region Validate Image Format Name: ValidationResponseType ojectNameValidationResponse = ValidationManager.IsValidImageFormatName(imageFormatName); if (!ojectNameValidationResponse.isValid) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = ojectNameValidationResponse.validationMessage }); } #endregion //CREATE NAME KEY var imageFormatNameKey = Sahara.Core.Common.Methods.ObjectNames.ConvertToObjectNameKey(imageFormatName); #region Validate GroupType Exists var imageGroupTypes = GetImageFormatGroupTypes(); bool typeExists = false; foreach (ImageFormatGroupTypeModel type in imageGroupTypes) { if (type.ImageFormatGroupTypeNameKey == imageGroupTypeNameKey) { typeExists = true; } } if (!typeExists) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Format group type '" + imageGroupTypeNameKey + "' does not exists!" }); } #endregion var imageFormats = GetImageFormats(account.AccountNameKey, imageGroupTypeNameKey); #region Validate Group Exists in this Type bool groupExistsInType = false; foreach (ImageFormatGroupModel group in imageFormats) { if (group.ImageFormatGroupTypeNameKey == imageGroupTypeNameKey && group.ImageFormatGroupNameKey == imageGroupNameKey) { groupExistsInType = true; } } if (!groupExistsInType) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Format group '" + imageGroupNameKey + "' does not exists!" }); } #endregion #region Validate Format name is unique to this group/type combo bool nameUniqueInGroup = true; foreach (ImageFormatGroupModel group in imageFormats) { if (group.ImageFormatGroupTypeNameKey == imageGroupTypeNameKey && group.ImageFormatGroupNameKey == imageGroupNameKey) { foreach (ImageFormatModel format in group.ImageFormats) { if (format.ImageFormatName == imageFormatName || format.ImageFormatNameKey == imageFormatNameKey) { nameUniqueInGroup = false; } } } } if (!nameUniqueInGroup) { return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "Format name '" + imageFormatNameKey + "' is not unique to the '" + imageGroupNameKey + "' group!" }); } #endregion #region Create Model & ID var imageFormat = new ImageFormatModel { ImageFormatGroupTypeNameKey = imageGroupTypeNameKey, ImageFormatGroupNameKey = imageGroupNameKey, ImageFormatID = Guid.NewGuid(), ImageFormatName = imageFormatName, ImageFormatNameKey = imageFormatNameKey, Height = height, Width = width, Listing = listing, Gallery = gallery }; #endregion //INSERT response = Sql.Statements.InsertStatements.InsertImageFormat(account.SqlPartition, account.SchemaName, imageFormat); //, account.PaymentPlan.MaxImageFormats); //CLear Cache if (response.isSuccess) { Caching.InvalidateImageFormatCaches(account.AccountNameKey); } return(response); }
public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { System.Workflow.Activities.Common.WalkerEventHandler handler = null; ValidationErrorCollection validationErrors = base.Validate(manager, obj); InvokeWorkflowActivity activity = obj as InvokeWorkflowActivity; if (activity == null) { throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(InvokeWorkflowActivity).FullName }), "obj"); } if (activity.TargetWorkflow == null) { ValidationError error = new ValidationError(SR.GetString("Error_TypePropertyInvalid", new object[] { "TargetWorkflow" }), 0x116) { PropertyName = "TargetWorkflow" }; validationErrors.Add(error); return(validationErrors); } ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider)); if (service == null) { throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName })); } Type targetWorkflow = activity.TargetWorkflow; if ((targetWorkflow.Assembly == null) && (service.LocalAssembly != null)) { Type type = service.LocalAssembly.GetType(targetWorkflow.FullName); if (type != null) { targetWorkflow = type; } } if (!TypeProvider.IsAssignable(typeof(Activity), targetWorkflow)) { ValidationError error2 = new ValidationError(SR.GetString("Error_TypeIsNotRootActivity", new object[] { "TargetWorkflow" }), 0x60e) { PropertyName = "TargetWorkflow" }; validationErrors.Add(error2); return(validationErrors); } Activity seedActivity = null; try { seedActivity = Activator.CreateInstance(targetWorkflow) as Activity; } catch (Exception) { } if (seedActivity == null) { ValidationError error3 = new ValidationError(SR.GetString("Error_GetCalleeWorkflow", new object[] { activity.TargetWorkflow }), 0x500) { PropertyName = "TargetWorkflow" }; validationErrors.Add(error3); return(validationErrors); } System.Workflow.Activities.Common.Walker walker = new System.Workflow.Activities.Common.Walker(); if (handler == null) { handler = delegate(System.Workflow.Activities.Common.Walker w, System.Workflow.Activities.Common.WalkerEventArgs args) { if ((args.CurrentActivity is WebServiceInputActivity) && ((WebServiceInputActivity)args.CurrentActivity).IsActivating) { ValidationError item = new ValidationError(SR.GetString("Error_ExecWithActivationReceive"), 0x614) { PropertyName = "Name" }; validationErrors.Add(item); args.Action = System.Workflow.Activities.Common.WalkerAction.Abort; } }; } walker.FoundActivity += handler; walker.Walk(seedActivity); bool flag = false; for (Activity activity3 = activity.Parent; activity3 != null; activity3 = activity3.Parent) { if ((activity3 is CompensatableTransactionScopeActivity) || (activity3 is TransactionScopeActivity)) { flag = true; break; } } if (flag) { ValidationError error4 = new ValidationError(SR.GetString("Error_ExecInAtomicScope"), 0x502); validationErrors.Add(error4); } foreach (WorkflowParameterBinding binding in activity.ParameterBindings) { PropertyInfo property = null; property = targetWorkflow.GetProperty(binding.ParameterName); if (property == null) { ValidationError error5 = new ValidationError(SR.GetString("Error_ParameterNotFound", new object[] { binding.ParameterName }), 0x504); if (InvokeWorkflowActivity.ReservedParameterNames.Contains(binding.ParameterName)) { error5.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(activity.GetType(), binding.ParameterName); } validationErrors.Add(error5); } else { Type propertyType = property.PropertyType; if (binding.GetBinding(WorkflowParameterBinding.ValueProperty) != null) { ValidationErrorCollection errors = System.Workflow.Activities.Common.ValidationHelpers.ValidateProperty(manager, activity, binding.GetBinding(WorkflowParameterBinding.ValueProperty), new PropertyValidationContext(binding, null, binding.ParameterName), new BindValidationContext(propertyType, AccessTypes.Read)); if (errors.Count != 0) { validationErrors.AddRange(errors); } } } } return(validationErrors); }
/// <summary> /// Validates the consumption kWh firgure of an invoice /// </summary> /// <param name="invoice">Invoice being validated</param> /// <returns>Updated invoice with kWh variation and costIsValid bool</returns> internal static Invoice validateConsumption(Invoice invoice) { if ((bool)invoice.ConsumptionCanBeValidated) { invoice.ConsumptionCanBeValidated = true; ValidationManager validationMgr = new ValidationManager(); double meteredkWh = validationMgr.getDataFromMeter(invoice.Meter.Id, invoice.StartDate.ToString(), invoice.EndDate.ToString(), (int)DataType.Energy); invoice.KWhVariance = invoice.KWh - meteredkWh; ///consumption within 15% is considered valid ///margin of error due to: /// - rounding /// - apportionment estimation invoice.ConsumptionIsValid = (Math.Abs((decimal)invoice.KWhVariance) < (decimal)(meteredkWh * 0.15)); } return invoice; }
protected void btnSave_Click(object sender, RoutedEventArgs e) { bool IsOk = true; if (null == this.CurrentWidnow) { return; } // UI Check if (!ValidationManager.Validate(this.basicInfo)) { return; } // 已选择的批次 this.selectedLst = new List <ProductBatchInfoVM>(); if (this.IsNotLend_Return) { batches.ToList <ProductBatchInfoVM>().ForEach((p) => { if (p.Quantity != 0) { selectedLst.Add(p); } }); } else { batchVM.ToList <ProductBatchInfoVM>().ForEach((p) => { if (p.ReturnQuantity.HasValue && p.ReturnQuantity != 0) { selectedLst.Add(p); } }); } // 根据商品编号获取商品信息 ProductQueryFacade facade = new ProductQueryFacade(CPApplication.Current.CurrentPage); PagingInfo paging = new PagingInfo { PageIndex = 0, PageSize = 1, }; List <ProductVM> productLst = new List <ProductVM>(); facade.QueryProduct(new ProductSimpleQueryVM { ProductSysNo = filterVM.ProductSysNo }, paging , (obj, args) => { if (args.FaultsHandle()) { return; } productLst = DynamicConverter <ProductVM> .ConvertToVMList <List <ProductVM> >(args.Result.Rows); // 附加批次信息 List <BatchInfoVM> batchList = EntityConverter <ProductBatchInfoVM, BatchInfoVM> .Convert(selectedLst); ProductVMAndBillInfo paramVM = new ProductVMAndBillInfo(); paramVM.ProductVM = productLst; if (paramVM.ProductVM.FirstOrDefault().IsHasBatch == 1) { paramVM.ProductVM.FirstOrDefault().ProductBatchLst = batchList; if (filterVM.ReturnDate.HasValue) { paramVM.ReturnDate = filterVM.ReturnDate; } // check batch info IsOk = PreCheckHasBatch(); } else if (paramVM.ProductVM.FirstOrDefault().IsHasBatch == 0) { switch (this.PType) { case PageType.Lend: paramVM.Quantity = Convert.ToInt32(filterVM.LendNum); paramVM.ReturnQuantity = Convert.ToInt32(filterVM.ReturnNum); break; case PageType.Adjust: paramVM.Quantity = Convert.ToInt32(filterVM.AdjustNum); break; case PageType.Convert: paramVM.Quantity = Convert.ToInt32(filterVM.ConvertNum); break; } if (filterVM.ReturnDate.HasValue) { paramVM.ReturnDate = filterVM.ReturnDate; } } if (!IsOk) { return; } this.DialogHandler.ResultArgs.Data = paramVM; this.DialogHandler.ResultArgs.DialogResult = DialogResultType.OK; this.DialogHandler.Close(); }); }