I am searching for a API function corresponding to the "find in all diagrams"-function (Strg + U) in Enterprise Architect.
The class element provides the attribute diagrams which should return a collection of diagrams but it returns in my case always an empty list. Is it the wrong way?
EDIT:
I would be happy about a function that returns a collection of diagrams which include the element.
THE SOLUTION:
public List<EA.Diagram> getAllDiagramsOfElement(EA.Element element){
String xmlQueryResult = repository.SQLQuery(
"select dobj1.Diagram_ID " +
"from t_diagramobjects dobj1 " +
"where dobj1.Object_ID = " + element.ElementID+";");
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlQueryResult);
XmlNodeList xnList = xml.SelectNodes("/EADATA/Dataset_0/Data/Row");
List<EA.Diagram> result = new List<EA.Diagram>();
foreach (XmlNode xn in xnList){
result.Add(repository.GetDiagramByID(Convert.ToInt32(xn["Diagram_ID"].InnerText)));
}
return result;
}
With kind regards
MK
You might have to use a query,
Try this
select * from t_diagramobjects dobj1, t_diagramobjects dobj2 where dobj1.object_id=dobj2.object_id and dobj1.diagram_id!=dobj2.diagram_id;
In case you would like to stay with the API, you have to walk the packages in the model tree recursively, adding diagrams to a collection (ok, Dictionary object in VBScript).
Then you find all Diagramobjects from Diagrams. DiagramObjects then relate to Elements (remember, Element may be represented in more Diagrams).
Another approach could be to use Repository.SQLQuery method, which should return XML-formatted resultset (I didn't test that yet). But you'd need MSXML present on the machine to parse it (and keep up with the versions).
Generally, if you want to scan whole model and you don't need parent-child relationships, SQL should be better fit. And vice versa.
I have this same function in my Enterprise Architect Add-in Framework, implemented in the class ElementWrapper:
//returns a list of diagrams that somehow use this element.
public override HashSet<T> getUsingDiagrams<T>()
{
string sqlGetDiagrams = #"select distinct d.Diagram_ID from t_DiagramObjects d
where d.Object_ID = " + this.wrappedElement.ElementID;
List<UML.Diagrams.Diagram> allDiagrams = this.model.getDiagramsByQuery(sqlGetDiagrams).Cast<UML.Diagrams.Diagram>().ToList(); ; ;
HashSet<T> returnedDiagrams = new HashSet<T>();
foreach (UML.Diagrams.Diagram diagram in allDiagrams)
{
if (diagram is T)
{
T typedDiagram = (T)diagram;
if (!returnedDiagrams.Contains(typedDiagram))
{
returnedDiagrams.Add(typedDiagram);
}
}
}
return returnedDiagrams;
}
The function getDiagramsByQuery in the Model class looks like this
//returns a list of diagrams according to the given query.
//the given query should return a list of diagram id's
public List<Diagram> getDiagramsByQuery(string sqlGetDiagrams)
{
// get the nodes with the name "Diagram_ID"
XmlDocument xmlDiagramIDs = this.SQLQuery(sqlGetDiagrams);
XmlNodeList diagramIDNodes =
xmlDiagramIDs.SelectNodes(formatXPath("//Diagram_ID"));
List<Diagram> diagrams = new List<Diagram>();
foreach (XmlNode diagramIDNode in diagramIDNodes)
{
int diagramID;
if (int.TryParse(diagramIDNode.InnerText, out diagramID))
{
Diagram diagram = this.getDiagramByID(diagramID);
diagrams.Add(diagram);
}
}
return diagrams;
}
Related
I need to know the correct way to handle SQL Injection when using the FromSQL command.
At runtime, I need to dynamically create a where statement. So I am using FromSql to create the SQL command. Now I know that using use string interpolation is the way to go. However, I need to step through a list of "Where Parameters" to generate the command. Simple enough to do;
foreach (var x in wp)
{
if (!string.IsNullOrEmpty(results))
results = $"{results} and {x.Field} = {x.Value}";
if (string.IsNullOrEmpty(results))
results = $"where {x.Field} = {x.Value}";
}
Problem is that this return a simple string and would not be string interpolation. How can I do this correctly?
Entityframework will parameterize your queries if you put it in the following format:
db.something.FromSql("SELECT * FROM yourTable WHERE AuthorId = {0}", id)
Is x.Field a form field that has a fixed number of possibilities? i.e. title, firstname etc. If so then something like the following:
var sqlstring = new StringBuilder();
var sqlp = new List<SqlParameter>();
var i = 0;
foreach (var x in wp)
{
var param = "#param" + i.ToString();
if (i!=0)
{
sqlstring.Append($" AND {x.Field} = " + param);
sqlp.Add(new SqlParameter(param, x.Value));
}
if (i==0)
{
sqlstring.Append($"WHERE {x.Field} = " + " #param" + i.ToString());
sqlp.Add(new SqlParameter(param, x.Value));
}
i++;
}
You'd then need to do something like this:
db.something.FromSql(sqlstring.ToString(), sqlp.ToArray())
Might be a better/cleaner way but that should work.
My solution to this problem is a VS extension, QueryFirst. QueryFirst generates a C# wrapper for sql that lives in a .sql file. As such, parameters are the only way to get data into your query and SQL injection is near impossible. There are numerous other advantages: you edit your sql in a real environment, it's constantly validated against your db, and using your query in your code is very simple.
I have some word templates(maybe thousands). Each template has merge fields which will be filled from database. I don`t like writing separate code for every template and then build the application and deploy it whenever a template is changed or a field on the template is added!
Instead, I'm trying to define all merge fields in a separate xml file and for each field I want to write the "query" which will be called when needed. EX:
mergefield1 will call query "Case.Parties.FirstOrDefault.NameEn"
mergefield2 will call query "Case.CaseNumber"
mergefield3 will call query "Case.Documents.FirstOrDefault.DocumentContent.DocumentType"
Etc,
So, for a particular template I scan its merge fields, and for each merge field I take it`s "query definition" and make that request to database using EntityFramework and LINQ. Ex. it works for these queries: "TimeSlots.FirstOrDefault.StartDateTime" or
"Case.CaseNumber"
This will be an engine which will generate word documents and fill it with merge fields from xml. In addition, it will work for any new template or new merge field.
Now, I have worked a version using reflection.
public string GetColumnValueByObjectByName(Expression<Func<TEntity, bool>> filter = null, string objectName = "", string dllName = "", string objectID = "", string propertyName = "")
{
string objectDllName = objectName + ", " + dllName;
Type type = Type.GetType(objectDllName);
Guid oID = new Guid(objectID);
dynamic Entity = context.Set(type).Find(oID); // get Object by Type and ObjectID
string value = ""; //the value which will be filled with data from database
IEnumerable<string> linqMethods = typeof(System.Linq.Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Select(s => s.Name).ToList(); //get all linq methods and save them as list of strings
if (propertyName.Contains('.'))
{
string[] properies = propertyName.Split('.');
dynamic object1 = Entity;
IEnumerable<dynamic> Child = new List<dynamic>();
for (int i = 0; i < properies.Length; i++)
{
if (i < properies.Length - 1 && linqMethods.Contains(properies[i + 1]))
{
Child = type.GetProperty(properies[i]).GetValue(object1, null);
}
else if (linqMethods.Contains(properies[i]))
{
object1 = Child.Cast<object>().FirstOrDefault(); //for now works only with FirstOrDefault - Later it will be changed to work with ToList or other linq methods
type = object1.GetType();
}
else
{
if (linqMethods.Contains(properies[i]))
{
object1 = type.GetProperty(properies[i + 1]).GetValue(object1, null);
}
else
{
object1 = type.GetProperty(properies[i]).GetValue(object1, null);
}
type = object1.GetType();
}
}
value = object1.ToString(); //.StartDateTime.ToString();
}
return value;
}
I`m not sure if this is the best approach. Does anyone have a better suggestion, or maybe someone has already done something like this?
To shorten it: The idea is to make generic linq queries to database from a string like: "Case.Parties.FirstOrDefault.NameEn".
Your approach is very good. I have no doubt that it already works.
Another approach is using Expression Tree like #Egorikas have suggested.
Disclaimer: I'm the owner of the project Eval-Expression.NET
In short, this library allows you to evaluate almost any C# code at runtime (What you exactly want to do).
I would suggest you use my library instead. To keep the code:
More readable
Easier to support
Add some flexibility
Example
public string GetColumnValueByObjectByName(Expression<Func<TEntity, bool>> filter = null, string objectName = "", string dllName = "", string objectID = "", string propertyName = "")
{
string objectDllName = objectName + ", " + dllName;
Type type = Type.GetType(objectDllName);
Guid oID = new Guid(objectID);
object Entity = context.Set(type).Find(oID); // get Object by Type and ObjectID
var value = Eval.Execute("x." + propertyName, new { x = entity });
return value.ToString();
}
The library also allow you to use dynamic string with IQueryable
Wiki: LINQ-Dynamic
I can't find good documentation on these operators. Can someone provide some examples of use and explain what they do?
Entity SQL's CREATEREF reference: http://msdn.microsoft.com/en-us/library/bb386880(v=VS.90)
It's used to "Fabricates references to an entity in an entityset". You can also find references of REF and DEREF from the link.
For VS 2010, the reference is: http://msdn.microsoft.com/en-us/library/bb386880(v=VS.100)
Sample from MSDN:
In the example below, Orders and BadOrders are both entitysets of type
Order, and Id is assumed to be the single key property of Order. The
example illustrates how we may produce a reference to an entity in
BadOrders. Note that the reference may be dangling. That is, the
reference may not actually identify a specific entity. In those cases,
a DEREF operation on that reference returns a null.
select CreateRef(LOB.BadOrders, row(o.Id))
from LOB.Orders as o
Sample code of using entity framework SQL:
using (EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities"))
{
conn.Open();
// Create a query that takes two parameters.
string esqlQuery =
#"SELECT VALUE Contact FROM AdventureWorksEntities.Contact
AS Contact WHERE Contact.LastName = #ln AND
Contact.FirstName = #fn";
try
{
using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
{
// Create two parameters and add them to
// the EntityCommand's Parameters collection
EntityParameter param1 = new EntityParameter();
param1.ParameterName = "ln";
param1.Value = "Adams";
EntityParameter param2 = new EntityParameter();
param2.ParameterName = "fn";
param2.Value = "Frances";
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// Iterate through the collection of Contact items.
while (rdr.Read())
{
Console.WriteLine(rdr["FirstName"]);
Console.WriteLine(rdr["LastName"]);
}
}
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}
Ok, I must be working too hard because I can't get my head around what it takes to use the Entity Framework correctly.
Here is what I am trying to do:
I have two tables: HeaderTable and DetailTable. The DetailTable will have 1 to Many records for each row in HeaderTable. In my EDM I set up a Relationship between these two tables to reflect this.
Since there is now a relationship setup between these tables, I thought that by quering all the records in HeaderTable, I would be able to access the DetailTable collection created by the EDM (I can see the property when quering, but it's null).
Here is my query (this is a Silverlight app, so I am using the DomainContext on the client):
// myContext is instatiated with class scope
EntityQuery<Project> query = _myContext.GetHeadersQuery();
_myContext.Load<Project>(query);
Since these calls are asynchronous, I check the values after the callback has completed. When checking the value of _myContext.HeaderTable I have all the rows expected. However, the DetailsTable property within _myContext.HeaderTable is empty.
foreach (var h in _myContext.HeaderTable) // Has records
{
foreach (var d in h.DetailTable) // No records
{
string test = d.Description;
}
I'm assuming my query to return all HeaderTable objects needs to be modified to somehow return all the HeaderDetail collectoins for each HeaderTable row. I just don't understand how this non-logical modeling stuff works yet.
What am I doing wrong? Any help is greatly appriciated. If you need more information, just let me know. I will be happy to provide anything you need.
Thanks,
-Scott
What you're probably missing is the Include(), which I think is out of scope of the code you provided.
Check out this cool video; it explained everything about EDM and Linq-to-Entities to me:
http://msdn.microsoft.com/en-us/data/ff628210.aspx
In case you can't view video now, check out this piece of code I have based on those videos (sorry it's not in Silverlight, but it's the same basic idea, I hope).
The retrieval:
public List<Story> GetAllStories()
{
return context.Stories.Include("User").Include("StoryComments").Where(s => s.HostID == CurrentHost.ID).ToList();
}
Loading the the data:
private void LoadAllStories()
{
lvwStories.DataSource = TEContext.GetAllStories();
lvwStories.DataBind();
}
Using the data:
protected void lvwStories_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Story story = e.Item.DataItem as Story;
// blah blah blah....
hlStory.Text = story.Title;
hlStory.NavigateUrl = "StoryView.aspx?id=" + story.ID;
lblStoryCommentCount.Text = "(" + story.StoryComments.Count.ToString() + " comment" + (story.StoryComments.Count > 1 ? "s" : "") + ")";
lblStoryBody.Text = story.Body;
lblStoryUser.Text = story.User.Username;
lblStoryDTS.Text = story.AddedDTS.ToShortTimeString();
}
}
I have a repository:
public ObservableCollection<ProjectExpenseBO> GetProjectExpenses()
{
//Get by query
IQueryable<ProjectExpenseBO> projectExpenseQuery =
from p in _service.project_expense
from e in _service.vw_employee
where p.employee_id == e.employee_id
select new ProjectExpenseBO()
{
ProjectExpenseID = p.project_expense_id
, EmployeeID = p.employee_id
, ProjectNumber = p.project_number
, PurchaseTypeID = p.purchase_type_id
, BuyerEmployeeID = p.buyer_employee_id
, PurchaseOrderNumber = p.purchase_order_number
, DeliveryDate = p.delivery_date
, EmployeeName = e.first_name + " " + e.last_name
};
ObservableCollection<ProjectExpenseBO> projectExpenseCollection = new ObservableCollection<ProjectExpenseBO>(projectExpenseQuery);
return projectExpenseCollection;
}
I am wondering if it is better to return an IList or IEnumerable (instead of an ObservableCollection) from my repository since my viewmodel may end up putting it in either an ObservableCollection or List, depending on my need. For instance, I may return data from the repository above to a read-only datagrid or dropdown list, or I may want the same data in an editable datagrid.
I am thinking (and could be wrong) that I want my repository to return a barebones list, then convert it to what suites my needs in the viewmodel. Is my thinking correct? Here is what I was thinking:
public IEnumerable<ProjectExpenseBO> GetProjectExpenses()
{
//Get by query
IQueryable<ProjectExpenseBO> projectExpenseQuery =
from p in _service.project_expense
from e in _service.vw_employee
where p.employee_id == e.employee_id
select new ProjectExpenseBO()
{
ProjectExpenseID = p.project_expense_id
, EmployeeID = p.employee_id
, ProjectNumber = p.project_number
, PurchaseTypeID = p.purchase_type_id
, BuyerEmployeeID = p.buyer_employee_id
, PurchaseOrderNumber = p.purchase_order_number
, DeliveryDate = p.delivery_date
, EmployeeName = e.first_name + " " + e.last_name
};
return projectExpenseQuery;
}
Thanks.
I would personally return an IEnumerable<T> or IList<T> instead of ObservableCollection. There are many times when you may not need the full behavior of ObservableCollection<T>, in which case you're putting more resources than necessary.
I like your second implementation - however, be aware that there is one potential downside. Some people don't like returning deferred execution IEnumerable<T> from a repository, since it defers execution until usage. While it has the upside of potentially saving resources, especially if you end up not using some or all of the enumerable, this can lead to an exception occuring later (when the IEnumerable<T> is actually used), instead of occuring within your repository yourself.
If this bothers you, you could just force the execution to occur (ie: call ToList() or similar).
Personally I'd return an IEnumerable<T> if you're simply using it to populate the UI. No need to return a List<T> if you aren't going to be adding/removing items from it.