/// <summary> /// Adds the specified jid. /// </summary> /// <param name="jid">The jid.</param> /// <param name="comparer">The comparer.</param> /// <param name="cb">The callback.</param> /// <param name="cbArg">The callback Arguments.</param> public void Add(Jid jid, IComparer comparer, PresenceCB cb, object cbArg) { lock (m_grabbing) { if (m_grabbing.ContainsKey(jid.ToString())) return; } TrackerData td = new TrackerData(); td.cb = cb; td.data = cbArg; td.comparer = comparer; lock (m_grabbing) { m_grabbing.Add(jid.ToString(), td); } }
//UPS private void SendRequestToUPSWebService(TrackerData Entry) { try { var Response = UPS.GetTrackingInfo(Entry.TrackingNumber); ParseRawUPSDataIntoList(Entry, Response); } catch (Exception ex) { if (ex.Message == "An exception has been raised as a result of client data.") { Entry.Location = "ERROR: Bad Credentials"; Entry.Status = PackageStatus.Other; } else { Entry.Location = "ERROR"; Entry.Status = PackageStatus.Other; } } }
private void SendRequestToFedExWebService(TrackerData Entry) { //open webservice, pass in tracking number var request = FedEx.CreateTrackRequest(Entry.TrackingNumber); var service = new FedExWebService.FedExWebReference.TrackService(); try { // Call the Track web service passing in a TrackRequest and returning a TrackReply var reply = service.track(request); if (reply.HighestSeverity != NotificationSeverityType.ERROR && reply.HighestSeverity != NotificationSeverityType.FAILURE) { //Parse raw data here ParseFedExRawDataIntoList(Entry, reply); } else { //error handling for blank and incomplete tracking numbers, or invalid requests due to faulty credentials Entry.Location = "ERROR"; Entry.Status = PackageStatus.Other; } } catch (SoapException e) { Console.WriteLine(e.Detail.InnerText); } catch (Exception e) { Console.WriteLine(e.Message); } }
private void ProcessEdit <T>(T fileId, TrackerData fileData) { if (ThirdPartySelector.GetAppByFileId(fileId.ToString()) != null) { return; } var users = FileTracker.GetEditingBy(fileId); var usersDrop = new List <string>(); string docKey; var app = ThirdPartySelector.GetAppByFileId(fileId.ToString()); if (app == null) { File <T> fileStable; fileStable = DaoFactory.GetFileDao <T>().GetFileStable(fileId); docKey = DocumentServiceHelper.GetDocKey(fileStable); } else { docKey = fileData.Key; } if (!fileData.Key.Equals(docKey)) { Logger.InfoFormat("DocService editing file {0} ({1}) with key {2} for {3}", fileId, docKey, fileData.Key, string.Join(", ", fileData.Users)); usersDrop = fileData.Users; } else { foreach (var user in fileData.Users) { if (!Guid.TryParse(user, out var userId)) { Logger.Error("DocService userId is not Guid: " + user); continue; } users.Remove(userId); try { var doc = FileShareLink.CreateKey(fileId); EntryManager.TrackEditing(fileId, userId, userId, doc); } catch (Exception e) { Logger.DebugFormat("Drop command: fileId '{0}' docKey '{1}' for user {2} : {3}", fileId, fileData.Key, user, e.Message); usersDrop.Add(userId.ToString()); } } } if (usersDrop.Any()) { if (!DocumentServiceHelper.DropUser(fileData.Key, usersDrop.ToArray(), fileId)) { Logger.Error("DocService drop failed for users " + string.Join(",", usersDrop)); } } foreach (var removeUserId in users) { FileTracker.Remove(fileId, userId: removeUserId); } SocketManager.FilesChangeEditors(fileId); }
private static string ProcessSave(string fileId, TrackerData fileData) { Guid userId; var comments = new List <string>(); if (fileData.Status == TrackerStatus.Corrupted) { comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted); } if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } try { SecurityContext.AuthenticateMe(userId); } catch (Exception ex) { Global.Logger.Info("DocService save error: anonymous author - " + userId, ex); if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous); } } File file = null; var saved = false; FileTracker.Remove(fileId); if (string.IsNullOrEmpty(fileData.Url)) { try { comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost); file = EntryManager.CompleteVersionFile(fileId, 0, false, false); using (var fileDao = Global.DaoFactory.GetFileDao()) { fileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments)); } } catch (Exception ex) { Global.Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex); } } else { try { file = EntryManager.SaveEditing(fileId, null, fileData.Url, null, string.Empty, string.Join("; ", comments), false); saved = fileData.Status == TrackerStatus.MustSave; } catch (Exception ex) { Global.Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex); StoringFileAfterError(fileId, userId.ToString(), fileData.Url); } } if (file != null) { var user = CoreContext.UserManager.GetUsers(userId); if (user != null) { FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false), file.Title); } SaveHistory(file, fileData.History.ToString(), fileData.ChangesUrl); } return(saved ? "0" //error:0 - saved : "1"); //error:1 - some error }
// POST api/values public void Post([FromBody] TrackerData trackerData) { MongoPersist.Persist(trackerData); }
/// <summary> /// Sends an IQ request and waits for the response. /// </summary> /// <param name="iqp">An IQ packet to send, and wait for.</param> /// <param name="millisecondsTimeout">Time to wait for response, in milliseconds</param> /// <returns>An IQ in reponse to the sent IQ.</returns> public IQ IQ(IQ iqp, int millisecondsTimeout) { AutoResetEvent are = new AutoResetEvent(false); TrackerData td = new TrackerData(SignalEvent, are, iqp.To, iqp.ID); string id = iqp.ID; lock (m_pending) { m_pending[id] = td; } m_cli.Write(iqp); if (!are.WaitOne(millisecondsTimeout, true)) { throw new Exception("Timeout waiting for IQ response"); } lock (m_pending) { IQ resp = td.Response; m_pending.Remove(id); return resp; } }
/// <summary> /// Overwrites tracker position data. /// </summary> /// <param name="src">source tracker data</param> /// <param name="x">new x value</param> /// <param name="y">new y value</param> /// <param name="z">new z value</param> /// <returns></returns> public static TrackerData SetPosition(TrackerData src, float x, float y, float z) { src.Position = new Vector3(x, y, z); return(src); }
/// <summary> /// Run on the tracker thread /// </summary> private void UpdateTrackerDirect() { // Copy the current data and reset the update pending flag. Reseting the flag indicates that // any writes to the data now need to force another update to make it to the tracker TrackerData copy; lock (m_lock) { copy = m_data; m_data = new TrackerData(); } UpdateTrackerDirectCore(copy, m_tracker); }
public void UpdateScores() { ScoreSet set = ScoreTracker.Data.GetScoreSet(); for (int i = 0; i < panels.Count; i++) { panels[i].entry = set[i]; panels[i].UpdatePanel(); } TrackerData run = ScoreTracker.Data; int total = run.GetScoreSet(0).GetComparisonTotal(); if (ScoreTracker.config["casual_mode"] == "0") { total = run.GetScoreSet().GetComparisonTotal(); } int sob = run.GetScoreSet(1).GetComparisonTotal(); if (ScoreTracker.config["layout"] == "0") { sobScoreName.Text = "SoB:"; if (ScoreTracker.Data.GetComparisonIndex() == 0 || ScoreTracker.config["casual_mode"] == "1") { topScoreName.Text = "Top:"; } else if (ScoreTracker.Data.GetComparisonIndex() == 1) { topScoreName.Text = "-"; } else { topScoreName.Text = "Cmp:"; } } else { sobScoreName.Text = "Sum of Best:"; if (ScoreTracker.Data.GetComparisonIndex() == 0 || ScoreTracker.config["casual_mode"] == "1") { topScoreName.Text = "Top:"; } else if (ScoreTracker.Data.GetComparisonIndex() == 1) { topScoreName.Text = "-"; } else { topScoreName.Text = "Comparison:"; } } if (ScoreTracker.Data.GetComparisonIndex() != 1) { topScore.Text = "" + total; } else { topScore.Text = "-"; } sobScore.Text = "" + sob; sobScore.Text = "" + ScoreTracker.Tracker.GetSOB(); if (!ScoreTracker.Tracker.IsRunning() && ScoreTracker.config["layout"] == "0") { currentScore.Text = ""; } else { currentScore.Text = "" + ScoreTracker.Tracker.GetTotalScore(); if (ScoreTracker.Tracker.GetTotalScore() == 0) { currentScore.Text = "-"; } } Color p = ScoreTracker.colors["text_color"]; if (ScoreTracker.Tracker.IsRunning() && ScoreTracker.config["casual_mode"] == "0") { p = GetPaceColor(ScoreTracker.Tracker.GetCurrentPace()); } currentScore.ForeColor = p; currentScoreName.Text = "Total:"; }
private static void UpdateTrackerDirectCore(TrackerData data, IProgressTracker tracker) { if (data.Title != null) { tracker.SetTitle(data.Title); } if (data.Summary != null) { tracker.SetSummary(data.Summary); } if (data.IsCancelAllowed != null) { tracker.IsCancelable = data.IsCancelAllowed.Value; } if (data.StepTotal != null && data.StepIncrement != null) { tracker.SetStepInformation(data.StepIncrement.Value, data.StepTotal.Value); } if (data.CurrentStep != null) { tracker.SetCurrentStep(data.CurrentStep.Value); } if (data.PerformStepCount != null) { for (int i = 0; i < data.PerformStepCount.Value; ++i) { tracker.PerformStep(); } } }
public void Start(bool deleteRecordAfterMigration, int startAt, int stopAfter, int docsImported) { var docNumber = startAt; try { var trackerDocuments = _mongoDatabase.GetCollection("TrackerData"); //var sqlPersister = new PersistToSQLServer(_sqlConnectionString, new ConsoleLogger()); foreach (var trackerDocument in trackerDocuments.FindAll().Skip(startAt)) { Debug.Write(trackerDocument); TrackerData trackerData = null; ITrackable tracker = null; string trackerTypeName = null; DateTime? timeSlot = null; foreach (var element in trackerDocument.Elements) { if (element.Name == "TypeName") { trackerTypeName = element.Value.ToString(); } } if (trackerTypeName != null) { trackerData = new TrackerData(trackerTypeName); foreach (var element in trackerDocument.Elements) { switch (element.Name) { case "Name": trackerData.Name = element.Value.ToString(); break; case "KeyFilter": trackerData.KeyFilter = element.Value.ToString(); break; case "TimeSlot": timeSlot = Convert.ToDateTime(element.Value.ToString()); break; //case "SearchFilters": // var filters = // element.Value.AsBsonArray.Select(p => p.AsString).ToArray(); // for (var i = 0; i < filters.Length; i++) // { // filters[i] = filters[i].Split(new [] {",,"}, StringSplitOptions.None).OrderBy(f => f).Aggregate((x, z) => string.Concat(x, ",,", z));//this is to fix a bug that was caused by the missing sort in the previous version. // } // trakerData.SearchFilters = filters; // break; case "Measurement": var mesurementDoc = (BsonDocument)element.Value; trackerData.Measurement = new Measure(); trackerData.Measurement.NamedMetrics = new ConcurrentDictionary <string, long>(); foreach (var measure in mesurementDoc.Elements) { //switch (measure.Name) //{ // case "_Total": // trakerData.Measurement._Total = Convert.ToInt32(measure.Value.ToString()); // break; // case "_Occurrence": // trakerData.Measurement._Occurrence = // Convert.ToInt32(measure.Value.ToString()); // break; // case "_Min": // trakerData.Measurement._Min = Convert.ToInt32(measure.Value.ToString()); // break; // case "_Max": // trakerData.Measurement._Max = Convert.ToInt32(measure.Value.ToString()); // break; // default: var val = Convert.ToInt32(measure.Value); trackerData.Measurement.NamedMetrics.AddOrUpdate(measure.Name, val, (i, t) => t + val); // break; //} } break; } } tracker = TrackerBuilder.CreateTrackerFromTypeName(trackerTypeName, trackerData.Name); object filter = null; if (!string.IsNullOrWhiteSpace(trackerData.KeyFilter)) { filter = TrackerBuilder.CreateFilterObject(trackerData.KeyFilter); } var grapheneContainer = typeof(Container <>).MakeGenericType(tracker.GetType()); var grapheneContainerInstance = Activator.CreateInstance(grapheneContainer); // var grapheneSetTrackerType = // grapheneContainer.GetMethod("SetTrackerType", BindingFlags.Instance | BindingFlags.NonPublic); // grapheneSetTrackerType.Invoke(grapheneContainerInstance, new[] { tracker }); var grapheneIncrement = grapheneContainer.GetMethod("Increment", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new[] { typeof(ITrackable), typeof(Resolution), typeof(DateTime), typeof(string), typeof(long), typeof(object) }, null); foreach (var metric in trackerData.Measurement.NamedMetrics) { grapheneIncrement.Invoke(grapheneContainerInstance, new[] { tracker, Resolution.Day, timeSlot, metric.Key, metric.Value, filter }); } if (deleteRecordAfterMigration) { trackerDocuments.Remove(Query <TrackerData> .EQ(td => td._id, trackerData._id)); } if (_logger != null) { _logger.Info(string.Format("Migrated Document with ID:{0}, Number{1}", trackerData._id, docNumber)); } docNumber++; docsImported++; if (_stopCalled || (stopAfter != -1 && docsImported >= stopAfter)) { break; } } } } catch (Exception exception) { _logger.Error(exception.Message, exception); if (exception is MongoDB.Driver.MongoQueryException && exception.Message == "Cursor not found.")//todo: find out the exception type. { Start(deleteRecordAfterMigration, docNumber, stopAfter, docsImported); } } }
public void Save(TrackerData data) { using (IDbConnection conn = new SqlConnection(_connectionString)) { using (IDbCommand command = new SqlCommand()) { command.Connection = conn; command.CommandType = CommandType.Text; command.CommandText = _commandText; IDbDataParameter param0 = command.CreateParameter(); param0.ParameterName = "@DeviceId"; param0.Value = data.DeviceId; IDbDataParameter param1 = command.CreateParameter(); param1.ParameterName = "@PhoneNumber"; param1.Value = data.PhoneNumber; IDbDataParameter param2 = command.CreateParameter(); param2.DbType = DbType.Decimal; param2.ParameterName = "@Longitude"; param2.Value = data.Longitude; param2.Precision = 10; param2.Scale = 7; IDbDataParameter param3 = command.CreateParameter(); param3.DbType = DbType.Decimal; param3.ParameterName = "@Latitude"; param3.Value = data.Latitude; param3.Precision = 10; param3.Scale = 7; IDbDataParameter param4 = command.CreateParameter(); param4.DbType = DbType.Decimal; param4.ParameterName = "@Velocity"; param4.Value = data.Velocity; param4.Precision = 10; param4.Scale = 7; IDbDataParameter param5 = command.CreateParameter(); param5.DbType = DbType.Decimal; param5.ParameterName = "@Altitude"; param5.Value = data.Altitude; param5.Precision = 10; param5.Scale = 7; IDbDataParameter param6 = command.CreateParameter(); param6.ParameterName = "@SourceAddress"; param6.Value = data.SourceAddress; IDbDataParameter param7 = command.CreateParameter(); param7.ParameterName = "@SourcePort"; param7.Value = data.SourcePort; command.Parameters.Add(param0); command.Parameters.Add(param1); command.Parameters.Add(param2); command.Parameters.Add(param3); command.Parameters.Add(param4); command.Parameters.Add(param5); command.Parameters.Add(param6); command.Parameters.Add(param7); try { conn.Open(); command.ExecuteNonQuery(); } finally { conn.Close(); } } } }
//USPS private void SendRequestToUSPSWebService(TrackerData Entry) { try { var Reply = USPS.GetTrackingInfo(Entry.TrackingNumber); ParseUSPSRawDataIntoList(Entry, Reply); } catch (USPSManagerException ex) { if (ex.Message == "Unable to connect to remote server") { Entry.Location = "ERROR: No Connection"; Entry.Status = PackageStatus.Other; } else { Entry.Location = "ERROR"; Entry.Status = PackageStatus.Other; } } }
/// <summary> /// Overwrites tracker rotation data /// </summary> /// <param name="src">source tracker data</param> /// <param name="x">new Euler x rotation</param> /// <param name="y">new Euler y rotation</param> /// <param name="z">new Ruler Z rotation</param> /// <returns></returns> public static TrackerData SetRotation(TrackerData src, float x, float y, float z) { src.Rotation = Quaternion.Euler(x, y, z); return(src); }
/// <summary> /// Send an IQ Request and store the object with callback in the Hashtable /// </summary> /// <param name="iq">The iq to send</param> /// <param name="cb">the callback function which gets raised for the response</param> /// <param name="cbArg">additional object for arguments</param> public void SendIq(IQ iq, IqCB cb, object cbArg) { // check if the callback is null, in case of wrong usage of this class if (cb != null) { TrackerData td = new TrackerData(); td.cb = cb; td.data = cbArg; m_grabbing[iq.Id] = td; } m_connection.Send(iq); }
/// <summary> /// Scales the rotation values in TrackerData by applying an x,y,z scale value /// to the rotations Euler angles. The most useful application is reversing /// rotations by scaling by -1. (Often used to convert between right handed /// and left handed coordinate systems.) /// </summary> /// <param name="src">Input TrackerData</param> /// <param name="x">X rotation scale</param> /// <param name="y">Y rotation scale</param> /// <param name="z">Z rotation scale</param> /// <returns></returns> public static TrackerData ScaleRotation(TrackerData src, float x, float y, float z) { src.Rotation = Quaternion.Euler(new Vector3(src.Rotation.eulerAngles.x * x, src.Rotation.eulerAngles.y * y, src.Rotation.eulerAngles.z * z)); return(src); }
public static void Main(string[] args) { Console.WriteLine("Running in: " + Directory.GetCurrentDirectory()); try { var handle = GetConsoleWindow(); ShowWindow(handle, SW_HIDE); } catch (Exception) { } for (int i = 0; i < args.Length; i++) { /*if (args[i] == "-s") * { * // If -s is found in the arguments check if the port is specified * for (int j = 0; j < args.Length; j++) * { * if (args[j] == "-p" && j < args.Length - 1) * { * // If -p is found set port to the next argument * port = Convert.ToInt32(args[j+1]); * } * } * // Start server and return from Main() before client is started * StartServer(port); * return; * }*/ } /*OpenFileDialog test = new OpenFileDialog(); * test.Filter = ".ini|*.ini"; * test.Title = "Test"; * test.ShowDialog();*/ try { //Test(); ConvertFiles(); } catch (Exception e) { Console.WriteLine("Conversion Error: " + e.Message + "\n" + e.StackTrace); } //try { config = new FileReader("config.ini", SortingStyle.Sort); config.AddNewItem("version", ""); config.AddNewItem("file_index", "0"); config.AddNewItem("casual_mode", "0"); config.AddNewItem("layout", "1"); config.AddNewItem("include_route_pbs_in_individuals_file", "0"); config.AddNewItem("sums_horizontal_alignment", "0"); List <string> fonts = new List <string>(); foreach (FontFamily f in System.Drawing.FontFamily.Families) { fonts.Add(f.Name); } if (fonts.Contains("Segoe UI")) { config.AddNewItem("font", "Segoe UI"); } else if (fonts.Contains("DejaVu Sans")) { config.AddNewItem("font", "DejaVu Sans"); } else if (fonts.Contains("Arial")) { config.AddNewItem("font", "Arial"); } else { config.AddNewItem("font", SystemFonts.MessageBoxFont.Name); } config.AddNewItem("font_size", "18"); config.AddNewItem("highlight_current", "0"); config.AddNewItem("start_highlighted", "1"); config.AddNewItem("horizontal_width", "1296"); config.AddNewItem("horizontal_height", "99"); config.AddNewItem("vertical_width", "316"); config.AddNewItem("vertical_height", "309"); config["version"] = version; if (config.ContainsKey("debug") && config["debug"] == "1") { try { var handle = GetConsoleWindow(); ShowWindow(handle, SW_SHOW); } catch (Exception) { } } if (config ["layout"] == "horizontal") { config ["layout"] = "0"; } if (config ["layout"] == "vertical") { config ["layout"] = "1"; } if (config ["layout"] != "0" && config ["layout"] != "1") { config ["layout"] = "0"; } if (config ["sums_horizontal_alignment"] == "right") { config ["sums_horizontal_alignment"] = "0"; } if (config ["sums_horizontal_alignment"] == "left") { config ["sums_horizontal_alignment"] = "1"; } if (config ["sums_horizontal_alignment"] != "0" && config ["sums_horizontal_alignment"] != "1") { config ["sums_horizontal_alignment"] = "0"; } config.Save(); colors = new ColorFileReader("color_theme.ini", SortingStyle.Validate); colors.AddNewItem("text_color", "#FFFFFF"); colors.AddNewItem("text_color_total", "#FFFFFF"); colors.AddNewItem("text_color_highlighted", "#FFFFFF"); colors.AddNewItem("background_color", "#0F0F0F"); colors.AddNewItem("background_color_highlighted", "#3373F4"); colors.AddNewItem("text_color_ahead", "#00CC36"); colors.AddNewItem("text_color_behind", "#CC1200"); colors.AddNewItem("text_color_best", "#D8AF1F"); if (config.ContainsKey("text_color")) { string c = config["text_color"]; config.RemoveKey("text_color"); colors["text_color"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("text_color_total")) { string c = config["text_color_total"]; config.RemoveKey("text_color_total"); colors["text_color_total"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("text_color_highlighted")) { string c = config["text_color_highlighted"]; config.RemoveKey("text_color_highlighted"); colors["text_color_highlighted"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("background_color")) { string c = config["background_color"]; config.RemoveKey("background_color"); colors["background_color"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("background_color_highlighted")) { string c = config["background_color_highlighted"]; config.RemoveKey("background_color_highlighted"); colors["background_color_highlighted"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("text_color_ahead")) { string c = config["text_color_ahead"]; config.RemoveKey("text_color_ahead"); colors["text_color_ahead"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("text_color_behind")) { string c = config["text_color_behind"]; config.RemoveKey("text_color_behind"); colors["text_color_behind"] = ColorTranslator.FromHtml(c); } if (config.ContainsKey("text_color_best")) { string c = config["text_color_best"]; config.RemoveKey("text_color_best"); colors["text_color_best"] = ColorTranslator.FromHtml(c); } files = new List <string>(); if (config.ContainsSection("Files")) { foreach (string key in config.GetSection("Files").Keys) { if (!System.IO.File.Exists(config["Files", key])) { config.RemoveKey("Files", key); continue; } try { FileReader tmp = new FileReader(config["Files", key]); if (!tmp.ContainsSection("Best Run")) { config.RemoveKey("Files", key); continue; } } catch (Exception) { config.RemoveKey("Files", key); continue; } files.Add(config["Files", key]); config.RemoveKey("Files", key); } int fileIndex = 0; foreach (string file in files) { config.AddNewItem("Files", "File_" + FormatNumber(fileIndex++), file); } } else { config["Files", "File_0000"] = "pb_easy.ini"; config["Files", "File_0001"] = "pb_hard.ini"; files.Add("pb_easy.ini"); files.Add("pb_hard.ini"); } colors.Save(); config.Save(); FileReader pbEasy = new FileReader("pb_easy.ini", SortingStyle.Validate); if (!File.Exists("pb_easy.ini")) { pbEasy.AddNewItem("Best Run", "Corneria", "0"); pbEasy.AddNewItem("Best Run", "Meteo", "0"); pbEasy.AddNewItem("Best Run", "Katina", "0"); pbEasy.AddNewItem("Best Run", "Sector X", "0"); pbEasy.AddNewItem("Best Run", "Macbeth", "0"); pbEasy.AddNewItem("Best Run", "Area 6", "0"); pbEasy.AddNewItem("Best Run", "Venom 2", "0"); pbEasy.Save(); } if (!pbEasy.ContainsKey("game")) { pbEasy["name"] = "Easy Route"; pbEasy["game"] = "Star Fox 64"; //pbEasy["IL Syncing"] = "on"; } TrackerData.ValidateFile(pbEasy); FileReader pbHard = new FileReader("pb_hard.ini", SortingStyle.Validate); if (!File.Exists("pb_hard.ini")) { pbHard.AddNewItem("Best Run", "Corneria", "0"); pbHard.AddNewItem("Best Run", "Sector Y", "0"); pbHard.AddNewItem("Best Run", "Aquas", "0"); pbHard.AddNewItem("Best Run", "Zoness", "0"); pbHard.AddNewItem("Best Run", "Macbeth", "0"); pbHard.AddNewItem("Best Run", "Area 6", "0"); pbHard.AddNewItem("Best Run", "Venom 2", "0"); pbHard.Save(); } if (!pbHard.ContainsKey("game")) { pbHard["name"] = "Hard Route"; pbHard["game"] = "Star Fox 64"; //pbHard["IL Syncing"] = "on"; } TrackerData.ValidateFile(pbHard); individualLevels = new FileReader(':', "pb_individuals.txt", SortingStyle.Unsort); fileIndex = Int32.Parse(config["file_index"]); if (fileIndex >= files.Count || fileIndex < 0) { fileIndex = 0; config["file_index"] = "0"; config.Save(); } data = new TrackerData(new FileReader(files[FileIndex], SortingStyle.Validate)); tracker = new TrackerCore(data); } /* * catch (Exception e) * { * Console.WriteLine("Startup Error: " + e.Message); * } */ try { Application.Run(new InputWindow()); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } if (config.ContainsKey("debug") && config["debug"] == "1") { Console.Read(); } }
public override NetworkState.NETWORK_STATE_TYPE Deserialize() { NetworkState.NETWORK_STATE_TYPE state = NetworkState.NETWORK_STATE_TYPE.SUCCESS; int count = BufferedNetworkUtilsClient.ReadInt(ref state); for (int i = 0; i < count; ++i) { string name = BufferedNetworkUtilsClient.ReadString(ref state); FduClusterInputType type = (FduClusterInputType)BufferedNetworkUtilsClient.ReadByte(ref state); switch (type) { case FduClusterInputType.Axis: float fvalue = BufferedNetworkUtilsClient.ReadFloat(ref state); if (!_axisMap.ContainsKey(name)) { AxisData _data = new AxisData(); _data.reset(); _data.setValue(fvalue); _axisMap.Add(name, _data); } else { _axisMap[name].setValue(fvalue); } break; case FduClusterInputType.Button: bool bvalue = BufferedNetworkUtilsClient.ReadBool(ref state); if (!_buttonMap.ContainsKey(name)) { ButtonData _data = new ButtonData(); _data.reset(); _data.setValue(bvalue); _buttonMap.Add(name, _data); } else { _buttonMap[name].setValue(bvalue); } break; case FduClusterInputType.Tracker: Vector3 v3Value = BufferedNetworkUtilsClient.ReadVector3(ref state); Quaternion quValue = BufferedNetworkUtilsClient.ReadQuaternion(ref state); if (!_trackerMap.ContainsKey(name)) { TrackerData _data = new TrackerData(); _data.reset(); _data.setPosValue(v3Value); _data.setRotValue(quValue); _trackerMap.Add(name, _data); } else { _trackerMap[name].setPosValue(v3Value); _trackerMap[name].setRotValue(quValue); } break; } } //if(!BufferedNetworkUtilsClient.ReadString(ref state).Equals("ClusterInputMgrEndFlag")) //{ // Debug.LogError("Wrong end!"); //} //StartCoroutine(swapValueCo()); return(state); }
private static void InitializeGeoData(DemoContent demoContent, TrackerData trackerData) { trackerData.GeoData = demoContent.GeoData; }
private static string ProcessSave(string fileId, TrackerData fileData) { Guid userId; var comments = new List <string>(); if (fileData.Status == TrackerStatus.Corrupted) { comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted); } if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } File file; var app = ThirdPartySelector.GetAppByFileId(fileId); if (app == null) { using (var fileDao = Global.DaoFactory.GetFileDao()) { file = fileDao.GetFile(fileId); } var docKey = DocumentServiceHelper.GetDocKey(file); if (!fileData.Key.Equals(docKey)) { Global.Logger.ErrorFormat("DocService saving file {0} ({1}) with key {2}", fileId, docKey, fileData.Key); StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); return("0"); } } try { SecurityContext.AuthenticateMe(userId); } catch (Exception ex) { Global.Logger.Info("DocService save error: anonymous author - " + userId, ex); if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous); } } file = null; var saved = false; if (string.IsNullOrEmpty(fileData.Url)) { try { comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost); file = EntryManager.CompleteVersionFile(fileId, 0, false, false); using (var fileDao = Global.DaoFactory.GetFileDao()) { fileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments)); } file = null; Global.Logger.ErrorFormat("DocService save error. Empty url. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key); } catch (Exception ex) { Global.Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex); } } else { if (fileData.Encrypted) { comments.Add(FilesCommonResource.CommentEditEncrypt); } try { file = EntryManager.SaveEditing(fileId, null, DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url), null, string.Empty, string.Join("; ", comments), false, fileData.Encrypted); saved = fileData.Status == TrackerStatus.MustSave; } catch (Exception ex) { Global.Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex); StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); } } FileTracker.Remove(fileId); if (file != null) { var user = CoreContext.UserManager.GetUsers(userId); if (user != null) { FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false), file.Title); } SaveHistory(file, (fileData.History ?? "").ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.ChangesUrl)); } Global.SocketManager.FilesChangeEditors(fileId, true); return(string.Format("{{\"error\":{0}{1}}}", saved ? "0" //error:0 - saved : "1", //error:1 - some error saved && file != null && file.Encrypted ? string.Format(",\"addresses\":[{0}]", string.Join(",", BlockchainAddress.GetAddress(file.ID.ToString()))) : string.Empty )); }
/// <summary> /// Start an XDB request. /// </summary> /// <param name="root"></param> /// <param name="xtype"></param> /// <param name="owner"></param> /// <param name="ns"></param> /// <param name="action"></param> /// <param name="cb"></param> /// <param name="cbArg"></param> public void BeginXdb(XmlElement root, XdbType xtype, string owner, string ns, XdbAction action, XdbCB cb, object cbArg) { Debug.Assert(owner != null); Debug.Assert(ns != null); Xdb xdb = new Xdb(m_comp.Document); xdb.NS = ns; xdb.Type = xtype; xdb.To = owner; xdb.From = m_comp.ComponentID; if (action != XdbAction.NONE) xdb.Action = action; if (root != null) xdb.AddChild(root); // if no callback, ignore response. if (cb != null) { TrackerData td = new TrackerData(); td.cb = cb; td.data = cbArg; lock (m_pending) { m_pending[xdb.ID] = td; } } m_comp.Write(xdb); }
// Update is called once per frame void Update() { // update the trackers only once per frame if (lastTrackerUpdateFrame != Time.frameCount) { updateTrackers(); lastTrackerUpdateFrame = Time.frameCount; } trackerData = (TrackerData)Marshal.PtrToStructure(trackerDataPointer, typeof(TrackerData)); if (reportType == ReportType.AVERAGE && trackerData.numReports > 0) { getAverageReport(); } else { getMostRecentReport(); } // if a custom origin has been specified // then update the transform coordinate space if (origin != null) { if (trackingMode != TrackingMode.POSITION_ONLY) { transform.rotation = origin.rotation * transform.rotation; } else { transform.rotation = origin.rotation; } if (trackingMode != TrackingMode.ORIENTATION_ONLY) { transform.position = origin.position + origin.rotation * transform.position; } else { transform.position = origin.position; } } // // Do something similar if you have a parent // Warning: It overrides previous assignments! /* * if (transform.parent != null) * { * if (trackingMode != TrackingMode.POSITION_ONLY) * transform.rotation = transform.parent.rotation * transform.rotation; * else * transform.rotation = transform.parent.rotation; * * if (trackingMode != TrackingMode.ORIENTATION_ONLY) * transform.position = transform.parent.position + transform.parent.rotation * transform.position; * else * transform.position = transform.parent.position; * } */ }
private static string ProcessMailMerge(string fileId, TrackerData fileData) { Guid userId; if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } var sended = false; try { SecurityContext.AuthenticateMe(userId); if (string.IsNullOrEmpty(fileData.Url)) { throw new ArgumentException("emptry url"); } if (fileData.MailMerge == null) { throw new ArgumentException("MailMerge is null"); } var message = fileData.MailMerge.Message; Stream attach = null; switch (fileData.MailMerge.Type) { case MailMergeType.AttachDocx: case MailMergeType.AttachPdf: var downloadRequest = (HttpWebRequest)WebRequest.Create(fileData.Url); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var downloadStream = new ResponseStream(downloadRequest.GetResponse())) { const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; attach = new MemoryStream(); while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { attach.Write(buffer, 0, readed); } attach.Position = 0; } if (string.IsNullOrEmpty(fileData.MailMerge.Title)) { fileData.MailMerge.Title = "Attach"; } var attachExt = fileData.MailMerge.Type == MailMergeType.AttachDocx ? ".docx" : ".pdf"; var curExt = FileUtility.GetFileExtension(fileData.MailMerge.Title); if (curExt != attachExt) { fileData.MailMerge.Title += attachExt; } break; case MailMergeType.Html: var httpWebRequest = (HttpWebRequest)WebRequest.Create(fileData.Url); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) using (var stream = httpWebResponse.GetResponseStream()) if (stream != null) { using (var reader = new StreamReader(stream, Encoding.GetEncoding(Encoding.UTF8.WebName))) { message = reader.ReadToEnd(); } } break; } using (var mailMergeTask = new MailMergeTask { From = fileData.MailMerge.From, Subject = fileData.MailMerge.Subject, To = fileData.MailMerge.To, Message = message, AttachTitle = fileData.MailMerge.Title, Attach = attach }) { var response = mailMergeTask.Run(); Global.Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}", fileData.MailMerge.RecordIndex, fileData.MailMerge.RecordCount, response); } sended = true; } catch (Exception ex) { Global.Logger.Error( string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}", (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount), userId, fileData.Url), ex); } if (fileData.MailMerge != null && fileData.MailMerge.RecordIndex == fileData.MailMerge.RecordCount - 1) { var errorCount = fileData.MailMerge.RecordErrorCount; if (!sended) { errorCount++; } NotifyClient.SendMailMergeEnd(userId, fileData.MailMerge.RecordCount, errorCount); } return(sended ? "0" //error:0 - sended : "1"); //error:1 - some error }
public abstract void Save(TrackerData data);
private TrackResponse ProcessSave <T>(T fileId, TrackerData fileData) { var comments = new List <string>(); if (fileData.Status == TrackerStatus.Corrupted || fileData.Status == TrackerStatus.CorruptedForceSave) { comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted); } var forcesave = fileData.Status == TrackerStatus.ForceSave || fileData.Status == TrackerStatus.CorruptedForceSave; if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out var userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } var app = ThirdPartySelector.GetAppByFileId(fileId.ToString()); if (app == null) { File <T> fileStable; fileStable = DaoFactory.GetFileDao <T>().GetFileStable(fileId); var docKey = DocumentServiceHelper.GetDocKey(fileStable); if (!fileData.Key.Equals(docKey)) { Logger.ErrorFormat("DocService saving file {0} ({1}) with key {2}", fileId, docKey, fileData.Key); StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); return(new TrackResponse { Message = "Expected key " + docKey }); } } UserInfo user = null; try { SecurityContext.AuthenticateMe(userId); user = UserManager.GetUsers(userId); var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } catch (Exception ex) { Logger.Info("DocService save error: anonymous author - " + userId, ex); if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous); } } File <T> file = null; var saveMessage = "Not saved"; if (string.IsNullOrEmpty(fileData.Url)) { try { comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost); file = EntryManager.CompleteVersionFile(fileId, 0, false, false); DaoFactory.GetFileDao <T>().UpdateComment(file.ID, file.Version, string.Join("; ", comments)); file = null; Logger.ErrorFormat("DocService save error. Empty url. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key); } catch (Exception ex) { Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex); } } else { if (fileData.Encrypted) { comments.Add(FilesCommonResource.CommentEditEncrypt); } var forcesaveType = ForcesaveType.None; if (forcesave) { switch (fileData.ForceSaveType) { case TrackerData.ForceSaveInitiator.Command: forcesaveType = ForcesaveType.Command; break; case TrackerData.ForceSaveInitiator.Timer: forcesaveType = ForcesaveType.Timer; break; case TrackerData.ForceSaveInitiator.User: forcesaveType = ForcesaveType.User; break; } comments.Add(fileData.ForceSaveType == TrackerData.ForceSaveInitiator.User ? FilesCommonResource.CommentForcesave : FilesCommonResource.CommentAutosave); } try { file = EntryManager.SaveEditing(fileId, null, DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url), null, string.Empty, string.Join("; ", comments), false, fileData.Encrypted, forcesaveType); saveMessage = fileData.Status == TrackerStatus.MustSave || fileData.Status == TrackerStatus.ForceSave ? null : "Status " + fileData.Status; } catch (Exception ex) { Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex); saveMessage = ex.Message; StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); } } if (!forcesave) { FileTracker.Remove(fileId); } if (file != null) { if (user != null) { FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false, DisplayUserSettingsHelper), file.Title); } if (!forcesave) { SaveHistory(file, (fileData.History ?? "").ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.ChangesUrl)); } } SocketManager.FilesChangeEditors(fileId, !forcesave); var result = new TrackResponse { Message = saveMessage }; return(result); }
private bool DecodePayload(AlternativeCompositeByteBuf buffer) { Logger.Debug("About to pass message {0} to {1}. Buffer to read: {2}.", Message, Message.SenderSocket, buffer.ReadableBytes); if (!Message.HasContent()) { return true; } int size; IPublicKey receivedPublicKey; while (_contentTypes.Count > 0) { Message.Content content = _contentTypes.Peek(); Logger.Debug("Go for content: {0}.", content); switch (content) { case Message.Content.Integer: if (buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return false; } Message.SetIntValue(buffer.ReadInt()); LastContent = _contentTypes.Dequeue(); break; case Message.Content.Long: if (buffer.ReadableBytes < Utils.Utils.LongByteSize) { return false; } Message.SetLongValue(buffer.ReadLong()); LastContent = _contentTypes.Dequeue(); break; case Message.Content.Key: if (buffer.ReadableBytes < Number160.ByteArraySize) { return false; } var keyBytes = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(keyBytes); Message.SetKey(new Number160(keyBytes)); LastContent = _contentTypes.Dequeue(); break; case Message.Content.BloomFilter: if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return false; } size = buffer.GetUShort(buffer.ReaderIndex); if (buffer.ReadableBytes < size) { return false; } Message.SetBloomFilter(new SimpleBloomFilter<Number160>(buffer)); LastContent = _contentTypes.Dequeue(); break; case Message.Content.SetNeighbors: if (_neighborSize == -1 && buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return false; } if (_neighborSize == -1) { _neighborSize = buffer.ReadByte(); } if (_neighborSet == null) { _neighborSet = new NeighborSet(-1, new List<PeerAddress>(_neighborSize)); } for (int i = _neighborSet.Size; i < _neighborSize; i++) { if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return false; } int header = buffer.GetUShort(buffer.ReaderIndex); size = PeerAddress.CalculateSize(header); if (buffer.ReadableBytes < size) { return false; } var pa = new PeerAddress(buffer); _neighborSet.Add(pa); } Message.SetNeighborSet(_neighborSet); LastContent = _contentTypes.Dequeue(); _neighborSize = -1; // TODO why here? not in prepareFinish()? _neighborSet = null; break; case Message.Content.SetPeerSocket: if (_peerSocketAddressSize == -1 && buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return false; } if (_peerSocketAddressSize == -1) { _peerSocketAddressSize = buffer.ReadUByte(); } if (_peerSocketAddresses == null) { _peerSocketAddresses = new List<PeerSocketAddress>(_peerSocketAddressSize); } for (int i = _peerSocketAddresses.Count; i < _peerSocketAddressSize; i++) { if (buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return false; } int header = buffer.GetUByte(buffer.ReaderIndex); bool isIPv4 = header == 0; // TODO check if works size = PeerSocketAddress.Size(isIPv4); if (buffer.ReadableBytes < size + Utils.Utils.ByteByteSize) { return false; } // skip the ipv4/ipv6 header buffer.SkipBytes(1); _peerSocketAddresses.Add(PeerSocketAddress.Create(buffer, isIPv4)); } Message.SetPeerSocketAddresses(_peerSocketAddresses); LastContent = _contentTypes.Dequeue(); _peerSocketAddressSize = -1; // TODO why here? not in prepareFinish()? _peerSocketAddresses = null; break; case Message.Content.SetKey640: if (_keyCollectionSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return false; } if (_keyCollectionSize == -1) { _keyCollectionSize = buffer.ReadInt(); } if (_keyCollection == null) { _keyCollection = new KeyCollection(new List<Number640>(_keyCollectionSize)); } for (int i = _keyCollection.Size; i < _keyCollectionSize; i++) { if (buffer.ReadableBytes < 4 * Number160.ByteArraySize) { return false; } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); _keyCollection.Add(new Number640(locationKey, domainKey, contentKey, versionKey)); } Message.SetKeyCollection(_keyCollection); LastContent = _contentTypes.Dequeue(); _keyCollectionSize = -1; // TODO why here? not in prepareFinish()? _keyCollection = null; break; case Message.Content.MapKey640Data: if (_mapSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return false; } if (_mapSize == -1) { _mapSize = buffer.ReadInt(); } if (_dataMap == null) { _dataMap = new DataMap(new Dictionary<Number640, Data>(2 * _mapSize)); } if (_data != null) { if (!_data.DecodeBuffer(buffer)) { return false; } if (!_data.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return false; } _data = null; // TODO why here? not in prepareFinish()? _key = null; } for (int i = _dataMap.Size; i < _mapSize; i++) { if (_key == null) { if (buffer.ReadableBytes < 4 * Number160.ByteArraySize) { return false; } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); _key = new Number640(locationKey, domainKey, contentKey, versionKey); } _data = Data.DeocdeHeader(buffer, _signatureFactory); if (_data == null) { return false; } _dataMap.BackingDataMap.Add(_key, _data); if (!_data.DecodeBuffer(buffer)) { return false; } if (!_data.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return false; } // if we have signed the message, set the public key anyway, but only if we indicated so if (Message.IsSign && Message.PublicKey(0) != null && _data.HasPublicKey && (_data.PublicKey == null || _data.PublicKey == PeerBuilder.EmptyPublicKey)) // TODO check empty key condition { _data.SetPublicKey(Message.PublicKey(0)); } _data = null; // TODO why here? not in prepareFinish()? _key = null; } Message.SetDataMap(_dataMap); LastContent = _contentTypes.Dequeue(); _mapSize = -1; // TODO why here? not in prepareFinish()? _dataMap = null; break; case Message.Content.MapKey640Keys: if (_keyMap640KeysSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return false; } if (_keyMap640KeysSize == -1) { _keyMap640KeysSize = buffer.ReadInt(); } if (_keyMap640Keys == null) { _keyMap640Keys = new KeyMap640Keys(new SortedDictionary<Number640, ICollection<Number160>>()); // TODO check TreeMap equivalent } const int meta = 4 * Number160.ByteArraySize; for (int i = _keyMap640Keys.Size; i < _keyMap640KeysSize; i++) { if (buffer.ReadableBytes < meta + Utils.Utils.ByteByteSize) { return false; } size = buffer.GetUByte(buffer.ReaderIndex + meta); if (buffer.ReadableBytes < meta + Utils.Utils.ByteByteSize + (size * Number160.ByteArraySize)) { return false; } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); int numBasedOn = buffer.ReadByte(); var value = new HashSet<Number160>(); for (int j = 0; j < numBasedOn; j++) { buffer.ReadBytes(me); var basedOnKey = new Number160(me); value.Add(basedOnKey); } _keyMap640Keys.Put(new Number640(locationKey, domainKey, contentKey, versionKey), value); } Message.SetKeyMap640Keys(_keyMap640Keys); LastContent = _contentTypes.Dequeue(); _keyMap640KeysSize = -1; // TODO why here? not in prepareFinish()? _keyMap640Keys = null; break; case Message.Content.MapKey640Byte: if (_keyMapByteSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return false; } if (_keyMapByteSize == -1) { _keyMapByteSize = buffer.ReadInt(); } if (_keyMapByte == null) { _keyMapByte = new KeyMapByte(new Dictionary<Number640, sbyte>(2 * _keyMapByteSize)); } for (int i = _keyMapByte.Size; i < _keyMapByteSize; i++) { if (buffer.ReadableBytes < 4 * Number160.ByteArraySize + 1) { return false; } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); sbyte value = buffer.ReadByte(); _keyMapByte.Put(new Number640(locationKey, domainKey, contentKey, versionKey), value); } Message.SetKeyMapByte(_keyMapByte); LastContent = _contentTypes.Dequeue(); _keyMapByteSize = -1; // TODO why here? not in prepareFinish()? _keyMapByte = null; break; case Message.Content.ByteBuffer: if (_bufferSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return false; } if (_bufferSize == -1) { _bufferSize = buffer.ReadInt(); } if (_buffer == null) { _buffer = new DataBuffer(); } int already = _buffer.AlreadyTransferred; int remaining = _bufferSize - already; // already finished if (remaining != 0) { int read = _buffer.TransferFrom(buffer, remaining); if (read != remaining) { Logger.Debug( "Still looking for data. Indicating that its not finished yet. Already Transferred = {0}, Size = {1}.", _buffer.AlreadyTransferred, _bufferSize); return false; } } ByteBuf buf2 = AlternativeCompositeByteBuf.CompBuffer(_buffer.ToByteBufs()); Message.SetBuffer(new Buffer(buf2, _bufferSize)); LastContent = _contentTypes.Dequeue(); _bufferSize = -1; _buffer = null; break; case Message.Content.SetTrackerData: if (_trackerDataSize == -1 && buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return false; } if (_trackerDataSize == -1) { _trackerDataSize = buffer.ReadUByte(); } if (_trackerData == null) { _trackerData = new TrackerData(new Dictionary<PeerAddress, Data>(2 * _trackerDataSize)); } if (_currentTrackerData != null) { if (!_currentTrackerData.DecodeBuffer(buffer)) { return false; } if (!_currentTrackerData.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return false; } _currentTrackerData = null; } for (int i = _trackerData.Size; i < _trackerDataSize; i++) { if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return false; } int header = buffer.GetUShort(buffer.ReaderIndex); size = PeerAddress.CalculateSize(header); if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return false; } var pa = new PeerAddress(buffer); _currentTrackerData = Data.DeocdeHeader(buffer, _signatureFactory); if (_currentTrackerData == null) { return false; } _trackerData.PeerAddresses.Add(pa, _currentTrackerData); if (Message.IsSign) { _currentTrackerData.SetPublicKey(Message.PublicKey(0)); } if (!_currentTrackerData.DecodeBuffer(buffer)) { return false; } if (!_currentTrackerData.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return false; } _currentTrackerData = null; // TODO why here? } Message.SetTrackerData(_trackerData); LastContent = _contentTypes.Dequeue(); _trackerDataSize = -1; _trackerData = null; break; case Message.Content.PublicKey: // fall-through case Message.Content.PublicKeySignature: receivedPublicKey = _signatureFactory.DecodePublicKey(buffer); if (content == Message.Content.PublicKeySignature) { if (receivedPublicKey == PeerBuilder.EmptyPublicKey) // TODO check if works { // TODO throw InvalidKeyException throw new SystemException("The public key cannot be empty."); } } if (receivedPublicKey == null) { return false; } Message.SetPublicKey(receivedPublicKey); LastContent = _contentTypes.Dequeue(); break; default: break; } } if (Message.IsSign) { var signatureEncode = _signatureFactory.SignatureCodec; size = signatureEncode.SignatureSize; if (buffer.ReadableBytes < size) { return false; } signatureEncode.Read(buffer); Message.SetReceivedSignature(signatureEncode); } return true; }
private void ParseFedExRawDataIntoList(TrackerData Entry, TrackReply NewData) { foreach (CompletedTrackDetail completedTrackDetail in NewData.CompletedTrackDetails) { foreach (TrackDetail trackDetail in completedTrackDetail.TrackDetails) { //Check for error, likely from invalid tracking number if (trackDetail.Notification.Severity == NotificationSeverityType.ERROR) { Entry.Location = "INVALID TRACKING NUMBER"; Entry.Status = PackageStatus.NotFound; } else { //check for error-less state of no record found by web service if (trackDetail.StatusDetail != null) { //Input city state location as single string Entry.Location = trackDetail.StatusDetail.Location.City + ", " + trackDetail.StatusDetail.Location.StateOrProvinceCode; } else { Entry.Location = "NO CURRENT LOCATION FOUND"; } Entry.Service = ParcelService.FedEx; //check for error-less state of no record found by web service if (trackDetail.StatusDetail != null) { //a small sample of the package status codes, mapped to PackageStatus ENUM switch (trackDetail.StatusDetail.Code) { case "DL": Entry.Status = PackageStatus.Delivered; break; case "OD": Entry.Status = PackageStatus.OutForDelivery; break; case "ED": Entry.Status = PackageStatus.OutForDelivery; break; case "RS": Entry.Status = PackageStatus.Returned; break; case "IT": Entry.Status = PackageStatus.Shipped; break; case "PU": Entry.Status = PackageStatus.Shipped; break; case "DP": Entry.Status = PackageStatus.Shipped; break; case "AP": Entry.Status = PackageStatus.NotShipped; break; case "OF": Entry.Status = PackageStatus.NotShipped; break; default: Entry.Status = PackageStatus.Other; break; } } else { Entry.Status = PackageStatus.NotFound; } } } } }
public async void Persist(TrackerData trackerData) { }
private void ParseRawUPSDataIntoList(TrackerData Entry, TrackResponse trackResponse) { Entry.Location = (trackResponse.Shipment[0].Package[0].Activity[0].ActivityLocation.Address.City + ", " + trackResponse.Shipment[0].Package[0].Activity[0].ActivityLocation.Address.StateProvinceCode); Entry.Service = ParcelService.UPS; switch (trackResponse.Shipment[0].Package[0].Activity[0].Status.Code) { case "I": Entry.Status = PackageStatus.Shipped; break; case "D": Entry.Status = PackageStatus.Delivered; break; case "X": Entry.Status = PackageStatus.Other; break; case "P": Entry.Status = PackageStatus.PickUp; break; default: Entry.Status = PackageStatus.Other; break; } }
public TrackerCore(TrackerData data) { scores = data; }
private void ParseUSPSRawDataIntoList(TrackerData Entry, TrackingInfo Reply) { //Only need the information in Reply.Summary if (Reply.Summary.Contains("delivered")) { Entry.Status = PackageStatus.Delivered; Entry.Location = ExtractAddressFromString(Reply.Summary); Entry.Service = ParcelService.USPS; } else if (Reply.Summary.Contains("departed")) { Entry.Status = PackageStatus.Shipped; Entry.Location = ExtractAddressFromString(Reply.Summary); Entry.Service = ParcelService.USPS; } else if (Reply.Summary.Contains("picked up")) { Entry.Status = PackageStatus.Shipped; Entry.Location = ExtractAddressFromString(Reply.Summary); Entry.Service = ParcelService.USPS; } else if (Reply.Summary.Contains("arrived")) { Entry.Status = PackageStatus.Shipped; Entry.Location = ExtractAddressFromString(Reply.Summary); Entry.Service = ParcelService.USPS; } else if (Reply.Summary.Contains("error")) { Entry.Status = PackageStatus.NotFound; Entry.Location = "Not Found"; } else { Entry.Status = PackageStatus.Other; Entry.Location = "Error"; } }
/****************************************************************************************************/ public LiveNetworking() { trackerData = new TrackerData(); prevTrackerData = null; reconnect = false; }
/// <summary> /// Send an IQ Request and store the object with callback in the Hashtable /// </summary> /// <param name="iq">The iq to send</param> /// <param name="cb">the callback function which gets raised for the response</param> /// <param name="cbArg">additional object for arguments</param> public void SendIq(IQ iq, IqCB cb, object cbArg,bool isTo) { // check if the callback is null, in case of wrong usage of this class //if (cb != null) //{ // TrackerData td = new TrackerData(); // td.cb = cb; // td.data = cbArg; // m_grabbing[iq.Id] = td; //} //m_connection.Send(iq); // check if the callback is null, in case of wrong usage of this class if (cb != null) { TrackerData td = new TrackerData(); td.cb = cb; td.data = cbArg; m_grabbing[iq.Id] = td; //iq��CSS.IM.XMPP�з���Iq�ڵ�ʱ����iq.RemoveAttribute("to") //iq.RemoveAttribute("to"); } m_connection.Send(iq); }
/// <summary> /// Starts an IQ request. /// </summary> /// <param name="iq">IQ to send.</param> /// <param name="cb">Callback to use when a response comes back.</param> /// <param name="cbArg">Arguments to the callback.</param> public void BeginIQ(IQ iq, IqCB cb, object cbArg) { // if no callback, ignore response. if (cb != null) { TrackerData td = new TrackerData(cb, cbArg, iq.To, iq.ID); lock (m_pending) m_pending[iq.ID] = td; } m_cli.Write(iq); }
public Message SetTrackerData(TrackerData trackerData) { if (!_presetContentTypes) { SetContentType(Content.SetTrackerData); } if (_trackerDataList == null) { _trackerDataList = new List<TrackerData>(1); } _trackerDataList.Add(trackerData); return this; }
// Update is called once per frame void Update() { if (threadingMode == ThreadingMode.SINGLE_THREADED) { // update the trackers only once per frame if (lastTrackerUpdateFrame != Time.frameCount) { UpdateTrackers(); lastTrackerUpdateFrame = Time.frameCount; } trackerData = (TrackerData)Marshal.PtrToStructure(trackerDataPointer, typeof(TrackerData)); } else { // update the trackers only once per frame if (lastTrackerUpdateFrame != Time.frameCount) { UpdateTrackersMultiThreaded(); lastTrackerUpdateFrame = Time.frameCount; } LockTrackerData(trackerDataPointer); trackerData = (TrackerData)Marshal.PtrToStructure(trackerDataPointer, typeof(TrackerData)); UnlockTrackerData(trackerDataPointer); } Vector3 transformPosition = transform.position; Quaternion transformRotation = transform.rotation; this.updateTransformFromTrackerData(ref transformPosition, ref transformRotation); // if a custom origin has been specified // then update the transform coordinate space if (origin != null) { if (trackingMode != TrackingMode.POSITION_ONLY) { transformRotation = origin.rotation * transformRotation; } else { transformRotation = origin.rotation; } if (trackingMode != TrackingMode.ORIENTATION_ONLY) { transformPosition = origin.position + origin.rotation * transformPosition; } else { transformPosition = origin.position; } } Matrix4x4 m3 = Matrix4x4.TRS(transformPosition, transformRotation, Vector3.one); float[] d3 = VRConvert.ToFloatArray(m3); VREvent e = new VREvent(eventName); e.AddData("EventType", "TrackerMove"); e.AddData("Transform", d3); pendingEvents.Add(e); if (applyUpdatesToGameObject) { transform.position = transformPosition; transform.rotation = transformRotation; } }