//-----------------------------------------------------------------------------// /// <summary> /// Run the high priority job in a separate thread. /// </summary> private void RunHighPriorityJob() { try { if (this.highPriorityJob != null) { IWorkUnit moreWork = null; try { moreWork = this.highPriorityJob.DoJob(); } finally { this.highPriorityJob = null; } if (moreWork != null) { this.AddJob(moreWork); } } } catch (System.Threading.ThreadAbortException) { DirPerfStat.Instance().IncrementHighPriorityThreadAborts(); } finally { this.highPriorityJob = null; this.highPriorityThread = null; } }
public static bool authenticate(IWorkUnit workUnit, SignInModel logOnModel) { var password = logOnModel.Password; Account account = null; try { //get the contact with the provided email account = workUnit.AccountRepository.Entities.First(x => x.EmailAddress.ToUpper() == logOnModel.Email.ToUpper()); } catch { return(false);//failed to find user account } //encode password var encodedPassword = SHA1PasswordSecurity.encrypt(password); //authenticate var databasePassword = account.Password; var pwValidation = comparePassword(encodedPassword, databasePassword); //if valid record log in datetime if (pwValidation) { try { account.LastLogin = DateTime.Now; workUnit.AccountRepository.UpdateEntity(account); workUnit.saveChanges(); } catch { //do error logging here } } return(pwValidation); }
/// <summary> /// Gets a connection for a work unit. /// </summary> /// <param name="unit"></param> /// <returns></returns> public IConnection GetConnection(IWorkUnit unit) { if (unit == null) { throw new ArgumentNullException("unit"); } // name... string name = unit.EntityType.DatabaseName; if (name == null || name.Length == 0) { // main? if (!(this.MainBound)) { this.StartMain(); } // return... return(Database.CreateConnection(name)); } else { return((IConnection)NamedConnections[name]); } }
public ReservationService(IWorkUnit database) { this.DataBase = database; fromDTOMapper = new MapperConfiguration( cfg => { cfg.CreateMap <ReservationDTO, Reservation>().ReverseMap(); cfg.CreateMap <RoomDTO, Room>().ReverseMap(); cfg.CreateMap <PriceCategoryDTO, PriceCategory>().ReverseMap(); cfg.CreateMap <CategoryDTO, Category>().ReverseMap(); cfg.CreateMap <ClientDTO, Client>().ReverseMap(); cfg.CreateMap <UserDTO, User>().ReverseMap(); }).CreateMapper(); toDTOMapper = new MapperConfiguration( cfg => { cfg.CreateMap <Reservation, ReservationDTO>().ReverseMap(); cfg.CreateMap <Room, RoomDTO>().ReverseMap(); cfg.CreateMap <PriceCategory, PriceCategoryDTO>().ReverseMap(); cfg.CreateMap <Category, CategoryDTO>().ReverseMap(); cfg.CreateMap <Client, ClientDTO>().ReverseMap(); cfg.CreateMap <User, UserDTO>().ReverseMap(); }).CreateMapper(); }
public void Bind(IWorkUnit wu) { if (wu.Type == typeof(ICPUWorkUnit)) { boundTo = wu as ICPUWorkUnit; } }
/// <summary> /// Initializes a new instance of the <see cref="Process"/> class. /// </summary> /// <param name="bucket">the bucket.</param> /// <param name="parent">the parent job.</param> /// <param name="current">the current job.</param> public Process(IBucket bucket, IProcess parent, IWorkUnit current) { this.bucket = bucket; this.Parent = parent?.Current; this.Route = $"{parent?.Route}{current.Name}"; this.Current = current; this.state = LifeCycle.Created; }
public CarImporter(IWorkUnit unitOfWork) { this.unitOfWork = unitOfWork; this.citiesRepository = unitOfWork.CitiesRepository; this.dealersRepository = unitOfWork.DealersRepository; this.manufacturersRepository = unitOfWork.ManufacturersRepository; this.carsRepository = unitOfWork.CarsRepository; }
/// <summary> /// Constructor. /// </summary> public WorkUnitCollection(IWorkUnit unit) { if (unit == null) { throw new ArgumentNullException("unit"); } this.Add(unit); }
/// <summary> /// Adds a IWorkUnit instance to the collection. /// </summary> /// <param name="item">The item to add.</param> public void Add(IWorkUnit item) { if (item == null) { throw new ArgumentNullException("item"); } List.Add(item); }
/// <summary> /// Inserts a IWorkUnit instance into the collection. /// </summary> /// <param name="item">The item to add.</param> public void Insert(int index, IWorkUnit item) { if (item == null) { throw new ArgumentNullException("item"); } List.Insert(index, item); }
public IConnection GetConnection(IWorkUnit workUnit) { if (workUnit.EntityType.HasDatabaseName) { throw new InvalidOperationException("Custom databases are not supported with this transaction manager."); } return(this.Connection); }
// mbr - 02-10-2007 - case 827 - added connection. // protected SaveChangesEventArgs(IWorkUnit unit) protected SaveChangesEventArgs(IWorkUnit unit, IConnection connection) : base(unit.Entity) { this.SetUnit(unit); // set... _connection = connection; }
public void Assign(IWorkUnit workUnit, IJob job, float sureness) { if (!assigns.ContainsKey(job)) { assigns[job] = new List <KeyValuePair <IWorkUnit, float> >(); } assigns[job].Add(new KeyValuePair <IWorkUnit, float>(workUnit, sureness)); }
//-----------------------------------------------------------------------------// /// <summary> /// Adds some work to the queue. /// </summary> /// <param name="job"></param> public void AddJob(IWorkUnit job) { lock( this.queue ) { if ( !this.stop ) { this.queue.Enqueue( job ); } } }
//-----------------------------------------------------------------------------// /// <summary> /// Adds some work to the queue. /// </summary> /// <param name="job"></param> public void AddJob(IWorkUnit job) { lock (this.queue) { if (!this.stop) { this.queue.Enqueue(job); } } }
//-----------------------------------------------------------------------------// /// <summary> /// Set a flag to pause the job loop. /// Once the job loop sets flag it is paused, then start this highpriority job. /// </summary> /// <param name="job"></param> public void AddPriorityJob(IWorkUnit job) { this.stopHighPriorityJob = true; while (this.highPriorityJob != null) { Thread.Sleep(25); } this.stopHighPriorityJob = false; this.highPriorityJob = job; }
public void Register([NotNull] IWorkUnit workUnit) { Type t = workUnit.Type; if (!workUnits.ContainsKey(t)) { workUnits[t] = new List <IWorkUnit>(); } workUnits[t].Add(workUnit); }
public WorkUnitState Execute(IWorkUnit workflowUnit) { var result = _blackList.ContainsKey(workflowUnit.HttpContext.Request.Url.AbsolutePath); if (result) { throw new WebServerException("Url is in the black list."); } return(WorkUnitState.Run); }
/// <summary> /// Discovers if the given item is in the collection. /// </summary> /// <param name="item">The item to find.</param> /// <returns>Returns true if the given item is in the collection.</returns> public bool Contains(IWorkUnit item) { if (IndexOf(item) == -1) { return(false); } else { return(true); } }
//-----------------------------------------------------------------------------// /// <summary> /// Set a flag to pause the job loop. /// Once the job loop sets flag it is paused, then start this highpriority job. /// </summary> /// <param name="job"></param> public void AddPriorityJob( IWorkUnit job ) { this.stopHighPriorityJob = true; while ( this.highPriorityJob != null ) { Thread.Sleep(25); } this.stopHighPriorityJob = false; this.highPriorityJob = job; }
public IConnection GetConnection(IWorkUnit unit) { string name = unit.EntityType.DatabaseName; if (name == null || name.Length == 0) { return(NamedConnections[DefaultKey]); } else { return(NamedConnections[name]); } }
//-----------------------------------------------------------------------------// /// <summary> /// Do one of two jobs. If first time, the createdNode will be null. In this case, /// test to see if the Drive letter exists, if so, create a Treenode. /// /// Secondly, if the createdNode already exists, then get a directory listing of folders. /// </summary> /// <returns></returns> public IWorkUnit DoJob() { IWorkUnit moreWork = null; if (this.ftp == null) { moreWork = this.DoJobOne(); } else { moreWork = this.DoJobThree(); } return(moreWork); }
public IWorkUnit DoJob() { IWorkUnit moreWork = null; KExplorerNode[] tempNodes = this.startNodes; foreach (KExplorerNode node in tempNodes) { if (node.DirInfo != null && this.pathToLookFor.Equals(node.DirInfo.FullName)) { this.expandThisNode = node; this.form.MainForm.Invoke(new InvokeDelegate(this.ExpandNode)); break; } else if (node.DirInfo != null && this.pathToLookFor.StartsWith(node.DirInfo.FullName)) { /// The node may or may not be loaded. If not, make sure to at least expand /// out to here. Then that will cause another job to get loaded to load it's /// sub nodes. Then, we just re-add this task. if (node.Nodes.Count == 0) { this.expandThisNode = node; this.form.MainForm.Invoke(new InvokeDelegate(this.ExpandNode)); Pipeline drivePipeline = (Pipeline)this.controller.DrivePipelines[this.pathToLookFor.Substring(0, 1)]; drivePipeline.AddJob(new FolderWorkUnit(node, this.form, (IWorkGUIFlagger)this.controller)); moreWork = this; } else { /// If the sub-nodes are already created. We re-add this job, but set it /// to look a the sub-nodes. KExplorerNode[] nextStartNodes = new KExplorerNode[node.Nodes.Count]; for (int i = 0; i < node.Nodes.Count; i++) { nextStartNodes[i] = (KExplorerNode)node.Nodes[i]; } this.startNodes = nextStartNodes; moreWork = this; } break; } } return(moreWork); }
//-----------------------------------------------------------------------------// /// <summary> /// Thread that runs a single low priority job. /// </summary> private void RunLowPriorityJob() { try { this.moreWorkToDoFromThread = this.currentNormalJob.DoJob(); } catch (System.Threading.ThreadAbortException) { DirPerfStat.Instance().IncrementLowPriorityThreadAborts(); } finally { this.lowPriorityThread = null; } }
//-----------------------------------------------------------------------------// /// <summary> /// Job One. Initialize all sub-dirs. /// Job Two. Initailize each additional sub-dir. /// </summary> /// <returns></returns> public IWorkUnit DoJob() { IWorkUnit moreWork = null; if (!this.jobOneComplete) { moreWork = this.DoJobOne(); } else { moreWork = this.DoJobTwo(); } return(moreWork); }
public async Task<ICollection<FoodDescription>> QueryFoodDescriptionsAsync(IWorkUnit workUnit, string searchText) { if (workUnit == null) { throw new ArgumentNullException("workUnit"); } if (string.IsNullOrWhiteSpace(searchText)) { return await workUnit.Collection<FoodDescription>().ToListAsync(); } return await workUnit.Collection<FoodDescription>() .Where(f => f.Name.Contains(searchText) || f.Description.Contains(searchText)) .ToListAsync(); }
/// <summary> /// Reconciles an insert. /// </summary> /// <param name="unit"></param> private void ReconcileAfterUpdate(IWorkUnit unit) { if (unit == null) { throw new ArgumentNullException("unit"); } object entity = unit.Entity; if (entity == null) { throw new ArgumentNullException("entity"); } // clear... Storage.ResetModifiedFlags(entity); }
public ConsoleClient( IDepartmentGenerator departmentGenerator, IEmployeeGenerator employeeGenerator, IProjectGenerator projectGenerator, IReportGenerator reportGenerator, ICompanyContext companyContext, IWorkUnit unitOfWork, IXmlProvider xmlProvider) { this.departmentGenerator = departmentGenerator; this.employeeGenerator = employeeGenerator; this.projectGenerator = projectGenerator; this.reportGenerator = reportGenerator; this.companyContext = companyContext; this.unitOfWork = unitOfWork; this.xmlProvider = xmlProvider; }
/// <summary> /// Reconciles an insert. /// </summary> /// <param name="unit"></param> private void ReconcileAfterDelete(IWorkUnit unit) { if (unit == null) { throw new ArgumentNullException("unit"); } object entity = unit.Entity; if (entity == null) { throw new ArgumentNullException("entity"); } // clear... Storage.MarkAsDeleted(entity); }
public PriceCategoryService(IWorkUnit database) { this.DataBase = database; fromDTOMapper = new MapperConfiguration( cfg => { cfg.CreateMap <PriceCategoryDTO, PriceCategory>().ReverseMap(); cfg.CreateMap <CategoryDTO, Category>().ReverseMap(); }).CreateMapper(); toDTOMapper = new MapperConfiguration( cfg => { cfg.CreateMap <PriceCategory, PriceCategoryDTO>().ReverseMap(); cfg.CreateMap <Category, CategoryDTO>().ReverseMap(); }).CreateMapper(); }
public static void initializePassword(IWorkUnit workUnit) { //var accountRepo = workUnit.AccountRepository; //var accounts = accountRepo.Entities; //foreach (var account in accounts) //{ // if (account.InitialPassword != null) // { // var encodedPassword = SHA1PasswordSecurity.encrypt(account.InitialPassword); // account.Password = encodedPassword; // account.Role = "user"; // accountRepo.UpdateEntity(account); // } //} //workUnit.saveChanges(); }
public ContactsViewModel(IWorkUnitProvider workUnitProvider) { WorkUnitProvider = workUnitProvider; LoadAllContacts = new SimplerCommand { Action = () => { WorkUnit = WorkUnitProvider.ProvideWorkUnit(); LoadedContacts = new ObservableCollection <Contact>(WorkUnit.Contacts.GetAll()); NotifyChangesMade(); } }; SaveAllContacts = new SimpleCommand { Action = () => { WorkUnit.Save(); LoadedContacts.ToList().ForEach(c => WorkUnit.Reload(c)); NotifyChangesMade(); }, CanExecuteFunc = () => WorkUnit?.IsChanged() ?? false }; OnEditEnding = new SimplerCommand { Action = SaveAllContacts.RaiseCanExecuteChanged }; DeleteSelected = new SimpleCommand { Action = () => { SelectedContacts.ToList().ForEach(c => LoadedContacts.Remove(c)); }, CanExecuteFunc = () => { return(SelectedContacts?.Count > 0); } }; OnSelectionChange = new SimplerCommand <IList> { Action = o => { SelectedContacts = new ObservableCollection <Contact>(o.OfType <Contact>()); } }; }
public async Task <FoodDescription> UpdateOrAddFoodDescriptionAsync(IWorkUnit workUnit, FoodDescription foodDescription) { if (workUnit == null) { throw new ArgumentNullException("workUnit"); } if (foodDescription == null) { throw new ArgumentNullException("foodDescription"); } var exists = await workUnit.Collection <FoodDescription>() .Select(f => f.Id) .FirstOrDefaultAsync(n => n == foodDescription.Id); workUnit.GetContext <FoodContext>().Entry(foodDescription).State = exists == null ? EntityState.Added : EntityState.Modified; return(foodDescription); }
public async Task<FoodDescription> UpdateOrAddFoodDescriptionAsync(IWorkUnit workUnit, FoodDescription foodDescription) { if (workUnit == null) { throw new ArgumentNullException("workUnit"); } if (foodDescription == null) { throw new ArgumentNullException("foodDescription"); } var exists = await workUnit.Collection<FoodDescription>() .Select(f => f.Id) .FirstOrDefaultAsync(n => n == foodDescription.Id); workUnit.GetContext<FoodContext>().Entry(foodDescription).State = exists == null ? EntityState.Added : EntityState.Modified; return foodDescription; }
public async Task<bool> DeleteFoodDescriptionAsync(IWorkUnit workUnit, string id) { if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException("id"); } if (workUnit == null) { throw new ArgumentNullException("workUnit"); } var ctx = workUnit.GetContext<FoodContext>(); var foodItem = await ctx.FoodDescriptions.FirstOrDefaultAsync( f => f.Id == id); if (foodItem != null) { ctx.Entry(foodItem).State = EntityState.Deleted; } return true; }
//-----------------------------------------------------------------------------// /// <summary> /// Run the high priority job in a separate thread. /// </summary> private void RunHighPriorityJob() { try { if ( this.highPriorityJob != null ) { IWorkUnit moreWork = null; try { moreWork = this.highPriorityJob.DoJob(); } finally { this.highPriorityJob = null; } if ( moreWork != null ) { this.AddJob( moreWork ); } } } catch ( System.Threading.ThreadAbortException ) { DirPerfStat.Instance().IncrementHighPriorityThreadAborts(); } finally { this.highPriorityJob = null; this.highPriorityThread = null; } }
/// <summary> /// Get hash similarity of one song /// </summary> /// <param name = "service">Fingerprint service</param> /// <param name = "hashTables">Number of hash tables in the LSH transformation</param> /// <param name = "hashKeys">Number of hash keys per table in the LSH transformation</param> /// <param name = "path">Path to analyzed file</param> /// <param name = "results">Results object to be filled with the appropriate data</param> private void GetHashSimilarity(IFingerprintService service, int hashTables, int hashKeys, IWorkUnit unitOfWork, IWorkUnit sameUnitOfWork, DumpResults results) { double sum = 0; int hashesCount = 0; int startindex = 0; List<bool[]> listDb = unitOfWork.GetFingerprintsUsingService(service).Result; List<bool[]> listQuery = sameUnitOfWork.GetFingerprintsUsingService(service).Result; IPermutations perms = new DbPermutations(ConfigurationManager.ConnectionStrings["FingerprintConnectionString"].ConnectionString); MinHash minHash = new MinHash(perms); List<int[]> minHashDb = listDb.Select(minHash.ComputeMinHashSignature).ToList(); List<int[]> minHashQuery = listQuery.Select(minHash.ComputeMinHashSignature).ToList(); /*Calculate Min Hash signature similarity by comparing 2 consecutive signatures*/ int countDb = minHashDb.Count; int countQuery = minHashQuery.Count; int minHashSignatureLen = minHashDb[0].Length; int similarMinHashValues = 0; for (int i = 0; i < countDb; i++) { for (int j = 0; j < countQuery; j++) { for (int k = 0; k < minHashSignatureLen; k++) if (minHashDb[i][k] == minHashQuery[j][k]) similarMinHashValues++; } } results.Results.SumIdenticalMinHash = similarMinHashValues; results.Results.AverageIdenticalMinHash = (double) similarMinHashValues/(countDb*countQuery*minHashSignatureLen); /*Group min hash signatures into LSH Buckets*/ List<Dictionary<int, long>> lshBucketsDb = minHashDb.Select(item => minHash.GroupMinHashToLSHBuckets(item, hashTables, hashKeys)).ToList(); List<Dictionary<int, long>> lshBucketsQuery = minHashQuery.Select(item => minHash.GroupMinHashToLSHBuckets(item, hashTables, hashKeys)).ToList(); int countSignatures = lshBucketsDb.Count; sum = 0; foreach (Dictionary<int, long> a in lshBucketsDb) { Dictionary<int, long>.ValueCollection aValues = a.Values; foreach (Dictionary<int, long> b in lshBucketsQuery) { Dictionary<int, long>.ValueCollection bValues = b.Values; hashesCount += aValues.Intersect(bValues).Count(); } } results.Results.SumJaqLSHBucketSimilarity = -1; results.Results.AverageJaqLSHBucketSimilarity = -1; results.Results.TotalIdenticalLSHBuckets = hashesCount; }
/// <summary> /// Get signature similarity between 2 different songs. /// </summary> /// <param name="service"> /// The service. /// </param> /// <param name="unitOfWork"> /// The unit Of Work. /// </param> /// <param name="unitOfWorkToCompareWith"> /// The unit Of Work To Compare With. /// </param> /// <param name="results"> /// The results. /// </param> private void GetFingerprintSimilarity(IFingerprintService service, IWorkUnit unitOfWork, IWorkUnit unitOfWorkToCompareWith, DumpResults results) { double sum = 0; List<bool[]> imglista = unitOfWork.GetFingerprintsUsingService(service).Result; List<bool[]> imglistb = unitOfWorkToCompareWith.GetFingerprintsUsingService(service).Result; int count = imglista.Count > imglistb.Count ? imglistb.Count : imglista.Count; double max = double.MinValue; for (int i = 0; i < count; i++) { int j = i; double value = MinHash.CalculateSimilarity(imglista[i], imglistb[j]); if (value > max) { max = value; } sum += value; } results.SumJaqFingerprintSimilarityBetweenDiffertSongs = sum; results.AverageJaqFingerprintsSimilarityBetweenDifferentSongs = sum / count; results.MaxJaqFingerprintsSimilarityBetweenDifferentSongs = max; }
//-----------------------------------------------------------------------------// /// <summary> /// The actual running thread. /// Monitor the queue for work to be done. On asking jobs to do their work, /// they may return a new task to add to the queue. /// </summary> private void GetToWork() { while ( !this.form.MainForm.Visible ) { Thread.Sleep( 100 ); } while ( !stop ) { for ( int i = 0; i < 100; i++ ) { // Check for pausing.. while( this.stopHighPriorityJob && this.highPriorityJob != null ) { this.highPriorityJob.Abort(); if ( this.highPriorityThread != null ) { this.highPriorityThread.Abort(); } Thread.Sleep(10); } if (this.highPriorityJob != null && this.highPriorityThread == null ) { this.highPriorityThread = new Thread( new ThreadStart(this.RunHighPriorityJob )); this.highPriorityThread.Start(); } if ( this.highPriorityJob != null ) { Thread.Sleep(10 ); continue; } if ( this.queue.Count > 0 ) { IWorkUnit x = null; lock( this.queue ) { x = (IWorkUnit)this.queue.Dequeue(); } this.moreWorkToDoFromThread = null; this.currentNormalJob = x; this.lowPriorityThread = new Thread( new ThreadStart( this.RunLowPriorityJob )); DateTime startTime = DateTime.Now; this.lowPriorityThread.Start(); while ( this.lowPriorityThread != null ) { int j = 10; while ( --j > 0 && this.lowPriorityThread != null ) { Thread.Sleep(10); } // Check on the lowpriority thread every 40 miliseconds. if ( this.lowPriorityThread != null ) { TimeSpan timeSpan = DateTime.Now.Subtract( startTime ); if ( timeSpan.Milliseconds > 5000 ) { // It's taking too long abort it. this.lowPriorityThread.Abort(); if ( this.currentNormalJob != null ){ this.currentNormalJob.YouWereAborted(); } } } } IWorkUnit moreWorkToDo = this.moreWorkToDoFromThread; if ( moreWorkToDo != null ) { this.AddJob( moreWorkToDo ); } } } Thread.Sleep(10); } }
//-----------------------------------------------------------------------------// /// <summary> /// Thread that runs a single low priority job. /// </summary> private void RunLowPriorityJob() { try { this.moreWorkToDoFromThread = this.currentNormalJob.DoJob(); } catch ( System.Threading.ThreadAbortException ) { DirPerfStat.Instance().IncrementLowPriorityThreadAborts(); } finally { this.lowPriorityThread = null; } }