Is there any way to share a string in C#? The string is not written in this code, but I want to share it between the public partial class MainWindow : Window and class Program. I am trying to string "{0} ({1}) {2}", course.Name, course.Id, course.CourseState into string name Courses to put into a Label. Thank you
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;
namespace Azimuth_Home
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
System.Windows.Threading.DispatcherTimer Timer = new System.Windows.Threading.DispatcherTimer();
public string? MessagIn { get; set; }
public MainWindow()
{
InitializeComponent();
Timer.Tick += new EventHandler(Timer_Click);
Timer.Interval = new TimeSpan(0, 0, 1);
Timer.Start();
DataContext = this;
}
private void Timer_Click(object sender, EventArgs e)
{
DateTime d;
d = DateTime.Now;
ClockLabelHome.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelHome.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelHome.FontSize = 20;
ClockLabelNews.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelNews.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelNews.FontSize = 20;
ClockLabelWork.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelWork.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelWork.FontSize = 20;
ClockLabelChat.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelChat.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelChat.FontSize = 20;
if (d.Minute < 10)
{
ClockLabelHome.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelNews.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelWork.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelChat.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
}
if (d.Second < 10)
{
ClockLabelHome.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelNews.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelWork.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelChat.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(MessagIn);
}
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
MessageInput.Text = "You Entered: " + MessageInput.Text;
}
}
}
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/classroom.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { ClassroomService.Scope.ClassroomCoursesReadonly };
static string ApplicationName = "Classroom API .NET Quickstart";
private static void main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Classroom API service.
var service = new ClassroomService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define request parameters.
CoursesResource.ListRequest request = service.Courses.List();
request.PageSize = 10;
// List courses.
ListCoursesResponse response = request.Execute();
Console.WriteLine("Courses:");
if (response.Courses != null && response.Courses.Count > 0)
{
foreach (var course in response.Courses)
{
Console.WriteLine("{0} ({1}) {2}", course.Name, course.Id, course.CourseState);
}
}
else
{
Console.WriteLine("No courses found.");
}
Console.Read();
}
}
}
Thank you very much.
You apparently want the same combination of Name, Id and CourseState for every time you want to "print a course". The standard way to do that is to override the ToString method:
public class Course
{
//...
public override string ToString()
{
return String. Format("{0} ({1}) {2}", Name, Id, CourseState);
}
}
And if you then Console.WriteLine(course), that ToString method is called by default.
Related
I am trying to record a video of a user desktop when he logged in via RDP, the monitoring is based on the windows service onSessionChange event, due the nature of it then I am facing what is so called Session 0 isolation, so what I am looking for is how to switch to the logged in user in order to be able record his session?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
namespace RdpMonitoringService
{
struct RdpSession
{
public int sessionId;
public string userName;
public string ipAddress;
public string sessionDateTime;
public string recordFileName;
public Recorder sessionRecorder;
public string generateRecordFileName()
{
string dirName = "RecordedSessions";
string path = AppDomain.CurrentDomain.BaseDirectory + "\\" + dirName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\" + dirName + "\\" + userName + " - " + sessionDateTime + ".mp4";
return filepath;
}
public override string ToString()
{
return "SessionId: " + sessionId + ", userName: " + userName;
}
}
public partial class RdpMonitoringService : ServiceBase
{
RdpSession onRdpSession;
Dictionary<int, RdpSession> rdpSessionList;
public RdpMonitoringService()
{
InitializeComponent();
this.CanPauseAndContinue = true;
this.CanHandleSessionChangeEvent = true;
rdpSessionList = new Dictionary<int, RdpSession>();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at: ============ " + DateTime.Now);
WriteToFile("this.CanHandleSessionChangeEvent: " + this.CanHandleSessionChangeEvent);
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
protected override void OnSessionChange(SessionChangeDescription sessionChangeDescription)
{
try {
var userInfo = TermServicesManager.GetSessionInfo(Dns.GetHostEntry("").HostName, sessionChangeDescription.SessionId);
IPAddress ipAddress = new IPAddress(userInfo.ClientAddress.Address.Skip(2).Take(4).ToArray());
if (!rdpSessionList.ContainsKey(sessionChangeDescription.SessionId))
{
onRdpSession.sessionId = sessionChangeDescription.SessionId;
onRdpSession.ipAddress = ipAddress.ToString();
onRdpSession.userName = userInfo.UserName;
onRdpSession.sessionDateTime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");
onRdpSession.recordFileName = onRdpSession.generateRecordFileName();
//onRdpSession.sessionRecorder = Recorder.CreateRecorder();
//onRdpSession.sessionRecorder.Record(onRdpSession.generateRecordFileName());
rdpSessionList.Add(sessionChangeDescription.SessionId, onRdpSession);
}
else
{
onRdpSession = rdpSessionList[sessionChangeDescription.SessionId];
}
WriteToFile("SessionChange event");
switch (sessionChangeDescription.Reason)
{
case SessionChangeReason.SessionLogon:
case SessionChangeReason.RemoteConnect:
case SessionChangeReason.SessionUnlock:
WriteToFile("SessionChange" + DateTime.Now.ToLongTimeString() + ", SessionUnlock|RemoteConnect|SessionLogon [" + sessionChangeDescription.SessionId.ToString() + "]" + ", User: " + userInfo.UserName + ", Connect state: " + userInfo.ConnectState.ToString() + ", Client address: " + ipAddress.ToString() + ", user: " + userInfo.UserName + ", WinStationName: " + userInfo.WinStationName.ToString());
// Currently the bellow line crash the service because there is no desktop
// onRdpSession.sessionRecorder = new Recorder(new RecorderParams(onRdpSession.generateRecordFileName(), 60, SharpAvi.KnownFourCCs.Codecs.MotionJpeg, 70));
// Switch to the user desktop based on his session id and start recording
break;
case SessionChangeReason.SessionLock:
case SessionChangeReason.SessionLogoff:
case SessionChangeReason.RemoteDisconnect:
WriteToFile("SessionChange: " + onRdpSession.ToString() + ", " + DateTime.Now.ToLongTimeString() + " RemoteDisconnect|SessionLogoff|SessionLock [" + sessionChangeDescription.SessionId.ToString() + "]" + ", User: " + userInfo.UserName + ", Connect state: " + userInfo.ConnectState.ToString() + ", Client address: " + ipAddress.ToString() + ", user: " + userInfo.UserName + ", WinStationName: " + userInfo.WinStationName.ToString());
onRdpSession.sessionRecorder.Dispose();
break;
default:
break;
}
}
catch(Exception ex)
{
WriteToFile("SessionChange exception: " + ex.Message + " || " + sessionChangeDescription.SessionId.ToString() + " || " + onRdpSession.sessionId.ToString());
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
First, I apologize for the length of this, but it's all I knew when I started. Now I'm experimenting with the foreach, List<t> and TreeView classes to avoid repetition as recmomended by SO community.
The form will collect information via text boxes, allow attachments of files with file dialogs and collate all info into a neat HTML bodied email. We sell slabs.. and my original code looked a little like this:
private void PrepareReturnEmailTwoSlabs()
{
LoadSettings();
string Fname = Properties.Settings.Default.FabricatorName;
string Facc = Properties.Settings.Default.FabricatorAccountNo;
string Fadd1 = Properties.Settings.Default.FabricatorAddress1;
string Fadd2 = Properties.Settings.Default.FabricatorAddress2;
string Ftown = Properties.Settings.Default.FabricatorTown;
string Fcounty = Properties.Settings.Default.FabricatorCounty;
string Fpostcode = Properties.Settings.Default.FabricatorPostcode;
string Fphoneno = Properties.Settings.Default.FabricatorPhone;
string Femail = Properties.Settings.Default.FabricatorEmail;
string Fclient = Properties.Settings.Default.ClientManagerEmail;
string Fcentre = Properties.Settings.Default.CentreEmail;
string FQt = Properties.Settings.Default.QTEmail;
string Dateofinv = dateTimePicker1.Value.ToShortDateString();
string Inv = textBox13.Text;
string Material1 = textBox14.Text;
string Thick1 = comboBox8.SelectedValue.ToString();
string Batch1 = textBox44.Text;
string Reason1 = comboBox1.SelectedValue.ToString();
string Notes = textBox18.Text;
string Thick2 = comboBox7.SelectedValue.ToString();
string Material2 = textBox15.Text;
string Batch2 = textBox45.Text;
string Reason2 = comboBox2.SelectedValue.ToString();
if (Thick2 == null)
{
Thick2 = "not selected";
}
if (Material2 == null)
{
Material2 = "not selected ";
}
if (Batch2 == null)
{
Batch2 = "not selected ";
}
if (Reason2 == null)
{
Reason2 = "not selected ";
}
GenerateUniqueRefReturn();
//construct email
var message = new MimeMessage();
message.From.Add(new MailboxAddress("************", "***************"));
message.To.Add(new MailboxAddress("**********", "********"));
message.Subject = "Return" + " " + Returnid;
//different message bodies dependant on how many slabs are chosen
TextPart body2 = new TextPart("html")
{
Text = #"Please See Below Information" + "<br/>" +
"<h4>Return ID: " + " " + Returnid + "</h4>" + "<br/>" +
"<b>Fabricator Name:</b>" + " " + Fname + "<br/>" + Environment.NewLine +
"<b>Account Number:</b>" + " " + Facc + "<br/>" + Environment.NewLine +
"<b>Address Line 1:</b>" + " " + Fadd1 + "<br/>" + Environment.NewLine +
"<b>Address Line 2:</b>" + " " + Fadd2 + "<br/>" + Environment.NewLine +
"<b>Town:</b>" + " " + Ftown + "<br/> " + Environment.NewLine +
"<b>County:</b>" + " " + Fcounty + "<br/>" + Environment.NewLine +
"<b>Postcode:</b>" + " " + Fpostcode + "<br/>" + Environment.NewLine +
"<b>Phone:</b>" + " " + Fphoneno + "<br/>" + Environment.NewLine +
"<b>Email:</b>" + " " + Femail + "<br/>" + Environment.NewLine + "<br/>" +
"<br/>" +
"<b>Date Of Invoice: </b>" + " " + DoI + "<br/>" +
"<b>Invoice: </b>" + " " + Inv + "<br/>" +
"<b>Material Information:</b>" + "<br/>" +
//slab 1
"<b>Thickness: </b>" + " " + Thick1 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material1 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch1 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason1 + "<br/>" + "<br/>" +
//slab 2
"<b>Thickness: </b>" + " " + Thick2 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material2 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch2 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason2 + "<br/>" + "<br/>" +
"<br/>" +
"<b>Notes:" + " " + Notes
};
var builder = new BodyBuilder();
//check for return attachment and if found, assign attachment to message via bodybuilder
if (checkBox5.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
message.Body = builder.ToMessageBody();
}
if (checkBox7.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
message.Body = builder.ToMessageBody();
}
if (checkBox6.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
builder.Attachments.Add(ReturnAttachment3);
message.Body = builder.ToMessageBody();
}
else
{
message.Body = body2;
}
//Connection to SMTP and Criteria to Send
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.gmail.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate("***************#********.com", "*********");
client.Send(message);
client.Disconnect(true);
This code was repeated all the way up to five slabs. So now, I have a class:
{
public string Thickness { get; set; }
public string Material { get; set; }
public string Batch { get; set; }
public Slab(string Thick, string Mat, string Batchno)
{
Thickness = Thick;
Material = Mat;
Batch = Batchno;
}
}
A List that holds this object:
private void button1_Click(object sender, EventArgs e)
{
string t = comboBox1.SelectedValue.ToString();
string m = comboBox2.SelectedValue.ToString();
string b = textBox6.Text;
Slab S = new Slab(t, m, b);
allSlabs.Add(S);
PaintTree();
}
public void PaintTree()
{
int ParentIndex;
TreeSlabs.Nodes.Clear();
foreach (Slab slab in allSlabs)
{
TreeSlabs.BeginUpdate();
TreeSlabs.Nodes.Add("Slab" + " " + (allSlabs.IndexOf(slab) + 1).ToString());
ParentIndex = allSlabs.IndexOf(slab);
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Thickness: " + $"{slab.Thickness}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Material: " + $"{slab.Material}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Batch: " + $"{slab.Batch}");
TreeSlabs.EndUpdate();
}
}
Now i want to create a foreach.. that iterates through each node.. and collects the info from the parent and its children foreach node, and somehow instantiate new HTML methods for each node..
Foreach Node:
Compose HTML Line - new HTML
Slab 1:
Thickness:
Material
Batch
Slab 2:... etc
If theres 8 nodes, it generates 8 of those bodies. i can think of ways.. but i KNOW they're defintely not the correct ways to go about it based on what ive read and seen out there.
Many Thanks
You don't need to iterate through the tree and try to reclaim the data you put into it from the List of Slabs; it would be simpler to enumerate the List:
By the way, some other tips:
don't beginupdate/endupdate inside the loop, do it outside
the Add method that adds a node to a tree returns the node it added; you don't have to find it again by index, just capture it var justAdded = rootnode.Add("parent node"); and then add your thickness etc to it justAdded.Nodes.Add("thickness..."). The only add command that doesn't return the added mode is the one that takes a treenode type object; it doesn't need to return it because you already have it
consider adding a method to your slab to return some html, to simplify things
you can tidy all that html up with some string interpolation like you did with your $"{slab.thickness}" etc
This doesn't work (e.g.: https://www.w3schools.com/html/html5_draganddrop.asp)
var item = WebDriver.FindElement(By.XPath(#"//img[#src='img_w3slogo.gif']"), 30);
var container = WebDriver.FindElement(By.XPath(#"//div[#id='div2']"), 30);
var actions = new OpenQA.Selenium.Interactions.Actions(this.WebDriver);
actions.DragAndDrop(item, container).Build().Perform();
System.Threading.Thread.Sleep(3000);
If it helps....
public static void DragAndDrop(IWebElement element1, IWebElement element2)
{
WaitForElementEnabled(element1);
WaitForElementEnabled(element2);
var builder = new Actions(_webDriver);
var dragAndDrop = builder.ClickAndHold(element1).MoveToElement(element2).Release(element2).Build();
dragAndDrop.Perform();
}
public static void WaitForElementEnabled(IWebElement element)
{
try { _wait.Until(webDriver => element.Enabled); }
catch (StaleElementReferenceException) { if (!WaitForNotFoundElement_Enabled(element)) { LogFunctions.WriteError("Enabled - Stale Element Exception"); TakeScreenshot("elementNotFound"); throw; } }
}
The only way I was able to get this to work was by using the helper function located here: https://gist.github.com/druska/624501b7209a74040175 and executing javascript (Java example):
String simulateFunction = "function simulateDragDrop(sourceNode, destinationNode) {\n" +
" var EVENT_TYPES = {\n" +
" DRAG_END: 'dragend',\n" +
" DRAG_START: 'dragstart',\n" +
" DROP: 'drop'\n" +
" }\n" +
"\n" +
" function createCustomEvent(type) {\n" +
" var event = new CustomEvent(\"CustomEvent\")\n" +
" event.initCustomEvent(type, true, true, null)\n" +
" event.dataTransfer = {\n" +
" data: {\n" +
" },\n" +
" setData: function(type, val) {\n" +
" this.data[type] = val\n" +
" },\n" +
" getData: function(type) {\n" +
" return this.data[type]\n" +
" }\n" +
" }\n" +
" return event\n" +
" }\n" +
"\n" +
" function dispatchEvent(node, type, event) {\n" +
" if (node.dispatchEvent) {\n" +
" return node.dispatchEvent(event)\n" +
" }\n" +
" if (node.fireEvent) {\n" +
" return node.fireEvent(\"on\" + type, event)\n" +
" }\n" +
" }\n" +
"\n" +
" var event = createCustomEvent(EVENT_TYPES.DRAG_START)\n" +
" dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event)\n" +
"\n" +
" var dropEvent = createCustomEvent(EVENT_TYPES.DROP)\n" +
" dropEvent.dataTransfer = event.dataTransfer\n" +
" dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent)\n" +
"\n" +
" var dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END)\n" +
" dragEndEvent.dataTransfer = event.dataTransfer\n" +
" dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent)\n" +
"} var toDrag =document.getElementById('drag1'); var toDrop = document.getElementById('div2');";
((JavascriptExecutor)driver).executeScript(simulateFunction + "simulateDragDrop(toDrag, toDrop);");
Did anyone get this working without javascript executor?
I want to log Exception in case of error on network. I have made changes in global.asax file and generated log file in it. The code works fine on localhost but when I upload the dll of global.asax file on another server and change the web config according to network credentials similar to the localhost. In case of error the method doesnot seem to work nor the file is created to write the exception. Please help
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
try
{
DffUtility.AddCookie("verystart", "Very start of error");
Exception exc = Server.GetLastError();
Uri refurl = Request.UrlReferrer;
DffUtility.AddCookie("star655", "getting exception start");
string networkLogFolderPath = ConfigurationManager.AppSettings["Logpath"] + "\\" + DffUtility.WebSiteInfo.Folder + "\\" + DffUtility.WebSiteInfo.ThemeName + "\\";
DffUtility.AddCookie("path", networkLogFolderPath.ToString());
Network.connectToRemote(ConfigurationManager.AppSettings["Logpath"],
ConfigurationManager.AppSettings["networkusername"],
ConfigurationManager.AppSettings["pass"]);
string LogFolderPath = HttpContext.Current.Server.MapPath("~/ExceptionLogFiles/");
string filePath = networkLogFolderPath;
string stacktracemessage, stacktrace, Errormsg, extype, exurl;
stacktracemessage = (exc.InnerException).Message;
stacktrace = exc.ToString();
Errormsg = exc.GetType().Name.ToString();
extype = exc.GetType().ToString();
exurl = HttpContext.Current.Request.Url.ToString();
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
if (DffUtility.Country > 0)
{
if (DffUtility.RegionArea > 0)
{
if (DffUtility.RegionCity > 0)
{
if (DffUtility.ProdID > 0)
{
filePath = (filePath + "Product_" + DffUtility.ProdID + "_" + DffUtility.RegionCity + "_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
else
{
filePath = (filePath + "City_" + DffUtility.RegionCity + "_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
}
else
{
filePath = (filePath + "Area_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
}
else
{
filePath = (filePath + "Country_" + DffUtility.Country + ".txt");
DffUtility.AddCookie("start8", "After generating product file");
}
}
System.IO.File.Create(filePath).Dispose();
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
string logFormat = Environment.NewLine + " " + Environment.NewLine;
DffUtility.AddCookie("start6", "in");
string error = "Error Message:" + " " + Errormsg + logFormat + "Exception Type:" + " " + extype + logFormat + " Error Page Url:" + " " + exurl + logFormat + " StackTraceMessage:" + " " + stacktracemessage + logFormat + " StackTrace:" + " " + stacktrace + logFormat + " " + refurl + logFormat;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(error);
sw.WriteLine(logFormat);
sw.Flush();
sw.Close();
DffUtility.AddCookie("start4", " after getting generated log");
}
It's because your application runs under NETWORK SERVICE account (by default) and don't have permissions to write in ExceptionLogFiles folder. Add user Everyone in folder properties and grant him that permission
I have the following bits of code:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strMovie, strGenre, tmpGenre = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
string strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
foreach (Movie m in mList)
{
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">" : " <tr id=\"even\" style=\"page-break-inside:avoid\">";
catalog.WriteLine(strMovie);
foreach (string genre in m.Genres)
tmpGenre += ", " + genre;
try
{ strGenre = tmpGenre.Substring(2); }
catch (Exception)
{ strGenre = null; }
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
lineID = lineID == 0 ? 1 : 0;
}
catalog.WriteLine(" </table>\r\n" + " </body>\r\n" + "</html>");
catalog.Close();
}
public static void WritePDF(string cFile, string pdfFile)
{
// Sets up PDF to write to
EO.Pdf.HtmlToPdf.Options.PageSize = new SizeF(8.5f, 11f);
EO.Pdf.HtmlToPdf.Options.OutputArea = new RectangleF(0.5f, .25f, 7.5f, 10.25f);
HtmlToPdf.ConvertUrl(cFile, pdfFile);
}
My HTML file writes fine, but when it tried to convert the HTML file to PDF I get an exception that it times out.
I did a test previously, and had it convert the code (not the file) within the WriteHTML function and it worked great. I have confirmed that the cFile exists and is a valid file (created previously in WriteHTML). The path to pdfFile is valid, and the documentation does not state the file needs to already exist (.ConvertHTML did not need an existing file).
Only thing I can think of is that the catalog.html file isn't released and ready to read yet. I made sure I closed it in the WriteHTML function. How can I test that the file is ready to be read?
Tried setting .MaxLoadWaitTime = 120000 with no luck.
Any clues would be greatly appreciated!
After a battery of further testing, and scouring the EO support forums, it appears to be a limitation of the free version of EO. It seems to have difficulty with HTML files over 3MB.
It's a shame since the EO product is very good, but not unfortunately not worth $250 IMO.