C# Add item to ObjectListView - c#

My program extracts Windows Updates, detects the version numbers and logs them to columns (KB, Version) in a list view, but I'm trying to change this to an ObjectListView so I can sort the columns. I can't for the life of me work out how to write the results to an ObjectListView and nothing I try seems to work. Here's my current code:
foreach (string file in msu)
{
string KB = GetKBNumber(file);
Expand.MSU(file, TempDirectory + "\\" + KB);
List<string> versions = GetVersionNumbers(TempDirectory + "\\" + KB);
foreach (string version in versions)
{
ListViewItem itm = new ListViewItem(new[] { KB, version });
olvOutput.Items.Add(itm);
}
PerformStep();
}
But it just writes blank data to the control. What am I doing wrong? Thanks in advance.
Edit: Here's the olvOutput designer code:
//
// olvOutput
//
this.olvOutput.AllColumns.Add(this.olvKBNumber);
this.olvOutput.AllColumns.Add(this.olvVersion);
this.olvOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.olvOutput.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvKBNumber,
this.olvVersion});
this.olvOutput.Location = new System.Drawing.Point(18, 12);
this.olvOutput.Name = "olvOutput";
this.olvOutput.ShowGroups = false;
this.olvOutput.Size = new System.Drawing.Size(571, 193);
this.olvOutput.TabIndex = 8;
this.olvOutput.UseAlternatingBackColors = true;
this.olvOutput.UseCompatibleStateImageBehavior = false;
this.olvOutput.View = System.Windows.Forms.View.Details;
//
// olvKBNumber
//
this.olvKBNumber.AspectName = "";
this.olvKBNumber.CellPadding = null;
this.olvKBNumber.MaximumWidth = 100;
this.olvKBNumber.MinimumWidth = 100;
this.olvKBNumber.Text = "KB Number";
this.olvKBNumber.Width = 100;
//
// olvVersion
//
this.olvVersion.AspectName = "";
this.olvVersion.CellPadding = null;
this.olvVersion.Text = "Version";
this.olvVersion.Width = 113;

Modify the first of your snippets as:
foreach (string file in msu)
{
string KB = GetKBNumber(file);
Expand.MSU(file, TempDirectory + "\\" + KB);
List<string> versions = GetVersionNumbers(TempDirectory + "\\" + KB);
foreach (string version in versions)
{
olvOutput.AddObject(new { kbAspectName = KB, versionAspectName = version });
}
PerformStep();
}
... and modify the second code snippet as:
//
// olvKBNumber
//
this.olvKBNumber.AspectName = "kbAspectName";
// ...
//
// olvVersion
//
this.olvVersion.AspectName = "versionAspectName";
Disclaimer:
never worked with ObjectListView before so I am not saying this is the best way to achieve what you want.

Related

How to I set a string variable that has CR\LF's into a Winform textbox?

I have a Winforms textbox set to AcceptReturns = true, Scrollbars = vertical, Multiline = true.
I construct a string called note by looping thru a datatable, putting the value into note with: note = note plus a "\n\n".
When I view the string with the text visualizer, it shows the CR\LF's correctly but after the command: remarks.text = note, the textbox DOES NOT have the CR\LF's.
How do I get the CR\LF's to be respected?
int x = 0;
string note = "";
command = null;
DataTable dtnew = new DataTable();
foreach (string rcd in app.feecd) // app.feecd is an array established earlier in code
{
command = GetConnectedClass.newsqlconnection("SELECT NoteDesc from dbo.inspnote where NoteCode = #selcode");
command.Parameters.AddWithValue("#selcode", rcd);
dtnew.Load(command.ExecuteReader());
note = note + dtnew.Rows[x].Field<string>("NoteDesc") + "\n\n";
command = null;
x = x + 1;
}
if (remarks.Text == "")
{ remarks.Text = note; } // note has CR\LF but remarks.Text NO CR\LF ????
else { remarks.Text = remarks.Text + "\n\n" + note; }

Cannot Write Multiple Paragraph in Aspose

