internal AsyncTask(int noOfThreads, DoTask TaskDelegate) { m_doTask = TaskDelegate; m_taskQueue = new ActivityQueue("AsyncTask Queue"); m_noOfThreads = noOfThreads; StartThreads(); }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { var access = Utilities.GetAuthToken(_credential, _profile); var client = new WebClient(); // list contacts JObject jEvent = null; do { var eventsUrl = jEvent == null ? string.Format( "https://graph.facebook.com/me/events?" + "fields=" + Update.EVENT_FIELDS + "&method=GET&format=json&access_token={0}", access) : jEvent["paging"].TryGetValue <string>("next"); var eventsData = client.DownloadData(eventsUrl); var events = Encoding.UTF8.GetString(eventsData); jEvent = JObject.Parse(events); var eventsJson = jEvent["data"]; foreach (var json in eventsJson) { var id = json.TryGetValue <long>("id"); Update.Event(id, json); } } while (jEvent["data"].Any()); }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { var searchTerm = context.ToString(); var data = new DatalayerDataContext(); var query = data.Filesystems.Where( x => x.Filepath.Contains(searchTerm) || x.Computer.Contains(searchTerm) || x.Username.Contains(searchTerm)); using (var command = data.GetCommand(query)) { command.Connection.Open(); using (var reader = command.ExecuteReader()) { foreach (var result in data.Translate <Filesystem>(reader)) { OnResulted(new TimelineEvent { Description = result.Filepath, //EventImage = Icon.ExtractAssociatedIcon(result.Filepath), StartDate = result.Time }, queue); } } } }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { var access = Utilities.GetAuthToken(_credential, _profile); var client = new WebClient(); // list contacts JObject jPhoto = null; do { //me?fields=id,name,photos.fields(from,source,place,created_time,name,id,height,width,album) var photosUrl = jPhoto == null ? string.Format( "https://graph.facebook.com/me/photos?" + "fields=" + Update.PHOTO_FIELDS + "&method=GET&format=json&access_token={0}", access) : jPhoto["paging"].TryGetValue <string>("next"); var photosData = client.DownloadData(photosUrl); var photos = Encoding.UTF8.GetString(photosData); jPhoto = JObject.Parse(photos); var photosJson = jPhoto["data"]; foreach (var json in photosJson) { var id = json.TryGetValue <long>("id"); Update.Photo(id, json); } } while (jPhoto["data"].Any()); }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { var searchTerm = context.ToString(); var data = new DatalayerDataContext(); var query = data.Researches.Where( x => x.Address.Contains(searchTerm) || x.InterestingHtml.Contains(searchTerm) || x.Title.Contains(searchTerm)); using (var command = data.GetCommand(query)) { command.Connection.Open(); using (var reader = command.ExecuteReader()) { foreach (var result in data.Translate <Research>(reader)) { OnResulted(new TimelineEvent { Description = result.Title, StartDate = DateTime.UtcNow }, queue); } } } }
public void InitClasses() { _bottleshelf = new List <Bottle>(); //TODO: replace with actual bottleshelf _drinkdb = new List <Drink>(); _bs = new Bottleshelf(shelfsize, 10); _queue = new OrderQueue(); _activity = new ActivityQueue(new Activity(ActivityType.Idle)); }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { var access = Utilities.GetAuthToken(_credential, _profile); Execute("inbox", access); Execute("outbox", access); Execute("feed", access); }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { lock (_profile) using (var history = new DatalayerDataContext()) { var places = _sync ? SynchronizePlaces() : GetPlaces(); using (var ff = new SQLiteConnection(_profile)) { foreach (var place in places) { var newHistory = history.Histories.FirstOrDefault(x => x.Id == place.id); if (newHistory == null) { newHistory = new History { Id = place.id, Url = place.url, Guid = place.guid }; history.Histories.InsertOnSubmit(newHistory); } var iconText = string.Empty; if (place.favicon_id.HasValue) { var icon = ff.Table <moz_favicons>().First(x => x.id == place.favicon_id.Value); var image = Convert.ToBase64String(icon.data); iconText = string.Format("data:{0};base64,{1}", icon.mime_type, image); } var visitTime = new DateTime?(); if (place.last_visit_date.HasValue) { visitTime = _epoch.AddSeconds(place.last_visit_date.Value / 1000000.0); } newHistory.Title = place.title; newHistory.Host = place.rev_host; newHistory.Visits = place.visit_count; newHistory.Hidden = place.hidden; newHistory.Typed = place.typed; newHistory.Icon = iconText; newHistory.Frecency = place.frecency; newHistory.LastVisit = visitTime; try { history.SubmitChanges(); } catch (Exception e) { Log.Error(e); } } } } }
protected void OnResulted(object obj, ActivityQueue queue) { var handler = _resulted; if (handler != null) { _resulted(obj, queue, this); } }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { // get the login information out of the credential store int count; IntPtr pCredentials; var ret = AdvApi32.CredEnumerate(null, 0, out count, out pCredentials); if (!ret) { throw new Win32Exception(); } var credentials = new IntPtr[count]; // convert pointer to array to array of pointers for (var n = 0; n < count; n++) { credentials[n] = Marshal.ReadIntPtr(pCredentials, n * Marshal.SizeOf(typeof(IntPtr))); } var login = credentials // convert each pointer to a structure .Select(ptr => (WinCred.Credential)Marshal.PtrToStructure(ptr, typeof(WinCred.Credential))) // select the structure with the matching credential name .FirstOrDefault(cred => cred.targetName.StartsWith(_credential)); // get the password var currentPass = Marshal.PtrToStringUni(login.credentialBlob, (int)login.credentialBlobSize / 2); var lastError = Marshal.GetLastWin32Error(); if (lastError != 0) { throw new Win32Exception(lastError); } // finally try to log in var hostArr = login.targetName.Substring(_credential.Length + 1).Split(':'); var host = hostArr[0]; var port = hostArr.Length > 1 ? int.Parse(hostArr[1]) : 143; var @params = new ImapParams { Host = host, Username = login.userName, Password = currentPass, Port = port, Validate = false, Ssl = port == 993 || port == 995, Queue = queue }; // start a thread to check for e-mail ThreadPool.QueueUserWorkItem(MailPoller, @params); }
public void Activityqueue() { Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 10)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 11)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 12)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.Idle), 10)); Assert.IsFalse(_activity.Add(new Activity(ActivityType.ProcessOrders), 10)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.Macro, "asd"), 10)); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual(ActivityType.Idle, _activity.Pop().Type); Assert.AreEqual(ActivityType.Macro, _activity.Pop().Type); Assert.AreEqual(0, _activity.Count); _activity = new ActivityQueue(new Activity(ActivityType.Macro, "testing")); Assert.AreEqual("testing", _activity.Pop().Data); Assert.AreEqual("testing", _activity.Pop().Data); Assert.AreEqual(ActivityType.Macro, _activity.Pop().Type); Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 10)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 20)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 1000)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.ProcessOrders), 0)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.Macro, "first"), 15)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.Macro, "second"), 100)); Assert.IsTrue(_activity.Add(new Activity(ActivityType.Idle), 100)); Assert.AreEqual(7, _activity.Count); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual("second", _activity.Pop().Data); Assert.AreEqual(ActivityType.Idle, _activity.Pop().Type); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual("first", _activity.Pop().Data); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual(ActivityType.ProcessOrders, _activity.Pop().Type); Assert.AreEqual(0, _activity.Count); Assert.AreEqual("testing", _activity.Pop().Data); Assert.AreEqual("testing", _activity.Pop().Data); Assert.AreEqual("testing", _activity.Pop().Data); try { _activity.Add(new Activity(ActivityType.Idle), -5); Assert.Fail("Expected a ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { } }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { IQueryable query; var data = new DatalayerDataContext(); var expression = context as LambdaExpression; if (expression != null) { try { expression = expression.AsExpressable() .Replace <Life.Controls.MessageRequest, Email, string>(message => message.From, email => email.From.Substring(0, 1000).Replace("\"", "")) .Replace <Life.Controls.MessageRequest, Email, string>(message => message.Message, email => email.Body) .Replace <Life.Controls.MessageRequest, Email, DateTime>(message => message.Time, email => email.Received) .AsExpression(); var compiled = expression.Compile(); var result = compiled.DynamicInvoke(data.Emails); query = result as IQueryable; if (query == null) { return; } } catch (Exception ex) { Log.Error(string.Format("Could not convert expression to known types: {0}", context), ex); return; } } else { var searchTerm = context.ToString(); query = data.Emails.Where( x => x.Subject.Contains(searchTerm) || x.Body.Contains(searchTerm)); } using (var command = data.GetCommand(query)) { command.Connection.Open(); using (var reader = command.ExecuteReader()) { var returnType = query.GetType().GetGenericArguments().First(); foreach (var result in data.Translate(returnType, reader)) { var entity = result; OnResulted(entity, queue); } } } }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { IQueryable query; var data = new DatalayerDataContext(); var expression = context as LambdaExpression; if (expression != null) { try { expression = expression.AsExpressable() .Replace <Life.Controls.MessageRequest, FacebookMessage, string>(message => message.From, msg => msg.FacebookContact.Name) .Replace <Life.Controls.MessageRequest, FacebookMessage, string>(message => message.Message, msg => msg.Message) .Replace <Life.Controls.MessageRequest, FacebookMessage, DateTime>(message => message.Time, msg => msg.TimeCreated) .AsExpression(); var compiled = expression.Compile(); var result = compiled.DynamicInvoke(data.FacebookMessages); query = result as IQueryable; if (query == null) { return; } } catch (Exception ex) { Log.Error(string.Format("Could not convert expression to known types: {0}", context), ex); return; } } else { throw new NotImplementedException(); } using (var command = data.GetCommand(query)) { command.Connection.Open(); using (var reader = command.ExecuteReader()) { var returnType = query.GetType().GetGenericArguments().First(); foreach (var result in data.Translate(returnType, reader)) { var entity = result; OnResulted(entity, queue); } } } }
public override Activity GetActivity() { // PPather.WriteLine("Pickup::GetActivity()"); if (!IsCloseToNPC()) { return(GetWalkToActivity()); } else { if (queueActivity == null) { queueActivity = new ActivityQueue(this, FindNPC(), Battlefield); } return(queueActivity); } }
static StatusProxy() { _statusQueue = new DatabaseWriterQueue <long, TwitterStatus>(200, TimeSpan.FromSeconds(30), async s => await StoreStatusesAsync(s).ConfigureAwait(false)); _favoriteQueue = new ActivityQueue(50, TimeSpan.FromSeconds(30), s => Task.Run(() => Database.FavoritesCrud.InsertAllAsync(s)), s => Task.Run(() => Database.FavoritesCrud.DeleteAllAsync(s))); _retweetQueue = new ActivityQueue(50, TimeSpan.FromSeconds(30), s => Task.Run(() => Database.RetweetsCrud.InsertAllAsync(s)), s => Task.Run(() => Database.RetweetsCrud.DeleteAllAsync(s))); App.ApplicationFinalize += () => { _statusQueue.Dispose(); _favoriteQueue.Writeback(); _retweetQueue.Writeback(); }; }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { try { // if there are no settings if (_listen == null && string.IsNullOrEmpty(_computer)) { throw new NotImplementedException("Cannot start auditer with no computer name."); } var newLog = new EventLog("Security", _computer, "File System") { EnableRaisingEvents = true }; newLog.EntryWritten += (o, e) => ProcessEntry(e.Entry, queue); // maintain referenced to global list MyNewLog.Add(newLog); // Enumerate through current log entries foreach (EventLogEntry entry in newLog.Entries) { ProcessEntry(entry, queue); } } catch (Exception e) { if (e is IndexOutOfRangeException) { Log.Error("Events purged before loading finished.", e); } else if (e is InvalidOperationException) { // must need a listener because it isn't windows InitializeTcpStringListener(); } else { Log.Error("There was an error initializing the event listener.", e); } } }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { var access = Utilities.GetAuthToken(_credential, _profile); // list contacts var contactsUrl = string.Format( "https://graph.facebook.com/me?fields=id%2Cname%2Cfriends&method=GET&format=json&access_token={0}", access); var client = new WebClient(); var contactsData = client.DownloadData(contactsUrl); var contacts = Encoding.UTF8.GetString(contactsData); var contactsJson = JObject.Parse(contacts); // save contacts to the database foreach (var json in contactsJson["friends"]["data"]) { var id = json.Value <long>("id"); Update.Contact(id, json); } }
public override void Execute(object context, ActivityQueue queue, Utilities.Trigger trigger) { if (!Application.Current.Dispatcher.CheckAccess()) { Application.Current.Dispatcher.Invoke( (Action <dynamic>)(context1 => Execute(context1, queue, trigger)), DispatcherPriority.Input, context); return; } var element = context as FrameworkElement; if (element != null) { } /*((MainWindow) Application.Current.MainWindow).Timeline.TimelineEvents.Add(new TimelineEvent * { * Description = context.ToString(), * StartDate = queue.TimeAdded.ToLocalTime() * }); * ((MainWindow) Application.Current.MainWindow).Timeline.RefreshEvents(true); * */ }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { if (!Directory.Exists(_logs)) { return; } var files = Directory.EnumerateFiles(_logs, "*.*", SearchOption.AllDirectories) .Where(x => (x.EndsWith(".xml") || x.EndsWith(".log")) && !(Path.GetFileNameWithoutExtension(x) ?? "").Contains(" - ")) .ToList(); //files = new List<string> { "C:\\Users\\bjcullinan\\AppData\\Roaming\\Trillian\\users\\bjcullinan\\logs\\logs\\old logs\\AIM\\Query\\APTWIRLER.xml" }; // read each files content var count = 0; foreach (var file in files) { if (file.IndexOf("prettyeuro", StringComparison.InvariantCultureIgnoreCase) > -1) { } Log.Debug(string.Format("{0}% complete: {1}", Math.Round((double)count / files.Count * 100, 2), file)); count++; var medium = (Path.GetFileNameWithoutExtension(file) ?? "").Split('-')[0].Trim(); if (!_media.Contains(medium, StringComparer.InvariantCultureIgnoreCase)) { medium = (Path.GetFileName(Path.GetDirectoryName(file) ?? "") ?? "").Trim(); } if (!_media.Contains(medium, StringComparer.InvariantCultureIgnoreCase)) { medium = (Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(file) ?? "") ?? "") ?? "").Trim(); } if (!_media.Contains(medium, StringComparer.InvariantCultureIgnoreCase)) { Log.Debug(string.Format("Could not detect medium: {0}", file)); continue; } // create a dictionary of time and text var messages = new Dictionary <long, Tuple <string, string, string> >(); var sessions = new List <Tuple <long, long> >(); // always prefer the data read from xml as it is more precise, but some of the old files don't support this var from = (Path.GetFileNameWithoutExtension(file) ?? "").ToLowerInvariant(); from = from.Replace(medium.ToLowerInvariant(), ""); from = from.Trim().Trim('-').Trim(); if (_synchronized.Contains(from)) { continue; } _synchronized.Add(from); var xmlFiles = files.Where(x => x.IndexOf(medium, StringComparison.InvariantCultureIgnoreCase) > -1 && x.EndsWith(from + ".xml", StringComparison.InvariantCultureIgnoreCase)) .ToList(); foreach (var xmlFile in xmlFiles) { try { LoadXml(xmlFile, ref sessions, ref messages); } catch (Exception ex) { Log.Debug(string.Format("Error in {0}", xmlFile), ex); } } var logFiles = files.Where(x => x.IndexOf(medium, StringComparison.InvariantCultureIgnoreCase) > -1 && x.EndsWith(from + ".log", StringComparison.InvariantCultureIgnoreCase)) .ToList(); foreach (var logFile in logFiles) { try { LoadLog(logFile, ref sessions, ref messages); } catch (Exception ex) { Log.Debug(string.Format("Error in {0}", logFile), ex); } } // add messages to database using (var data = new DatalayerDataContext()) { var ids = data.TrillianMessages .Where(x => x.From == from && x.Medium == medium) .Select(x => x.Id) .ToList(); foreach (var message in messages) { var msgId = new DateTime(message.Key * TimeSpan.TicksPerMillisecond); if (ids.Contains(msgId)) { continue; } var msg = new TrillianMessage { Id = msgId, Medium = medium, From = from, Message = message.Value.Item3 }; data.TrillianMessages.InsertOnSubmit(msg); } try { data.SubmitChanges(); } catch (Exception ex) { Log.Error(string.Format("There was an error saving the chat log: {0} {1}", string.Join(Environment.NewLine, xmlFiles), string.Join(Environment.NewLine, logFiles)), ex); } if (sessions != null) { foreach (var session in sessions) { var start = new DateTime(session.Item1 * TimeSpan.TicksPerMillisecond); var stop = new DateTime(session.Item2 * TimeSpan.TicksPerMillisecond); if (data.TrillianSessions.Any(x => x.From == from && x.Start == start && x.Stop == stop)) { continue; } var ses = new TrillianSession { From = from, Start = start, Stop = stop }; data.TrillianSessions.InsertOnSubmit(ses); } } try { data.SubmitChanges(); } catch (Exception ex) { Log.Error(string.Format("There was an error saving the chat sessions: {0} {1}", string.Join(Environment.NewLine, xmlFiles), string.Join(Environment.NewLine, logFiles)), ex); } } } }
private void ProcessEntry(EventLogEntry entry, ActivityQueue queue) { const int MAX = 0; using (var data = new DatalayerDataContext()) { // Do something with log entries if ((entry.InstanceId != 4656 && entry.InstanceId != 4663) || entry.Index <= MAX) { return; } var events = data.Filesystems.Where(x => x.EventId == entry.Index); if (events.Any()) { return; } var log = new Filesystem(); var num = AccessMask.Unknown; switch (entry.InstanceId) { case 4656: num = (AccessMask) Int32.Parse(entry.ReplacementStrings[11].Substring(2), NumberStyles.HexNumber); break; case 4663: num = (AccessMask) Int32.Parse(entry.ReplacementStrings[9].Substring(2), NumberStyles.HexNumber); break; } if ((num & _mask) == 0) { return; } /*if ((num & (int)AccessCodes.Delete) == (int)AccessCodes.Delete) * log.Type += (log.Type != "" ? "," : "") + "Delete"; * * if ((num & (int)AccessCodes.ReadControl) == (int)AccessCodes.ReadControl || (num & (int)AccessCodes.Read) == (int)AccessCodes.Read) * log.Type += (log.Type != "" ? "," : "") + "Read"; * * if ((num & (int)AccessCodes.WriteDac) == (int)AccessCodes.WriteDac || (num & (int)AccessCodes.WriteOwner) == (int)AccessCodes.WriteOwner) * log.Type += (log.Type != "" ? "," : "") + "Write"; * * if ((num & (int)AccessCodes.Create) == (int)AccessCodes.Create) * log.Type += (log.Type != "" ? "," : "") + "Create"; */ log.Filepath = entry.ReplacementStrings[6]; log.Time = entry.TimeGenerated.ToUniversalTime(); log.EventId = entry.Index; log.Username = entry.ReplacementStrings[2] + "\\" + entry.ReplacementStrings[1]; log.AccessMask = (decimal)num; log.Success = entry.EntryType == EventLogEntryType.SuccessAudit; log.Computer = _computer; data.Filesystems.InsertOnSubmit(log); try { data.SubmitChanges(); OnResulted(log, queue); } catch (Exception e) { Log.Error("Error saving audit entry.", e); } } }
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { lock (_profile) using (var data = new DatalayerDataContext()) { var places = _sync ? SynchronizeBookmarks() : GetBookmarks(); using (var ff = new SQLiteConnection(_profile)) { foreach (var mark in places) { var newHistory = data.Bookmarks.FirstOrDefault(x => x.Id == mark.id); if (newHistory == null) { newHistory = new Bookmark { Id = mark.id, Guid = mark.guid, }; data.Bookmarks.InsertOnSubmit(newHistory); } // check if the last modified date is after the date in the database else if (mark.lastModified.HasValue && _epoch.AddSeconds(mark.lastModified.Value / 1000000.0) <= newHistory.LastModified) { continue; } var url = string.Empty; if (mark.fk.HasValue) { url = ff.Table <moz_places>().First(x => x.id == mark.fk.Value).url; } var keywords = string.Empty; if (mark.keyword_id.HasValue) { keywords = ff.Table <moz_keywords>().First(x => x.id == mark.keyword_id.Value).keyword; } var lastModified = new DateTime?(); if (mark.lastModified.HasValue) { lastModified = _epoch.AddSeconds(mark.lastModified.Value / 1000000.0); } var dateAdded = new DateTime?(); if (mark.dateAdded.HasValue) { dateAdded = _epoch.AddSeconds(mark.dateAdded.Value / 1000000.0); } newHistory.Url = url; newHistory.DateAdded = dateAdded; newHistory.LastModified = lastModified; newHistory.Keywords = keywords; newHistory.Parent = mark.parent; newHistory.Position = mark.position; newHistory.Title = mark.title; newHistory.Type = mark.type; try { data.SubmitChanges(); } catch (Exception e) { Log.Error(e); } } } } }
public abstract void Execute(object context, ActivityQueue queue, Trigger trigger);
public override void Execute(object context, ActivityQueue queue, Trigger trigger) { }