So i am using Log4Net in my application.
And beside the .txt file i have another List that populate once my Logger form is opening.
So currently i am add .txt Log this way:
log.Info("My message");
And i have another function that add log into my List:
public static ObservableCollection<LogEntry> LogEntries { get; set; }
public static void AddLog(Level level, string message, string source)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
LogEntry logEntry = new LogEntry()
{
DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"),
Index = LogEntries.Count + 1,
Level = level,
Source = source,
Message = message
};
LogEntries.Add(logEntry);
}));
}
Usage:
LogHelper.AddLog(Level.Info, "My message", $"{ GetType().Name }\\{ MethodBase.GetCurrentMethod().Name }");
So now every time i want to add log i wrote it this way:
log.Info("My message");
LogHelper.AddLog(Level.Info, "My message", $"{ GetType().Name }\\{ MethodBase.GetCurrentMethod().Name }");
So i want to try a way to send to my generic function all the relevant data (Level level, string message, string source) in inside this function add also the log into my .txt file but my problem is that i cannot know how to do that because after the log i need to specify the Level for example:
log.Error...
Any suggestions ?
Related
I want to save a list of dialogue items. I made a script called dialogue item which is just one message, I made an array of that so it can be a conversation, and I made a list of that conversation so that I can have multiple conversations.
[SerializeField] public List<DialogueList> dialogue = new List<DialogueList();
So I made this variable of a class named DialogueList, that contains the dialogueitems.
[System.Serializable]
public class DialogueList
{
[SerializeField] public string convoName;
[SerializeField] public int dialogueID;
[SerializeField] public DialogueItem[] dialogues;
}
I want to save these conversations so that I can load them in specific languages in later stages. But for some reason my JSON file is empty when I try to save my variable named dialogue.
string jsonData = JsonUtility.ToJson(dialogue, true);
string _fullPath = "/caroline-dialogue" + ".json";
File.WriteAllText(Application.persistentDataPath + _fullPath, jsonData);
I tried using a different method, that actually works, but it can get really messy.
for (int i = 0; i < dialogue.Count; i++)
{
string jsonData = JsonUtility.ToJson(dialogue[i], true);
string _fullPath = "/caroline-dialogue-" + i + ".json";
File.WriteAllText(Application.persistentDataPath + _fullPath, jsonData);
}
My question is: What am I doing wrong? Am I forgetting something? My guess it that something is wrong with the variable named dialogue, since saving all the dialogueitems with a for loop works.
I hope I explained my problem well enough.
Serialization/deserialization of the arrays or lists is not supported using the JsonUtility. You would need to wrap the list in a serializable class:
[Serializable]
private class DialogueListWrapper
{
public List<DialogueList> objects;
}
In my app, I create a file with a comma-separated array by writing to an OutputStream. Then I want to be able to share this by e-mail so a user can get the data. This is the code I use to create the file:
public String getLogFile(String logName) {
String path = FileSystemStorage.getInstance().getAppHomePath() + "exp " + logName + ".csv";
Set<Long> keys;
OutputStream os = null;
try {
os = FileSystemStorage.getInstance().openOutputStream(path);
Hashtable<Long, Integer> log = (Hashtable<Long, Integer>) dataStorage
.readObject(logName);
keys = log.keySet();
for (Long key : keys) {
String outString = (key + "," + log.get(key) + "\n");
System.out.println(outString);
byte[] buffer = outString.getBytes();
os.write(buffer);
}
} catch (IOException e) {
AnalyticsService.sendCrashReport(e, "Error writing log", false);
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return path;
}
Then, I've created a button that when pressed passes the path of the file to share. I've tried to use MIME types such as "text/plain" and "text/comma-separated-values", but that causes errors. Here is the code executed when the button is pressed.
public void exportLog(String logName) {
String path = dataBuffer.getLogFile(logName);
EmailShare email = new EmailShare();
// email.share("Here is your log.", path, "text/plain");
email.share("Here is your log.", path, "text/comma-separated-values");
}
When pressed (in the simulator). I get this stack after selecting the dummy e-mail contact to send to:
java.lang.NullPointerException
at com.codename1.impl.javase.JavaSEPort.scale(JavaSEPort.java:3483)
at com.codename1.ui.Image.scale(Image.java:963)
at com.codename1.ui.Image.scaledImpl(Image.java:933)
at com.codename1.ui.Image.scaled(Image.java:898)
at com.codename1.impl.javase.JavaSEPort$60.save(JavaSEPort.java:6693)
at com.codename1.share.ShareForm.<init>(ShareForm.java:75)
at com.codename1.share.EmailShare$1$2$1.actionPerformed(EmailShare.java:102)
at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:455)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:358)
at com.codename1.ui.List.fireActionEvent(List.java:1532)
at com.codename1.ui.List.pointerReleasedImpl(List.java:2011)
at com.codename1.ui.List.pointerReleased(List.java:2021)
at com.codename1.ui.Form.pointerReleased(Form.java:2560)
at com.codename1.ui.Component.pointerReleased(Component.java:3108)
at com.codename1.ui.Display.handleEvent(Display.java:2017)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1065)
at com.codename1.ui.Display.mainEDTLoop(Display.java:994)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
The EmailShare class expects a path to an image file not an arbitrary file as its second argument so loading that fails.
The Message class is better suited for that indeed. You can also use the cloud send option which won't launch the native email app. E.g. the Log class includes that ability directly thru the Log.sendLog API.
It looks like the Messages class is better suited for this task, and should allow attachments, etc.
I read where someone was able to do this, but I'm having a hard time getting it to work.
Basically, I'm scheduling an HTTP callout to a page that has a controller that builds a CSV and emails it to a recipient.
The Scheduled class:
global class ReportExporter implements System.Schedulable {
global void execute(SchedulableContext sc) {
getmailReportOutput ex = new getmailReportOutput();
ex.exportCSV();
}
}
The getEmailReportOutput class:
public class getmailReportOutput{
public Static String strSessionID;
public getmailReportOutput() {
}
public void exportCSV() {
makeReportRequest();
}
#future (callout=true)
public Static void makeReportRequest() {
strHost ='c.cs4.visual.force.com';
strSessionID = UserInfo.getSessionId();
String requestUrl = 'https://' + strHost + '/apex/TestSendReport#';
HttpRequest req = new HttpRequest();
req.setEndpoint(requestUrl);
req.setMethod('GET');
req.setHeader('Cookie','sid=' + strSessionID );
String output = new Http().send(req).getBody();
System.debug('HTTP RESPONSE RETURNED: ' + output);
}
}
The getEmailReportOutput class does an HTTP Callout to a VF page: I make sure to send the sessionID with the request:
And the "TestSendReport" is just a simple callout to a controller:
<apex:page controller="Exporter" action="{!runrpt}">
</apex:page>
...And the controller is calling the report content:
public class Exporter {
public static Boolean isTest;
public static String strEmailAddr;
public void runrpt() {
executeRpt();
}
#future
public static void executeRpt() {
System.debug('CALLING REPORT EXPORTER...');
String ReportName__c = '00OP0000000Jp3N';
String strEmailAddr = 'myname#email.com';
ApexPages.PageReference report = new ApexPages.PageReference( '/' + RptName__c + '?csv=1');
Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
attachment.setFileName('report.csv');
attachment.setBody(report.getContent());
attachment.setContentType('text/csv');
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
message.setSubject('Report');
message.setPlainTextBody('The report is attached.');
message.setToAddresses( new String[] { strEmailAddr } );
Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
}
}
...Any ideas? The debug logs show all is well, but nothing is received. I know this is a wall of code, but it seems to be what people recommend to accomplish the task - I just can't see anything wrong.
I don't see anything obviously missing here :/
Just to be safe - getEmailReportOutput & getmailReportOutput are the same class (typo error in the post, not in your actual code)?
This looks like jumping a lot of hops, do I read it correctly that it's scheduled class -> REST callout -> VF page with action -> #future -> send an email? Geez, a lot can go wrong here ;) I've read somewhere that SF will keep some kind of reference counter and calling out to same instance might block you from using page.getContent...
Can you see the report body System.debug(report.getContent().toString());? Can you try saving this email as task for your own user or under a sample Account for example (setSaveAsActivity())?
As blatant plug as it is - I've used different path to solve similar requirement. Check out https://salesforce.stackexchange.com/questions/4303/scheduled-reports-as-attachment and see if you can get it to work?
In a WPF application, I have a 3rd party library that is publishing messages.
The messages are like :
public class DialectMessage
{
public string PathAndQuery { get; private set; }
public byte[] Body { get; private set; }
public DialectMessage(string pathAndQuery, byte[] body)
{
this.PathAndQuery = pathAndQuery;
this.Body = body;
}
}
And I setup the external message source from my app.cs file :
public partial class App : Application
{
static App()
{
MyComponent.MessageReceived += MessageReceived;
MyComponent.Start();
}
private static void MessageReceived(Message message)
{
//handle message
}
}
These messages can be publishing from multiple thread at a time, making possible to call the event handler multiple times at once.
I have a service object that have to parse the incoming messages. This service implements the following interface :
internal interface IDialectService
{
void Parse(Message message);
}
And I have a default static instance in my app.cs file :
private readonly static IDialectService g_DialectService = new DialectService();
In order to simplify the code of the parser, I would like to ensure only one message at a time is parsed.
I also want to avoid locking in my event handler, as I don't want to block the 3rd party object.
Because of this requirements, I cannot directly call g_DialectService.Parse from my message event handler
What is the correct way to ensure this single threaded execution?
My first though is to wrap my parsing operations in a Produce/Consumer pattern. In order to reach this goal, I've try the following :
Declare a BlockingCollection in my app.cs :
private readonly static BlockingCollection<Message> g_ParseOperations = new BlockingCollection<Message>();
Change the body of my event handler to add an operation :
private static void MessageReceived(Message message)
{
g_ParseOperations.Add(message);
}
Create a new thread that pump the collection from my app constructor :
static App()
{
MyComponent.MessageReceived += MessageReceived;
MyComponent.Start();
Task.Factory.StartNew(() =>
{
Message message;
while (g_ParseOperations.TryTake(out message))
{
g_DialectService.Parse(message);
}
});
}
However, this code does not seems to work. The service Parse method is never called.
Moreover, I'm not sure if this pattern will allow me to properly shutdown the application.
What have I to change in my code to ensure everything is working?
PS: I'm targeting .Net 4.5
[Edit] After some search, and the answer of ken2k, i can see that I was wrongly calling trytake in place of take.
My updated code is now :
private readonly static CancellationTokenSource g_ShutdownToken = new CancellationTokenSource();
private static void MessageReceived(Message message)
{
g_ParseOperations.Add(message, g_ShutdownToken.Token);
}
static App()
{
MyComponent.MessageReceived += MessageReceived;
MyComponent.Start();
Task.Factory.StartNew(() =>
{
while (!g_ShutdownToken.IsCancellationRequested)
{
var message = g_ParseOperations.Take(g_ShutdownToken.Token);
g_DialectService.Parse(message);
}
});
}
protected override void OnExit(ExitEventArgs e)
{
g_ShutdownToken.Cancel();
base.OnExit(e);
}
This code acts as expected. Messages are processed in the correct order. However, as soon I exit the application, I get a "CancelledException" on the Take method, even if I just test the IsCancellationRequested right before.
The documentation says about BlockingCollection.TryTake(out T item):
If the collection is empty, this method immediately returns false.
So basically your loop exits immediately. What you may want is to call the TryTake method with a timeout parameter instead, and exit your loop when a mustStop variable becomes true:
bool mustStop = false; // Must be set to true on somewhere else when you exit your program
...
while (!mustStop)
{
Message yourMessage;
// Waits 500ms if there's nothing in the collection. Avoid to consume 100% CPU
// for nothing in the while loop when the collection is empty.
if (yourCollection.TryTake(out yourMessage, 500))
{
// Parses yourMessage here
}
}
For your edited question: if you mean you received a OperationCanceledException, that's OK, it's exactly how methods that take a CancellationToken object as parameter must behave :) Just catch the exception and exit gracefully.
Our winforms application has long allowed a "print" option which basically uses RDLC.
The customer has requested that we add a feature allowing users to send the "printed" output via email.
Now, we know that an EMF file is created (in the TEMP folder) as a sort of hidden byproduct of our current printing process.
Seems to us we can simply grab this EMF file and attach it to a new email and the job is done.
Is this the best option?
Can we rely on an EMF file be opened by any Windows machine?
How we identify the EMF file? ... just seems to be named %TEMP%\DiaryGrid_1.emf currently. OK so DiaryGrid is the name of our RDLC file but the _1 gets added somewhere along the way.
I did it before. I did it exporting programatically the report to a pdf to a specific location, then we email the pdf file and delete it. I will try to find the code for you (Not in home now)
EDITED:
Sorry for the later. Now i'm in home and I will give you some code blocks that I think will give you some help to acomplish your task. I will include some comments to the code so you can understand some things that are specific in my project. This code are tested and are working well in my clients, but i'm sure that it can be improved. Please, let me know if you can improve this code ;)
First of all, we will export the report to pdf.
private string ExportReportToPDF(string reportName)
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = ReportViewer1.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
string filename = Path.Combine(Path.GetTempPath(), reportName);
using (var fs = new FileStream(filename, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
return filename;
}
Now, we need a class that control the Mail system. Every mail system has their own caracteristics, so maybe you will need modify this class. The behaviour of the class is simple. You only need to fill the properties, and call the Send method. In my case, windows don't let me delete the pdf file once I send it (Windows says the file is in use), so I program the file to be deleted in the next reboot. Take a look to the delete method. Please, note that the send method use a cutom class named MailConfig. This is a small class that has some config strings like Host, User Name, and Password. The mail will be send using this params.
public class Mail
{
public string Title { get; set; }
public string Text { get; set; }
public string From { get; set; }
public bool RequireAutentication { get; set; }
public bool DeleteFilesAfterSend { get; set; }
public List<string> To { get; set; }
public List<string> Cc { get; set; }
public List<string> Bcc { get; set; }
public List<string> AttachmentFiles { get; set; }
#region appi declarations
internal enum MoveFileFlags
{
MOVEFILE_REPLACE_EXISTING = 1,
MOVEFILE_COPY_ALLOWED = 2,
MOVEFILE_DELAY_UNTIL_REBOOT = 4,
MOVEFILE_WRITE_THROUGH = 8
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName,
string lpNewFileName,
MoveFileFlags dwFlags);
#endregion
public Mail()
{
To = new List<string>();
Cc = new List<string>();
Bcc = new List<string>();
AttachmentFiles = new List<string>();
From = MailConfig.Username;
}
public void Send()
{
var client = new SmtpClient
{
Host = MailConfig.Host,
EnableSsl = false,
};
if (RequireAutentication)
{
var credentials = new NetworkCredential(MailConfig.Username,
MailConfig.Password);
client.Credentials = credentials;
}
var message = new MailMessage
{
Sender = new MailAddress(From, From),
From = new MailAddress(From, From)
};
AddDestinataryToList(To, message.To);
AddDestinataryToList(Cc, message.CC);
AddDestinataryToList(Bcc, message.Bcc);
message.Subject = Title;
message.Body = Text;
message.IsBodyHtml = false;
message.Priority = MailPriority.High;
var attachments = AttachmentFiles.Select(file => new Attachment(file));
foreach (var attachment in attachments)
message.Attachments.Add(attachment);
client.Send(message);
if (DeleteFilesAfterSend)
AttachmentFiles.ForEach(DeleteFile);
}
private void AddDestinataryToList(IEnumerable<string> from,
ICollection<MailAddress> mailAddressCollection)
{
foreach (var destinatary in from)
mailAddressCollection.Add(new MailAddress(destinatary, destinatary));
}
private void DeleteFile(string filepath)
{
// this should delete the file in the next reboot, not now.
MoveFileEx(filepath, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
}
}
Now, you can create a form to ask for the destinataries, add some validation, etc, return to you an instance of the Mail class... or you can simply "hard code" the values and fill the class.
Here is the code that I use in a button to call this form, in my example it is named SendMailView.
private void BtnSendByMail_Click(object sender, EventArgs e)
{
SendMailView sendMailView = new SendMailView();
if (sendMailView.ShowDialog()== DialogResult.OK)
{
Mail mail = sendMailView.CurrentItem;
mail.AttachmentFiles.Add(ExportReportToPDF("Invoice.pdf"));
mail.DeleteFilesAfterSend = true;
mail.RequireAutentication = true;
mail.Send();
}
sendMailView.Dispose();
}
In this example senMailView.CurrentItem is the instance of the mail class. We simply need to call to the Send methis and the work is done.
This is the largest answer I ever wrote in SO... I hope it help you :D If you have any problem using it, call me. By the way, i'm not very proud of my english, so forgive me if the text has any mistake.