I have an issue when I try to write multiple paragraphs in existing Shape. Only the first paragraph is written. I debug the code and I found that the Shape object as all the paragraphs I want. The problem is when I write to file I found only the first one. I share with you the project code.
class Program
{
public static void Run()
{
string dataDir = ConfigurationManager.AppSettings["directoryToSave"];
string srcDir = ConfigurationManager.AppSettings["Source"];
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string file = Path.Combine(appData, srcDir);
using (Presentation presentation = new Presentation(srcDir))
{
IMasterLayoutSlideCollection layoutSlides = presentation.Masters[0].LayoutSlides;
ILayoutSlide layoutSlide = null;
foreach (ILayoutSlide titleAndObjectLayoutSlide in layoutSlides)
{
if (titleAndObjectLayoutSlide.Name == "TITRE_CONTENU")
{
layoutSlide = titleAndObjectLayoutSlide;
break;
}
}
var contenu = File.ReadAllText(#"E:\DemosProject\PF_GEN\PF_GEN\Source\contenu.txt", Encoding.UTF8);
IAutoShape contenuShape = (IAutoShape)layoutSlide.Shapes.SingleOrDefault(r => r.Name.Equals("contenu"));
ITextFrame txt = ((IAutoShape)contenuShape).TextFrame;
txt.Paragraphs.Clear();
string[] lines = contenu.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Where(str => !String.IsNullOrEmpty(str)).ToArray();
for (int i = 0; i < lines.Length; i++)
{
var portion = new Portion();
portion.Text = lines[i];
var paragraphe = new Paragraph();
paragraphe.Portions.Add(portion);
txt.Paragraphs.Add(paragraphe);
}
presentation.Slides.InsertEmptySlide(0, layoutSlide);
presentation.Save(dataDir + "AddLayoutSlides_out.pptx", SaveFormat.Pptx);
}
}
static void Main(string[] args)
{
try
{
var path = ConfigurationManager.AppSettings["sourceAsposeLicensePath"];
License license = new License();
license.SetLicense(path);
Run();
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex.Message);
}
finally
{
Console.WriteLine("Terminated");
Console.ReadKey();
}
}
}
You can find the ppt file (source file) in the attachement file. (https://gofile.io/?c=JpBDS8 1)
Is there any thing missing in my code?
Thanks
I have observed your requirements and suggest you to please try using following sample code on your end. In your sample code, you are adding different paragraphs to a shape inside LayoutSlide and then adding a slide using that LayoutSlide to contain the desired shape. This approach is not correct. You actually need to first add slide based on LayoutSlide and then add text to that shape as per your requirements. The following code will be helpful to you.
public static void RunParaText()
{
string path = #"C:\Aspose Data\";
string dataDir = path;
string srcDir = path + "Master.pptx";
//string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
//string file = Path.Combine(appData, srcDir);
using (Presentation presentation = new Presentation(srcDir))
{
IMasterLayoutSlideCollection layoutSlides = presentation.Masters[0].LayoutSlides;
ILayoutSlide layoutSlide = null;
foreach (ILayoutSlide titleAndObjectLayoutSlide in layoutSlides)
{
if (titleAndObjectLayoutSlide.Name == "TITRE_CONTENU")
{
layoutSlide = titleAndObjectLayoutSlide;
break;
}
}
var contenu = File.ReadAllText(dataDir+"contenu.txt", Encoding.UTF8);
var slide=presentation.Slides.InsertEmptySlide(0, layoutSlide);
IAutoShape contenuShape = (IAutoShape)slide.Shapes.SingleOrDefault(r => r.Name.Equals("contenu"));
//IAutoShape contenuShape = (IAutoShape)layoutSlide.Shapes.SingleOrDefault(r => r.Name.Equals("contenu"));
ITextFrame txt = ((IAutoShape)contenuShape).TextFrame;
txt.Paragraphs.Clear();
string[] lines = contenu.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Where(str => !String.IsNullOrEmpty(str)).ToArray();
for (int i = 0; i < lines.Length; i++)
{
var portion = new Portion();
portion.Text = lines[i];
var paragraphe = new Paragraph();
paragraphe.Portions.Add(portion);
txt.Paragraphs.Add(paragraphe);
}
//Change font size w.r.t shape size
contenuShape.TextFrame.TextFrameFormat.AutofitType = TextAutofitType.Normal;
presentation.Save(dataDir + "AddLayoutSlides_out.pptx", SaveFormat.Pptx);
}
}
I am working as Support developer/ Evangelist at Aspose.

Use different font for SyndicationFeed title than summary in richtextbox - C#

I am making an RSS Reader in C#. It gets the feed and adds it to a rich text box. Is there a way to have the title in a feed be a separate font than the summary in the rich text box? If so, how? Here is my code:
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
feedTxt.Text = feedTxt.Text + item.Title.Text;
feedTxt.Text = feedTxt.Text + "\n\n" + item.Summary.Text + "\n\n";
}
}
Thanks in advance!
You can use Selection property of on RichTextBox control. Something Like this:
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
// Store current content length of RichTextBox
int currentLength = feedTxt.Length;
// Append new content
feedTxt.Text += item.Title.Text + "\n\n";
feedTxt.Text += item.Summary.Text + "\n\n";
// Set the font for Title using selection
feedTxt.SelectionStart = currentLength.Length;
feedTxt.SelectionLength = item.Title.Text.Length;
feedTxt.SelectionFont = new System.Drawing.Font("Tahoma", 24);
// Set the font for Summary using selection
feedTxt.SelectionStart = currentLength + item.Title.Text.Length;
feedTxt.SelectionLength = item.Summary.Text;
feedTxt.SelectionFont = new System.Drawing.Font("Arial", 16);
// Reset Selection
txtTest.SelectionStart = 0;
txtTest.SelectionLength = 0;
}
}
Update
Looks like you can't append new content and style at the same time (possible limitation of Winforms?). My simple solution is to append all the content in one sweep and calculate all the selections you want to style and push them to a List.
Then you do a second pass looping through all your selections and do the styling.
You need this struct first:
struct ArticleSelection
{
public int TitleStart { get; set; }
public int TitleEnd { get; set; }
public int SummaryStart { get; set; }
public int SummaryEnd { get; set; }
};
Updated Code
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
// Create List to store our selections
List<ArticleSelection> articleSelections = new List<ArticleSelection>();
// Loop all incoming content
foreach (SyndicationItem item in feed.Items)
{
// Store current content length of RichTextBox
int currentLength = feedTxt.Length;
// Append new content
feedTxt.Text += item.Title.Text + "\n\n";
feedTxt.Text += item.Summary.Text + "\n\n";
// Calculate selection
articleSelections.Add(new ArticleSelection()
{
TitleStart = currentLength,
TitleEnd = feed.Item1.Length,
SummaryStart = currentLength + feed.Item1.Length,
SummaryEnd = feedTxt.Text - currentLength // This accounts for new lines above
}); ;
}
// Loop through the content and style it
foreach (ArticleSelection selection in articleSelections)
{
// Set the selection for Title
txtTest.SelectionStart = selection.TitleStart;
txtTest.SelectionLength = selection.TitleEnd;
txtTest.SelectionFont = new Font("Tahoma", 24);
// Set the selection for Summary
txtTest.SelectionStart = selection.SummaryStart;
txtTest.SelectionLength = selection.SummaryEnd;
txtTest.SelectionFont = new Font("Arial", 14);
}
// Remove Selection
txtTest.DeselectAll();
}
You should get something like this:

