Websocket sharp log file output - c#

I'm using Websocket sharp (https://github.com/sta/websocket-sharp) for a console program, how do I output all debug/trace information that are displayed on the console to a text file?
For example:
using (var ws = new WebSocket(WebAddr))
{
ws.Log.Level = LogLevel.Debug;
ws.OnOpen += (ss, ee) =>
{
System.IO.File.WriteAllText(#"C:\log.txt", ws.Log.ToString());
};
But the output for this is "WebSocketSharp.Logger".
I would expecting something like this:
Screenshot

Set the property File:
using (var ws = new WebSocket(WebAddr))
{
ws.Log.Level = LogLevel.Debug;
ws.Log.File = #"C:\log.txt";
}

You will need to provide alot more information (which data?, how often? etc.) but you can use the System.IO.File methods for easy writing to a file;
// To create a new file
System.IO.File.WriteAllText(#"FileNameToWriteTo.txt", aString);
System.IO.File.WriteAllLines(#"FileNameToWriteTo.txt", listOfStrings);
// To add to the end of an existing file
System.IO.File.AppendAllText(#"FileNameToWriteTo.txt", aString);
System.IO.File.AppendAllLines(#"FileNameToWriteTo.txt", listOfStrings);

Related

XmlMap.Import without using Interopt

I've defined an Excel template using Xml mappings that will generate the Excel report based on the Xml that I import.
I need to generate this report on the server so I can't use Microsoft Interopt. How can I do the following (C#) with an open source library?
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(Path.Combine(Directory.GetCurrentDirectory(), "TestTemplate.xlsx"));
var result = workbook.XmlMaps[1].Import(Path.Combine(Directory.GetCurrentDirectory(), "TestData.xml"), true);
workbook.Save();
workbook.Close();
excel.Workbooks.Close();
This allows me to do formatting of the Excel sheet on my own PC (with Office 365) and then save the template and publish with the project and just update the XML data and save as a new report.
I ended up going with ClosedXML's reporting plugin that has a variable replacement function that ended up working just as well.
The example from their website:
protected void Report()
{
const string outputFile = #".\Output\report.xlsx";
var template = new XLTemplate(#".\Templates\report.xlsx");
using (var db = new DbDemos())
{
var cust = db.customers.LoadWith(c => c.Orders).First();
template.AddVariable(cust);
template.Generate();
}
template.SaveAs(outputFile);
//Show report
Process.Start(new ProcessStartInfo(outputFile) { UseShellExecute = true });
}

Is there a programmatically way for Excels "Protect Workbook"?

I'm moving some legacy code using Office Interop libraries to epplus, one thing I can't figure out is how to set a Workbook to ask the user on open the file to open it read only. Like if the user clicks on File -> Info -> Protect Workbook -> Always Open Read-Only
I've tried to set the DocSecurity property stated here (https://sno.phy.queensu.ca/~phil/exiftool/TagNames/OOXML.html), but to no success. excelWorkBook.Properties.SetExtendedPropertyValue("DocSecurity", "2");
I also tried to add the following node to the workbookxml <fileSharing readOnlyRecommended="1"/>
I even tried to compare the unzipped excel files protected, non protected, but there were too many changes.
It can be done but it is not really straightforward. Setting DocSecurity can be done by generating the Workbook.Properties object. But that is only half of it. You also need to set the flag inside the Workbook itself which can only be done via XML manipulation.
[TestMethod]
public void DocSecurity_Test()
{
//https://stackoverflow.com/questions/58335624/is-there-a-programmatically-way-for-excels-protect-workbook
var fi = new FileInfo(#"c:\temp\DocSecurity_Test.xlsx");
if (fi.Exists)
fi.Delete();
using (var package = new ExcelPackage(fi))
{
//Create a simple workbook
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].Value = "Test";
//Extended properties is a singleton so reference it to generate the app.xml file
//needed and add the security setting
var extProps = workbook.Properties;
extProps.SetExtendedPropertyValue("DocSecurity", "2");
//Also need to tell the workbook itself but can only do it via XML
var xml = workbook.WorkbookXml;
var att = xml.CreateAttribute("readOnlyRecommended");
att.Value = "1";
const string mainNs = #"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var fileSharing = xml.CreateElement("fileSharing", mainNs);
fileSharing.Attributes.Append(att);
//Element must be at the beginning of the tree
xml.DocumentElement.PrependChild(fileSharing);
package.Save();
}
}
Which will look like this:

Editing record in delimited file using FileHelper

I have a simple Delimited log file. I`m using FileHelper library to parse the file using the following code:
LogLine record;
FileHelperAsyncEngine<LogLines> engine = new FileHelperAsyncEngine<LogLines>();
engine.BeginReadFile(#"C:\logs\Log.log");
while (engine.ReadNext() != null)
{
record = engine.LastRecord;
//record.Reported = true; <---I want to be able to edit this!
// Your Code Here
}
Is there any way I can edit this record?
Will something like this be fine for you?
This will modify second element of that file; could not find method similar to seek for that class.
public static void WriteExample()
{
FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));
// to Read use:
SampleType[] res = engine.ReadFile("source.txt") as SampleType[];
res[1].Field1 = "test";
res[1].Field2 = 9;
// to Write use:
engine.WriteFile("source2.txt", res);
}

Storing RTSP to a file location

I am able to stream an rtsp on windows 7 64 bit machine through C# Winform application. This is the library i used - VLCDotNet and here is the code sample to play the RTSP stream:
LocationMedia media = new LocationMedia(#"rtsp://192.168.137.73:554/live.sdp");
vlcControl1.Media = media;
vlcControl1.Play();
I would like to store the streams to a file in my PC on a button click and stop the same with another button. How do i achieve this?
Here is the code:
Vlc.DotNet.Core.Medias.MediaBase media1
= new Vlc.DotNet.Core.Medias.PathMedia("rtsp://192.168.137.73:554/live.sdp");
media.AddOption(":sout=#transcode{vcodec=theo,vb=800,
scale=1,acodec=flac,ab=128,channels=2,samplerate=44100}:std{access=file,mux=ogg,
dst=D:\\123.mp4}");
VlcControl control = new VlcControl();
control.Media = media;
control.Play();
VlcContext.StartupOptions.IgnoreConfig = true;
VlcContext.StartupOptions.LogOptions.LogInFile = true;
VlcContext.StartupOptions.LogOptions.ShowLoggerConsole = true;
VlcContext.StartupOptions.LogOptions.Verbosity = VlcLogVerbosities.Debug;
// Disable showing the movie file name as an overlay
// VlcContext.StartupOptions.AddOption("--no-video-title-show");
// VlcContext.StartupOptions.AddOption("--no-audio");
VlcContext.StartupOptions.AddOption("--rtsp-tcp"); //this line was important to make this work
As of Vlc.DotNet.Core 2.1.62, The way to do this is use the extra opts param of the .Play on the vlc control.
var opts = new string[] { #":sout=file/ogg:C:\video.ogg" };
vlc.MediaPlayer.Play(new Uri(videoURI), opts);
`

Can't upload to a specific folder getting 503 error

I am trying to upload a simple text file to a specific folder in google documents but with no luck.
FileStream fileStream = new FileStream(#"c:\test.txt", System.IO.FileMode.Open);
DocumentEntry lastUploadEntry =
globalData.service.UploadDocument("c:\\test.txt", null);
string feed =
"https://docs.google.com/feeds/upload/create-session/default/private/full/folder%folder:0B2dzFB6YvN-kYTRlNmNhYjEtMTVmNC00ZThkLThiMjQtMzFhZmMzOGE2ZWU1/contents/";
var result =
globalData.service.Insert(new Uri(feed), fileStream, "application/pdf", "test");
I get an error saying
"The remote server returned an error: (503) Server Unavailable."
I am suspecting that the destination folders uri is wrong but i can't figure out the correct one.
There's a complete sample at https://developers.google.com/google-apps/documents-list/#uploading_a_new_document_or_file_with_both_metadata_and_content that uses the resumable upload component:
using System;
using Google.GData.Client;
using Google.GData.Client.ResumableUpload;
using Google.GData.Documents;
namespace MyDocumentsListIntegration
{
class Program
{
static void Main(string[] args)
{
DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
// TODO: Instantiate an Authenticator object according to your authentication
// mechanism (e.g. OAuth2Authenticator).
// Authenticator authenticator = ...
// Instantiate a DocumentEntry object to be inserted.
DocumentEntry entry = new DocumentEntry();
// Set the document title
entry.Title.Text = "Legal Contract";
// Set the media source
entry.MediaSource = new MediaFileSource("c:\\contract.txt", "text/plain");
// Define the resumable upload link
Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri);
link.Rel = ResumableUploader.CreateMediaRelation;
entry.Links.Add(link);
// Set the service to be used to parse the returned entry
entry.Service = service;
// Instantiate the ResumableUploader component.
ResumableUploader uploader = new ResumableUploader();
// Set the handlers for the completion and progress events
uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnDone);
uploader.AsyncOperationProgress += new AsyncOperationProgressEventHandler(OnProgress);
// Start the upload process
uploader.InsertAsync(authenticator, entry, new object());
}
static void OnDone(object sender, AsyncOperationCompletedEventArgs e) {
DocumentEntry entry = e.Entry as DocumentEntry;
}
static void OnProgress(object sender, AsyncOperationProgressEventArgs e) {
int percentage = e.ProgressPercentage;
}
}
}
Just follow the article Google Apps Platform Uploading documents
Also check out Google Documents List API version 3.0
Uri should be something similar to below:
string feed = #"https://developers.google.com/google-apps/documents-list/#getting_a_resource_entry_again";
//it may not be exact, just check and read from the links
Try this uri:
"https://docs.google.com/feeds/default/private/full/folder%3A" + fRid + "/contents"
//fRid is the Resource Id of the folder.. in your case: 0B2dzFB6YvN-kYTRlNmNhYjEtMTVmNC00ZThkLThiMjQtMzFhZmMzOGE2ZWU1
Also I guess your URI is giving this error because you are using folder resource ID as - folder:resourceID
Try removing folder: and use only RID
Code to cutout "folder:" -
int ridIndex = dRid.IndexOf(":");
Rid = Rid.Substring(ridIndex + 1);

Categories