public async Task <ResetPasswordResponse> Handle(ResetPasswordRequest request, CancellationToken cancellationToken) { var result = new ResetPasswordResponse(); var user = await _context.Users.FindAsync(request.UserID); if (user != null) { string passwordSalt; string passwordHash; if (!string.IsNullOrEmpty(request.Password)) { if (!AppUtility.VerifyPasswordHash(request.Password, user.PasswordSalt, user.PasswordHash)) { passwordSalt = AppUtility.CreatePasswordSalt(); passwordHash = AppUtility.CreatePasswordHash(request.Password, passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; } } await _context.SaveChangesAsync(cancellationToken); } else { throw new Exception("Maaf, User tidak ditemukan"); } return(result); }
/// <summary> /// Finds the by. /// </summary> /// <param name="where">The where.</param> /// <returns></returns> public virtual IEnumerable <TEntity> FindBy(Expression <Func <TEntity, bool> > where) { IEnumerable <TEntity> query; AppUtility.ValidateContext(CurrentDbContext); try { var dbSet = CurrentDbContext.Set <TEntity>(); query = dbSet.Where(where).ToList(); } catch (SqlException sqex) { Audit.Log.Error(AppConstants.ErrorMessages.SqlExceptionMessage, sqex); throw; } catch (DbException dbex) { Audit.Log.Error(AppConstants.ErrorMessages.DbExceptionMessage, dbex); throw; } catch (Exception ex) { Audit.Log.Error(AppConstants.ErrorMessages.ExceptionMessage, ex); throw; } return(query); }
public static void Log(string Message, string Code = "", string Page = "") { try { string file = HttpContext.Current.Server.MapPath("~/App_Data/ErrorLog.xml"); XDocument errorLog = XDocument.Load(file); if (string.IsNullOrEmpty(Code)) { Code = HttpContext.Current.Response.StatusCode.ToString(); } if (string.IsNullOrEmpty(Page)) { Page = HttpContext.Current.Request.Url.AbsolutePath.ToString(); } errorLog.Root.Add(new XElement("log", new XAttribute("code", Code), new XAttribute("message", Message), new XAttribute("datetime", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()), new XAttribute("page", Page), new XAttribute("ip", AppUtility.GetUserIPAddress()))); errorLog.Save(file); } catch (Exception ex) { string msg = ex.Message; } }
private void btnActivate_Click(object sender, RoutedEventArgs e) { _Reg.ActivationKey = Guid.NewGuid().ToString(); _Reg.ActivatedBy = "Test"; _Reg.ActivatedDtTm = DateTime.Now; _Reg.ActivatedTillDtTm = txtValidUpto.SelectedDate; _Reg.IsActivated = true; _Reg.CompanyName = licvm.CompanyName; _Reg.LicenseCount = licvm.SystemCount; db.RegistrationMasters.Add(_Reg); db.SaveChanges(); licvm.ActivationKey = _Reg.ActivationKey; licvm.ActivationDtTm = _Reg.ActivatedDtTm; licvm.ActivationUptoDtTm = _Reg.ActivatedTillDtTm; licvm.IsActivated = _Reg.IsActivated; foreach (var item in licvm.ServiceList) { RegistrationWiseSearchTypes reg = new RegistrationWiseSearchTypes(); reg.CreatedBy = 1; reg.CreatedDtTm = DateTime.Now; reg.IsActive = true; reg.IsActivated = (item.IsRequired == true) ? true : false; reg.RegistrationID = _Reg.RegistrationID; reg.IsRequired = item.IsRequired; reg.SearchTypeID = item.ServiceID; db.RegistrationWiseSearchTypes.Add(reg); db.SaveChanges(); item.IsActivated = (item.IsRequired == true) ? true : false; } MessageBox.Show("Registration has been done;"); MailData(licvm, _Reg.RegistrationID); Frame MainFrame = AppUtility.FindChild <Frame>(Application.Current.MainWindow, "MainFrame"); MainFrame.Navigate(new System.Uri("Forms/Home.xaml", UriKind.RelativeOrAbsolute)); }
public List <SampleItem> GetCollection() { //Debug.Listeners.Add(new TextWriterTraceListener(new System.IO.FileStream(@"C:\logs\hi.txt", System.IO.FileMode.Append))); //Debug.WriteLine("GetCollection: " + OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.GetHashCode()); tsource.TraceEvent(TraceEventType.Start, 0, "GetCollection Trace Event"); tsource.TraceEvent(TraceEventType.Stop, 0, "GetCollection Trace Event"); //String username = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name; //String username = AppUtility.context.UserName; String username = "******"; try { username = AppUtility.GetAppContext().UserName; } catch (Exception ex) { return(new List <SampleItem>() { new SampleItem() { Id = 1, StringValue = ex.ToString() } }); } return(new List <SampleItem>() { new SampleItem() { Id = 1, StringValue = "HelloX: " + username } }); }
public CremaAppHostViewModel(ICremaHost cremaHost, IAppConfiguration configs, IBuildUp buildUp, CremaSettings settings, Lazy <DataBaseServiceViewModel> dataBaseService, Lazy <DataBaseListViewModel> dataBaseSelections, Lazy <IShell> shell) { this.cremaHost = cremaHost; this.cremaHost.Opened += CremaHost_Opened; this.configs = configs; this.buildUp = buildUp; this.settings = settings; this.dataBaseService = dataBaseService; this.dataBaseSelections = dataBaseSelections; this.shell = shell; this.theme = Themes.Keys.FirstOrDefault(); this.themeColor = FirstFloor.ModernUI.Presentation.AppearanceManager.Current.AccentColor; this.ConnectionItems = ConnectionItemCollection.Read(this, AppUtility.GetDocumentFilename("ConnectionList.xml")); this.buildUp.BuildUp(this.ConnectionItems); this.ConnectionItem = this.ConnectionItems.FirstOrDefault(item => item.IsDefault); this.authenticator = this.cremaHost.GetService(typeof(Authenticator)) as Authenticator; this.configs.Update(this); this.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(this.IsProgressing)) { this.Shell.IsProgressing = this.IsProgressing; } else if (e.PropertyName == nameof(this.ProgressMessage)) { this.Shell.ProgressMessage = this.ProgressMessage; } }; }
public string SaveAttachment(AttachmentRequest request) { try { DropNetClient _client = new DropNetClient(AppConstants.DropboxClientId, AppConstants.DropboxClientSecret); _client.UserLogin = Storage.Dropbox.Token; DropNet.Models.UserLogin login = _client.GetAccessToken(); Attachment attachment = AppUtility.GetAttachment(request.AttachmentId, request.AuthToken, request.EwsUrl); _client.UploadFile("/", attachment.AttachmentName, attachment.AttachmentBytes); return("Uploaded Sucessfully."); } catch (Exception s) { return(s.Message); } //return ""; }
/// <summary> /// Gets all. /// </summary> /// <returns></returns> public virtual IEnumerable <TEntity> GetAll() { AppUtility.ValidateDbSet(CurrentDbSet); try { return(CurrentDbSet.AsEnumerable()); } catch (SqlException sqex) { Audit.Log.Error(AppConstants.ErrorMessages.SqlExceptionMessage, sqex); throw; } catch (DbException dbex) { Audit.Log.Error(AppConstants.ErrorMessages.DbExceptionMessage, dbex); throw; } catch (Exception ex) { Audit.Log.Error(AppConstants.ErrorMessages.ExceptionMessage, ex); throw; } }
/// <summary> /// Finds the by. /// </summary> /// <param name="where">The predicate.</param> /// <returns></returns> public virtual IEnumerable <TEntity> FindBy(Expression <Func <TEntity, bool> > @where) { IEnumerable <TEntity> query; AppUtility.ValidateDbSet(CurrentDbSet); try { query = CurrentDbSet.Where(where).AsEnumerable(); } catch (SqlException sqex) { Audit.Log.Error(AppConstants.ErrorMessages.SqlExceptionMessage, sqex); throw; } catch (DbException dbex) { Audit.Log.Error(AppConstants.ErrorMessages.DbExceptionMessage, dbex); throw; } catch (Exception ex) { Audit.Log.Error(AppConstants.ErrorMessages.ExceptionMessage, ex); throw; } return(query); }
/// <summary> /// Creating super admin /// </summary> public void CreateSuperAdmin() { Users user; this._usersColl = _db.GetCollection <Users>(typeof(Users).Name); var dbset = typeof(Users).Name; var collections = _db.ListCollectionNames().ToList(); if (!collections.Any(x => x == dbset)) { var firstName = _config.GetSection("DBInit").GetSection("SuperUser").GetValue <string>("FirstName"); var lastName = _config.GetSection("DBInit").GetSection("SuperUser").GetValue <string>("LastName"); var email = _config.GetSection("DBInit").GetSection("SuperUser").GetValue <string>("Email"); var passcode = AppUtility.Encrypt(_config.GetSection("DBInit").GetSection("SuperUser").GetValue <string>("Password")); user = new Users { FirstName = firstName, LastName = lastName, Email = email, Password = passcode, IsUserVerified = true, CreatedDate = DateTime.Now, CreatedBy = AppUtility.DefaultCreatedBy, RoleId = AdminRoleId }; _usersColl.InsertOne(user); } }
/// <summary> /// Attaches the specified entity. /// </summary> /// <param name="entity">The entity.</param> public void Attach(TEntity entity) { AppUtility.ValidateContext(CurrentDbContext); try { var dbset = CurrentDbContext.Set <TEntity>(); dbset?.Attach(entity); } catch (SqlException sqex) { Audit.Log.Error(AppConstants.ErrorMessages.SqlExceptionMessage, sqex); throw; } catch (DbException dbex) { Audit.Log.Error(AppConstants.ErrorMessages.DbExceptionMessage, dbex); throw; } catch (Exception ex) { Audit.Log.Error(AppConstants.ErrorMessages.ExceptionMessage, ex); throw; } }
void createResultSet(RootTrainObject rootStationObj) { TRAINRESULTS trainResults = rootStationObj.RESULTS; TRAINQUERY trainQuery = rootStationObj.QUERY; DirectTrains directTrains = trainResults.directTrains; ConnectingTrains connectingTrains = trainResults.connectingTrains; List <TrainsList> directTrainsList = directTrains.trainsList; List <TrainsList2> connectedTrainsList = connectingTrains.trainsList; foreach (TrainsList value in directTrainsList) { TrainListViewModel list = new TrainListViewModel(); list.depatureTime = value.depatureTime; list.arrivalTime = value.arrivalTimeEndStation; list.trainType = AppUtility.ToCamelCase(value.trainType); list.trainTypeFlag = 1; list.scheduleDetail = getScheduleDetailObj(trainQuery, value); formatLitNode(list); combinedTrainList.Add(list); } foreach (TrainsList2 value in connectedTrainsList) { TrainListViewModel list = new TrainListViewModel(); list.depatureTime = value.recordHeader[0].startArrivalTime; list.arrivalTime = value.recordHeader[0].endArrivalTime; list.trainType = APPCONTEXT.globalConnectedTrain; list.trainTypeFlag = 2; list.scheduleDetail = getScheduleDetailObj(trainQuery, value); formatLitNode(list); combinedTrainList.Add(list); } }
public override CompBase Clone(string name, bool bRecursivley) { AppPart clonedPart = base.Clone(name, bRecursivley) as AppPart; AppUtility.CloneAllProperties(this, clonedPart); return(clonedPart); }
private void btnAddRecipe_Click(object sender, EventArgs e) { if (tbNewRecipe.Text == "") { AppUtility.ShowKryptonMessageBox("No Recipe Name", "Please input recipe name", "", ComponentFactory.Krypton.Toolkit.TaskDialogButtons.OK, MessageBoxIcon.Error, this); return; } if (_allRecipe.ChildExists(tbNewRecipe.Text)) { AppUtility.ShowKryptonMessageBox("Recipe Name Exist", String.Format("Recipe name \"{0}\" already exist.", tbNewRecipe.Text), "", ComponentFactory.Krypton.Toolkit.TaskDialogButtons.OK, MessageBoxIcon.Error, this); return; } try { AppProductRecipe newRecipe = new AppProductRecipe(tbNewRecipe.Text); newRecipe.PropertyValChanged += new PropertyChangedEventHandler(AppMachine.Comp.AppMachine.This.RecipePropValue_OnChange); _allRecipe.Add(newRecipe); componentBrowser.Rebuild(_allRecipe); AppUtility.ShowKryptonMessageBox("Add New Product Completed", String.Format("Add New Product \"{0}\" Completed", tbNewRecipe.Text), "", ComponentFactory.Krypton.Toolkit.TaskDialogButtons.OK, MessageBoxIcon.Information, this); tbNewRecipe.Clear(); } finally { } }
/* Terminate: Administrator function, for killing jobs. * IJobProducerContract */ public void Terminate() { string user = AppUtility.GetAppContext().UserName; using (TurbineModelContainer container = new TurbineModelContainer()) { Job obj = container.Jobs.Single <Job>(s => s.Id == id); if (obj.User.Name != user) { throw new AuthorizationError( String.Format("Termination Authorization Denied For {0}", user) ); } if (obj.State == "running" || obj.State == "setup") { obj.State = "terminate"; obj.Finished = DateTime.UtcNow; } else { throw new InvalidStateChangeException( String.Format("Cannot terminate a job {0} in state {1}", id, obj.State) ); } container.SaveChanges(); } }
/// <summary> /// Initializes a new instance of the <see cref="GenericRepository{TEntity}" /> class. /// </summary> /// <param name="context">The context.</param> /// <exception cref="ArgumentNullException"></exception> public GenericRepository(DbContext context) { Context = context; AppUtility.ValidateContext(CurrentDbContext); try { CurrentDbSet = CurrentDbContext.Set <TEntity>(); } catch (SqlException sqex) { Audit.Log.Error(AppConstants.ErrorMessages.SqlExceptionMessage, sqex); throw; } catch (DbException dbex) { Audit.Log.Error(AppConstants.ErrorMessages.DbExceptionMessage, dbex); throw; } catch (Exception ex) { Audit.Log.Error(AppConstants.ErrorMessages.ExceptionMessage, ex); throw; } }
/// <summary> /// copyFromCache: copies simulation files from cache, return true if cache exists. /// </summary> /// <param name="job"></param> /// <returns></returns> private bool copyFromCache(IJobConsumerContract job) { string cacheDir = Path.Combine(AppUtility.GetAppContext().BaseWorkingDirectory, job.SimulationId.ToString()); //string shortConfigFileName = "sinter_configuration.txt"; //configFileName = Path.Combine(job.Process.WorkingDirectory, shortConfigFileName); if (Directory.Exists(cacheDir)) { // Shallow Copy cacheDir to Working Directory var source = new DirectoryInfo(cacheDir); var target = new DirectoryInfo(job.Process.WorkingDirectory); /*foreach (FileInfo finfo in source.GetFiles()) * { * Debug.WriteLine(String.Format("Found Cached file {0}: {1}", job.SimulationId, finfo.FullName), * "SinterConsumer.copyFromCache"); * finfo.CopyTo(Path.Combine(target.ToString(), finfo.Name), true); * }*/ Debug.WriteLine("Copying Cached files", "SinterConsumerRun.CopyFromCache"); DirectoryCopy(source.ToString(), target.ToString(), true); return(true); } return(false); }
private void strUserInputCode_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (String.IsNullOrEmpty(strUserInputCode.Text)) { return; } bool success = VerifyUser(); if (success) { this.Hide(); string message = String.Format("User Change to User: {0} En: {1} Level: {2}", AppMachine.This.CurrentUser.UserName, AppMachine.This.CurrentUser.UserEN, AppMachine.This.CurrentUser.UserLevel); U.LogInfo(message); AppUtility.ShowKryptonMessageBox("User Change Completed", "User Change Completed", message, TaskDialogButtons.OK, MessageBoxIcon.Information, this); } else { string message = String.Format("Could not find user code: {0} ", strUserInputCode.Text); this.Hide(); AppUtility.ShowKryptonMessageBox("User Change Fail", "User Change Fail", message, TaskDialogButtons.OK, MessageBoxIcon.Error, this); strUserInputCode.Clear(); this.Show(); } } }
private void Button_AddSales_Click(object sender, EventArgs e) { try { byte[] data = AppUtility.StringToByte("{\"user_id\":\"" + User_Textbox.Text + "\",\"pass_id\":\"" + Pass_Textbox.Text + "\",\"fullname\":\"" + SalesName_Textbox.Text + "\",\"region_name\":\"" + list_region_acc.Substring(0, list_region_acc.Length - 1) + "\",\"phone\":\"" + PH_Textbox.Text + "\",\"user_roles\":\"3\",\"segment\":\"" + Segment_list_Label.Text.Substring(0, Segment_list_Label.Text.Length - 1) + "\"}"); SimpleREST rest = new SimpleREST("http://ultimindserver.mywire.org:3000/register/user"); rest.RequestAsync(data, delegate(bool status, string message, StreamReader reader) { if (status) { if (reader != null) { string output = reader.ReadToEnd(); if (!string.IsNullOrEmpty(output)) { MessageBox.Show(output); } } else { if (reader != null) { string output = reader.ReadToEnd(); MessageBox.Show(output); } } this.Close(); } }, "Content-Type", "application/json"); } catch (Exception) { PicBox_Validation.Visible = true; } }
private void ApplicationBarIconButton_Click(object sender, EventArgs e) { string[] args = { scheduleDetailObj.startStationName, scheduleDetailObj.endStationName, scheduleDetailObj.departureTime, scheduleDetailObj.arrivalTimeEndStation, scheduleDetailObj.travelTime, scheduleDetailObj.trainFrequncy }; string shareMessage = string.Format(APPCONTEXT.scheduleDetailShareMessage, args); AppUtility.shareStatusTask(shareMessage); }
void formatStationName() { for (int i = 0; i < stationList.Count; i++) { stationList[i].stationName = AppUtility.ToCamelCase(stationList[i].stationName); } }
public IJobQueue Register(IConsumerRun run) { this.run = run; IConsumerContext ctx = Turbine.Consumer.AppUtility.GetConsumerContext(); //Guid consumerId = ctx.Id; //Guid consumerId = Guid.NewGuid(); String hostname = ctx.Hostname; String appName = run.SupportedApplications.ElementAtOrDefault(0); Debug.WriteLine(String.Format("Register({0}) as {1}, {2}", appName, run.ConsumerId, hostname), this.GetType().Name); using (ProducerContext db = new ProducerContext()) { // TODO: Registering as a single application is dubious. // IF support multiple apps in single consumer need to expose that via the database ( update SCHEMA!! ) var app = db.Applications.Single(a => a.Name == appName); var consumer = new Turbine.Data.Entities.JobConsumer { Application = app, Id = run.ConsumerId, hostname = hostname, processId = System.Diagnostics.Process.GetCurrentProcess().Id, keepalive = DateTime.UtcNow, status = "up" }; db.Consumers.Add(consumer); db.SaveChanges(); } queue = AppUtility.GetJobQueue(run); //((DBJobQueue)queue).consumerId = consumerId; return(queue); }
/// <summary> /// Loads necessary data and perfor initialisation checks /// </summary> private void InitialiseApp() { try { SetLicenseInfo(); var isDbUpgraded = AppUtility.UpdateSchema(); if (!isDbUpgraded) { AppUtility.MigrateXmlDataToDatabase(); ReminderUtility.ClearAllRemindersOnUpgrade(); BirthdayUtility.SaveLocalCards(); } UpdateLocalizedRes(); CheckFriendBirthdayFile(); } catch (Exception ex) { MessageBox.Show(AppResources.ErrAppInitialise, AppResources.ErrInitialiseTitle, MessageBoxButton.OK); AppLog.WriteToLog(DateTime.Now, "Error during initialisation. Error : " + ex.Message + ". Stack : " + ex.StackTrace, LogLevel.Error); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); } }
/// <summary> /// </summary> /// <param name="filename"></param> private void ExportToExcel(string filename) { using (FileStream fs = new FileStream(AppUtility.GetAppPath() + @"templates\prizewinner.xls", FileMode.Open, FileAccess.Read, FileShare.Read)) { IWorkbook workBook = new HSSFWorkbook(fs); ISheet sheet = workBook.GetSheetAt(0); sheet.GetRow(1).GetCell(1).SetCellValue(cbxGroup.SelectedItem.ToString()); int i = 3; foreach (DataGridViewRow row in dgvPrizewinnerList.Rows) { IRow erow = sheet.CreateRow(i++); erow.CreateCell(0).SetCellValue(row.Cells["txtEmpId"].Value.ToString()); erow.CreateCell(1).SetCellValue(row.Cells["txtName"].Value.ToString()); erow.CreateCell(2).SetCellValue(row.Cells["txtDept"].Value.ToString()); erow.CreateCell(3).SetCellValue(row.Cells["txtPost"].Value.ToString()); erow.CreateCell(4).SetCellValue(row.Cells["txtAward"].Value.ToString()); erow.CreateCell(5).SetCellValue(row.Cells["boolsign"].Value.ToString()); } using (FileStream fs2 = new FileStream(filename, FileMode.Create, FileAccess.Write)) { workBook.Write(fs2); fs2.Flush(); } } }
public CremaAppHostViewModel(ICremaHost cremaHost, IAppConfiguration configs, ICompositionService compositionService) { this.cremaHost = cremaHost; this.cremaHost.Opened += CremaHost_Opened; this.configs = configs; this.compositionService = compositionService; this.theme = Themes.Keys.FirstOrDefault(); this.themeColor = FirstFloor.ModernUI.Presentation.AppearanceManager.Current.AccentColor; this.loginCommand = new DelegateCommand((p) => this.Login(), (p) => this.CanLogin); this.connectionItems = ConnectionItemCollection.Read(AppUtility.GetDocumentFilename("ConnectionList.xml")); this.compositionService.SatisfyImportsOnce(this.connectionItems); this.ConnectionItem = this.connectionItems.FirstOrDefault(item => item.IsDefault); this.authenticator = this.cremaHost.GetService(typeof(Authenticator)) as Authenticator; this.configs.Update(this); this.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(this.IsProgressing)) { this.Shell.IsProgressing = this.IsProgressing; } else if (e.PropertyName == nameof(this.ProgressMessage)) { this.Shell.ProgressMessage = this.ProgressMessage; } }; }
public async Task <IActionResult> Issue(LoginCredentials creds) { string prefix = nameof(Issue) + Constants.FNSUFFIX; string sInvalid = "Invalid Credentials - "; if (!ModelState.IsValid) { return(BadRequest(sInvalid + "(A)")); } if (creds == null) { return(BadRequest(sInvalid + "(B)")); } if (string.IsNullOrWhiteSpace(creds.UserName)) { return(BadRequest(sInvalid + "(C)")); } if (string.IsNullOrWhiteSpace(creds.Password)) { return(BadRequest(sInvalid + "(D)")); } var identity = await getClaimsIdentity(creds); // creds=un+pw if (identity == null) { _logger.LogInformation(prefix + $"Invalid username ({creds.UserName}) or password ({creds.Password})"); return(BadRequest("Invalid credentials (E)")); } string ip = AppUtility.GetRequestIP(HttpContext, true); return(await issueTokens(identity, ip)); }
/// <summary> /// Finds the by asynchronous. /// </summary> /// <param name="where">The where.</param> /// <param name="include">The include.</param> /// <returns></returns> public virtual async Task <IEnumerable <TEntity> > FindByAsync(Expression <Func <TEntity, bool> > where, Expression <Func <TEntity, object> > include) { IEnumerable <TEntity> result; AppUtility.ValidateContext(CurrentDbContext); try { var dbSet = CurrentDbContext.Set <TEntity>(); result = await dbSet.Where(where).Include(include).ToListAsync(); } catch (SqlException sqex) { Audit.Log.Error(AppConstants.ErrorMessages.SqlExceptionMessage, sqex); throw; } catch (DbException dbex) { Audit.Log.Error(AppConstants.ErrorMessages.DbExceptionMessage, dbex); throw; } catch (Exception ex) { Audit.Log.Error(AppConstants.ErrorMessages.ExceptionMessage, ex); throw; } return(result); }
/* Submit * * IJobProducerContract event requires user name check * Better solution to use DIJ for Producer.CheckUser * and State Checks, throw Application Specific * Exceptions. Move to POCO Data Model first. */ public void Submit() { string user = AppUtility.GetAppContext().UserName; using (TurbineModelContainer container = new TurbineModelContainer()) { Job obj = container.Jobs.Single <Job>(s => s.Id == id); //Pulls the job that matches id if (obj.User.Name != user) { throw new ArgumentException( String.Format("Authorization Denied For {0}, Owner {1}", user, obj.User.Name) ); } if (obj.State != "create") { throw new InvalidStateChangeException("Violation of state machine"); } // Backup and Config must be valid to submit/run ValidateBackup(obj.Simulation); ValidateConfig(obj.Simulation); obj.State = "submit"; obj.Submit = DateTime.UtcNow; container.SaveChanges(); } }
private void Page_Loaded(object sender, RoutedEventArgs e) { //Page Logger PageLogID = AppUtility.PageLogger(2, 1); // Page Event Logger AppUtility.PageEventLogger(PageLogID, "Constructor", 1, "Form Load", "Normal"); }
/// <summary> /// copyFilesToDisk copies files from data contract to working directory. Assumes the sinter configuration file /// is named 'configuration' in the job description. Currently handles all the mapping from 'resource' names /// specified in the database schema to file names. /// </summary> /// <param name="job"></param> protected override void copyFilesToDisk(IJobConsumerContract job) { string cacheDir = Path.Combine(AppUtility.GetAppContext().BaseWorkingDirectory, job.SimulationId.ToString()); // NOTE: Aspen implementations only // Find 'aspenfile' // configuration file SimpleFile config = job.GetSimulationInputFiles().Single(f => f.name == "configuration"); string content = System.Text.Encoding.ASCII.GetString(config.content); var cacheFile = Path.Combine(cacheDir, configFileName); var filepath = Path.Combine(job.Process.WorkingDirectory, configFileName); File.WriteAllBytes(cacheFile, config.content); File.Copy(cacheFile, filepath); Dictionary <String, Object> jsonConfig = JsonConvert.DeserializeObject <Dictionary <String, Object> >(content); string modelfilename = (String)jsonConfig["model"]; SimpleFile model = job.GetSimulationInputFiles().Single(g => g.name == "model"); cacheFile = Path.Combine(cacheDir, modelfilename); filepath = Path.Combine(job.Process.WorkingDirectory, modelfilename); File.WriteAllBytes(cacheFile, model.content); File.Copy(cacheFile, filepath); }