[C#] Bild mittels HttpWebRequest und HttpWebResponse herunterladen

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;

private long DownloadImage(string url)
{
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    long contentlength = 0;
    
    try
    {
        request = (HttpWebRequest)WebRequest.Create(url);
        response = (HttpWebResponse)request.GetResponse();

        if ((response.StatusCode == HttpStatusCode.OK ||
             response.StatusCode == HttpStatusCode.Moved ||
             response.StatusCode == HttpStatusCode.Redirect) &&
             response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
        {
            Bitmap b = new Bitmap(response.GetResponseStream());

            // do something here
            ...

            b.Dispose();
            b = null;
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
    finally
    {
        if (response != null)
        {
            contentlength = response.ContentLength;
            response.Close();
            response = null;
        }

        if (request != null)
        {
            request = null;
        }
    }
    
    // returns bytes read
    return contentlength;
}

[Zedgraph] Achsentitel per Event anpassen

public void InitGraph()
{
        zedGraph.GraphPane.XAxis.ScaleTitleEvent += new Axis.ScaleTitleEventHandler(XAxis_ScaleTitleEvent);
}

private string XAxis_ScaleTitleEvent(Axis axis)
{
        // immer Datum zw. x-Min und x-Max anzeigen
        double d = (axis.Scale.Min + axis.Scale.Max) / 2.0;
        return DateTime.FromOADate(d).ToString("dd.MM.yyyy");
}

[C#] Mehrere DataGridViews über eine Scollbar scrollen

// Scrollereignis der Scrollbar
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
    // Column des ersten DataGridViews setzen
    GridView1.FirstDisplayedScrollingColumnIndex = (int)(GridView1.ColumnCount * hScrollBar1.Value / 100.0);
    // Column des zweiten DataGridViews setzen
    GridView2.FirstDisplayedScrollingColumnIndex = (int)(GridView2.ColumnCount * hScrollBar1.Value / 100.0);
}

[C#] AssemblyLoad Event – geladene Assemblies ausgeben

static class Program
{
    /// <summary->
    /// Der Haupteinstiegspunkt für die Anwendung.
    /// </summary->
    [STAThread]
    static void Main()
    {
        // Event anmelden
        AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    /// <summary->
    /// statische Event-Funktion, wird beim Laden einer Assembly aufgerufen
    /// </summary->
    /// <param name=&quot;sender&quot;-></param->
    /// <param name=&quot;args&quot;-></param->
    private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
    {
        Console.WriteLine(args.LoadedAssembly.FullName);
    }
}

[C#] Tooltip beim Überfahren eines ListViewSubItem anzeigen

// auf dem Formular muss sich noch ein ToolTip namens "toolTip" befinden
// letztes SubItem unter der Maus
private ListViewItem.ListViewSubItem _currentsubitem = null;
// Offset für Tooltip
private const int TOOLTIPP_Y_OFFSET = 24;

private void ListView1_MouseMove(object sender, MouseEventArgs e)
{
    ListView lv = sender as ListView;

    if (lv != null)
    {
        ListViewHitTestInfo htInfo = lv.HitTest(e.X, e.Y);
        if (htInfo != null)
        {
            if (htInfo.Item != null && htInfo.SubItem != null)
            {
                // wenn Subitem in Spalte 2 (Index == 1) gewählt
                if (htInfo.Item.SubItems.IndexOf(htInfo.SubItem) == 1)
                {
                    if (_currentsubitem != htInfo.SubItem)
                    {
                        toolTip.Show(htInfo.Item.Tag as string, lv, e.X, e.Y + TOOLTIPP_Y_OFFSET);
                        _currentsubitem = htInfo.SubItem;
                    }
                }
                else
                {
                    toolTip.Hide(lv);
                    _currentsubitem = null;
                }
            }
            else
            {
                toolTip.Hide(lv);
                _currentsubitem = null;
            }
        }
    }
}

private void ListView1_MouseLeave(object sender, EventArgs e)
{
    ListView lv = sender as ListView;

    if (lv != null)
    {
        toolTip.Hide(lv);
        _currentsubitem = null;
    }
}

[C#] Excel Interop

Möchte man von .NET aus auf Excel zugreifen kann man sich sogenannter Interop-Mechanismen von .NET bedienen. Dazu müssen bestimmte Office-Bibliotheken eingebunden werden.
Dabei ist folgendes zu beachten:

  • Versionsnummern aller eingebundener Office-DLLs beachten, d.h. die Versionen müssen gleich sein
  • für die Bibliotheksverweise im Projektbaum unter Verweise->Rechtsklick->Eigenschaften->Lokale Kopie = true setzen
  • ggf. auch die Redistributable Primary Interop Assemblies (PIA) auf dem Zielsystem nachinstallieren
  • Wird mit einer englischen Version von Excel gearbeitet, darf das lokale Gebietsschema nicht verschieden von Englisch konfiguriert sein. Andernfalls muss das lokale Gebietsschema auf Englisch umgestellt werden: Link
  • ab .NET 4.0 wurde mit dem dynamic-Datentyp eine Vereinfachung des Zugriffes per Interop ermöglicht (s.u.).
// Verweise->Verweis hinzufügen...->.NET->Microsoft.Office.Interop.Excel
using Excel = Microsoft.Office.Interop.Excel;
// Verweise->Verweis hinzufügen...->COM->Microsoft Office Excel 12.0 Object Library
using Microsoft.Office.Core; // für MsoTriState

public void ExcelExample()
{
    Excel.Application excel = null;
    Excel.Workbook book = null;
    Excel.Worksheet sheet = null;
    Excel.Worksheet new_sheet = null;
    
    try
    {
        // open excel
        excel = new Excel.Application();
        // set visible
        excel.Visible = true;
        // no update
        excel.ScreenUpdating = false;
        // display no alerts
        excel.DisplayAlerts = false;
        // always one sheet in new workbook
        excel.SheetsInNewWorkbook = 1;

        // add new workbook
        book = excel.Workbooks.Add(Missing.Value);

        // get current (first) sheet of workbook
        sheet = book.Worksheets[1] as Excel.Worksheet;
        // set sheet name
        sheet.Name = "Testresult";
        
        // merge cell range
        sheet.get_Range("A1:D1", Type.Missing).Merge(Type.Missing);
        
        // colwidth for column A
        // Values are not in pixel!
        (sheet.Columns["A", Type.Missing] as Excel.Range).ColumnWidth = 25.0;
        
        // text (row, column)
        sheet.Cells[1, 1] = "text";
        
        // bold range
        sheet.get_Range("A1:A7", Type.Missing).Font.Bold = true;
        
        // border around cell A1
        sheet.get_Range("A1", Type.Missing).BorderAround(Type.Missing, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Type.Missing);
        
        // border around range A1:B1
        sheet.get_Range("A1:B1", Type.Missing).BorderAround(Type.Missing, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Type.Missing);
        
        // font color for cell A1
        // needs always Colortranslator!
        sheet.get_Range("A1", Type.Missing).Font.Color = ColorTranslator.ToOle(Color.Green);
        
        // new worksheet after first (current) worksheet
        new_sheet = book.Worksheets.Add(Type.Missing, book.Worksheets[1], Type.Missing, Type.Missing) as Excel.Worksheet;
        new_sheet.Name = "sheet1";
        
        // insert picture upper left to new sheet
        // first version with shapes, without STA-Thread problems
        new_sheet.Shapes.AddPicture(@"c:\temp\test.bmp", MsoTriState.msoFalse, MsoTriState.msoCTrue, 0.0f, 0.0f, -1.0f, -1.0f);
        
        // second version without the need of Microsoft.Office.Core
        // but STA-Thread-problems
        Clipboard.SetDataObject(Image.FromFile(@"c:\temp\test.bmp"), true);
        new_sheet.Paste(new_sheet.Cells[1, 1], Type.Missing);
        
        // save Excel-file
        // try different Excel.XlFileFormat
        book.SaveAs(@"c:\temp\test1", Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

        // path + name + extension of saved ExcelWorkbook
        string fullfilename = book.FullName;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
    }
    finally
    {
        // release new_sheet
        if (new_sheet != null)
        {
            Marshal.ReleaseComObject(new_sheet);
            new_sheet = null;
        }

        // release first sheet
        if (sheet != null)
        {
            Marshal.ReleaseComObject(sheet);
            sheet = null;
        }

        // release workbook
        if (book != null)
        {
            try
            {
                book.Close(Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception)
            {
            }

            Marshal.ReleaseComObject(book);
            book = null;
        }

        // release excel
        if (excel != null)
        {
            try
            {
                excel.Workbooks.Close();
            }
            catch (Exception)
            {
            }

            try
            {
                excel.Quit();
            }
            catch (Exception)
            {
            }

            Marshal.ReleaseComObject(excel);
            excel = null;
        }

        GC.Collect();
    }
}

Ab .NET 4.0 kann der Code durch den dynamic-Datentyp vereinfacht werden. Die Typecasts und überflüssigen Type.Missing fehlen und die Parametrierung der COM-Funktionen kann nun direkt per Bezeichner: erfolgen:

// ab .NET 4.0
// Verweise->Verweis hinzufügen...->.NET->Microsoft.Office.Interop.Excel
using Excel = Microsoft.Office.Interop.Excel;
// Verweise->Verweis hinzufügen...->COM->Microsoft Office Excel 12.0 Object Library
using Microsoft.Office.Core; // für MsoTriState

private void ExcelExample(string savename)
{
    Excel.Application excel = null;
    Excel.Workbook book = null;
    Excel.Worksheet sheet = null;
    Excel.Worksheet new_sheet = null;

    try
    {
        // open excel
        excel = new Excel.Application();

        // set visible
        excel.Visible = true;
        // no update
        excel.ScreenUpdating = false;
        // display no alerts
        excel.DisplayAlerts = false;
        // always one sheet in new workbook
        excel.SheetsInNewWorkbook = 1;

        // add new workbook
        book = excel.Workbooks.Add();

        // get current (first) sheet of workbook
        sheet = book.Worksheets[1];
        // set sheet name
        sheet.Name = "Testresult";

        // merge cell range
        sheet.get_Range("A1:D1").Merge();

        // colwidth for column A
        // Values are not in pixel!
        sheet.Columns["A"].ColumnWidth = 25.0;

        // text (row, column)
        sheet.Cells[1, 1] = "Testeintrag";

        // bold range
        sheet.get_Range("A1:D1").Font.Bold = true;

        // border around cell A1:D1
        sheet.get_Range("A1:D1").BorderAround(Weight: Excel.XlBorderWeight.xlThin, ColorIndex: Excel.XlColorIndex.xlColorIndexAutomatic);

        // border around range A1:B1
        sheet.get_Range("A2:B2").BorderAround(Weight: Excel.XlBorderWeight.xlThin, ColorIndex: Excel.XlColorIndex.xlColorIndexAutomatic);

        // font color for cell A1
        // needs always Colortranslator!
        sheet.get_Range("A1").Font.Color = ColorTranslator.ToOle(Color.Green);

        // new worksheet after first (current) worksheet
        new_sheet = book.Worksheets.Add(After: book.Worksheets[1]);
        new_sheet.Name = "new_sheet";

        // insert picture upper left to new sheet
        // first version with shapes, without STA-Thread problems
        new_sheet.Shapes.AddPicture(@"c:\temp\test.bmp", MsoTriState.msoFalse, MsoTriState.msoCTrue, 0.0f, 0.0f, -1.0f, -1.0f);
        
        // second version without the need of Microsoft.Office.Core
        // but STA-Thread-problems
        Clipboard.SetDataObject(Image.FromFile(@"c:\temp\test.bmp"), true);
        new_sheet.Paste(new_sheet.Cells[1, 1]);

        // save Excel-file
        // try different Excel.XlFileFormat
        book.SaveAs(Filename: @"c:\temp\test1", FileFormat:  Excel.XlFileFormat.xlWorkbookNormal, AccessMode: Excel.XlSaveAsAccessMode.xlNoChange);

        fullfilename = book.FullName;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
    }
    finally
    {
        // release workbook
        if (book != null)
        {
            book.Close();
        }

        // release excel
        if (excel != null)
        {
            excel.Quit();
        }
    }
}

[C#] technischen Wert auf 0…100% normieren

/// <summary>
/// normiert einen technischen Wert abhängig von dessen Minimum und Maximum auf 0...100%
/// </summary>
/// <param name="val">Wert(techn.)</param>
/// <param name="min">Minimum (techn.)</param>
/// <param name="max">Maximum (techn.)</param>
/// <returns>normierter Wert</returns>
public double Normieren(double val, double min, double max)
{
    return (100.0f * ((val - min) / (max - min)));
}

[C#] Gleitkommazahlen richtig vergleichen

using System;

/// <summary>
/// freeware helper class for little math problems
/// (W) 2014 by admin of codezentrale.6x.to
/// </summary>
public static class MathTools
{
    /// <summary>
    /// Epsilon for float comparision
    /// </summary>
    public const float EPSILON_FLOAT = 1.192093E-07f;
    /// <summary>
    /// Epsilon for double comparision
    /// </summary>
    public const double EPSILON_DOUBLE = 2.22044604925031E-16;

    /// <summary>
    /// Gleitkommavergleich für float
    /// </summary>
    /// <param name="f1"->1. Zahl</param>
    /// <param name="f2"->2. Zahl</param>
    /// <returns>true, wenn gleich</returns>
    public static bool FloatIsEqual(float f1, float f2)
    {
        return (Math.Abs(f1 - f2) < EPSILON_FLOAT);
    }
    /// <summary>
    /// Gleitkommavergleich für double
    /// </summary>
    /// <param name="d1"->1. Zahl</param>
    /// <param name="d2"->2. Zahl</param>
    /// <returns>true, wenn gleich</returns>
    public static bool DoubleIsEqual(double d1, double d2)
    {
        return (Math.Abs(d1 - d2) < EPSILON_DOUBLE);
    }
}