make if statements look better - c#

How can I make this look better:
lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb"; // Total world size
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem)) // World itself
{
lblWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem) * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem + "_nether")) // Nether
{
lblNetherSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem + "_nether") * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem + "_the_end")) // The End
{
lblTheEndSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem + "_the_end") * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
It really looks like a mess and I can't seem to find any questions like this.

Well, there are several things that can help here:
A helper method (you're performing the same conversion from "path" to "size string" each time)
The conditional operator
Extracting a common local variable
Something like this:
// Note that _worldsDirectory must be an absolute path)
string prefix = Path.Combine(_worldsDirectory, selectedItem, selectedItem);
lblWorldSize.Text = GetDirectorySizeOrDefault(prefix, "Couldn't find world");
lblNetherSize.Text = GetDirectorySizeOrDefault(prefix + "_nether",
"Couldn't find _nether");
lblTheEndSize.Text = GetDirectorySizeOrDefault(prefix + "_the_end",
"Couldn't find _the_end");
...
static string GetDirectorySizeOrDefault(string directory, string defaultText)
{
return Directory.Exists(directory)
? GetDirectorySize(directory) * 1024 + " kb"
: defaultText;
}
Note that I've corrected the fact that your original code always assigns to lblWorldSize.Text on error - I assume that wasn't deliberate.

Please use Path.Combine for path creation, and not string concatenation like you do.

Is it possible that this method does more than 1 things? You could refactor this in a few other methods maybe.

I would suggest to use intention and variable substitution to enhance readability:
string dir = "_worldsDirectory + selectedItem";
string dirItemPath = #"_worldsDirectory + selectedItem \\" + selectedItem;
// Total World Size
lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb";
// World itself
if (Directory.Exists(dirItemPath)) {
lblWorldSize.Text = GetDirectorySize(dirItemPath) * 1024 + " kb";
} else {
lblWorldSize.Text = "Couldn't find world.";
}
// Nether
if (Directory.Exists(dirItemPath + "_nether")) {
lblNetherSize.Text = GetDirectorySize(dirItemPath + "_nether") * 1024 + " kb";
} else {
lblWorldSize.Text = "Couldn't find world.";
}
// The End
if (Directory.Exists(dirItemPath + "_the_end")) {
lblTheEndSize.Text = GetDirectorySize(dirItemPath + "_the_end") * 1024 + " kb";
} else {
lblWorldSize.Text = "Couldn't find world.";
}

lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb"; // Total world size
DoOnDirectoryExists(lblWorldSize, "");
DoOnDirectoryExists(lblNetherSize, "_nether");
DoOnDirectoryExists(lblWorldSize, "_the_end");
//Change the name to something more appropriate to your program, same with the LBL type and tempString
public bool DoOnDirectoryExists(LBL lbl, string suffix)
{
string tempString = _worldsDirectory + selectedItem + "\\" + selectedItem + suffix;
if (Directory.Exists(tempString))
{
lbl.Text = GetDirectorySize(tempString) * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
}
Best way to get rid of clutter and make your code more readable - remove code duplication.

Related

How can I do a header for a CSV using StringBuilder? C#

I will edit my post because I couldn't express very well.
I want to do this:
This
And I don't know how to do a unique header. I achieved this:
Achieved
but now I need to do the header. I will post more of my code here:
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < Shift)
return;
string header = "Time" + ";" + "Close[0]" + ";" + "ATR_7" + ";" + "VOL_7" + ";" + "LABEL";
string Label = "NULL";
if(Alcista)
{
if(Open[0] >= Open[Shift - 1] && Open[0]/Open[Shift - 1] >= 1.0001)
{
Label = "UP";
}
else
{
Label = "DOWN";
}
}
switch(Indicar2_Sesgo)
{
case Sesgo.Alcista:
StringBuilder csvcontent = new StringBuilder();
csvcontent.AppendLine(Convert.ToString(Times[0][0].TimeOfDay + ";" + Close[0] + ";" + ATR1[0] + ";" + VOL1[0] + ";" + Label));
string csvpath = "D:\\xyz.csv";
File.AppendAllText(csvpath, csvcontent.ToString());
break;
}
}
It is a little difficult to know what your output is supposed to look like, but if you are simply trying to write a header, your code may look something like this:
var csvPath = "D:\\xyz.csv";
var csvHeader = "Time;Close;Atr1;Atr2";
File.WriteAllText(csvPath, csvHeader + Environment.NewLine);
As others have mentioned you would be better off using a helper library (like csvhelper) and setting the delimiter to a semicolon.

Delete file which cannot delete because is used by another process

