I am aware that there are already a few threads on this already created and closed (like 2-dimensional Integer array to DataGridView)
My problem is that since I have only been working with console applications, I am not aware of what I need to do in order to apply the code.
Up till now I have drag and dropped a new dataGridView and chose program.cs (where my main is) as a source. Now when I apply the code from the aforementioned link in program.cs, visualstudio is saying that dataGridView1 "does not exist in the current context". When I try to declare it beforehand, I get that the type/namespace can't be found. Any ideas?
With regard to the errors you got: All you need to do is add the namespace: using System.Windows.Forms; and also a reference to it! This works just fine for Console applications. Of course it will never show up but other than that you can make use of its abilities..
But the real question is: What do you want to achieve and why do you stick to a console application?
This is not to say that you may not have a good reason! For example it is sometimes necessary to run a service application without a display screen. This could still create output from DataGridViews or from Chart controls..
But it always helps to understand the situation fully when we answer questions here..
Here is an example that creates and fills a DataGridView DGV and then saves an image of the data to a png file.
For this to work you also need to add System.Drawing. As for Windows.Forms you need to add both the using clause and the reference:
(I have only a German VS version here; instead of the 'Aktuell' (ie 'Current') group you should search the references in the 'Framework'! The result is the same - I chose the other one becasue it is not so big on the screenshot..)
Once the references are in place..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; // <--- add namespace AND reference!!
using System.Drawing; // <--- add namespace AND reference!!
..this simple console application will compile and run:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataGridView DGV = new DataGridView();
List<string> test = new List<string>()
{ "Anna", "Bertha", "Carol", "Doreen", "Erica", "Fran", "Gisa" };
DGV.Columns.Add("No", "Number");
DGV.Columns.Add("Name", "Name");
DGV.Columns.Add("Age", "Age");
DGV.Columns["Name"].DefaultCellStyle.Font =
new Font(DGV.Font, FontStyle.Bold);
for (int i = 0; i < test.Count; i++) DGV.Rows.Add(new[]
{ (i + 1)+ "", test[i], i + 21 +""}); // cheap string array
DGV.ScrollBars = ScrollBars.None;
DGV.AllowUserToAddRows = false;
DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
DGV.RowHeadersVisible = false;
var width = DGV.Columns.GetColumnsWidth(DataGridViewElementStates.None);
DGV.ClientSize = new Size(width,
DGV.ColumnHeadersHeight + DGV.RowCount * (DGV.Rows[0].Height) );
Bitmap bmp = new Bitmap(DGV.ClientSize.Width, DGV.ClientSize.Height);
DGV.DrawToBitmap(bmp, DGV.ClientRectangle);
bmp.Save("D:\\testDGV.png", System.Drawing.Imaging.ImageFormat.Png);
bmp.Dispose();
}
}
}
Related
I am trying to access the macros inside of an Access database (accdb).
I tried using:
using Microsoft.Office.Interop.Access.Dao;
...
DBEngine dbe = new DBEngine();
Database ac = dbe.OpenDatabase(fileName);
I found a container["Scripts"] that had a document["Macro1"] which is my target. I am struggling to access the contents of the document. I also question if the Microsoft.Office.Interop.Access.Dao is the best reference for what I am trying to achieve.
What is the best way to view the content of the macros and modules?
You can skip the DAO part, it's not needed in this case. Macros are project specific, so in order to get them all, you would need to loop through your projects. In my example, i just have one project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Access;
namespace Sandbox48
{
public class Program
{
public static void Main(string[] args)
{
Microsoft.Office.Interop.Access.Application oAccess = null;
string savePath = #"C:\macros\";
oAccess = new Microsoft.Office.Interop.Access.Application();
// Open a database in exclusive mode:
oAccess.OpenCurrentDatabase(
#"", //filepath
true //Exclusive
);
var allMacros = oAccess.CurrentProject.AllMacros;
foreach(var macro in allMacros)
{
var fullMacro = (AccessObject)macro;
Console.WriteLine(fullMacro.Name);
oAccess.SaveAsText(AcObjectType.acMacro, fullMacro.FullName, $"{savePath}{ fullMacro.Name}.txt");
}
Console.Read();
}
}
}
I am VERY new to C# so it is possible this is a really easy problem, but even after all my reading I cant find a way to add the definitions Visual Studio 2010 wants despite having added the using statements and the references on the MSDN docs page for each expression.
My Error:
System.windows.forms does not contain a definition for document
I added the reference "presentationframework" based on something I was reading on the Microsoft site. Thanks to some of the comments below I discovered I was apparently mixing two different ways to get text from the box. All I need to be able to do is paste content into the textbox, and get the contents of the box when i press a button. Can someone tell (or better yet show) me definitively how to do this without mixing strategies?
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Controls.RichTextBox;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class HackController : Form
{
ArrayList ipList = new ArrayList();
ArrayList acctList = new ArrayList();
int myAcct = 0;
string myIp = "";
public HackController()
{
InitializeComponent();
}
public void sync_Click(object sender, EventArgs e)
{
string data = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;// ERROR HERE
string[] lines = Regex.Split(data, "\n");
Regex ipMatch = new Regex(#"\d+.\d+.\d+.\d+");
Regex acctMatch = new Regex(#"#\d+");
foreach(string line in lines)
{
foreach(Match m in ipMatch.Matches(line))
{
ipList.Add(m);
}
foreach( Match m in acctMatch.Matches(line))
{
acctList.Add(m);
}
}
}
}
}
Here's a (rather strange) sample showing one way to display data in a WinForms RichTextBox control. (Sorry, but it's the only sample I can find in my programming because I'm usually using Developer Express WinForms controls instead of the basic .Net ones.)
But first, to be 100% sure you are not mixing WinForms and WPF, make sure that when you create the project you select WinForms as the project template type (not WPF). And when you drag-and-drop the RichTextBox control from the Visual Studio toolbox onto your form, make sure it is the WinForms RichTextBox, not the WPF one.
You can check this by looking in the .Designer.cs file, and find the definition of the RTB control created by the Visual Studio designer. It should look something like this:
this.rtbResults = new System.Windows.Forms.RichTextBox();
...
...
//
// rtbResults
//
this.rtbResults.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtbResults.Location = new System.Drawing.Point(12, 52);
this.rtbResults.Name = "rtbResults";
this.rtbResults.Size = new System.Drawing.Size(640, 133);
this.rtbResults.TabIndex = 17;
this.rtbResults.Text = "";
...
...
private System.Windows.Forms.RichTextBox rtbResults;
The important thing being that it says "System.Windows.Forms.RichTextBox", not something else.
OK, here's my strange example, which displays the results of a Scrabble cheater program:
/// <summary>
/// Method to display the results in the RichTextBox, prefixed with "Results: " and with the
/// letters J, Q, X and Z underlined.
/// </summary>
private void DisplayResults(string resultString)
{
resultString = UnderlineSubString(resultString, "J");
resultString = UnderlineSubString(resultString, "Q");
resultString = UnderlineSubString(resultString, "X");
resultString = UnderlineSubString(resultString, "Z");
rtbResults.Rtf = #"{\rtf1\ansi " + "Results: " + resultString + "}";
}
/// <summary>
/// Method to apply RTF-style formatting to make all occurrences of a substring in a string
/// underlined.
/// </summary>
private static string UnderlineSubString(string theString, string subString)
{
return theString.Replace(subString, #"\ul " + subString + #"\ul0 ");
}
This uses Microsoft's proprietary Rich Text Format, but RichTextBox can also use straight text. And this demo only writes to the RTB, it doesn't read from it, although doing that is fairly trivial.
Hope this helps.
I apologize in advance as I have not used visual studio much before and I used a template for the most part to create the code below. But I really need some help.
I'm trying to generate a report from a system using visual studio through an API. The code below works and doesn't give me any errors when debugging, but I need to find a way to retrieve the reportURL variable at the end (the report is generated with the specifications below and I should receive a URL to download the report). I am building as a windows application.
Is there anything like console.log or console.writeline in visual studio I can use? Or can I output it to a textbox of some kind? (Again, I am building as a windows form and not a console application). Can anyone help me figure out some kind of code I can use to retrieve the URL based on what is provided below? (Please be detailed if possible as I am still getting used to the program). Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ReportsApplication2
{
using ServiceReference1;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ReportExecutionServiceClient client = new ReportExecutionServiceClient();
ReportSubmission submissionRequest = new ReportSubmission();
ReportSubmissionResponse submissionResponse = new ReportSubmissionResponse();
PollReportResponse pollResponse = new PollReportResponse();
WebMediaReportRequest webRepReq = new WebMediaReportRequest();
UserCredentials userCredentials = new UserCredentials();
DateFilter dateFilter = new DateFilter();
userCredentials.UserName = "xxxxx";
userCredentials.Password = "xxxxx";
submissionRequest.UserCredentials = userCredentials;
submissionRequest.DeveloperToken = "xxxxxx";
dateFilter.DateFilterType = DateFilterType.Total;
dateFilter.RelativeDateRange = RelativeDateRange.LastMonth;
webRepReq.Columns = new WebMediaReportColumn[2] { WebMediaReportColumn.MediaPlanName, WebMediaReportColumn.Impressions };
List<WebMediaFilter> webRepFilterList = new List<WebMediaFilter>();
WebMediaFilter webRepFilter = new WebMediaFilter();
webRepFilter.Column = WebMediaReportFilter.ClientGUID;
webRepFilter.Values = new string[1] {"xxxxxx"};
webRepFilterList.Add(webRepFilter);
webRepFilter = new WebMediaFilter();
webRepFilter.Column = WebMediaReportFilter.BuyGUID;
webRepFilter.Values = new string[1] { "xxxxxxxx" };
webRepFilterList.Add(webRepFilter);
webRepReq.ReportName = "test";
webRepReq.Filters = webRepFilterList.ToArray();
webRepReq.Format = FormatType.CSV;
webRepReq.DateFilter = dateFilter;
submissionRequest.ReportRequest = webRepReq;
submissionResponse = client.SubmitReport(submissionRequest);
string reportURL = string.Empty;
do { // Loop until report complete or failed
PollReportRequest pollRequest = new PollReportRequest();
pollRequest.DeveloperToken = "xxxxxxx";
pollRequest.UserCredentials = userCredentials;
pollRequest.ReportId = submissionResponse.ReportId;
pollResponse = client.PollReport(pollRequest);
reportURL = pollResponse.Url;
} while ((pollResponse.Status != ReportStatus.Failed) || ((pollResponse.Status != ReportStatus.Complete)));
}//end
You actually already know what you need. The Console.WriteLine method will write anything you want to the Console.
While you are debugging in Visual Studio, you can view the Console window by turning on the "Output" window. You can find it in the View menu
Even though you are writing a WinForms application, this will still write to the Output window while debugging. It can be an effective tool when debugging, but of course, when you actually publish the application, the command will be meaningless since you won't have a Console to write too.
If you are using Winforms, the simplest approach to show messages is MessageBox.Show():
MessageBox.Show(reportURL);
It will block the program until you click Ok.
http://msdn.microsoft.com/en-us/library/0x49kd7z(v=vs.110).aspx
If you want to output debug info during development, then Console.WriteLine() will work:
Console.WriteLine(reportURL);
It will show in the Output window. If you don't see that, go to the main menu in Visual Studio and select View -> Output, while in debug mode.
Console.WriteLine() will only work within Visual Studio for a Winforms app; after deploying it, the console window doesn't show, so you'll need to show it via a GUI method.
If you need to output it at runtime, either drag a TextBox from the toolbox onto your main form, and do:
textBox.Text = reportURL;
If you can't show it on the main form, then you may want to create your own custom message dialog that includes a TextBox and show it with ShowDialog()
The simplest solution is to use Console.WriteLine.
Is there a way to get the objects (queries, forms, reports, macros, etc.) from an .accdb file? I am not looking for storing data, I want to examine the structure and design of those objects.
Edit: To make the question clear. I want to access those objects from C#, so that I can do automatic checking.
The following C# console app lists all of the controls in a specified Form:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace comAutoTest
{
class Program
{
static void Main(string[] args)
{
// this code requires the following COM reference in the project:
// Microsoft Access 14.0 Object Library
//
var objAccess = new Microsoft.Office.Interop.Access.Application();
objAccess.Visible = false;
objAccess.OpenCurrentDatabase(#"C:\Users\Public\Database1.accdb");
string formName = "MembersForm";
Console.WriteLine(String.Format("The form [{0}] contains the following controls:", formName));
objAccess.DoCmd.OpenForm(formName, Microsoft.Office.Interop.Access.AcFormView.acDesign);
Microsoft.Office.Interop.Access.Form frm = objAccess.Forms[formName];
foreach (Microsoft.Office.Interop.Access.Control ctl in frm.Controls)
{
Console.WriteLine();
Console.WriteLine(String.Format(" [{0}]", ctl.Name));
Console.WriteLine(String.Format(" {0}", ctl.GetType()));
}
objAccess.DoCmd.Close(Microsoft.Office.Interop.Access.AcObjectType.acForm, formName);
objAccess.CloseCurrentDatabase();
objAccess.Quit();
Console.WriteLine();
Console.WriteLine("Done.");
}
}
}
The output is:
The form [MembersForm] contains the following controls:
[LastName]
Microsoft.Office.Interop.Access.TextBoxClass
[Label0]
Microsoft.Office.Interop.Access.LabelClass
[MemberDonationsSubform]
Microsoft.Office.Interop.Access.SubFormClass
[MemberDonationsSubform Label]
Microsoft.Office.Interop.Access.LabelClass
[Command3]
Microsoft.Office.Interop.Access.CommandButtonClass
Done.
Edit: For Relationships, do something like this
Microsoft.Office.Interop.Access.Dao.Database cdb = objAccess.CurrentDb();
foreach (Microsoft.Office.Interop.Access.Dao.Relation rel in cdb.Relations)
{
Console.WriteLine(rel.Name);
}
There is a feature in Access that is called "Database Document". You can access it through the Database Tools ribbon panel. When you run the tool fol all objects it will generate a report called Objects Definition. You can print it, but I recommend you export it to a file of some sort (e.g. Excel, or Text). That way it will be easier to analyse.
I'm looking for a SDK, plugin or code that will videorecord a specific window (hwnd).
If possible in C# or Java. Does anyone know if this exists? I've been googling, but haven't come across anything.
Install Microsoft Expression Encoder 4 with Service Pack 2 (SP2).
Here's a sample program to use it. A fuller sample comes with the SDK, which is included in the download.
using System;
using System.Drawing;
using Microsoft.Expression.Encoder.ScreenCapture;
// Added references to:
// Microsoft.Expression.Encoder
// Microsoft.Expression.Encoder.Types
// Microsoft.Expression.Encoder.Utilities
// WindowsBase
// System.Drawing (for Rectangle)
namespace scrcap
{
class Program
{
static void Main(string[] args)
{
ScreenCaptureJob job = new ScreenCaptureJob();
// You can capture a window by setting its coordinates here
job.CaptureRectangle = new Rectangle(100, 100, 200, 200);
// Include the mouse pointer in the captured video
job.CaptureMouseCursor = true;
// Output file; you can transcode the xesc file to something else later.
// Note that this silently does nothing if the file already exists.
job.OutputScreenCaptureFileName = #"C:\Users\arx\scrcap\capture.xesc";
// Do some capture
job.Start();
// Wait for a keypress
Console.ReadKey();
// And stop
job.Stop();
}
}
}