Snippet:
Assembly assembly = Assembly.GetExecutingAssembly();
string filePath = assembly.GetName().Name + ".filename.xml";
using (Stream stream = assembly.GetManifestResourceStream(filePath))
{
if (stream != null)
{
// do something with Stream from file
}
}
WebClient class is very handy and useful but has one big gap. There is no build in cookies handling between requests. Luckily somebody wrote briliant solution for this :) http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html
With above snippet the WebClient class will be enough for most common web tasks.
Below you find my rich (maybe to rich) commented example of use WebClient class (enhanced) to send data(POST, GET) and retrieve response (webpage source). There are also HttpWebRequest/HttpWebResponse classes example so you can compare both methods.
In my examples I ‘m going to connect to http://www.phpbb.com, login into this community site and after success pull some data from Phpbb User Configuration Panel.
Full code available to download: WebClientEnhancedFetchWebpage Example (84)
So in below example we will login into phpbb.com forum.

Read more…
We can use for this _CellFormatting event. See below example:
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView gv = (DataGridView)sender;
if (gv.Columns[e.ColumnIndex].Name == "ColumnName")
{
// If cell has a value and contains char '-'
if (e.Value != null && e.Value.ToString().Contains("-"))
{ // Change cell text color to red
e.CellStyle.ForeColor = Color.Red;
//e.CellStyle.Font = new Font("Arial", 10, FontStyle.Bold);
}
}
}
I often would like to have ProgressBar (hidden and shown only while some background application work is doing) in my StatusStrip. My expectation is the ProgressBar should always fill entire available free space in StatusStrip, when form is Maximizing, Resizing etc. This kind of behaviour can’t be set in Visual Studio Designer with control properties settings. Below is my solution to solve this problem. If you know better, simplest way then please let me know by your comment :)
// Method to calculate suitable ToolStripProgressBar width
private int CalculateControlSizeInStatusStrip(StatusStrip statusStrip,
Control statusProgressBar)
{
int width = statusStrip.ClientSize.Width;
int gripWidth = 20;
if (statusStrip.Items.Count > 1)
{ // Calculate width for progress bar if more controls
// on StatusStrip
for (int i = 0; i < statusStrip.Items.Count - 1; i++)
{
// width calculation
width -= statusStrip.Items[i].Width;
}
}
return width - gripWidth;
}
on your StatusStrip Resize event:
private void statusStripMain_Resize(object sender, EventArgs e)
{
// Expand dynamically width of ToolStripProgressBar to
// fill entire free space in StatusStrip
toolStripStatusProgressBarMainTask.ProgressBar.Width = CalculateControlSizeInStatusStrip((StatusStrip)sender, toolStripStatusProgressBarMainTask);
}
I did something like that today so I thought to share. Example of use DataTable with DataGridView control. In addition HeaderText property of DataGridView is assigned based on DataTable DataColumn.Caption property value.
using System.Data;
using System;
private DataTable myDataTable = new DataTable();
DataColumn getNewColumn(string columnName, string columnCaption
, string columnType)
{
// Create a new column to be used in the DataTable
DataColumn dc =
new DataColumn(columnName, System.Type.GetType(columnType));
// Column caption can be used later for HeaderText prop
// in DataGridView
dc.Caption = columnCaption;
return dc;
}
void CreateNewRow(string[] rowData)
{
// Create a DataRow based on the DataTable
DataRow dr = myDataTable.NewRow();
// Add values to the DataRow columns
int i = 0;
foreach (string fieldData in rowData)
{
if (i < dataTable.Columns.Count)
// assign by index
dr[i] = fieldData;
else
break;
i++;
}
// Add the row to the DataTable
myDataTable.Rows.Add(dr);
}
private void FillDataGridViewFromTextFile(string filename)
{
// Clear last results from DataGridView
if (DataGridView1.RowCount > 0)
myDataTable.Rows.Clear();
if (myDataTable.Columns.Count == 0)
{ // if DataTable is not constructed than Add Columns
// to the datatable
myDataTable.Columns.Add(getNewColumn("ComputerName"
, "Computer name"
, "System.String"));
}
// Load data from text file into DataTable
using (System.IO.StreamReader reader
= new System.IO.StreamReader(filename))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
if (!String.IsNullOrEmpty(line))
{
// add row data to "columns array"
string[] rowData = new string[] { line };
// add new row to DataTable
CreateNewRow(rowData);
}
}
}
// Assign DataTable to DataGridView
DataGridView1.DataSource = myDataTable;
// Copy DataTable columns Caption property
// to DataGridView HeaderText property
foreach (DataColumn dc in myDataTable.Columns)
{
DataGridView1.Columns[dc.ColumnName].HeaderText = dc.Caption;
}
}
P.S. To get all the data OUT of the gridview and back INTO a datatable
DateTable tbl = Gridview1.DataSource as DataTable;
frmOptions formOptions = new frmOptions();
// open form only if is not open already
bool isFormOpen = false;
// iterate through all open forms
foreach (Form frm in Application.OpenForms)
{
if (frm is frmOptions)
{
// open already so just bring it to the front
frm.BringToFront();
isFormOpen = true;
break;
}
}
if (!isFormOpen)
// not open so show it
formOptions.Show();
else
formOptions.Dispose();
When using Webclient to retrieve some file from the web you can face problem with caching your files.
For example: You have a xml file with version number inside. After downloading first time by Webclient class, you changed content of the xml file and start process again. Unfortunately you will receive old content downloaded earlier instead newest content of the file.
That happens because of Microsoft Internet Explorer (as far as I know) Cache settings used by Webclient class.
So to disallow for caching your requests you have to change Weblicent CachePolicy property. You can do it as shown below:
string xmlUrl = "http://myserver.com/xmlfile.xml";
WebClient client = new WebClient();
// prevent file caching by windows
client.CachePolicy = new System.Net.Cache.RequestCachePolicy(
System.Net.Cache.RequestCacheLevel.NoCacheNoStore
);
// read content of file
Stream rssStream = client.OpenRead(xmlUrl);