I know you are going to tell me that this question is stupid but I really cannot find a solution to delete my file.
In fact, I open a connection to an .add file (same style as SQL in a way) but afterwards I cannot delete it because it is used by another process which is the process of my application.
While doing some research on the internet I was able to find the solution to kill the process however if I do this it stops my application. Then I also found the GC collect but it doesn't work : /
There is my code :
try
{
string idClient = "parfilux";
string tableName = "ACT,ACF";
string dataSourceDBF = "C:/winbooks/data/parfilux";
string path = dataSourceDBF ;
string pathTemp = dataSourceDBF + "/CopyTempWebService/";
if (!Directory.Exists(pathTemp)) Directory.CreateDirectory(pathTemp);
string addFile = path + "/" + idClient + ".add";
File.Copy(addFile, pathTemp + idClient.ToUpper() + ".add");
File.Copy(addFile.Replace(".add", ".ai"), pathTemp + "/" + idClient.ToUpper() + ".ai");
File.Copy(addFile.Replace(".add", ".am"), pathTemp + "/" + idClient.ToUpper() + ".am");
tableName = tableName.Replace(" ", "");
string[] tables = tableName.Split(',');
string pathTable = null;
foreach (string tab in tables)
{
pathTable = path + "/" + idClient.ToUpper() + "_" + tab.ToUpper() + ".dbf";
File.Copy(pathTable, pathTemp + idClient.ToUpper() + "_" + tab.ToUpper() + ".dbf");
File.Copy(pathTable.Replace(".dbf", ".cdx"), pathTemp + idClient.ToUpper() + "_" + tab.ToUpper() + ".cdx");
}
AdsConnection dbfCo;
//dbfCo.Close();
dbfCo = new AdsConnection(#"data Source=" + dataSourceDBF + "/CopyTempWebService/" + idClient + ".add;User ID=admin;Password=;ServerType=Local;ReadOnly=true;pooling=true;TrimTrailingSpaces=true;ShowDeleted=TRUE;TableType=CDX;LockMode=COMPATIBLE");
dbfCo.Open();
//QueryDataDBF(tableName, idClient, false);
dbfCo.Close();
dbfCo.Dispose();
//Process process = Process.GetCurrentProcess();
//Console.WriteLine(process.MainModule);
//process.Kill();
//foreach(Process pro in process)
//{
// Console.WriteLine(pro);
// if(pro.ProcessName == pathTemp + idClient.ToUpper() + ".add")
// {
// pro.Kill();
// }
//}
//System.GC.Collect();
//System.GC.WaitForPendingFinalizers();
//File.Delete(pathTemp + idClient.ToUpper() + ".add");
Directory.Delete(dataSourceDBF + "/CopyTempWebService", true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I open a connection to my .add with the Advantage Data Provider library.
Do you have any idea to fix this problem ? thank you in advance ;)

Is there any to shorten the code that needs variables?

I've always wondered, are there ways to shorten this kind of code?
private void Update01()
{
item01.text = item01n + "\nCost: " + Math.Round(cost01, 2) + "\nYou have: " + n01;
}
private void Update02()
{
item02.text = item02n + "\nCost: " + Math.Round(cost02, 2) + "\nYou have: " + n02;
}
private void Update03()
{
item03.text = item03n + "\nCost: " + Math.Round(cost03, 2) + "\nYou have: " + n03;
}
.
.
.
Thanks for the help.
As 12seconds said, just return a string and pass in 3 variables:
private string GetUpdate(item, cost, n)
{
return item + "\nCost: " + Math.Round(cost, 2) + "\nYou have: " + n;
}
And then simply do:
item01.text = GetUpdate(item01n, cost01, n01);
item02.text = GetUpdate(item02n, cost02, n02);
item03.text = GetUpdate(item03n, cost03, n03);

Insert Word Heading with Selection

I try to insert a word heading at a specific position but it is always added at the end of the document. Where is my mistake?:
foreach (Publish p in tempstructure)
{
if (p.element_type_id == 3)
{
Word.Paragraph par = selection.Paragraphs.Add();
par.Range.Text = "test";
par.Range.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
par.Range.InsertParagraphAfter();
selection.TypeParagraph();
}
else
{
if (File.Exists(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx"))
{
selection.InsertFile(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx");
selection = word.Selection;
}
else
{
selection.TypeText("Missing file: " + p.filename + "_" + language + ".docx");
selection.TypeParagraph();
}
}
selection = word.Selection;
}
Best regards ...
The simple solution is:
foreach (Publish p in tempstructure)
{
if (p.element_type_id == 3)
{
selection.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
selection.TypeText(p.name);
selection.TypeParagraph();
}
else
{
if (File.Exists(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx"))
{
selection.InsertFile(#Properties.Settings.Default.documentsPath + p.filename + "_" + language + ".docx");
selection = word.Selection;
}
else
{
selection.TypeText("Missing file: " + p.filename + "_" + language + ".docx");
selection.TypeParagraph();
}
}
selection = word.Selection;
}

How to convert a HTML File to PDF using WkHTMLToSharp / wkhtmltopdf with Images in C#

I am generating HTML files on the fly, and I would like to create a PDF from the final file. I am using the following to generate the HTML file:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strHeader, strMovie, strGenre, tmpGenre = null;
string strPDF = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
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);
strPDF = strHeader;
foreach (Movie m in mList)
{
tmpGenre = null;
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">\r\n" : " <tr id=\"even\" style=\"page-break-inside:avoid\">\r\n";
catalog.WriteLine(strMovie);
strPDF += strMovie;
foreach (string genre in m.Genres)
tmpGenre += ", " + genre + "";
strGenre = tmpGenre != null ? tmpGenre.Substring(2) : 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);
strPDF += strMovie;
lineID = lineID == 0 ? 1 : 0;
}
string closingHTML = " </table>\r\n" + " </body>\r\n" + "</html>";
catalog.WriteLine(closingHTML);
strPDF += closingHTML;
WritePDF(strPDF, cFile + ".PDF");
catalog.Close();
}
Once completed, I want to call the following function to generate the PDF file:
public static void WritePDF(string cFile, string pdfFile)
{
WkHtmlToPdfConverter w = new WkHtmlToPdfConverter();
byte[] strHTML = w.Convert(cFile);
File.WriteAllBytes(pdfFile, strHTML);
w.Dispose();
}
I've discovered that the .Convert function will convert HTML code to PDF, not a file. Secondly, when I pass in the HTML code directly, the images are not appearing in the PDF. I know there is an issue with .GIF files, but these are all .JPG files.
I've read a lot about how good wkhtmltopdf is, and the guy who wrote WkHTMLToSharp posted his project all over SO, but I've been disappointed by the lack of documentation for it.
I WANT to be able to pass in a file to convert, change the margins (I know this is possible, I just need to figure out the correct settings), have it convert images correctly, and most importantly, to not break up my items across multiple pages (support "page-break-inside:avoid" or something similar).
I'd love to see how others are using this!
I have coded an example about how to create a PDF from HTML. I just updated it to also print images.
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PdfGeneration
(In my blog post I explain most of the project https://hmadrigal.wordpress.com/2015/10/16/creating-pdf-reports-from-html-using-dotliquid-markup-for-templates-and-wkhtmltoxsharp-for-printing-pdf/ )
Pretty much you have two options:
1: Using file:// and the fullpath to the file.
<img alt="profile" src="{{ employee.PorfileFileName | Prepend: "Assets\ProfileImage\" | ToLocalPath }}" />
2: Using URL Data (https://en.wikipedia.org/wiki/Data_URI_scheme)
<img alt="profile" src="data:image/png;base64,{{ employee.PorfileFileName | Prepend: "Assets\ProfileImage\" | ToLocalPath | ToBase64 }}" />
Cheers,
Herb
Use WkHtmlToXSharp.
Download the latest DLL from Github
public static string ConvertHTMLtoPDF(string htmlFullPath, string pageSize, string orientation)
{
string pdfUrl = htmlFullPath.Replace(".html", ".pdf");
try
{
#region USING WkHtmlToXSharp.dll
//IHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
IHtmlToPdfConverter converter = new MultiplexingConverter();
converter.GlobalSettings.Margin.Top = "0cm";
converter.GlobalSettings.Margin.Bottom = "0cm";
converter.GlobalSettings.Margin.Left = "0cm";
converter.GlobalSettings.Margin.Right = "0cm";
converter.GlobalSettings.Orientation = (PdfOrientation)Enum.Parse(typeof(PdfOrientation), orientation);
if (!string.IsNullOrEmpty(pageSize))
converter.GlobalSettings.Size.PageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pageSize);
converter.ObjectSettings.Page = htmlFullPath;
converter.ObjectSettings.Web.EnablePlugins = true;
converter.ObjectSettings.Web.EnableJavascript = true;
converter.ObjectSettings.Web.Background = true;
converter.ObjectSettings.Web.LoadImages = true;
converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
Byte[] bufferPDF = converter.Convert();
System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);
converter.Dispose();
#endregion
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return pdfUrl;
}
You can use Spire.Pdf to do so.
This component could convert html to pdf.
PdfDocument pdfdoc = new PdfDocument();
pdfdoc.LoadFromHTML(fileFullName, true, true, true);
//String url = "http://www.e-iceblue.com/";
//pdfdoc.LoadFromHTML(url, false, true, true);
pdfdoc.SaveToFile("FromHTML.pdf");
We're also using wkhtmltopdf and are able to render images correctly. However, by default the rendering of images is disabled.
You have to specify those options on your converter instance:
var wk = _GetConverter()
wk.GlobalSettings.Margin.Top = "20mm";
wk.GlobalSettings.Margin.Bottom = "10mm";
wk.GlobalSettings.Margin.Left = "10mm";
wk.GlobalSettings.Margin.Right = "10mm";
wk.GlobalSettings.Size.PaperSize = PdfPaperSize.A4;
wk.ObjectSettings.Web.PrintMediaType = true;
wk.ObjectSettings.Web.LoadImages = true;
wk.ObjectSettings.Web.EnablePlugins = false;
wk.ObjectSettings.Web.EnableJavascript = true;
result = wk.Convert(htmlContent);

Categories

Resources