Archiv der Kategorie: Programmierung

Visual Basic und VBA: Dynamische String Array / Dynamic string array in VBA

Problem

In VBA soll ein dynamisches String-Array verwendet werden.

Solution – Lösung

Array initialisieren:

      Dim cbValuesStringArray() As String

      While i<10
        i = i + 1
        ReDim Preserve cbValuesStringArray(i - 1)
        cbValuesStringArray(i - 1) = CStr(i)
      End While

Array auslesen:

    For j = 0 To UBound(cbValuesStringArray)
        Debug.Print CStr(j) & " - " & cbValuesStringArray(j)
    Next j

C# + Reguläre Ausdrücke / Regular Expressions / Progress Tags : Alle Vorkommnisse zwischen einem Start-Teilstring und End-Teilstring (z.B. bei HTML Tags) finden und verarbeiten / Find all occurencies of start and end tag and progress them

Problem

Es sollen alle Vorkommnisse eine Start- und End-Tags gefunden werden und der Text dazwischen verarbeitet werden.

Ansatz – Approach

Verwendung von regulären Ausdrücken:

Regex.Matches findet alle Auftreten anhand eines Patterns, was den Regulären Ausdruck definiert:

(diagram://{[^>]+})

Eine Funktion string replaceDiagramAndElementLinkURLs(string eaNoteString) baut einen neuen String zusammen und schickt ihr wieder zurück.

Lösung – Solution

Im folgenden Beispiel gibt es in einem String mehrere Vorkommnisse des Start-Tags „$diagram://{“ und dem End-Tag „}“.
Zwischen dem Diagramm steht eine Nummer (guid) die an eine aspx-Seite übergeben werden soll.

Z.B. lautet der String

string verarbeiten = @"
<html>
...
Dies ist ein Diagramm: <a href="$diagram://{1234465}">Link 1</a> hier steht noch 
ein Diagramm: <a href="$diagram://{3455565}">Link 2</a> und das führt sich fort..
...
</html>
";

und nach dem Verarbeiten ist der Inhalt:

string verarbeiten = @"
<html>
...
Dies ist ein Diagramm: <a href="Level2Process.aspx?map=1234465">Link 1</a> hier steht noch 
ein Diagramm: <a href="Level2Process.aspx?map=3455565">Link 2</a> und das führt sich fort..
...
</html>
";

Dazu kann man folgenden Regulären Ausdruck verwenden:

    public static string replaceDiagramAndElementLinkURLs(string eaNoteString)
    {
        string neuerString = eaNoteString;
        string pattern = @"(diagram://{[^>]+})";

        MatchCollection matches = Regex.Matches(neuerString, pattern);

        if (matches.Count > 0)
        {
            foreach (Match m in matches)
            {
                string toReplace = "$" + m.Groups[1].ToString();
                string guid = toReplace.ToString().Replace("$diagram://", "");

                neuerString = neuerString.Replace(toReplace, "Level2Process.aspx?map="+guid );
            }
        }
        return neuerString;
}

Sparx Systems Enterprise Architect: Get Images of Diagram By Diagram Name SQL

Problem

The Images of a specific diagram in the data structure of the Sparx Systems Enterprise Architect should be read by diagram name.

Approach

Usage of MDB Plus and Data Mining

Solution

This is SQL for the Access / .eap-File – it should be rewritten for other SQL Servers (i.e. the brackets can be removed and Functions like InStr/Mid shall be replaced)

SELECT	dia.Name As Diagram,
		IIF(Trim(objstart.[Name]) = 'Text', 'Text', objstart.stereotype) As stereotype, 
		diaobj.RectLeft As x,
		diaobj.RectTop As y,
		diaobj.RectRight-diaobj.RectLeft As Width,
		Abs(diaobj.RectBottom-diaobj.RectTop) As Height,
		objstart.Object_ID,
		IIF(Trim(objstart.[Name]) = 'Text', 'Text-'& objstart.Object_ID ,objstart.Alias) As [key],
		IIF(objstart.[Name] = 'Text', objstart.Note, objstart.[Name]) As phaseName,
		objstart.[ea_guid] As [guid],
		diaobj.ObjectStyle,
		IIF(
                    InStr(diaobj.ObjectStyle, "ImageID")>0, 
                    Mid(diaobj.ObjectStyle, InStr(diaobj.ObjectStyle, "ImageID")+8 , Len(diaobj.ObjectStyle)- (InStr( diaobj.ObjectStyle, "ImageID")+8) ),
                    ''
        ) As ImageId     
FROM
((
		[t_diagram] dia LEFT JOIN (Select Diagram_ID, Object_ID, RectLeft, RectTop, RectRight, RectBottom, ObjectStyle from [t_diagramobjects]) diaobj ON dia.[Diagram_ID]=diaobj.[Diagram_ID])
LEFT JOIN [t_object] objstart ON objstart.[Object_ID]=diaobj.[Object_ID])
WHERE objstart.Object_Type IN ('Text','Boundary') AND IIF(InStr(diaobj.ObjectStyle, "ImageID")>0, 
                                                                Mid(diaobj.ObjectStyle, InStr(diaobj.ObjectStyle, "ImageID")+8 , 
                                                                Len(diaobj.ObjectStyle)- (InStr( diaobj.ObjectStyle, "ImageID")+8) ),
                                                                '') <> ''
AND dia.Name='0' 
ORDER BY 12 DESC,1,2,3,4,5,6,7,8,9       

Sparx Systems Enterprise Architect SQL: Get all Images with ImageID of a diagram

Problem

All Images of an Diagram (the ImageIds) shall be determined, so that can be read out from the table t_image (see previous article about BLOB and EA).

Approach – Ansatz

Usage of the tables
– t_diagram
– t_diagramobjects
– t_object

Solution – Lösung

SELECT	dia.Name As Diagram,
		IIF(Trim(objstart.[Name]) = 'Text', 'Text', objstart.stereotype) As stereotype, 
		diaobj.RectLeft As x,
		diaobj.RectTop As y,
		diaobj.RectRight-diaobj.RectLeft As Width,
		Abs(diaobj.RectBottom-diaobj.RectTop) As Height,
		objstart.Object_ID,
		IIF(Trim(objstart.[Name]) = 'Text', 'Text-'& objstart.Object_ID ,objstart.Alias) As [key],
		IIF(objstart.[Name] = 'Text', objstart.Note, objstart.[Name]) As phaseName,
		objstart.[ea_guid] As [guid],
		diaobj.ObjectStyle,
		IIF(
                    InStr(diaobj.ObjectStyle, "ImageID")>0, 
                    Mid(diaobj.ObjectStyle, InStr(diaobj.ObjectStyle, "ImageID")+8 , Len(diaobj.ObjectStyle)- (InStr( diaobj.ObjectStyle, "ImageID")+8) ),
                    ''
        ) As ImageId     
FROM
((
		[t_diagram] dia LEFT JOIN (Select Diagram_ID, Object_ID, RectLeft, RectTop, RectRight, RectBottom, ObjectStyle from [t_diagramobjects]) diaobj ON dia.[Diagram_ID]=diaobj.[Diagram_ID])
LEFT JOIN [t_object] objstart ON objstart.[Object_ID]=diaobj.[Object_ID])
WHERE objstart.Object_Type IN ('Text','Boundary') AND IIF(InStr(diaobj.ObjectStyle, "ImageID")>0, 
                                                                Mid(diaobj.ObjectStyle, InStr(diaobj.ObjectStyle, "ImageID")+8 , 
                                                                Len(diaobj.ObjectStyle)- (InStr( diaobj.ObjectStyle, "ImageID")+8) ),
                                                                '') <> ''
AND dia.Name='{PutInYourDiagramNameHere}' 
ORDER BY 12 DESC,1,2,3,4,5,6,7,8,9    

Sparx Systems Enterprise Architect SQL : Query to get the order of objects / elements in the project browser tree

Problem

The order of tree elements in the project browser should be queried in SQL.
Die Reihenfolge der Objekte im Projekt-Browser soll über SQL abgefragt werden

Approach – Ansatz

Usage of the TPos column within the tables t_object and t_package.
Verwendung der TPos Spalte in den Tabellen t_object und t_package.

Solution – Lösung

SELECT b.TPos as Package_Position, 
       b.Name as Package_Name, 
       a.TPos as Object_Tree_Position, 
       a.Object_ID, 
       a.Name as Object_Description
FROM t_object a INNER JOIN t_package b ON a.Package_ID=b.Package_ID 
WHERE Stereotype='Process Step'
ORDER BY 1,2,3

C# .NET Eine geeignete Datenstruktur für Tabellen / DataTable erstellen / Best .NET DataType for tables

Problem

Die Datenstruktur DataTable von .NET muss richtig initialisiert wreden

Lösung

public DataTable initDataGrid()
{
	DataColumn c0 = new DataColumn("ID");
	DataColumn c1 = new DataColumn("FILE");
	DataColumn c2 = new DataColumn("SITE");
	DataColumn c3 = new DataColumn("OBJEKTSTEREOTYPE");
	DataColumn c4 = new DataColumn("TAB");
	DataColumn c5 = new DataColumn("STEREOTYPE");
	DataColumn c6 = new DataColumn("CONNECTION");
	DataColumn c7 = new DataColumn("LINK");
	DataColumn c8 = new DataColumn("LINK_TO_ID");
	DataColumn c9 = new DataColumn("ALIAS");

	dataTable.Columns.Add(c0);
	dataTable.Columns.Add(c8);
	dataTable.Columns.Add(c1);
	dataTable.Columns.Add(c2);
	dataTable.Columns.Add(c9);
	dataTable.Columns.Add(c3);
	dataTable.Columns.Add(c4);
	dataTable.Columns.Add(c5);
	dataTable.Columns.Add(c6);
	dataTable.Columns.Add(c7);

	return dataTable;
}

public void main()
{
    DataTable dataTable = new DataTable("Tabellenname");
    dataTable.Clear(); 

    // Hier in einer Schleife die Tabelle befüllen
    // Use i.e. Loops to fill the table like this
    DataRow row = dataTable.NewRow();
    row["ID"] = "1";
    row["FILE"] = "2";
    row["SITE"] = "3";
    row["OBJEKTSTEREOTYPE"] = "4";
    row["TAB"] = "5";
    row["STEREOTYPE"] = "6";
    row["CONNECTION"] = "7";
    row["LINK"] = "8";
    row["ALIAS"] = "9";
    dataTable.Rows.Add(row);
}

.NET Winforms C# : Eine Baum-Komponente befüllen (TreeView)

Problem

Der TreeView-Baum soll anhand von Strings befüllt werden

Ansatz

Verwendung eines Backslashes wie bei Dateipfaden zur Baumeinrückung

Lösung

private void populateTreeFromStringArray(string[] lines)
{
	SortedList sl = new SortedList();
	this.treeView1.Nodes.Clear();
	this.treeView1.BeginUpdate();
	// this.treeView1.ShowRootLines;
	TreeNodeCollection parentNodes = this.treeView1.Nodes;
	foreach (string line in lines)
	{
		string[] stringParts = line.Split('\\');

		TreeNode nd = null;
		// Der Parent Key wird leer inititalisiert
		string strParentKey = string.Empty;
		foreach (string s in stringParts)
		{

			string sTrimmed = s.Trim();

			if (sTrimmed == string.Empty)
			{
				continue;
			}

			if (strParentKey.Length > 0)
			{
				strParentKey = string.Concat(strParentKey, @"\", sTrimmed);
			}
			else
			{
				strParentKey = string.Concat(strParentKey, sTrimmed);
			}

			if (sl.ContainsKey(strParentKey))
			{
				//verwende diesen
				nd = sl[strParentKey] as TreeNode;
			}
			else
			{
				//create new
				nd = new TreeNode(sTrimmed);
				//den FullPath adden
				sl.Add(strParentKey, nd);
				parentNodes.Add(nd);
			}

			parentNodes = nd.Nodes;
		}
	}
	this.treeView1.EndUpdate();
}

private void button4_Click(object sender, EventArgs e)
{
	 string[] lines=new string[]
	 {
		 @"E:\",
		 @"E:\Bier",
		 @"D:\Eigene Dateien",
		 @"D:\Programme\Games",
		 @"D:\Eigene Dateien\Eigene Musik2",
		 @"D:\",
		 @"D:\Eigene Dateien\Eigene Downloads\Multi",
		 @"D:\Eigene Dateien\Eigene Downloads\Multi\CD 1",
		 @"D:\Eigene Dateien\Eigene Downloads\Multi\CD 2",
		 @"D:\Eigene Dateien\Eigene Downloads\Multi\CD 3",
		 @"D:\Eigene Dateien\Eigene Downloads\Multi\CD 3\Teil 2",
		 @"D:\Eigene Dateien\Eigene Downloads\Multi\CD 4"
	 };

	 populateTreeFromStringArray(lines);
 }

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();
        }
    }
}

