Insert Word Heading with Selection - c#

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;
}

Related

Im looking for a way to delete the bot command after the bot has posted in Discord code written in Discord.net

Below is The code after the embed message is posted I would like the bot to delete the command that it was give to post the embed. Also if anyone knows how to add a footer to this embed that would be awesome
if (raid == "gos")
{
if (day == "Sun")
{
var filename = "gos_Sun.png";
var embed = new EmbedBuilder()
{
Title = "Garden of Salvation",
Description = "```" + day + ", " + date + " # " + time + " " + ampm + " " + "\n" + description + "```" + description2,
ImageUrl = $"attachment://{filename}",
}.Build();
SentEmbed = await Context.Channel.SendFileAsync(filename, embed: embed);
await SentEmbed.AddReactionsAsync(myReactions);
}
}
var footer = new EmbedFooterBuilder().WithText("React Below");
if (raid == "gos")
{
if (day == "Sun")
{
var filename = "gos_Sun.png";
var embed = new EmbedBuilder()
{
Title = "Garden of Salvation",
Description = "```" + day + ", " + date + " # " + time + " " + ampm + " " + "\n" + description + "```" + description2,
ImageUrl = $"attachment://{filename}",
}.WithFooter(footer).Build();

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 ;)

Dynamic Breadcrumbs in ASP.NET

i have a problem concerning a breadcrumb navigation.
In my application i have a Start.aspx where i build a navigation menu for the next module (control1.ascx, control2.ascx, ...) which should be loaded after clicking.
This ascx contains a grid with some data rows and link buttons to load other ascx on the start page
This is the common way the app works.
Now i need to visualize which ascx is loaded in the breadcrumb
Maybe we can viaualize it like this:
Start.aspx -> control1.ascx -> control1_1.ascx
Right now the app would be on the lowest level and if i click on "control1.ascx" this control should be loaded again or if i choose Start.aspx the "Home" should be loaded.
protected override void Render(HtmlTextWriter output)
{
NavigationDataTable moduleNameList = new NavigationDataTable();
List<usp_GetNavigationElements_Result> ModuleList = moduleNameList.GetModulesList(1, LoggedInUser);
StringBuilder sbResult1 = new StringBuilder();
//string sbResult;
if (Page.Items["title"] != null)
{
string id = Page.Items["title"].ToString();
PageTitle = Page.Items["title"].ToString();
}
//------------------------------------------------------------------------------------------
var request = HttpContext.Current.Request;
System.Collections.Specialized.NameValueCollection coll;
// Load ServerVariable collection into NameValueCollection object.
coll = request.ServerVariables;
string serverName = request.ServerVariables["SERVER_NAME"];
//------------------------------------------------------------------------------------------
string strDomain = "";
if (serverName == "localhost")
{
//Lokal
strDomain = "localhost:49573";
}
else
{
//Intranet
strDomain = "i";
}
string strURL = "/Start.aspx";
string strDirs = "control1.ascx";
Separator3 = new Image();
Separator3.Height = 52;
Separator3.Width = 52;
ArrowSeparator = new Image();
ArrowSeparator.ImageUrl = "/img/mb_arrow_separator.png";
HomeSymbol = new Image();
HomeSymbol.ImageUrl = "/img/mb_home.png";
// Home-Navigation for Start
sbResult1.Append("<img src='" + HomeSymbol.ImageUrl + "'>");
sbResult1.Append("<a href='http://" + strDomain + "/modules" + strURL + "'style='text-decoration:none;'>" + RootName + " " + "</a>");
sbResult1.Append("<img src='" + ArrowSeparator.ImageUrl + "' hspace='10'>");
//-------------------------------------------------------------------------------------------------------------------------------
foreach (var item in ModuleList)
{
if (HttpContext.Current.Session["ModuleTitle"] != null)
{
if (item.ModuleTitle == HttpContext.Current.Session["ModuleTitle"].ToString() )
{
//sbResult1.Append("<a href='http://" + strDomain + "/modules" + strURL + "?" + item.ModuleName + "'>" + item.ModuleTitle + "</a>" + Separator);
Separator3.ImageUrl = "/img/" + HttpContext.Current.Session["ModuleTitle"].ToString() + ".png";
sbResult1.Append("<img src='" + Separator3.ImageUrl + " 'hspace='10'>");
sbResult1.Append(HttpContext.Current.Session["ModuleTitle"]).ToString();
}
}
}
if (!ModuleList.Contains(HttpContext.Current.Session["ModuleTitle"]))
{
if (HttpContext.Current.Session["ModuleTitle"] != null)
{
if (HttpContext.Current.Session["ModuleTitle"].ToString().Contains("_"))//|| HttpContext.Current.Session["ModuleSubTitle"] != null)
{
string[] std = HttpContext.Current.Session["ModuleTitle"].ToString().Split('_');
Separator3.ImageUrl = "/img/" + std[0] + ".png";
sbResult1.Append("<img src='" + Separator3.ImageUrl + "' hspace='10'>");
sbResult1.Append("<a href='http://" + strDomain + "/modules" + strURL + "?" + std[0] + "'style='text-decoration:none;'>" + std[0] + " " + "</a>");
sbResult1.Append("<img src='" + ArrowSeparator.ImageUrl + "' hspace='10'>");
sbResult1.Append("<img src='/img/Prozess.png' hspace='10'>");
sbResult1.Append(std[1]);
}
}
}
//-------------------------------------------------------------------------------------------------------------------------------
output.Write(sbResult1.ToString());
}
Do i have to make this Breadcrumb.cs and override Render() or is there a better way.
Greets DarkGecko
have you considered a SiteMapPath?
<asp:SiteMapPath ID="SiteMapPath1" Runat="server"></asp:SiteMapPath>
https://msdn.microsoft.com/en-us/library/x20z8c51.aspx

Problem with C# File IO in Winforms

I'm having issues with a C# Winforms file IO. The code complies just fine, but then it returns errors on execution.
The output code is here:
private void saveData()
{
string fullPath = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
StreamWriter writer = new StreamWriter(fullPath + textBox2.Text + ".txt");
writer.WriteLine(textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + "," + comboBox1.SelectedText + "," +
numericUpDown25.Value + "," + numericUpDown1.Value + "," + numericUpDown2.Value + "," + numericUpDown3.Value + "," + numericUpDown4.Value + "," +
numericUpDown5.Value + "," + numericUpDown6.Value + "," + numericUpDown7.Value + "," + numericUpDown8.Value + "," + numericUpDown9.Value + "," +
numericUpDown10.Value + "," + numericUpDown11.Value + "," + numericUpDown12.Value + "," + numericUpDown13.Value + "," + numericUpDown14.Value
+ "," + numericUpDown15.Value + "," + numericUpDown16.Value + "," + numericUpDown17.Value + "," + numericUpDown18.Value + "," +
numericUpDown19.Value + "," + numericUpDown20.Value + "," + numericUpDown21.Value + "," + numericUpDown22.Value);
writer.Close();
}
And the code to load the data is here:
private void loadData()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
List<string> myData = parseCSV(System.Convert.ToString(myStream));
textBox1.Text = myData[0];
textBox2.Text = myData[1];
textBox3.Text = myData[3];
textBox4.Text = myData[4];
comboBox1.SelectedText = myData[5];
numericUpDown25.Value = System.Convert.ToDecimal(myData[6]);
numericUpDown1.Value = System.Convert.ToDecimal(myData[7]);
numericUpDown2.Value = System.Convert.ToDecimal(myData[8]);
numericUpDown3.Value = System.Convert.ToDecimal(myData[9]);
numericUpDown4.Value = System.Convert.ToDecimal(myData[10]);
numericUpDown5.Value = System.Convert.ToDecimal(myData[11]);
numericUpDown6.Value = System.Convert.ToDecimal(myData[12]);
numericUpDown7.Value = System.Convert.ToDecimal(myData[13]);
numericUpDown8.Value = System.Convert.ToDecimal(myData[14]);
numericUpDown9.Value = System.Convert.ToDecimal(myData[15]);
numericUpDown10.Value = System.Convert.ToDecimal(myData[16]);
numericUpDown11.Value = System.Convert.ToDecimal(myData[17]);
numericUpDown12.Value = System.Convert.ToDecimal(myData[18]);
numericUpDown13.Value = System.Convert.ToDecimal(myData[19]);
numericUpDown14.Value = System.Convert.ToDecimal(myData[20]);
numericUpDown15.Value = System.Convert.ToDecimal(myData[21]);
numericUpDown16.Value = System.Convert.ToDecimal(myData[22]);
numericUpDown17.Value = System.Convert.ToDecimal(myData[23]);
numericUpDown18.Value = System.Convert.ToDecimal(myData[24]);
numericUpDown19.Value = System.Convert.ToDecimal(myData[25]);
numericUpDown20.Value = System.Convert.ToDecimal(myData[26]);
numericUpDown21.Value = System.Convert.ToDecimal(myData[27]);
numericUpDown22.Value = System.Convert.ToDecimal(myData[28]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
And that compiles just fine. But when I use it, I get the following errors:
"Could not find file "C:\Users\collmark\Documents\Visual Studio
2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Release\System.IO.Filestream".
"Error: Could not read file from disk. Original error: Index out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index."
Thanks
your save data seems to save 22 fields while the read expects 28.
I suspect the myData object does not contain the fields index you are trying to read, hence index out of range.
do yourself a favour when printing exception data don't limit yourself to the message but print the whole stack trace, it will tell you which line is faulty giving you a hint at the actual problem.
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.ToString());

C# two message boxes popping up - need to stop one

Both message boxes run after each other when no buttons are checked when only the following should show:
{ MessageBox.Show("Incomplete order. Please review.", "Incomplete Order."); }
How do I prevent the following messagebox from running when no buttons are checked?
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
"Code"
private void ConfirmOrder_Click(object sender, EventArgs e)
{
string pizzaChoice = "";
if (NeapolitanStyle.Checked == false & NEGreekStyle.Checked == false & ChicagoStyle.Checked == false & SmallPizza.Checked == false & MediumPizza.Checked == false & LargePizza.Checked == false)
{
MessageBox.Show("Incomplete order. Please review.", "Incomplete Order.");
}
if (SmallPizza.Checked)
{
pizzaChoice = pizzaChoice + SmallPizza.Text + " ";
}
if (MediumPizza.Checked)
{
pizzaChoice = pizzaChoice + MediumPizza.Text + " ";
}
if (LargePizza.Checked)
{
pizzaChoice = pizzaChoice + LargePizza.Text + " ";
}
if (NEGreekStyle.Checked)
{
pizzaChoice = pizzaChoice + NEGreekStyle.Text + " pizza" + "\n";
}
if (ChicagoStyle.Checked)
{
pizzaChoice = pizzaChoice + ChicagoStyle.Text + " pizza" + "\n";
}
if (NeapolitanStyle.Checked)
{
pizzaChoice = pizzaChoice + NeapolitanStyle.Text + " pizza" + "\n";
}
if (VeryHotChilis.Checked)
{
pizzaChoice = pizzaChoice + "& " + VeryHotChilis.Text + "." + "\n";
}
if (Onions.Checked)
{
pizzaChoice = pizzaChoice + "& " + Onions.Text + "." + "\n";
}
if (Mushrooms.Checked)
{
pizzaChoice = pizzaChoice + "& " + Mushrooms.Text + "." + "\n";
}
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
}
You will go a long way if you changed
if (SmallPizza.Checked)
to
else if (SmallPizza.Checked)
You can exit the function after the first error message appears. just place a return; after the messagebox
Slight variation to the else if suggestions by Frank Pytel. Rather than changing subsequent if's to else if's it needs to be an if else for the first validation check then the series of if statements within the else block as follows..
private void ConfirmOrder_Click(object sender, EventArgs e)
{
string pizzaChoice = "";
if (NeapolitanStyle.Checked == false & NEGreekStyle.Checked == false & ChicagoStyle.Checked == false & SmallPizza.Checked == false & MediumPizza.Checked == false & LargePizza.Checked == false)
{
MessageBox.Show("Incomplete order. Please review.", "Incomplete Order.");
}
else {
if (SmallPizza.Checked)
{
pizzaChoice = pizzaChoice + SmallPizza.Text + " ";
}
if (MediumPizza.Checked)
{
pizzaChoice = pizzaChoice + MediumPizza.Text + " ";
}
if (LargePizza.Checked)
{
pizzaChoice = pizzaChoice + LargePizza.Text + " ";
}
if (NEGreekStyle.Checked)
{
pizzaChoice = pizzaChoice + NEGreekStyle.Text + " pizza" + "\n";
}
if (ChicagoStyle.Checked)
{
pizzaChoice = pizzaChoice + ChicagoStyle.Text + " pizza" + "\n";
}
if (NeapolitanStyle.Checked)
{
pizzaChoice = pizzaChoice + NeapolitanStyle.Text + " pizza" + "\n";
}
if (VeryHotChilis.Checked)
{
pizzaChoice = pizzaChoice + "& " + VeryHotChilis.Text + "." + "\n";
}
if (Onions.Checked)
{
pizzaChoice = pizzaChoice + "& " + Onions.Text + "." + "\n";
}
if (Mushrooms.Checked)
{
pizzaChoice = pizzaChoice + "& " + Mushrooms.Text + "." + "\n";
}
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
}
}
You also can do like
if (MessageBox.Show("First MessageBox", "Test", MessageBoxButtons.OK) == System.Windows.Forms.DialogResult.OK) {
MessageBox.Show("Second messageBox", "Test", MessageBoxButtons.OK);
}
Okay entering return; did the trick. I tried putting the 'else if' in but both message boxes were still popping up.
Thanks guys. Most appreciated.

Categories

Resources