/* GET request * */ public AsyncHTTPClient(string _toUrl) { m_ToUrl = _toUrl; m_FromData = null; m_Method = ""; state = State.INIT; header = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); m_Handle = (IntPtr)0; tag = ""; statusCallback = null; }
void StartClient() { networkClient = new NetworkingSockets(); Address address = new Address(); address.SetAddress("::1", 7777); connection = networkClient.Connect(address); status = OnClientStatusUpdate; }
void StartServer() { isServer = true; networkClient = new NetworkingSockets(); Address address = new Address(); address.SetAddress("::0", 7777); listenSocket = networkClient.CreateListenSocket(address); status = OnServerStatusUpdate; }
public static void DownloadLeaderboardScores(StatusCallback callback, string pchLeaderboardName, ArcadeLeaderboard.LeaderboardTimeRange eLeaderboardDataTimeRange, int nCount) { if (callback == null) { throw new InvalidOperationException("callback == null"); } Viveport.Internal.StatusCallback downloadLeaderboardScoresCB = new Viveport.Internal.StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(downloadLeaderboardScoresCB); eLeaderboardDataTimeRange = ArcadeLeaderboard.LeaderboardTimeRange.AllTime; Viveport.Internal.ArcadeLeaderboard.DownloadLeaderboardScores(downloadLeaderboardScoresCB, pchLeaderboardName, (ELeaderboardDataTimeRange)eLeaderboardDataTimeRange, nCount); }
public AsyncHTTPClient(string _toUrl, string _method) { this.m_ToUrl = _toUrl; this.m_FromData = null; this.m_Method = _method; this.state = State.INIT; this.header = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); this.m_Handle = IntPtr.Zero; this.tag = string.Empty; this.statusCallback = null; }
public AsyncHTTPClient(string _toUrl, string _method) { this.m_ToUrl = _toUrl; this.m_FromData = null; this.m_Method = _method; this.state = State.INIT; this.header = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); this.m_Handle = IntPtr.Zero; this.tag = string.Empty; this.statusCallback = null; }
public void SetAutoSync(bool linked) { if (this.button1.InvokeRequired) { StatusCallback d = new StatusCallback(SetAutoSync); this.Invoke(d, new object[] { linked }); } else { if (linked) { this.button1.ForeColor = Color.Blue; } else { this.button1.ForeColor = Color.Black; } } }
public void GetStatus(StatusCallback cb) { var request = WebRequest.Create(url + "/status" + "?auth=" + authtoken) as HttpWebRequest; if (request != null) { request.Method = "GET"; request.ContentType = "application/json"; } try { var httpResponse = (HttpWebResponse)request.GetResponse(); if (httpResponse.StatusCode == HttpStatusCode.OK) { using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var responseText = streamReader.ReadToEnd(); ZeroTierStatus status = null; try { status = JsonConvert.DeserializeObject <ZeroTierStatus>(responseText); } catch (JsonReaderException e) { Console.WriteLine(e.ToString()); } cb(status); } } else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { APIHandler.initHandler(true); } } catch (System.Net.Sockets.SocketException) { cb(null); } catch (System.Net.WebException e) { if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized) { APIHandler.initHandler(true); } else { cb(null); } } }
private void SetStatus(string text, Color color) { if (this.lblStatus.InvokeRequired) { StatusCallback d = new StatusCallback(SetStatus); this.Invoke(d, new object[] { text, color }); } else { this.lblStatus.Text = text; this.lblStatus.ForeColor = Color.Green; } }
/// <summary> /// Generate the necessary parameters /// </summary> public List <KeyValuePair <string, string> > GetParams() { var p = new List <KeyValuePair <string, string> >(); if (To != null) { p.Add(new KeyValuePair <string, string>("To", To.ToString())); } if (From != null) { p.Add(new KeyValuePair <string, string>("From", From.ToString())); } if (MessagingServiceSid != null) { p.Add(new KeyValuePair <string, string>("MessagingServiceSid", MessagingServiceSid.ToString())); } if (Body != null) { p.Add(new KeyValuePair <string, string>("Body", Body)); } if (MediaUrl != null) { p.AddRange(MediaUrl.Select(prop => new KeyValuePair <string, string>("MediaUrl", prop.ToString()))); } if (StatusCallback != null) { p.Add(new KeyValuePair <string, string>("StatusCallback", StatusCallback.ToString())); } if (ApplicationSid != null) { p.Add(new KeyValuePair <string, string>("ApplicationSid", ApplicationSid.ToString())); } if (MaxPrice != null) { p.Add(new KeyValuePair <string, string>("MaxPrice", MaxPrice.Value.ToString())); } if (ProvideFeedback != null) { p.Add(new KeyValuePair <string, string>("ProvideFeedback", ProvideFeedback.Value.ToString())); } return(p); }
public void SerialPortStatus(bool linked) { if (this.button2.InvokeRequired) { StatusCallback d = new StatusCallback(SerialPortStatus); this.Invoke(d, new object[] { linked }); } else { if (linked) { this.button2.Text = "æ–å¼€"; this.button2.ForeColor = Color.Blue; } else { this.button2.Text = "连接"; this.button2.ForeColor = Color.Black; } } }
// Token: 0x06000EBB RID: 3771 RVA: 0x0005DE58 File Offset: 0x0005C058 public static int UploadLeaderboardScore(StatusCallback callback, string pchLeaderboardName, int nScore) { if (callback == null) { throw new InvalidOperationException("callback == null"); } UserStats.uploadLeaderboardScoreIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(UserStats.UploadLeaderboardScoreIl2cppCallback)); if (IntPtr.Size == 8) { return(UserStats.UploadLeaderboardScore_64(new StatusCallback(UserStats.UploadLeaderboardScoreIl2cppCallback), pchLeaderboardName, nScore)); } return(UserStats.UploadLeaderboardScore(new StatusCallback(UserStats.UploadLeaderboardScoreIl2cppCallback), pchLeaderboardName, nScore)); }
// Token: 0x06000EAA RID: 3754 RVA: 0x0005DBB4 File Offset: 0x0005BDB4 public static int DownloadStats(StatusCallback callback) { if (callback == null) { throw new InvalidOperationException("callback == null"); } UserStats.downloadStatsIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(UserStats.DownloadStatsIl2cppCallback)); if (IntPtr.Size == 8) { return(UserStats.DownloadStats_64(new StatusCallback(UserStats.DownloadStatsIl2cppCallback))); } return(UserStats.DownloadStats(new StatusCallback(UserStats.DownloadStatsIl2cppCallback))); }
// Token: 0x06000EE8 RID: 3816 RVA: 0x0005E5C8 File Offset: 0x0005C7C8 public static int IsDlcReady(StatusCallback callback) { if (callback == null) { throw new InvalidOperationException("callback == null"); } DLC.isDlcReadyIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(DLC.IsDlcReadyIl2cppCallback)); if (IntPtr.Size == 8) { return(DLC.IsReady_64(new StatusCallback(DLC.IsDlcReadyIl2cppCallback))); } return(DLC.IsReady(new StatusCallback(DLC.IsDlcReadyIl2cppCallback))); }
// Token: 0x06000EB9 RID: 3769 RVA: 0x0005DDD0 File Offset: 0x0005BFD0 public static int DownloadLeaderboardScores(StatusCallback callback, string pchLeaderboardName, UserStats.LeaderBoardRequestType eLeaderboardDataRequest, UserStats.LeaderBoardTimeRange eLeaderboardDataTimeRange, int nRangeStart, int nRangeEnd) { if (callback == null) { throw new InvalidOperationException("callback == null"); } UserStats.downloadLeaderboardScoresIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(UserStats.DownloadLeaderboardScoresIl2cppCallback)); if (IntPtr.Size == 8) { return(UserStats.DownloadLeaderboardScores_64(new StatusCallback(UserStats.DownloadLeaderboardScoresIl2cppCallback), pchLeaderboardName, (ELeaderboardDataRequest)eLeaderboardDataRequest, (ELeaderboardDataTimeRange)eLeaderboardDataTimeRange, nRangeStart, nRangeEnd)); } return(UserStats.DownloadLeaderboardScores(new StatusCallback(UserStats.DownloadLeaderboardScoresIl2cppCallback), pchLeaderboardName, (ELeaderboardDataRequest)eLeaderboardDataRequest, (ELeaderboardDataTimeRange)eLeaderboardDataTimeRange, nRangeStart, nRangeEnd)); }
// Token: 0x06000E97 RID: 3735 RVA: 0x0005D4B4 File Offset: 0x0005B6B4 public static int Init(StatusCallback callback, string appId) { if (callback == null || string.IsNullOrEmpty(appId)) { throw new InvalidOperationException("callback == null || string.IsNullOrEmpty(appId)"); } Api.initIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(Api.InitIl2cppCallback)); if (IntPtr.Size == 8) { return(Api.Init_64(new StatusCallback(Api.InitIl2cppCallback), appId)); } return(Api.Init(new StatusCallback(Api.InitIl2cppCallback), appId)); }
public override void FetchStatus(StatusCallback onFinish, bool clearAssetBundles = true) { base.FetchStatus((bool success, string message, long fileSize) => { if (success) { StopAllCoroutines(); StartCoroutine(DownloadMeta(assetBundleNames, onFinish)); } else { onFinish(false, null, 0); } }, clearAssetBundles); }
// Token: 0x06000E99 RID: 3737 RVA: 0x0005D538 File Offset: 0x0005B738 public static int Shutdown(StatusCallback callback) { if (callback == null) { throw new InvalidOperationException("callback == null"); } Api.shutdownIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(Api.ShutdownIl2cppCallback)); if (IntPtr.Size == 8) { return(Api.Shutdown_64(new StatusCallback(Api.ShutdownIl2cppCallback))); } return(Api.Shutdown(new StatusCallback(Api.ShutdownIl2cppCallback))); }
private void ParseJsonResult(string json, out string result, StatusCallback logger) { try { var doc = JsonDocument.Parse(json); var builder = new StringBuilder(); if (doc.RootElement.ValueKind == JsonValueKind.Array) { // simple array of text for (var i = 0; i < doc.RootElement.GetArrayLength(); i++) { builder.Append(doc.RootElement[i].GetString()); } } else { // sentence array var sentences = doc.RootElement.GetProperty("sentences"); for (var i = 0; i < sentences.GetArrayLength(); i++) { // spaces between sentences are retained in the translations // so no need to insert them manually // also there may additional elements in the array beyond trans entries if (sentences[i].TryGetProperty("trans", out var trans)) { builder.Append(trans.GetString()); } } } // escape Unicode \u0000 escape sequences to store in XML [<>&'"] var text = builder.ToString(); result = Regex.Unescape(text).XmlEscape(); } catch (Exception exc) { if (logger != null) { logger(exc.Message, Color.Red); logger(json, Color.Brown); } result = string.Empty; } }
/// <summary> /// Get the status according to git of the specified directory. /// </summary> /// <param name="workingdir"></param> /// <param name="callback"></param> public void Status(string workingdir, StatusCallback callback) { runApp(workingdir, "git.exe", "status", delegate(int status, BinOutput output) { if (0 != status) { throw new Exception("Unknown error"); } // Can match modified files pretty easily List<FileInfo> modified = new List<FileInfo>(); Regex regex = new Regex(@"/modified:\s+(.*)$/", RegexOptions.IgnoreCase | RegexOptions.Multiline); MatchCollection results = regex.Matches(output.stdout); }); }
protected override void DoWork(InitializeProgressCallback initializeCallback, ProgressCallback progressCallback, StatusCallback primaryStatusTextCallback, StatusCallback secondaryStatusTextCallback) { while (_countForWork < 100) { if (Canceling) { wasCancelled = true; return; } DoPretendWork(); _countForWork++; } }
// Token: 0x06000EFE RID: 3838 RVA: 0x0005EB0C File Offset: 0x0005CD0C public static void IsReady(StatusCallback callback) { if (callback == null) { throw new InvalidOperationException("callback == null"); } Token.isReadyIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(Token.IsReadyIl2cppCallback)); if (IntPtr.Size == 8) { Token.IsReady_64(new StatusCallback(Token.IsReadyIl2cppCallback)); return; } Token.IsReady(new StatusCallback(Token.IsReadyIl2cppCallback)); }
private void SetStatus(string status, Color color) { if (Status != null) { if (Status.InvokeRequired) { StatusCallback method = SetStatus; Status.Invoke(method, status, color); } else { Status.ForeColor = color; Status.Text = status; } } }
private void SerialPortStatus(bool linked) { if (this.textBox2.InvokeRequired) { StatusCallback d = new StatusCallback(SerialPortStatus); this.Invoke(d, new object[] { linked }); } else { if (linked) { this.label4.Text = "已连接"; this.label4.ForeColor = Color.Blue; this.button2.Text = "æ–å¼€"; } else { this.label4.Text = "未连接"; this.label4.ForeColor = Color.Red; this.button2.Text = "连接"; } } }
/// <summary> /// Remove a callback from the LifeStatus list /// </summary> /// <param name="callback"></param> public void RemoveCallback(StatusCallback callback) { lock (theLock) { Queue <StatusCallback> tcallbacks = new Queue <StatusCallback>(); while (callbacks.Count > 0) { StatusCallback t = callbacks.Dequeue(); if (t != callback) { tcallbacks.Enqueue(t); } } callbacks = tcallbacks; } }
// Token: 0x06000EC4 RID: 3780 RVA: 0x0005E004 File Offset: 0x0005C204 public static void DownloadLeaderboardScores(StatusCallback callback, string pchLeaderboardName, ArcadeLeaderboard.LeaderboardTimeRange eLeaderboardDataTimeRange, int nCount) { if (callback == null) { throw new InvalidOperationException("callback == null"); } ArcadeLeaderboard.downloadLeaderboardScoresIl2cppCallback = new StatusCallback(callback.Invoke); Api.InternalStatusCallbacks.Add(new StatusCallback(ArcadeLeaderboard.DownloadLeaderboardScoresIl2cppCallback)); eLeaderboardDataTimeRange = ArcadeLeaderboard.LeaderboardTimeRange.AllTime; if (IntPtr.Size == 8) { ArcadeLeaderboard.DownloadLeaderboardScores_64(new StatusCallback(ArcadeLeaderboard.DownloadLeaderboardScoresIl2cppCallback), pchLeaderboardName, (ELeaderboardDataTimeRange)eLeaderboardDataTimeRange, nCount); return; } ArcadeLeaderboard.DownloadLeaderboardScores(new StatusCallback(ArcadeLeaderboard.DownloadLeaderboardScoresIl2cppCallback), pchLeaderboardName, (ELeaderboardDataTimeRange)eLeaderboardDataTimeRange, nCount); }
private void SetStatus(string status, Color color) { // ignore the call if we haven't init'd the window yet if (Status == null) { return; } if (Status.InvokeRequired) { StatusCallback cb = SetStatus; Status.Invoke(cb, status, color); return; } Status.ForeColor = color; Status.Text = status; }
private string FindHint(XElement data, StatusCallback logger) { var name = data.Attribute("name").Value; var hint = hints.Elements() .FirstOrDefault(e => e.Attribute("name").Value == name); if (hint != null) { if (data.Element("value").Value.Trim() == hint.Element("source").Value.Trim()) { return(hint.Element("preferred").Value.Trim()); } logger($" \u2192 hint override is obsolete", Color.Maroon); } return(null); }
void Start() { Library.Initialize(); ushort port = 8080; this.client = new NetworkingSockets(); Address address = new Address(); address.SetAddress("::1", port); this.connection = client.Connect(ref address); this.status = (info, context) => { switch (info.connectionInfo.state) { case ConnectionState.None: break; case ConnectionState.Connected: Debug.Log("Client connected to server - ID: " + connection); break; case ConnectionState.ClosedByPeer: client.CloseConnection(connection); Debug.Log("Client disconnected from server"); break; case ConnectionState.ProblemDetectedLocally: client.CloseConnection(connection); Debug.Log("Client unable to connect"); break; } }; DebugCallback debug = (type, message) => { Debug.Log("Debug - Type: " + type + ", Message: " + message); }; NetworkingUtils utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Everything, debug); }
public void SetAutoSync(bool linked) { if (this.button1.InvokeRequired) { StatusCallback d = new StatusCallback(SetAutoSync); this.Invoke(d, new object[] { linked }); } else { if (linked) { this.button1.ForeColor = Color.Blue; } else { this.button1.ForeColor = Color.Black; } } }
public void CreateAndVerifyStatusCallbackTest() { StatusCallback sc = StatusCallback.fromJson("{ \"accountId\": \"ACae05391ecca1352e9108d545482a1e6f384e7a49\", \"callDuration\": 41, \"callId\": \"CAbde0362aef3d228b3a39baafa9e4f0204e724966\", \"callStatus\": \"completed\", \"conferenceId\": null, \"direction\": \"inbound\", \"from\": \"+17083168669\", \"parentCallId\": null, \"queueId\": null, \"requestId\": \"RQa766ca5ee92fc6c528b72aff5e8b48f5f4e056e8\", \"requestType\": \"callStatus\", \"to\": \"+12248806211\" }"); Assert.AreEqual(sc.getAccountId, "ACae05391ecca1352e9108d545482a1e6f384e7a49"); Assert.AreEqual(sc.getCallDuration, 41); Assert.AreEqual(sc.getCallId, "CAbde0362aef3d228b3a39baafa9e4f0204e724966"); Assert.AreEqual(sc.getCallStatus, ECallStatus.Completed); Assert.IsNull(sc.getConferenceId); Assert.AreEqual(sc.getDirection, EDirection.Inbound); Assert.AreEqual(sc.getFrom, "+17083168669"); Assert.IsNull(sc.getParentCallId); Assert.IsNull(sc.getQueueId); Assert.AreEqual(sc.getRequestId, "RQa766ca5ee92fc6c528b72aff5e8b48f5f4e056e8"); Assert.AreEqual(sc.getRequestType, ERequestType.CallStatus); Assert.AreEqual(sc.getTo, "+12248806211"); Assert.IsNull(sc.getRecordingUrl); Assert.IsNull(sc.getRecordingUrl); Assert.AreEqual(sc.getRecordingDurationSec, 0); }
public int Init(Action <byte, DolphiimoteData> newData, Action <byte, bool> wiimoteConnectionChanged, Action <byte, DolphiimoteCapabilities> capabilitiesChanged, Action <byte, DolphiimoteStatus> statusChanged, Action <string> newLogMessage) { dataCallback = (wiimote, data, user) => newData(wiimote, MarshalType <DolphiimoteData>(data)); capabilitiesCallback = (wiimote, capabilities, user) => capabilitiesChanged(wiimote, MarshalType <DolphiimoteCapabilities>(capabilities)); connectionCallback = (wiimote, status) => wiimoteConnectionChanged(wiimote, Convert.ToBoolean(status)); statusCallback = (wiimote, status, user) => statusChanged(wiimote, MarshalType <DolphiimoteStatus>(status)); logCallback = (str, length) => newLogMessage(Marshal.PtrToStringAnsi(str, (int)length)); var callbacks = new DolphiimoteCallbacks { dataReceived = MarshalFunction(dataCallback), capabilitiesChanged = MarshalFunction(capabilitiesCallback), connectionChanged = MarshalFunction(connectionCallback), statusChanged = MarshalFunction(statusCallback), onLog = MarshalFunction(logCallback), userData = IntPtr.Zero }; return(dolphiimoteInit(callbacks)); }
void StartServer() { Debug.Log("Starting server..."); utils = new NetworkingUtils(); utils.SetDebugCallback(DebugType.Message, debug); status = OnServerStatusUpdate; utils.SetStatusCallback(status); server = new NetworkingSockets(); Address address = new Address(); address.SetAddress("::0", port); listenSocket = server.CreateListenSocket(ref address); //connectedPollGroup = server.CreatePollGroup(); }
/// <summary> /// Generate the necessary parameters /// </summary> public List <KeyValuePair <string, string> > GetParams() { var p = new List <KeyValuePair <string, string> >(); if (EnableTurn != null) { p.Add(new KeyValuePair <string, string>("EnableTurn", EnableTurn.Value.ToString())); } if (Type != null) { p.Add(new KeyValuePair <string, string>("Type", Type.ToString())); } if (UniqueName != null) { p.Add(new KeyValuePair <string, string>("UniqueName", UniqueName)); } if (StatusCallback != null) { p.Add(new KeyValuePair <string, string>("StatusCallback", StatusCallback.ToString())); } if (StatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString())); } if (MaxParticipants != null) { p.Add(new KeyValuePair <string, string>("MaxParticipants", MaxParticipants.Value.ToString())); } if (RecordParticipantsOnConnect != null) { p.Add(new KeyValuePair <string, string>("RecordParticipantsOnConnect", RecordParticipantsOnConnect.Value.ToString())); } return(p); }
/// <summary> /// Generate the necessary parameters /// </summary> public List <KeyValuePair <string, string> > GetParams() { var p = new List <KeyValuePair <string, string> >(); if (Url != null) { p.Add(new KeyValuePair <string, string>("Url", Url.ToString())); } if (Method != null) { p.Add(new KeyValuePair <string, string>("Method", Method.ToString())); } if (Status != null) { p.Add(new KeyValuePair <string, string>("Status", Status.ToString())); } if (FallbackUrl != null) { p.Add(new KeyValuePair <string, string>("FallbackUrl", FallbackUrl.ToString())); } if (FallbackMethod != null) { p.Add(new KeyValuePair <string, string>("FallbackMethod", FallbackMethod.ToString())); } if (StatusCallback != null) { p.Add(new KeyValuePair <string, string>("StatusCallback", StatusCallback.ToString())); } if (StatusCallbackMethod != null) { p.Add(new KeyValuePair <string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString())); } return(p); }
public static void PopulateDatabase(ResourceManager resourceManager, StatusCallback callback) { // Lock to prevent indexing twice, without blocking tile requests. lock (SearchEngine.s_lock) { // NOTE: This (re)initializes a static data structure used for // resolving names into sector locations, so needs to be run // before any other objects (e.g. Worlds) are loaded. SectorMap map = SectorMap.GetInstance(resourceManager); using (var connection = DBUtil.MakeConnection()) { SqlCommand sqlCommand; // // Repopulate the tables - locally first // FUTURE: will need to batch this up rather than keep it in memory! // DataTable dt_sectors = new DataTable(); for (int i = 0; i < 3; ++i) dt_sectors.Columns.Add(new DataColumn()); DataTable dt_subsectors = new DataTable(); for (int i = 0; i < 4; ++i) dt_subsectors.Columns.Add(new DataColumn()); DataTable dt_worlds = new DataTable(); for (int i = 0; i < 13; ++i) dt_worlds.Columns.Add(new DataColumn()); DataTable dt_labels = new DataTable(); for (int i = 0; i < 4; ++i) dt_labels.Columns.Add(new DataColumn()); Dictionary<string, List<Point>> labels = new Dictionary<string, List<Point>>(); Action<string, Point> AddLabel = (string text, Point coords) => { if (text == null) return; text = SanifyLabel(text); if (!labels.ContainsKey(text)) labels.Add(text, new List<Point>()); labels[text].Add(coords); }; callback("Parsing data..."); foreach (Sector sector in map.Sectors) { if (!sector.Tags.Contains("OTU") && !sector.Tags.Contains("Faraway")) continue; foreach (Name name in sector.Names) { DataRow row = dt_sectors.NewRow(); row.ItemArray = new object[] { sector.X, sector.Y, name.Text }; dt_sectors.Rows.Add(row); } if (!string.IsNullOrEmpty(sector.Abbreviation)) { DataRow row = dt_sectors.NewRow(); row.ItemArray = new object[] { sector.X, sector.Y, sector.Abbreviation }; dt_sectors.Rows.Add(row); } foreach (Subsector subsector in sector.Subsectors) { DataRow row = dt_subsectors.NewRow(); row.ItemArray = new object[] { sector.X, sector.Y, subsector.Index, subsector.Name }; dt_subsectors.Rows.Add(row); } foreach (Border border in sector.Borders.Where(b => b.ShowLabel)) { AddLabel(border.GetLabel(sector), Astrometrics.LocationToCoordinates(new Location(sector.Location, border.LabelPosition))); } foreach (Label label in sector.Labels) { AddLabel(label.Text, Astrometrics.LocationToCoordinates(new Location(sector.Location, label.Hex))); } #if DEBUG if (!sector.Selected) continue; #endif // NOTE: May need to page this at some point WorldCollection worlds = sector.GetWorlds(resourceManager, cacheResults: false); if (worlds == null) continue; var world_query = from world in worlds where !world.IsPlaceholder select world; foreach (World world in world_query) { DataRow row = dt_worlds.NewRow(); row.ItemArray = new object[] { world.Coordinates.X, world.Coordinates.Y, sector.X, sector.Y, world.X, world.Y, string.IsNullOrEmpty(world.Name) ? (object)DBNull.Value : (object)world.Name, world.UWP, world.Remarks, world.PBG, string.IsNullOrEmpty(world.Zone) ? "G" : world.Zone, world.Allegiance, sector.Names.Count > 0 ? (object)sector.Names[0] : (object)DBNull.Value }; dt_worlds.Rows.Add(row); } } foreach (KeyValuePair<string, List<Point>> entry in labels) { string name = entry.Key; List<Point> points = entry.Value; Point avg = new Point( (int)Math.Round(points.Select(p => p.X).Average()), (int)Math.Round(points.Select(p => p.Y).Average())); Point min = new Point(points.Select(p => p.X).Min(), points.Select(p => p.Y).Min()); Point max = new Point(points.Select(p => p.X).Max(), points.Select(p => p.Y).Max()); Size size = new Size(max.X - min.X, max.Y - min.Y); int radius = Math.Max(size.Width, size.Height); DataRow row = dt_labels.NewRow(); row.ItemArray = new object[] { avg.X, avg.Y, radius, entry.Key }; dt_labels.Rows.Add(row); } // // Rebuild the tables with fresh schema // const string INDEX_OPTIONS = " WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)"; const string DROP_TABLE_IF_EXISTS = "IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'{0}') AND type = (N'U')) DROP TABLE {0}"; string[] rebuild_schema = { string.Format(DROP_TABLE_IF_EXISTS, "sectors"), "CREATE TABLE sectors (x int NOT NULL, y int NOT NULL, name nvarchar(50) NULL)", "CREATE NONCLUSTERED INDEX sector_name ON sectors ( name ASC )" + INDEX_OPTIONS, string.Format(DROP_TABLE_IF_EXISTS, "subsectors"), "CREATE TABLE subsectors (sector_x int NOT NULL, sector_y int NOT NULL, subsector_index char(1) NOT NULL, name nvarchar(50) NULL)", "CREATE NONCLUSTERED INDEX subsector_name ON subsectors ( name ASC )" + INDEX_OPTIONS, string.Format(DROP_TABLE_IF_EXISTS, "worlds"), "CREATE TABLE worlds (" + "x int NOT NULL, " + "y int NOT NULL, " + "sector_x int NOT NULL, " + "sector_y int NOT NULL, " + "hex_x int NOT NULL, " + "hex_y int NOT NULL, " + "name nvarchar(50) NULL, " + "uwp nchar(9) NULL, " + "remarks nvarchar(50) NULL, " + "pbg nchar(3) NULL, " + "zone nchar(1) NULL, " + "alleg nchar(4) NULL, " + "sector_name nvarchar(50) NULL)", "CREATE NONCLUSTERED INDEX world_name ON worlds ( name ASC )" + INDEX_OPTIONS, "CREATE NONCLUSTERED INDEX world_uwp ON worlds ( uwp ASC )" + INDEX_OPTIONS, "CREATE NONCLUSTERED INDEX world_pbg ON worlds ( pbg ASC )" + INDEX_OPTIONS, "CREATE NONCLUSTERED INDEX world_alleg ON worlds ( alleg ASC )" + INDEX_OPTIONS, "CREATE NONCLUSTERED INDEX world_sector_name ON worlds ( sector_name ASC )" + INDEX_OPTIONS, string.Format(DROP_TABLE_IF_EXISTS, "labels"), "CREATE TABLE labels (x int NOT NULL, y int NOT NULL, radius int NOT NULL, name nvarchar(50) NULL)", "CREATE NONCLUSTERED INDEX name ON labels ( name ASC )" + INDEX_OPTIONS, }; callback("Rebuilding schema..."); foreach (string cmd in rebuild_schema) { sqlCommand = new SqlCommand(cmd, connection); sqlCommand.ExecuteNonQuery(); } // // And shovel the data into the database en masse // Action<string, DataTable, int> BulkInsert = (string name, DataTable table, int batchSize) => { using (var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null)) { callback(string.Format("Writing {0} {1}...", table.Rows.Count, name)); bulk.BatchSize = batchSize; bulk.DestinationTableName = name; bulk.WriteToServer(table); } }; BulkInsert("sectors", dt_sectors, dt_sectors.Rows.Count); BulkInsert("subsectors", dt_subsectors, dt_subsectors.Rows.Count); BulkInsert("worlds", dt_worlds, 4096); BulkInsert("labels", dt_labels, dt_labels.Rows.Count); } callback("Complete!"); } }
protected abstract void DoWork( InitializeProgressCallback initializeCallback, ProgressCallback progressCallback, StatusCallback primaryStatusTextCallback, StatusCallback secondaryStatusTextCallback );
protected override void DoWork(InitializeProgressCallback initializeCallback, ProgressCallback progressCallback, StatusCallback primaryStatusTextCallback, StatusCallback secondaryStatusTextCallback) { while (_countForWork < 100) { if(Canceling ) { wasCancelled = true; return; } DoPretendWork(); _countForWork++; } }
public static void PopulateDatabase(ResourceManager resourceManager, StatusCallback callback) { // Lock on this class rather than the cacheResults. Tile requests are not // blocked but we don't index twice. lock (typeof(SearchEngine)) { // NOTE: This (re)initializes a static data structure used for // resolving names into sector locations, so needs to be run // before any other objects (e.g. Worlds) are loaded. SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager); using (var connection = DBUtil.MakeConnection()) { SqlCommand sqlCommand; // // Repopulate the tables - locally first // FUTURE: will need to batch this up rather than keep it in memory! // DataTable dt_sectors = new DataTable(); for (int i = 0; i < 3; ++i) dt_sectors.Columns.Add(new DataColumn()); DataTable dt_subsectors = new DataTable(); for (int i = 0; i < 4; ++i) dt_subsectors.Columns.Add(new DataColumn()); DataTable dt_worlds = new DataTable(); for (int i = 0; i < 6; ++i) dt_worlds.Columns.Add(new DataColumn()); callback("Parsing data..."); foreach (Sector sector in map.Sectors) { if (!sector.Tags.Contains("OTU")) continue; foreach (Name name in sector.Names) { DataRow row = dt_sectors.NewRow(); row.ItemArray = new object[] { sector.X, sector.Y, name.Text }; dt_sectors.Rows.Add(row); } foreach (Subsector subsector in sector.Subsectors) { DataRow row = dt_subsectors.NewRow(); row.ItemArray = new object[] { sector.X, sector.Y, subsector.Index, subsector.Name }; dt_subsectors.Rows.Add(row); } #if DEBUG if (!sector.Selected) continue; #endif // NOTE: May need to page this at some point WorldCollection worlds = sector.GetWorlds(resourceManager, cacheResults: false); if (worlds == null) continue; foreach (World world in worlds) { DataRow row = dt_worlds.NewRow(); row.ItemArray = new object[] { sector.X, sector.Y, world.X, world.Y, world.Name != null && world.Name.Length > 0 ? (object)world.Name : (object)DBNull.Value, world.UWP }; dt_worlds.Rows.Add(row); } } // // Rebuild the tables with fresh schema // string[] rebuild_schema = { "IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'sectors') AND type = (N'U')) DROP TABLE sectors", "CREATE TABLE sectors(x int NOT NULL,y int NOT NULL,name nvarchar(50) NULL)", "CREATE NONCLUSTERED INDEX sector_name ON sectors ( name ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)", "IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'subsectors') AND type = (N'U')) DROP TABLE subsectors", "CREATE TABLE subsectors (sector_x int NOT NULL, sector_y int NOT NULL, subsector_index char(1) NOT NULL, name nvarchar(50) NULL )", "CREATE NONCLUSTERED INDEX subsector_name ON subsectors ( name ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)", "IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'worlds') AND type = (N'U')) DROP TABLE worlds", "CREATE TABLE worlds( sector_x int NOT NULL, sector_y int NOT NULL, hex_x int NOT NULL, hex_y int NOT NULL, name nvarchar(50) NULL, uwp nchar(9) NULL )", "CREATE NONCLUSTERED INDEX world_name ON worlds ( name ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)", "CREATE NONCLUSTERED INDEX world_uwp ON worlds ( uwp ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)", }; callback("Rebuilding schema..."); foreach (string cmd in rebuild_schema) { sqlCommand = new SqlCommand(cmd, connection); sqlCommand.ExecuteNonQuery(); } // // And shovel the data into the database en masse // using (var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null)) { callback(String.Format("Writing {0} sectors...", dt_sectors.Rows.Count)); bulk.BatchSize = dt_sectors.Rows.Count; bulk.DestinationTableName = "sectors"; bulk.WriteToServer(dt_sectors); bulk.Close(); } using (var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null)) { callback(String.Format("Writing {0} subsectors...", dt_subsectors.Rows.Count)); bulk.BatchSize = dt_subsectors.Rows.Count; bulk.DestinationTableName = "subsectors"; bulk.WriteToServer(dt_subsectors); bulk.Close(); } using (var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null)) { callback(String.Format("Writing {0} worlds...", dt_worlds.Rows.Count)); bulk.BatchSize = 4096; bulk.DestinationTableName = "worlds"; bulk.WriteToServer(dt_worlds); bulk.Close(); } } callback("Complete!"); } }