Sparx Systems Enterprise Architect: SQL to get all Links with their start and end objects and a tagged value

Problem

A SQL statement is needed, that returns a list of all link relations with start and end object name. Additionally a tagged value (here it is called ‚Object identifier‘) should be appended

Approach

Usage of MDB Plus

Solution

Note: If you do not need tagged values, you can customize the following Access / .eap-File Statement in the way that you reduce it by leaving out the last 2 LEFT JOINs (and don’t forget to remove the Columns from the Select clause).

SELECT      objstart.[Object_ID] As EAIDSource,
            objstart.[Name] AS EANameSource,
            objpropstart.[Value] AS DoorsSoruceObjectID,
            tconn.[Connector_ID] AS EAConnectorID,
            tconn.[Direction] AS EADirection,
            tconn.[Connector_Type] AS EAConnectorType,
            tconn.[Stereotype] AS EAStereoType,
            objend.[Object_ID] AS EAIDTarget,
            objend.[Name] AS EANameTarget,
            objpropende.[Value] AS DoorsTargetObjectID
FROM                                                                                          
(((                                                              
[t_connector] tconn LEFT JOIN [t_object] objstart ON tconn.[Start_Object_ID]=objstart.[Object_ID])
                    LEFT JOIN [t_object] objend ON tconn.[End_Object_ID]=objend.[Object_ID])                                                                           
                    LEFT JOIN (SELECT [Object_ID], [Property], [Value] FROM [t_objectproperties] WHERE [Property]="Object identifier" ) objpropstart ON tconn.[Start_Object_ID]=objpropstart.[Object_ID] )
                    LEFT JOIN (SELECT [Object_ID], [Property], [Value] FROM [t_objectproperties] WHERE [Property]="Object identifier" ) objpropende ON tconn.[End_Object_ID]=objpropende.[Object_ID]

