|
Can you show me example? I want to pass log dir as parameter too. Yes it compiles
but also who and how would actual logging be called (item 2)
|
|
|
|
|
namespace GlobalLog {
private static Logger _logger;
static public init() {
_logger = LoggerManager.GetLogger("example");
}
static public Logger inst { get{ return inst_; } }
}
|
|
|
|
|
Try something like this:
static class GMLogger
{
private static readonly ILogger _logger = GetLogger();
private static ILogger GetLogger()
{
var config = new LoggingConfiguration();
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
fileTarget.Layout = @"${date:format=HH\:mm\:ss} - ${message}";
fileTarget.FileName = "c:/myFolder/" + "${date:format=yyyy-MM-dd}.log";
var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule2);
LogManager.Configuration = config;
return LogManager.GetLogger("Example");
}
public static void Trace(string message) { _logger.Trace(message); }
public static void Debug(string message) { _logger.Debug(message; }
public static void Info(string message) { _logger.Info(message; }
public static void Warn(string message) { _logger.Warn(message); }
public static void Error(string message) { _logger.Error(message; }
public static void Fatal(string message) { _logger.Fatal(message); }
}
The static field initializer is guaranteed to only run once per AppDomain.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
" The static field initializer is guaranteed to only run once per AppDomain."
What happens not per app domain? and I think there is some situation about that approach and beforefieldinit - don't you need a static constructor there because of this flag?
Also can I specify log dir parameter during initialization using your approach? I think no? but this I need.
Please feel free also to comment on the approach I had: http://codepad.org/p3gtJQPy[^], I don't know why I am struggling to know hot to properly use NLog. You can see my Log class there is internal. I don't need clients outside DLL to directly use it, but other classes in DLL should use it.
modified 23-Oct-15 8:26am.
|
|
|
|
|
|
Hello Every Body!
I just try to text analysis program by C# .In the program i uses RichTextEdit . I want to load word file, text file , pdf to Richtext Edit Box. Now i can load these file to RichText Edit . But i can't change font these text. Just i used Microsoft.Office.Interop.Word; . Check my code below. Thanks for your kindness!
public void ReadMsWord()
{
// variable to store file path
string filePath=null;
// open dialog box to select file
OpenFileDialog file= new OpenFileDialog();
// dilog box title name
file.Title="Word File";
// set initial directory of computer system
file.InitialDirectory= "c:\\";
// set restore directory
file.RestoreDirectory= true;
// execute if block when dialog result box click ok button
if (file.ShowDialog() ==DialogResult.OK)
{
// store selected file path
filePath=file.FileName.ToString();
}
try
{
// create word application
Microsoft.Office.Interop.Word.Application word =new Microsoft.Office.Interop.Word.Application();
// create object of missing value
object miss= System.Reflection.Missing.Value;
// create object of selected file path
object path=filePath;
// set file path mode
object readOnly= false;
//Microsoft.Office.Interop.Word.Font f = new Microsoft.Office.Interop.Word.Font();
//f.Name = "Zawgyi-One, 8.25pt";
//object fo = f;
// open document
Microsoft.Office.Interop.Word.Document docs=word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
// select whole data from active window document
docs.ActiveWindow.Selection.WholeStory();
// handover the data to cllipboard
docs.ActiveWindow.Selection.Copy();
// clipboard create reference of idataobject interface which transfer the data
IDataObject data= Clipboard.GetDataObject();
//Microsoft.Office.Interop.Word.Range rng = docs.Paragraphs[1].Range;
//rng.Font.Name = "Zawgyi-One";
//set data into richtextbox control in text format
richTextBox1.Text=data.GetData(DataFormats.Text).ToString();
//word.Selection.Font.Name = "Zawgyi-One";
// Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.Document();
// this.richTextBox1.SelectAll();
//System.Drawing.Font currentFont = richTextBox1.SelectionFont;
// richTextBox1.SelectionFont = new System.Drawing.Font(currentFont.FontFamily,currentFont.Size,newFontStyle);
// read bitmap image from clipboard with help of iddataobject interface
Image img= (Image)data.GetData(DataFormats.Bitmap);
// close the document
docs.Close(ref miss, ref miss, ref miss);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
|
|
|
|
|
naylynn wrote: Now i can load these file to RichText Edit That is not entirely what the code does; it copies it to the clipboard, and pastes that in the RichTextBox. That means that it is a copy, in RTF format, and will no longer support everything that Word does.
You can change the font, it's style and color, by programmatically setting a selection (like SelectAll would do) and setting its SelectionFont.
If you want to do it using Word-interop, then you will have to make the changes before copying the data to the clipboard. After that, it becomes RTF.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
|
Hi,
I have a server with MySQL and Windows Services installed on it for my C# WinForm application and I have clients connecting to this server.
I want to alert the users (clients) if my windows service was stopped for any reason on the server.
Is it possible to check the windows service on the server from the client?
otherwise, I was thinking to let the windows services to log the last run every hour to MySQL database and when the client connect to the MySQL server on the server and found the service was not running for more than one hour then it will alert them?
What do you think?
Thanks,
Jassim[^]
Technology News @ www.JassimRahma.com
|
|
|
|
|
The ServiceController[^] class is what you're looking for. Just pass the service name and server name to this constructor[^], and you should be able to check the status of the service.
var controller = new ServiceController("Service Name", "Server Name");
switch (controller.Status)
{
case ServiceControllerStatus.Running:
{
break;
}
case ServiceControllerStatus.StartPending:
case ServiceControllerStatus.ContinuePending:
{
controller.WaitForStatus(ServiceControllerStatus.Running);
break;
}
case ServiceControllerStatus.StopPending:
case ServiceControllerStatus.PausePending:
{
break;
}
case ServiceControllerStatus.Stopped:
case ServiceControllerStatus.Paused:
{
break;
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi,
Is it possible to have one KeyDown for the form and all its Controls so wherever F5 is press then I can run a specific code without having to include the KeyDown in every control on the form?
How can I do this please?
Thanks,
Jassim[^]
Technology News @ www.JassimRahma.com
|
|
|
|
|
Yes.The way you do it is to search CodeProject for "global hook," and read one of the many articles that will provide the code for you to do that.
In your case, you want an "application keyboard hook."
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
If you're talking about hitting F5 anywhere in your own application you don't need a keyboard hook. All you need is to handle the KeyDown event of the Form and set the Form's KeyPreview property[^] to true.
|
|
|
|
|
You can do as Dave said, but do note what MS documentation says:
A control on a form may be programmed to cancel any keystrokes it receives. Since the control never sends these keystrokes to the form, the form will never see them regardless of the setting of KeyPreview.
Another way is to override the ProcessCmdKey in your form, and return true for F5 key.
Best,
John
|
|
|
|
|
If you are using WPF and do find that you need to add an intercept for pressing F5 for all your controls on the page, this code should work, just pass in the reference to the Window's main panel (grid, canvas, etc...)
public static void AddF5CaptureEvent(Panel mainContentContainer)
{
foreach (UIElement child in mainContentContainer.Children)
{
child.PreviewKeyDown += (s, e) => { if (e.Key == Key.F5) { InterceptFunction() } };
if (child is Panel)
{
AddF5CaptureEvent(child);
}
}
}
|
|
|
|
|
wap to divide a number by another no. and handle all possible exception plz help me
|
|
|
|
|
Not very clear.
Anyway assuming you have int s, there are two bad cases:
1) anything divided by zero.
2) int.MinValue / -1
Just test both.
if (y == 0 || y == -1 && x == int.MinValue)
{
}
else
{
int d = x / y;
}
|
|
|
|
|
Hmmm....
Can you be a little more vague?
|
|
|
|
|
Can I ask you your opinion if you see some major problems with this class I wrote? As you can see this is meant to be thread safe log class.
I don't want to use 3rd party solution. Thanks.
static class GMLogger
{
private static List<string> _buffer = new List<string>();
private static int _maxBufferSize = 25;
public static string _logDir = "C:\\Logs";
private static readonly object _syncObject = new object();
public static void Log(string logMessage)
{
try
{
lock (_syncObject)
{
_buffer.Add(logMessage);
Save(_buffer);
}
}
catch (Exception ex)
{
throw;
}
}
private static void Save(List<string> buffer)
{
if (buffer.Count > _maxBufferSize)
{
if (!_logDir.EndsWith("\\")) _logDir += "\\";
DirectoryInfo di = Directory.CreateDirectory(_logDir);
var todaysLogFilePath = Path.Combine(_logDir,
("Log" + DateTime.Now.ToString("yyyy-MMMM-dd") + ".txt"));
using (FileStream aFile = new FileStream(todaysLogFilePath, FileMode.Append, FileAccess.Write, FileShare.None))
using (StreamWriter sw = new StreamWriter(aFile))
{
for (int i = 0; i < buffer.Count(); i++)
{
sw.WriteLine(buffer[i]);
}
}
buffer.Clear();
}
}
}
|
|
|
|
|
I'm in the habit of searching CodeProject for articles that demonstrate the functionality I look for: in this case, I'd sure want to read: "Simple Log" by Jochen Scharr [^] "Essential logging in one simple, robust, static, thread-safe class. No initialization, no configuration, no dependencies."
What "jumps out" at me from the code is your use of '_buffer and 'buffer: since you are not passing '_buffer by reference to the 'Save method, is '_buffer ever really getting cleared when the 'Save method calls 'buffer.Clear(); ?
On the "big picture" level:
1. I would most probably want to create a "daily log" class which I'd serialize to a stream, and then append to a "master" log file.
2. I'd evaluate if there's anywhere I could use a StringBuilder here.
3. I'd test for the save Directory's existence, perhaps set a boolean flag to indicate it's defined. I'd create the day's log file once, and check whether it's up to date.
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
about buffer that's a typo thanks. Apart all people usually day don't write your own, but I don't understand what can go wrong with this class?
In that way also the article you linked, maybe that one also isn't that reliable?
|
|
|
|
|
user20044 wrote: maybe that one also isn't that reliable Hi, I'm not sure; I haven't used it: I wrote my own logger; it uses a collection of 'Log Class "instances" which is written to a stream, compressed with GZip, and, then, serialized. But, it's not written to be thread-safe, something I intend to get around to doing when it's called for.
In terms of "what can go wrong" with your implementation, well: you need to test it.
cheers, Bill
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Hmm tested and it works. Your link seems a nice class I would really appreciate if you or someone else can tell me if that class is reliable?
|
|
|
|
|
Hopefully, you'll get some other responses here that are useful to you.
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Actually your comment about buffer! - initially it was written correctly and it would still clear the original member variable _buffer, since buffer points to _buffer
|
|
|
|