public static void ReportStats() { var client = new WebClient { Proxy = CodeStatsPackage.GetProxy() }; client.Headers[HttpRequestHeader.UserAgent] = Constants.PluginUserAgent; string HtmlResult = client.DownloadString("https://p0358.cf/codestats/report.php?pluginver=" + Constants.PluginVersion + "&cid=" + CodeStatsPackage.Guid + "&editorname=" + Constants.EditorName + "&editorver=" + Constants.EditorVersion + "&is64proc=" + ProcessorArchitectureHelper.Is64BitProcess.ToString().ToLowerInvariant()); // expected response: ok if (HtmlResult.Contains("ok")) { _reportedStats = true; } }
static void beNotified(IntPtr notifyCode) { ScNotification notification = (ScNotification)Marshal.PtrToStructure(notifyCode, typeof(ScNotification)); if (notification.Header.Code == (uint)NppMsg.NPPN_TBMODIFICATION) { PluginBase._funcItems.RefreshItems(); CodeStatsPackage.SetToolBarIcon(); } else if (notification.Header.Code == (uint)NppMsg.NPPN_SHUTDOWN) { CodeStatsPackage.PluginCleanUp(); Marshal.FreeHGlobal(_ptrPluginName); } else { CodeStatsPackage.OnNotification(notification); } }
static void setInfo(NppData notepadPlusData) { PluginBase.nppData = notepadPlusData; CodeStatsPackage.CommandMenuInit(); }
private static void LoadExtensionMapping() { try { //MessageBox.Show("test1"); //Logger.Debug(Assembly.GetExecutingAssembly().GetManifestResourceNames().ToString()); //Logger.Debug(Assembly.GetExecutingAssembly().GetName().Name); Assembly _assembly; StreamReader _textStreamReader; Stream _stream; string extensionMappingJson; var serializer = new JavaScriptSerializer(); // Load precompiled/included extension mapping first _assembly = Assembly.GetExecutingAssembly(); _stream = _assembly.GetManifestResourceStream("CodeStats.Resources.extension_mapping.json"); _textStreamReader = new StreamReader(_stream); extensionMappingJson = _textStreamReader.ReadToEnd(); extensionMapping = serializer.Deserialize <Dictionary <string, string> >(extensionMappingJson); Logger.Debug("Loaded local precompiled extension mapping"); //MessageBox.Show("test2"); // fetch up-to-date mappings from network asynchronously Task.Run(() => { string extensionMappingJsonNew = ""; var serializer2 = new JavaScriptSerializer(); try { var client = new WebClient { Proxy = CodeStatsPackage.GetProxy() }; client.Headers[HttpRequestHeader.UserAgent] = Constants.PluginUserAgent; try { extensionMappingJsonNew = client.DownloadString("https://raw.githubusercontent.com/p0358/notepadpp-CodeStats/master/CodeStats/Resources/extension_mapping.json"); if (!extensionMappingJsonNew.Trim().StartsWith("{") || !extensionMappingJson.Trim().EndsWith("}")) { extensionMappingJsonNew = string.Empty; Logger.Error("Invalid response when trying to download latest extension mappings, using local ones instead"); } } catch (Exception ex) { extensionMappingJson = string.Empty; Logger.Error("Exception when trying to download latest extension mappings, using local ones instead", ex); } // update extension mapping JSON } catch { extensionMappingJson = string.Empty; } // get webclient, set proxy, update extension mapping JSON //MessageBox.Show("test3"); if (!String.IsNullOrWhiteSpace(extensionMappingJsonNew) && extensionMappingJsonNew != extensionMappingJson) { extensionMapping = serializer2.Deserialize <Dictionary <string, string> >(extensionMappingJson); Logger.Debug("Loaded latest extension mapping JSON"); } else { Logger.Debug("There are no updates to extension mapping JSON"); } }); //Logger.Debug("Extension mapping JSON: " + extensionMappingJson); //var json = "{\"id\":\"13\", \"value\": true}"; //var serializer = new JavaScriptSerializer(); //var table = serializer.Deserialize<dynamic>(json); //Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json); //extensionMapping = serializer.Deserialize<Dictionary<string, string>>(extensionMappingJson); //Logger.Debug(values["id"]); //Logger.Debug(table["value"]); } catch (Exception ex) { Logger.Error("Error loading extension mappings!", ex); } }
private static void InitializeAsync() { try { // Delete existing log file to save space Logger.Delete(); } catch { } try { Logger.Info(string.Format("Initializing Code::Stats v{0}", Constants.PluginVersion)); //Logger.Debug(Assembly.GetExecutingAssembly().GetManifestResourceNames().ToString()); //Logger.Debug(Assembly.GetExecutingAssembly().GetName().Name); Assembly _assembly; StreamReader _textStreamReader; Stream _stream; string extensionMappingJson; try { var client = new WebClient { Proxy = CodeStatsPackage.GetProxy() }; client.Headers[HttpRequestHeader.UserAgent] = Constants.PluginUserAgent; try { extensionMappingJson = client.DownloadString("https://raw.githubusercontent.com/p0358/notepadpp-CodeStats/master/CodeStats/Resources/extension_mapping.json"); if (!extensionMappingJson.Trim().StartsWith("{") || !extensionMappingJson.Trim().EndsWith("}")) { extensionMappingJson = string.Empty; } } catch (Exception ex) { extensionMappingJson = string.Empty; Logger.Error("Exception when trying to download latest extension mappings, using local ones instead", ex); } } catch { extensionMappingJson = string.Empty; } if (String.IsNullOrWhiteSpace(extensionMappingJson)) { // Load precompiled/included extension mapping _assembly = Assembly.GetExecutingAssembly(); _stream = _assembly.GetManifestResourceStream("CodeStats.Resources.extension_mapping.json"); _textStreamReader = new StreamReader(_stream); extensionMappingJson = _textStreamReader.ReadToEnd(); } Logger.Debug("Extension mapping JSON: " + extensionMappingJson); //var json = "{\"id\":\"13\", \"value\": true}"; var serializer = new JavaScriptSerializer(); //var table = serializer.Deserialize<dynamic>(json); //Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json); extensionMapping = serializer.Deserialize <Dictionary <string, string> >(extensionMappingJson); //Logger.Debug(values["id"]); //Logger.Debug(table["value"]); } catch (Exception ex) { Logger.Error("Error loading extension mappings!", ex); } try { // Settings Form _settingsForm = new CodeStats.Forms.SettingsForm(); _settingsForm.ConfigSaved += SettingsFormOnConfigSaved; // Load config file _CodeStatsConfigFile = new ConfigFile(); GetSettings(); try { // Check for updates string latest = Constants.LatestPluginVersion(); if (Constants.PluginVersion != latest && !String.IsNullOrWhiteSpace(latest)) { MessageBox.Show("There is Code::Stats plugin update available!\nDownload it from Plugin Manager or GitHub.\nYour version: " + Constants.PluginVersion + "\nLatest: " + latest, "Code::Stats"); } } catch { } currentPulse = new Pulse(); if (string.IsNullOrEmpty(ApiKey)) { Stats = false; // Disable stats reporting for this session/launch PromptApiKey(); // Prompt for API token if not already set } // setup timer to process queued pulses timer.Interval = pulseFrequency; timer.Elapsed += ProcessPulses; timer.Start(); if (Stats) { ReportStats(); } Logger.Info(string.Format("Finished initializing Code::Stats v{0}", Constants.PluginVersion)); } catch (Exception ex) { Logger.Error("Error Initializing Code::Stats", ex); } }
private static void ProcessPulses() { if (pulseQueue != null && ((currentPulse != null && !currentPulse.isEmpty()) || !pulseQueue.IsEmpty) && EnoughTimePassed(DateTime.Now)) { if (currentPulse != null && !currentPulse.isEmpty()) { pulseQueue.Enqueue(currentPulse); currentPulse = new Pulse(); currentCount = 0; } if (String.IsNullOrWhiteSpace(ApiKey)) { Logger.Debug("No API token - cannot pulse!"); return; } var client = new WebClient { Proxy = CodeStatsPackage.GetProxy() }; var jsonSerializer = new JavaScriptSerializer(); string URL; if (String.IsNullOrWhiteSpace(_CodeStatsConfigFile.ApiUrl)) { URL = Constants.ApiMyPulsesEndpoint; } else { URL = _CodeStatsConfigFile.ApiUrl; } client.Headers[HttpRequestHeader.UserAgent] = Constants.PluginUserAgent; client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.Headers[HttpRequestHeader.Accept] = "*/*"; client.Headers["X-API-Token"] = ApiKey; Pulse result; while (pulseQueue.TryDequeue(out result)) { if (!result.isEmpty()) { bool error = false; // Try to pulse to API try { string json = jsonSerializer.Serialize(result); Logger.Debug("Pulsing " + json); string HtmlResult = client.UploadString(URL, json); _lastPulse = DateTime.Now; if (!HtmlResult.Contains(@"""ok""") && !HtmlResult.Contains(@"success")) { error = true; Logger.Error(@"Error pulsing, response does not contain ""ok"" or ""success"": " + HtmlResult); } } catch (WebException ex) { error = true; if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null && (int)response.StatusCode == 403) { if (!_shownInvalidApiTokenMessage) // we want to inform user only once, and if he does not provide the token, let's not bomb him with error each time after he types something { MessageBox.Show("Could not pulse. Please make sure you entered a valid API token in Code::Stats settings.", "Code::Stats - error 403", MessageBoxButtons.OK, MessageBoxIcon.Error); _shownInvalidApiTokenMessage = true; } Logger.Error("Could not pulse. Please make sure you entered a valid API token in Code::Stats settings.", ex); } else { // response==null - no http status code available Logger.Error("Could not pulse. Are you behind a proxy? Try setting a proxy in Code::Stats settings with format https://user:pass@host:port. Exception Traceback", ex); } } else { Logger.Error("Could not pulse. Are you behind a proxy? Try setting a proxy in Code::Stats settings with format https://user:pass@host:port. Exception Traceback", ex); } } catch (Exception ex) { error = true; Logger.Error("Error pulsing. Exception Traceback", ex); } if (error) { pulseQueue.Enqueue(result); // Requeue, since we failed to pulse return; } } } } UpdateStatusbar(); }