Sparx Systems Enterprise Architect: SQL To get (x,y) Coordinates , width and height of Diagram Objects

Problem

A SQL Statement is needed to get the coordinates of Diagram Object like Activities, Classes, Lanes and so on…
In this statement only the stereotypes ‚Project Phase‘, ‚Gate‘, ‚Product Maturity‘, ‚Lane‘ of the diagram ‚Product Creation Process‘ will be selected

Approach

Usage of MDB Plus or another SQL Tool

Solution

This example is for Access / .eap-Files

SELECT  dia.Name As Diagram,
                objstart.stereotype,
                diaobj.RectLeft As x,
                diaobj.RectTop As y,
                diaobj.RectRight-diaobj.RectLeft As Width,
                Abs(diaobj.RectBottom-diaobj.RectTop) As Height,
                objstart.Object_ID,                               
                objstart.Alias,
                objstart.[Name] As ProcessStep
FROM                                                 
((
                [t_diagram] dia LEFT JOIN (Select Diagram_ID, Object_ID, RectLeft, RectTop, RectRight, RectBottom from [t_diagramobjects]) diaobj ON dia.[Diagram_ID]=diaobj.[Diagram_ID])
                                LEFT JOIN [t_object] objstart ON objstart.[Object_ID]=diaobj.[Object_ID])
WHERE dia.Name='Product Creation Process'
AND objstart.stereotype IN ('Project Phase', 'Gate', 'Product Maturity', 'Lane')
ORDER BY 1,2,3,4,5,6,7,8,9