using c# how to Print Line number of randomly selected line from parsed file

this is a snippet of my program that catches an incomplete line in the file, however I need it to tell me the line number that it pulled so I can do error handling better.
var testLines = File.ReadAllLines(openFileDialog1.FileName);
Item.ran = new Random(Guid.NewGuid().GetHashCode());
var randomTestLine = testLines[Item.ran.Next(testLines.Length)];
if (randomTestLine.StartsWith("*"))
{
pick++;
count = pick.ToString();
Picks.Font = new Font("Microsoft Sans Serif", 12, FontStyle.Bold);
Picks.Text = count;
ItemGenerated.Text = ( !!something needs to go here!! + "Incomplete Item Entry\n" + randomTestLine);
return false;
}
var lineNumber = Item.ran.Next(testLines.Length);
var randomTestLine = testLines[lineNumber];
...
ItemGenerated.Text = ( lineNumber + "Incomplete Item Entry\n" + randomTestLine);
?

Old printer text format c#

I have the following output generated by an UNIX machine from 1996... We are upgrading the software for Windows, and I need to create this exact output http://pastebin.com/YBHpSYDW from C#
There are some problems I can't handle, because I don't know how...
How can I determinate the columns, set aligment for the "IMPORTE" column to the right, if it is plaintext?
I have done this output in Excel which is more readable, flexible.. but they want this creepy old stuff because a lot of reasons and they I'll become insane working for this people, they don't want to upgrade anything, just the software but keep every old creepy thing # output...
So if anyone knows a way to do this, it'll be so much helpful, thank you.
EDIT
The output is a list of data from an SQL Server, old data was stored into MultiValue .DAT and .IDX files, but now they're in a SQL Server... So basically, the code that generates the values is the following
var Query = getRows(sel.DataTable).Select(row =>
{
return new
{
banco = row["banco"].ToString(),
emisora = row["emisora"].ToString(),
sucursal = row["sucursal"].ToString(),
fecha = row["fecha"].ToString(),
identificacion = row["identificacion"].ToString(),
importe = row["importe"].ToString(),
importe_dec = row["importe_dec"].ToString(),
provincia = row["provincia"].ToString(),
referencia = row["referencia"].ToString(),
};
});
Then I do some foreach to make the magic... For example
foreach (var banco in Query.GroupBy(l => l.banco))
So the problem is the output file for printing...
EDIT 2
Got it working, here's the code
private void generarFicheroPrt()
{
try
{
SelectBD sel = new SelectBD(Program.ConexBD, "SELECT * FROM Seguros");
var Query = getRows(sel.DataTable).Select(row =>
{
return new
{
banco = row["banco"].ToString(),
emisora = row["emisora"].ToString(),
sucursal = row["sucursal"].ToString(),
fecha = row["fecha"].ToString(),
identificacion = row["identificacion"].ToString(),
importe = row["importe"].ToString(),
importe_dec = row["importe_dec"].ToString(),
provincia = row["provincia"].ToString(),
referencia = row["referencia"].ToString(),
};
});
using (StreamWriter sw = new StreamWriter(Program.path + #"\CV9005.prt"))
{
int i = 1;
int pag = 0;
int linea = 1;
sw.WriteLine();
sw.WriteLine("\x1b&l1O\x1b(s14H");
decimal total = 0;
foreach (var valor in Query.OrderBy(l => l.emisora))
{
if (linea == 48) linea = 1;
if (linea == 1)
{
pag++;
sw.WriteLine("\xc\t0125 BANCOFAR" + string.Empty.PadLeft(37, '\x20') + "COBRO POR VENTANILLA S. S. - CONTROL DE DOCUMENTOS PAG. "+ pag +"\n\n");
sw.WriteLine("\t N.ORDEN NUMERO REFERENCIA IMPORTE SUC. EMISORA");
sw.WriteLine("\t ------- ----------------- ---------------- ---- -----------------------------------------------------------");
sw.WriteLine();
}
setSufijoEmisora(valor.emisora);
decimal importe = Convert.ToDecimal(Int32.Parse(valor.importe) + "," + valor.importe_dec);
string imp = importe.ToString("N2", Cultures.Spain);
sw.WriteLine("\t\t" + string.Format("{0, 4}\t{1, -13}\t\t{2, 13}{3,6} {4, -59}", i.ToString(), valor.referencia, imp, valor.sucursal, valor.emisora + " " + sufijoEmisora));
i++;
linea++;
total = total + importe;
}
sw.WriteLine();
sw.WriteLine("\t\t\t\t\t TOTAL .....\t" + string.Format("{0, 13}", total.ToString("N2", Cultures.Spain)));
};
}
catch (Exception ex)
{
Logger.log(ex);
}
}
Use the "PrintDocument" tool from the toolbox.
http://msdn.microsoft.com/en-gb/library/system.drawing.printing.printdocument%28v=vs.110%29.aspx
This will help you with basic formating.
Edit
For more richer formating and saving to file use the Microsoft.Office.Core namespace,
http://msdn.microsoft.com/en-us/library/microsoft.office.core.aspx
If you want non ASCII encoding, make sure to set the encoding as per your requirement and save the file with the required encoding.
http://msdn.microsoft.com/en-us/library/microsoft.office.core.msoencoding.aspx
using(StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
writer.WriteLine(s);
}

Categories

Resources