/// <summary> /// Reads <see cref="IdentificationModel"/> from XML file /// </summary> /// <param name="filePath">Full path to model XML file</param> /// <returns><see cref="IdentificationModel"/> instance read from <paramref name="filePath"/></returns> /// <exception cref="ArgumentNullException">If <paramref name="filePath"/> is null or empty</exception> public static IdentificationModel Open(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } FileInfo modelFileInfo = new FileInfo(filePath); IdentificationModel model = new IdentificationModel(); using (FileStream modelFileStream = File.OpenRead(modelFileInfo.FullName)) using (XmlReader modelFileReader = XmlReader.Create(modelFileStream, modelFileReaderSettings)) { XDocument modelFileDocument = XDocument.Load(modelFileReader, LoadOptions.None); XElement optimizationParametersCollectionElement = ReadCollectionElement(Elements.OptimizationParameters, modelFileDocument.Root); XElement identificationParametersCollectionElement = ReadCollectionElement(Elements.IdentificationParameters, modelFileDocument.Root); XElement criteriaCollectionElement = ReadCollectionElement(Elements.Criteria, modelFileDocument.Root); XElement constraintsCollectionElement = ReadCollectionElement(Elements.FunctionalConstraints, modelFileDocument.Root); XElement realExperimentsCollectionElement = ReadCollectionElement(Elements.RealExperiments, modelFileDocument.Root); XElement identificationExperimentsCollectionElement = ReadCollectionElement(Elements.IdentificationExperiments, modelFileDocument.Root); XElement propertiesCollectionElement = ReadCollectionElement(Elements.Properties, modelFileDocument.Root, false); ReadParameters(model.OptimizationParameters, optimizationParametersCollectionElement, Elements.OptimizationParameter); ReadParameters(model.IdentificationParameters, identificationParametersCollectionElement, Elements.IdentificationParameter); ReadCriteria(model.Criteria, criteriaCollectionElement); ReadConstraints(model.FunctionalConstraints, constraintsCollectionElement); ReadRealExperiments(model.RealExperiments, realExperimentsCollectionElement); ReadIdentificationExperiments(model.IdentificationExperiments, identificationExperimentsCollectionElement); ReadPropertyCollection(model.Properties, propertiesCollectionElement); } return(model); }
public IActionResult Index(string IIN, IFormFile file) { try { var claims = User.Claims.ToList(); if (String.IsNullOrEmpty(IIN)) { throw new Exception("Вы не указали ИИН"); } if (IIN.Length != 12) { throw new Exception("Введен некорректный ИИН"); } if (file == null) { throw new Exception("Вы не загрузили файл"); } if (file.ContentType != "image/png" && file.ContentType != "image/jpeg" && file.ContentType != "image/jpg" && file.ContentType != "image/gif") { throw new Exception("Файл не является изображением"); } string img; using (var ms = new MemoryStream()) { file.CopyTo(ms); var fileBytes = ms.ToArray(); img = Convert.ToBase64String(fileBytes); } IdentificationModel data = new IdentificationModel { IIN = IIN, Photo = img }; RequestClass <IdentificationModel> request = new RequestClass <IdentificationModel> { Login = claims[0].Value, Password = claims[2].Value, Token = claims[1].Value, Data = data }; ResponseClass <decimal> identity = _repository.Identity(request); if (identity.Code == 0) { ViewBag.Validate = "ИИН " + IIN + "\n Результат: " + Convert.ToDecimal(identity.Data).ToString("0.0000"); } else { ViewBag.Validate = "Не удалось провести идентификацию"; } return(View("Index")); } catch (Exception e) { ViewBag.Validate = e.Message; return(View("Index")); } }
public ModelCalculator(string modelFilePath) { if (string.IsNullOrEmpty(modelFilePath)) { throw new ArgumentNullException("modelFilePath"); } model = XmlIdentificationModelProvider.Open(modelFilePath); modelFile = modelFilePath; }
public void ProcessModel(object data) { CancellationToken cancellationToken; if (data == null) { cancellationToken = new CancellationToken(false); } else { cancellationToken = (CancellationToken)data; } if (cancellationToken.IsCancellationRequested) { OnProcessingComplete(new EventArgs()); return; } model = XmlIdentificationModelProvider.Open(optFile); if (cancellationToken.IsCancellationRequested) { OnProcessingComplete(new EventArgs()); return; } int maxProgress = model.IdentificationExperiments.Count; OnProgressChanged(new ProgressChangedEventArgs(0, maxProgress, 0, "Initialized")); int exp = 0; foreach (IdentificationExperiment experiment in model.IdentificationExperiments.Values) { if (cancellationToken.IsCancellationRequested) { break; } ProcessExperiment(experiment); OnProgressChanged(new ProgressChangedEventArgs(0, maxProgress, ++exp, "Processed experiment #" + experiment.Number.ToString())); } if (cancellationToken.IsCancellationRequested) { OnProcessingComplete(new EventArgs()); return; } XmlIdentificationModelProvider.Save(model, optFile); OnProcessingComplete(new EventArgs()); }
/// <summary> /// Copies values of optimization <see cref="Parameter"/>s from <paramref name="identificationModel"/> /// to the <see cref="Experiment"/> instances in <paramref name="destination"/> collection /// </summary> /// <param name="identificationModel"><see cref="IdentificationModel"/> instance to take values from</param> /// <param name="destination">Destination collection (set values to)</param> private static void CopyOptimizationParametersValues(IdentificationModel identificationModel, ExperimentCollection destination) { foreach (IdentificationExperiment experiment in identificationModel.IdentificationExperiments.Values) { Experiment toModify = destination[experiment.Id]; Experiment realExperiment = identificationModel.RealExperiments[experiment.RealExperimentId]; foreach (KeyValuePair <TId, double> optimizationParameter in realExperiment.ParameterValues) { toModify.ParameterValues.Add(optimizationParameter.Key, optimizationParameter.Value); } } }
/// <summary> /// 更新联系人信息和证件信息 /// </summary> /// <param name="contactInfo"></param> private void UpdateContact(ContactInfoModel contactInfo) { if (contactInfo.ContactId == 0) { return; } //更新联系人信息 _contactBll.UpdateContact(contactInfo); //根据联系人Id获取证件信息 if (contactInfo.CardNoType.HasValue && !string.IsNullOrEmpty(contactInfo.CardNo)) { List <IdentificationModel> identificationModels = _identificationInfoBll.GetIdentificationInfoByContactId(new List <int>() { contactInfo.ContactId }); if (identificationModels == null) { _identificationInfoBll.AddIdentificationInfo(new IdentificationModel() { ContactId = contactInfo.ContactId, Iid = contactInfo.CardNoType.Value, CardNo = contactInfo.CardNo }); } else { IdentificationModel identificationModel = identificationModels.Find(n => n.Iid == contactInfo.CardNoType.Value);//根据证件类型获取证件信息 if (identificationModel != null) { if (identificationModel.CardNo != contactInfo.CardNo)//有该证件类型,但是证件号不一致,则更新 { identificationModel.CardNo = contactInfo.CardNo; _identificationInfoBll.UpdateIdentificationInfo(identificationModel); } } else//没有该证件,则新增 { _identificationInfoBll.AddIdentificationInfo(new IdentificationModel() { ContactId = contactInfo.ContactId, Iid = contactInfo.CardNoType.Value, CardNo = contactInfo.CardNo }); } } } }
public static Identification ToEntity(this IdentificationModel identification) { return(new Identification { IdentificationId = identification.Id, Type = identification.Type, Name = identification.Name, VatNumber = identification.VatNumber, EmailAddress = identification.EmailAddress, Description = identification.Description, IsValidated = identification.IsValidated, Logo = identification.Logo, Informations = identification.Informations?.Select(i => i.ToEntity()).ToList() }); }
/// <summary> /// Writes <paramref name="model"/> to XML file /// </summary> /// <param name="model"><see cref="IdentificationModel"/> instance to be written to XML</param> /// <param name="filePath">Full path to target XML file</param> public static void Save(IdentificationModel model, string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } XDocument modelDocument = GetXDocument(model); FileInfo modelFileInfo = new FileInfo(filePath); using (FileStream modelFileStream = modelFileInfo.Open(FileMode.Create, FileAccess.Write, FileShare.None)) using (XmlWriter modelFileWriter = XmlWriter.Create(modelFileStream, modelFileWriterSettings)) { modelDocument.Save(modelFileWriter); } }
void ManualInitDeviceHolder(INvtSession session, DeviceDescriptionHolder devHolder) { devHolder.session = session; facade = new OdmSession(session); var model = new IdentificationModel(); IdentitySubscriptions.Add( facade.GetIdentity(() => model) .ObserveOnCurrentDispatcher() .Subscribe(mod => { devHolder.Init(mod); }, err => { //dbg.Error(err); //MessageBox.Show(err.Message); }) ); }
/// <summary> /// Calculates adequacy criteria values for all identification experiments in the given <paramref name="model"/> /// </summary> /// <param name="model">Instance of <see cref="IdentificationModel"/> to take data from and /// put calculation results to</param> /// <remarks>Utilizes <see cref="ResidualFunctionRegistry"/>. Overwrites existing adequacy criteria values</remarks> public static void CalculateAdequacyCriteriaValues(IdentificationModel model) { if (model == null) { throw new ArgumentNullException("model"); } foreach (IdentificationExperiment identificationExperiment in model.IdentificationExperiments.Values) { identificationExperiment.AdequacyCriterionValues.Clear(); foreach (AdequacyCriterion criterion in model.Criteria.Values) { double mathCriterionValue = identificationExperiment.MathematicalCriterionValues[criterion.Id]; double realCriterionValue = model.RealExperiments[identificationExperiment.RealExperimentId].CriterionValues[criterion.Id]; identificationExperiment.AdequacyCriterionValues.Add(criterion.Id, GetResidual(criterion.AdequacyType, mathCriterionValue, realCriterionValue)); } } }
/// <summary> /// Creates <see cref="XDocument"/> with <paramref name="model"/> contents /// </summary> /// <param name="model"><see cref="IdentificationModel"/> instance to be written to XML</param> /// <returns><see cref="XDocument"/> with <paramref name="model"/> contents</returns> private static XDocument GetXDocument(IdentificationModel model) { if (model == null) { throw new ArgumentNullException("model"); } XDocument modelDocument = new XDocument(new XDeclaration("1.0", "UTF-8", null)); WriteModelElement(modelDocument); WriteParameters(model.OptimizationParameters, modelDocument.Root, Elements.OptimizationParameters, Elements.OptimizationParameter); WriteParameters(model.IdentificationParameters, modelDocument.Root, Elements.IdentificationParameters, Elements.IdentificationParameter); WriteCriteria(model.Criteria, modelDocument.Root); WriteFunctionalConstraints(model.FunctionalConstraints, modelDocument.Root); WriteRealExperiments(model.RealExperiments, modelDocument.Root); WriteIdentificationExperiments(model.IdentificationExperiments, modelDocument.Root); WritePropertyCollection(model.Properties, modelDocument.Root); return(modelDocument); }
void InitDeviceHolder(INvtSession session, DeviceDescriptionHolder devHolder, bool publish) { devHolder.session = session; facade = new OdmSession(session); var model = new IdentificationModel(); IdentitySubscriptions.Add( facade.GetIdentity(() => model) .ObserveOnCurrentDispatcher() .Subscribe(mod => { devHolder.Init(mod); if (publish) { DeviceSelectedPublish(devHolder, sessionFactory); } }, err => { //dbg.Error(err); //MessageBox.Show(err.Message); }) ); }
public async Task <ActionResult> Delete([Bind("Id", "Type", "Name", "VatNumber", "EmailAddress", "Description")] IdentificationModel task) { try { var httpResponse = await Client.DeleteAsync($"{BaseUrl}/{task.Id}"); if (!httpResponse.IsSuccessStatusCode) { throw new Exception("Cannot retieve tasks"); } TempData["Message"] = "This Idendification was delete successfully !"; return(RedirectToAction("Index")); } catch { return(View("NotFound")); } }
/// <summary> /// Creates new instance of <see cref="Model"/> and fills it with data taken from /// <paramref name="identificationModel"/> /// </summary> /// <param name="identificationModel"><see cref="IdentificationModel"/> instance to be converted</param> /// <returns>New instance of <see cref="Model"/> based on <paramref name="identificationModel"/></returns> public static Model ConvertToOptimization(IdentificationModel identificationModel) { Model optimizationModel = new Model(); // 1. Copy the optimization parameters (X) CopyParameters(identificationModel.OptimizationParameters, optimizationModel.Parameters); // 2. Copy the identification parameters (α) Dictionary <TId, TId> parameterIds = CopyParameters(identificationModel.IdentificationParameters, optimizationModel.Parameters, true); // 3. Copy adequacy criteria (Φ). No conversion is needed CopyModelEntites <AdequacyCriterion, Criterion>(identificationModel.Criteria, optimizationModel.Criteria); // 4. Copy functional constraints (f) CopyModelEntites <Constraint, Constraint>(identificationModel.FunctionalConstraints, optimizationModel.FunctionalConstraints); // 5. Copy experiments CreateExperiments(identificationModel, optimizationModel.Experiments, parameterIds); CopyOptimizationParametersValues(identificationModel, optimizationModel.Experiments); return(optimizationModel); }
public async Task <ActionResult> Create([Bind("Type", "Name", "VatNumber", "EmailAddress", "Description", "IsValidated")] IdentificationModel task) { try { var content = JsonConvert.SerializeObject(task); var httpResponse = await Client.PostAsync(BaseUrl, new StringContent(content, Encoding.Default, "application/json")); if (!httpResponse.IsSuccessStatusCode) { throw new Exception("Cannot create this Identification !"); } TempData["Message"] = "This Identification is create successfully !"; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["Message"] = ex.Message; return(View("NotFound")); } }
public decimal GetIdentification(IdentificationModel identification, int key) { try { if (key == 0) { return(0.995125M); } else { var handler = new HttpClientHandler(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cert\\hgg.p12"); handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword)); using (var httpClient = new HttpClient(handler)) { using (var request = new HttpRequestMessage(new HttpMethod("POST"), _identityUrl + "iin=" + identification.IIN + "&vendor=" + _vendor)) { string token = GetToken(); request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token); request.Headers.TryAddWithoutValidation("x-idempotency-key", "key:" + "hggKey-" + key); request.Method = new HttpMethod("POST"); //request.Content = new StringContent(identification.Photo); request.Content = new StreamContent(new MemoryStream(Convert.FromBase64String(identification.Photo))); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); var response = httpClient.SendAsync(request); string data = response.Result.Content.ReadAsStringAsync().Result; return(JsonConvert.DeserializeObject <dynamic>(data).result); } } } } catch { throw new Exception("Не удалось провести идентификацию"); } }
/// <summary> /// Creates <see cref="Model"/>'s experiments (<see cref="Experiment"/>) based on the <see cref="IdentificationExperiment"/> /// stored in the <paramref name="identificationModel"/> and puts them to the <paramref name="destination"/> collection /// </summary> /// <param name="identificationModel"><see cref="IdentificationModel"/> instance to take experiments from</param> /// <param name="destination">Destination collection (save experiments to)</param> /// <param name="identificationParameterIdMap">IDs map for parameters (<see cref="ModelsConverter.CopyParameters"/></param> private static void CreateExperiments(IdentificationModel identificationModel, ExperimentCollection destination, IDictionary <TId, TId> identificationParameterIdMap) { destination.Clear(); foreach (IdentificationExperiment experiment in identificationModel.IdentificationExperiments.Values) { // Here we are leaving Custom Properties behind, but that should be fine for now Experiment toAdd = new Experiment(experiment.Id, experiment.Number); foreach (Parameter identificationParameter in identificationModel.IdentificationParameters.Values) { TId parameterId = identificationParameterIdMap[identificationParameter.Id]; if (experiment.IdentificationParameterValues.ContainsKey(identificationParameter.Id)) { toAdd.ParameterValues.Add(parameterId, experiment.IdentificationParameterValues[identificationParameter.Id]); } } foreach (AdequacyCriterion criterion in identificationModel.Criteria.Values) { if (experiment.AdequacyCriterionValues.ContainsKey(criterion.Id)) { toAdd.CriterionValues.Add(criterion.Id, experiment.AdequacyCriterionValues[criterion.Id]); } } foreach (Constraint constraint in identificationModel.FunctionalConstraints.Values) { if (experiment.ConstraintValues.ContainsKey(constraint.Id)) { toAdd.ConstraintValues.Add(constraint.Id, experiment.ConstraintValues[constraint.Id]); } } destination.Add(toAdd); } }
public async Task <ActionResult> Edit([Bind("Id", "Type", "Name", "VatNumber", "EmailAddress", "Description")] IdentificationModel task) { try { var content = JsonConvert.SerializeObject(task); var httpResponse = await Client.PutAsync($"{BaseUrl}/{task.Id}", new StringContent(content, Encoding.Default, "application/json")); if (!httpResponse.IsSuccessStatusCode) { throw new Exception("Cannot Edit this Identification !"); } TempData["Message"] = "This Identification was update successfully !"; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["Message"] = ex; return(RedirectToAction("Error", "Shared")); } }
public bool PostIdentification(IdentificationModel model, int cid) { var contact = _contactDal.Query <ContactInfoEntity>(a => a.PCid == cid).FirstOrDefault(); if (contact == null) { throw new Exception("当前客户信息异常,不能修改"); } if (model.IsDefault == 1) { contact.DefaultIdentificationId = model.Iid; _contactDal.Update <ContactInfoEntity>(contact, new string[] { "DefaultIdentificationId" }); } else { if (contact.DefaultIdentificationId.HasValue && contact.DefaultIdentificationId.Value == model.Iid) { contact.DefaultIdentificationId = 0; _contactDal.Update <ContactInfoEntity>(contact, new string[] { "DefaultIdentificationId" }); } } model.ContactId = contact.Contactid; //判断当前公司下,是否存在相同证件,如果存在,则不许修改 CustomerModel customerModel = _getCustomerBll.GetCustomerByCid(cid); if (!string.IsNullOrEmpty(customerModel.CorpID)) { List <CustomerModel> customerModels = _getCustomerBll.GetCustomerByCorpId(customerModel.CorpID); List <int> cidList = new List <int>(); customerModels.ForEach(n => { if (n.Cid != cid) { cidList.Add(n.Cid); } }); List <ContactInfoEntity> contactInfoEntities = _contactDal.Query <ContactInfoEntity>(a => cidList.Contains(a.PCid ?? 0)).ToList(); List <int> contactIdList = new List <int>(); contactInfoEntities.ForEach(n => contactIdList.Add(n.Contactid)); List <ContactIdentificationInfoEntity> infoList = _contactIdentificationDal.Query <ContactIdentificationInfoEntity>( n => contactIdList.Contains(n.Contactid) && !string.IsNullOrEmpty(n.CardNo) && n.CardNo.ToUpper() == model.CardNo.ToUpper() && n.Iid == model.Iid) .ToList(); if (infoList != null && infoList.Count > 0) { throw new Exception("当前公司存在相同证件号,不能修改"); } } var identifications = _contactIdentificationDal.Query <ContactIdentificationInfoEntity>(a => a.Contactid == model.ContactId && a.Iid == model.Iid); var entity = Mapper.Map <IdentificationModel, ContactIdentificationInfoEntity>(model); entity.LastUpdateTime = DateTime.Now; entity.CardNo = entity.CardNo ?? ""; if (identifications != null && identifications.Any()) { _contactIdentificationDal.Update <ContactIdentificationInfoEntity>(entity); } else { _contactIdentificationDal.Insert <ContactIdentificationInfoEntity>(entity); } return(true); }
private ModelStorage() { Model = new IdentificationModel(); }