public void WriteTest_Default() { LogDefinition log = new LogDefinition("Test", @"C:\Temp\TestLog.txt"); log.WriteLine("Test log entry"); LogDefinitionList.Instance.Flush(); }
public IActionResult ChangePassword(FrameChangePassword model) { if (ModelState.IsValid) { var dal = new AdministratorDal(); try { CryptoHelper helper = new CryptoHelper(); var p = CurrentAdmin; var old = dal.FindByAccounts(model.Accounts.Trim().ToLower()); if (old != null) { if (old.AdministratorId != p.AdministratorId) { ModelState.AddModelError("", "该账号已经被占用."); return(View(model)); } } if (model.OldPassword.Trim() == helper.Decrypt(p.PassWord.Trim())) { var logMode = new LogDefinition() { Content = "修改密码", AdminName = p.Name, AfterUpdate = "", BeforeUpdate = "", UpdateDateTime = DateTime.Now, }; var logDal = new LogDal(); logDal.Add(logMode); p.PassWord = helper.Encrypt(model.NewPassword); p.Accounts = model.Accounts.Trim().ToLower(); dal.Update(p); CurrentAdmin = null; return(RedirectToAction("LogOn", "Account")); } else { ModelState.AddModelError("", "密码不正确."); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } //model.OldPassword = ""; //model.NewPassword = ""; //model.ConfirmPassword = ""; return(View(model)); }
public IActionResult LogOn(AccountLogOnModel model) { if (ModelState.IsValid) { var administratorDal = new AdministratorDal(); try { var p = administratorDal.FindByAccounts(model.Accounts.ToLower()); if (p != null) { //Url.IsLocalUrl(returnUrl) CryptoHelper helper = new CryptoHelper(); if (p.PassWord.Trim() == helper.Encrypt(model.Password)) { Cache.SetString("CurrentAdmin", p.AdministratorId); HttpContext.Session.SetString("CurrentAdmin", p.AdministratorId); var logMode = new LogDefinition() { Content = "登录", AdminName = p.Name, AfterUpdate = "", BeforeUpdate = "", UpdateDateTime = DateTime.Now, }; var logDal = new LogDal(); logDal.Add(logMode); return(RedirectToAction("Index", "Frame")); } else { ModelState.AddModelError("", "密码不正确."); } } else { ModelState.AddModelError("", "找不到该账号."); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } // If we got this far, something failed, redisplay form return(View(model)); }
private LogDefinition ParseLogDefinition(JObject logNode) { var definition = new LogDefinition(); definition = ParseDefinition(definition, logNode, "", "formatter", "listeners", "sinks"); var formatterNode = logNode["formatter"]; if (formatterNode != null) { if (formatterNode.Type == JTokenType.String) { definition.FormatterName = formatterNode.Value <string>(); } else { var formatterDefinition = new FormatterDefinition(); string name = definition.Id + "_formatter"; formatterDefinition = ParseDefinition(formatterDefinition, formatterNode, name); _configuration.Formatters.Add(name, formatterDefinition); definition.FormatterName = name; } } var listenerNodes = logNode["listeners"]; if (listenerNodes != null) { foreach (var listenerNode in listenerNodes) { if (listenerNode.Type == JTokenType.String) { definition.ListenerNames.Add(formatterNode.Value <string>()); } else { var name = definition.Id + "_listener" + DateTime.Now.Ticks; var listenerDefinition = new ListenerDefinition(); listenerDefinition = ParseDefinition(listenerDefinition, listenerNode, name); _configuration.Listeners.Add(name, listenerDefinition); definition.ListenerNames.Add(name); } } } var sinkNodes = logNode["sinks"]; if (sinkNodes != null) { foreach (var sinkNode in sinkNodes) { if (sinkNode.Type == JTokenType.String) { } else { var name = definition.Id + "_sink" + DateTime.Now.Ticks; var sinkDefinition = new SinkDefinition(); sinkDefinition = ParseDefinition(sinkDefinition, sinkNode, name); _configuration.Sinks.Add(name, sinkDefinition); definition.SinkNames.Add(name); } } } return(definition); }
/// <summary> /// The List Log Definitions operation lists the log definitions for /// the resource. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// logs for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name of the log definition. For example, "name.value eq /// 'Percentage CPU'". Name is optional, meaning the expression may be /// "". /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Log Definitions operation response. /// </returns> public async Task <LogDefinitionListResponse> GetLogDefinitionsAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetLogDefinitionsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/providers/microsoft.insights/logDefinitions"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2015-07-01"); List <string> odataFilter = new List <string>(); if (filterString != null) { odataFilter.Add(Uri.EscapeDataString(filterString)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LogDefinitionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LogDefinitionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LogDefinitionCollection logDefinitionCollectionInstance = new LogDefinitionCollection(); result.LogDefinitionCollection = logDefinitionCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LogDefinition logDefinitionInstance = new LogDefinition(); logDefinitionCollectionInstance.Value.Add(logDefinitionInstance); JToken categoryValue = valueValue["category"]; if (categoryValue != null && categoryValue.Type != JTokenType.Null) { LocalizableString categoryInstance = new LocalizableString(); logDefinitionInstance.Category = categoryInstance; JToken valueValue2 = categoryValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); categoryInstance.Value = valueInstance; } JToken localizedValueValue = categoryValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); categoryInstance.LocalizedValue = localizedValueInstance; } } JToken resourceIdValue = valueValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); logDefinitionInstance.ResourceId = resourceIdInstance; } JToken retentionValue = valueValue["retention"]; if (retentionValue != null && retentionValue.Type != JTokenType.Null) { TimeSpan retentionInstance = TimeSpan.Parse(((string)retentionValue), CultureInfo.InvariantCulture); logDefinitionInstance.Retention = retentionInstance; } JToken blobLocationValue = valueValue["blobLocation"]; if (blobLocationValue != null && blobLocationValue.Type != JTokenType.Null) { BlobLocation blobLocationInstance = new BlobLocation(); logDefinitionInstance.BlobLocation = blobLocationInstance; JToken blobEndpointValue = blobLocationValue["blobEndpoint"]; if (blobEndpointValue != null && blobEndpointValue.Type != JTokenType.Null) { string blobEndpointInstance = ((string)blobEndpointValue); blobLocationInstance.BlobEndpoint = blobEndpointInstance; } JToken blobInfoArray = blobLocationValue["blobInfo"]; if (blobInfoArray != null && blobInfoArray.Type != JTokenType.Null) { foreach (JToken blobInfoValue in ((JArray)blobInfoArray)) { BlobInfo blobInfoInstance = new BlobInfo(); blobLocationInstance.BlobInfo.Add(blobInfoInstance); JToken blobUriValue = blobInfoValue["blobUri"]; if (blobUriValue != null && blobUriValue.Type != JTokenType.Null) { string blobUriInstance = ((string)blobUriValue); blobInfoInstance.BlobUri = blobUriInstance; } JToken startTimeValue = blobInfoValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); blobInfoInstance.StartTime = startTimeInstance; } JToken endTimeValue = blobInfoValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); blobInfoInstance.EndTime = endTimeInstance; } JToken sasTokenValue = blobInfoValue["sasToken"]; if (sasTokenValue != null && sasTokenValue.Type != JTokenType.Null) { string sasTokenInstance = ((string)sasTokenValue); blobInfoInstance.SasToken = sasTokenInstance; } } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { //Initialise log output LogDefinition log = new LogDefinition(LOG_ID, Environment.CurrentDirectory + @"\Logs\SparkConsole.log"); LogDefinitionList.Instance.Add(LOG_ID, log); //Log arguments StringBuilder argText = new StringBuilder(); for (int i = 0; i < args.Count(); i++) { argText.Append(string.Format("[{0}]={1} ", i, args[i])); } log.WriteLine("Intiated"); log.WriteLine("ARGUMENTS: " + argText.ToString()); //Execute command try { //Get command identifier if (args.Count() == 0) { throw new ArgumentException("Command not specified"); } string commandId = args[0].ToLower(); IConsoleCommand command = null; switch (commandId) { case "exportmarket": command = new ExportMarketCommand(log); break; case "exportsecurity": command = new ExportSecurityCommand(log); break; case "diagnostic": command = new DiagnosticCommand(log); break; case "test": log.WriteLine("Test log entry"); break; default: throw new ArgumentException("Command '" + commandId + "' not recognised"); } //Execute command if (command != null) { command.Execute(args); } } catch (ArgumentException ex) { log.WriteLine("ERROR: " + ex.Message); } catch (Exception ex) { log.WriteLine("ERROR: " + ex.Message + "\r\n" + ex.StackTrace); } //Flush log buffer log.WriteLine("Completed\r\n"); LogDefinitionList.Instance.Flush(); }
/// <summary> /// Does the search operation on the records in a log file. /// </summary> void searcher() { #region Variables FileInfo fileInfo; string LogFileAbs = ""; // this is the full pathname of the log file that will be read string LogFileRel = ""; // this is the relative filename string LogFileName = ""; // this is the short filename (no path) string DlogId = ""; // DLOG file id extracted from the DLOG Uri LogFileUri; string[] MessageBuffer; // this is the buffer that the messages get stored in. bool[] PrintFlag; int MessageIndex = 0; int StillPrinting = 0; FileStream LogFileStream; // file manipulation variables. MatchCollection Matches; MatchCollection FileMatches; bool done = false; // temp variables, and controll variables string MessageString; int i; int j; int tempInt1; bool DoneRecursing = false; int FileMatchCount = 0; int PattMatchCount = 0; MessageBuffer = new string[BackPrint]; PrintFlag = new Boolean[BackPrint]; #endregion LogDefinition LogFile = new LogDefinition(); while (!DoneRecursing) { #region Get the file name lock (LogFileManager) { DoneRecursing = LogFileManager.done; fileInfo = LogFileManager.Next(); LogFileAbs = fileInfo.FullName; LogFileName = fileInfo.Name; } // Check for the termination file if (DoneRecursing) { Debug.WriteLine("Finished the stack"); break; } // Console.WriteLine("file: " + LogFileName); // Check if the file name pattern matches FileMatches = FilePattern.Matches(LogFileName); if (FileMatches.Count == 0) { done = true; } // Check if file size meets min/max criteria else if (fileInfo.Length < MinFileLen || fileInfo.Length > MaxFileLen) { // Console.WriteLine("dlgrep: file too small/big: " + LogFileRel + " sizeKB=" + fileInfo.Length / 1024); done = true; } else // this file is okay for searching { done = false; } #endregion if (!done) { LogFileRel = LogFileAbs.Substring(TopDir.FullName.Length + 1); LogFileUri = new Uri(LogFileAbs); string rel = TopDirUri.MakeRelativeUri(LogFileUri).ToString(); LogFileRel = rel.Substring(TopDir.Name.Length + 1); Debug.WriteLine(string.Format("File Name : {0}", LogFileAbs)); // reset for a new file MessageIndex = BackPrint; StillPrinting = 0; PattMatchCount = 0; DlogId = LogFileName; // Open the file try { LogFileStream = File.OpenRead(LogFileAbs); // initialize the file LogFile.InitializeLog(LogFileStream); // if it's available, use the DLOG id instead of a path if (LogFile.EmbeddedLogFileId.Length > 0) { DlogId = LogFile.EmbeddedLogFileId; } } #region Catches catch (ApplicationException ApEx) { if (!(ApEx.Message == "Deflated stream ends early.")) { Debug.WriteLine("Log_Grep_Main :"); Debug.WriteLine("Application Exception found in file : " + LogFileAbs); Debug.WriteLine(" Exception Message : " + ApEx.Message); } } catch (Exception Ex) { if ((Ex is IOException) && (Ex.Message == "EOF")) { done = true; } else { Debug.WriteLine("Main: InitializeLog: no catch for Exception: " + Ex.GetType()); Debug.WriteLine("Main:File.OpenRead: no catch for Exception: " + Ex.GetType()); Debug.WriteLine(" In file : " + LogFileAbs); Debug.WriteLine(" Exception Message : " + Ex.Message); done = true; } } #endregion // Read message records and look for matches try { while (!done) { try { MessageString = LogFile.ReadMessage(); } #region catches catch (IOException IOEx) { throw new IOException(IOEx.Message); } #endregion if (MessageString == "") { done = true; } else { // DEBUG message Debug.WriteLine(MessageString); // store the message. MessageIndex++; MessageBuffer[MessageIndex % BackPrint] = MessageString; PrintFlag[MessageIndex % BackPrint] = false; #region pattern matching // For each pattern defined ... for (i = 0; i < PatternCount; i++) { Matches = RegexPattern[i].Matches(MessageString); if (Matches.Count > 0) // we have a match { PattMatchCount++; if (Optionl) { // We're done with this file on the first match done = true; lock (WriteControl) { Console.WriteLine(LogFileRel); } break; } if (Optionc) { // Counting the lines that have a match; skip out on first match // and proceed to the next line break; } StillPrinting = ForwardPrint; // set the forward print variable for (j = (BackPrint - 1); j >= 0; j--) { // print these messages in the backlog that // haven't been printed yet tempInt1 = (MessageIndex - j) % BackPrint; if (!(PrintFlag[tempInt1])) { lock (WriteControl) { // Print a Head-Line file banner with the relative pathname if (OptionHL && PattMatchCount == 1) { if (OptionH) { Console.Write(DlogId + "|"); } else // use the time stamp of 1st record as a prefix for sortability { // 2013/10/29_10:00:08.566 Console.Write(MessageBuffer[tempInt1].Substring(0, 24)); } Console.WriteLine("======================================== " + LogFileRel); } if (OptionH) { Console.Write(DlogId + "|"); } Console.WriteLine(MessageBuffer[tempInt1]); } PrintFlag[tempInt1] = true; } } } } #endregion // print message if it is required. #region printing if ((StillPrinting > 0) && (!(PrintFlag[MessageIndex % BackPrint]))) { lock (WriteControl) { if (OptionH) { Console.Write(LogFileRel + ":"); } Console.WriteLine(MessageBuffer[MessageIndex % BackPrint]); } PrintFlag[MessageIndex % BackPrint] = true; StillPrinting--; } #endregion } } // while ! done reading records on the current file if (PattMatchCount > 0) { // Count this file as having had a match FileMatchCount++; } if (Optionc && PattMatchCount >= OptioncThresh) { lock (WriteControl) { Console.WriteLine(LogFileRel + ":" + PattMatchCount); } } Debug.WriteLine("---(EOF)---"); } // try #region Catches catch (IOException IOEx) { if (IOEx.Message != "EOF") { Debug.WriteLine("Log_Grep_Main :"); Debug.WriteLine("IO Exception found in file : " + LogFileAbs); Debug.WriteLine(" Exception Message : " + IOEx.Message); } } catch (ApplicationException ApEx) { if (!(ApEx.Message == "Deflated stream ends early.")) { Debug.WriteLine("Log_Grep_Main :"); Debug.WriteLine("Application Exception found in file : " + LogFileAbs); Debug.WriteLine(" Exception Message : " + ApEx.Message); } } catch (ZipException ZipEx) { Debug.WriteLine("Log_Grep_Main :"); Debug.WriteLine("Zip Exception found in file : " + LogFileAbs); Debug.WriteLine(" Exception Message : " + ZipEx.Message); } catch (Exception Ex) { Debug.WriteLine("Log_Grep_Main :"); Debug.WriteLine("Exception found in file : " + LogFileAbs); Debug.WriteLine(" Exception type : " + Ex.GetType()); Debug.WriteLine(" Exception Message : " + Ex.Message); } #endregion try { LogFile.CloseLog(); } #region Catches catch { Debug.WriteLine("Log File Failed To Close: File name : " + LogFileAbs); } #endregion } } // Update the total file match count Interlocked.Add(ref TotFileMatchCount, FileMatchCount); }