how to call FileHelpers.RecordTypeSelector correctly? - filehelpers

I'm working with FileHelpers: https://www.filehelpers.net/
I have a source file which contains a set of approximately 10 different RecordTypes. To accommodate, I intend to use a MultiRecordEngine (https://www.filehelpers.net/example/Advanced/MultiRecordEngine/).
As I read the instructions, I should declare the engine
var engine = new MultiRecordEngine(typeof (Orders),
typeof (Customer),
typeof (SampleType));
... and then feed the "CustomSelector" ...
engine.RecordSelector = new RecordTypeSelector(CustomSelector);
Looking at the documentation at the link provided, "CustomSelector" is a private method inside Selector.cs.
private Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (Char.IsLetter(recordLine[0]))
return typeof (Customer);
else if (recordLine.Length == 14)
return typeof (SampleType);
else
return typeof (Orders);
}
There's no mention of a delegate, and declaring one didn't improve Mister Compiler's opinion of my code. Does anybody have experience with MultiRecordEngine to tell me what perfectly obvious fact I'm missing? Thanks!

Okay, the documentation and my eyes were having a tiff. As given, this code...
engine.RecordSelector = new RecordTypeSelector(CustomSelector);
... is useful only if CustomSelector is a local function, which strikes me as bad form. I stuck with a separate Selector class, and declared "CustomSelector" as public static:
public static Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (Char.IsLetter(recordLine[0]))
return typeof (Customer);
else if (recordLine.Length == 14)
return typeof (SampleType);
else
return typeof (Orders);
}
Once I tell MultiRecordEngine where to find it,
engine.RecordSelector = new RecordTypeSelector(Selector.CustomSelector);
... you're golden.
I hope this helps save the next person the 10 minutes I spent typing the question and answer. Enjoy! :)

Related

Returning distinct data for a dropdownlist box with selectlistItem

I have a field in my database with duplicates. I want to use it in a dropdown list, which has to return distinct data.
Here is the method that I created to do this:
public IEnumerable<SelectListItem> GetBranches(string username)
{
using (var objData = new BranchEntities())
{
IEnumerable<SelectListItem> objdataresult = objData.ABC_USER.Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
}).Distinct(new Reuseablecomp.SelectListItemComparer());
return objdataresult;
}
}
Here is the class I am using:
public static class Reuseablecomp
{
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
}
Nothing is returned and I get the error below. When I try a basic query without Distinct, everything works fine.
{"The operation cannot be completed because the DbContext has been disposed."}
System.Exception {System.InvalidOperationException}
Inner exception = null
How can I return distinct data for my dropdown?
Technically, your problem can be solved simply by appending .ToList() after your Distinct(...) call. The problem is that queries are evaluated JIT (just in time). In other words, until the actual data the query represents is needed, the query is not actually sent to the database. Calling ToList is one such thing that requires the actual data, and therefore will cause the query to be evaluated immediately.
However, the root cause of your problem is that you are doing this within a using statement. When the method exits, the query has not yet been evaluated, but you have now disposed of your context. Therefore, when it comes time to actually evaluate that query, there's no context to do it with and you get that exception. You should really never use a database context in conjuction with using. It's just a recipe for disaster. Your context should ideally be request-scoped and you should use dependency injection to feed it to whatever objects or methods need it.
Also, for what it's worth, you can simply move your Distinct call to before your Select and you won't need a custom IEqualityComparer any more. For example:
var objdataresult = objData.ABC_USER.Distinct().Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
});
Order of ops does matter here. Calling Distinct first includes it as part of the query to the database, but calling it after, as you're doing, runs it on the in-memory collection, once evaluated. The latter requires, then, custom logic to determine what constitutes distinct items in an IEnumerable<SelectListItem>, which is obviously not necessary for the database query version.

Get all SmartForm items from Ektron 9 in a Taxonomy

I'm using Ektron CMS version 9.0
I have smart form content which is allocated to taxonomies e.g. I might have five smart form content items (all of same) type allocated to a taxonomy, and another three to a different taxonomy:
I need to get all content of a smart form type from a taxonomy:
public IEnumerable<T> GetListOfSmartFormFromTaxonomy<T>(long taxonomyId, bool isRecursive) where T : class
{
// TODO
}
What I have working, based on links below, is this:
public IEnumerable<TaxonomyItemData> GetListOfSmartFormFromTaxonomy(long taxonomyId)
{
TaxonomyItemCriteria criteria = new TaxonomyItemCriteria();
criteria.AddFilter(TaxonomyItemProperty.TaxonomyId, CriteriaFilterOperator.EqualTo, taxonomyId);
TaxonomyItemManager taxonomyItemManager = new TaxonomyItemManager();
List<TaxonomyItemData> taxonomyItemList = taxonomyItemManager.GetList(criteria);
return taxonomyItemList;
}
But this just gets the item's titles and ids, not the smart form data itself.
As an Ektron newbie, I don't know how to get all the items of one Smart Form type using only one call (instead of looping through each item and fetching it by ID which is not efficient)
What have I missed? I am working on this actively today and will post my findings here.
References used so far:
http://reference.ektron.com/developer/framework/Organization/TaxonomyItemManager/GetList.asp
Ektron taxonomy and library items (in v9)
EDIT
Posted my just-got-it-working solution below as an fyi and awarded closest answer as accepted. Thanks everyone for your help. Please chime in with any improvements ;)
I'd recommend using the ContentTaxonomyCriteria with the ContentManager.
long smartFormId = 42;
long taxonomyId = 127;
bool isRecursive = true;
var cm = new ContentManager();
var taxonomyCriteria = new ContentTaxonomyCriteria();
taxonomyCriteria.AddFilter(ContentProperty.XmlConfigurationId, CriteriaFilterOperator.EqualTo, smartFormId);
taxonomyCriteria.AddFilter(taxonomyId, isRecursive);
var content = cm.GetList(taxonomyCriteria);
UPDATE
The ContentData object has a property called XmlConfiguration. When the content is based on a smartform, this property will be non-null and have a positive (non-zero) Id: content[0].XmlConfiguration.Id for example.
I often add an Extension Method to my code that will tell me whether a given ContentData is based on a smart form:
public static class ContentDataExtensions
{
public static bool IsSmartFormContent(this ContentData content)
{
return content != null && content.XmlConfiguration != null && content.XmlConfiguration.Id > 0;
}
}
That way I can take a content (or list of content) and check it very quickly in code to see if it's based on a smartform or not:
foreach (var contentData in contentList)
{
if (contentData.IsSmartFormContent())
{
// Do smart-form stuff here...
}
}
Of course, if your content is coming from the framework api and you used a criteria object that is selecting based on a specific XmlConfigurationId, then in theory you wouldn't have to use that, but it still comes in handy quite often.
I'm not quite sure I understand your organizational structure, but you do have the ability to do your own sub clauses that select directly against the database.
In this case I wouldn't use the TaxonomyItemManager, I would use the ContentManager with a special criteria:
ContentManager cApi = new ContentManager();
var criteria = new ContentCriteria();
criteria.AddFilter(ContentProperty.Id, CriteriaFilterOperator.InSubClause, "select taxonomy_item_id where taxonomy_id = " + taxonomyId);
criteria.AddFilter(ContentProperty.XmlConfigurationId, CriteriaFilterOperator.EqualTo, smartformTypeId);
var yourContent = cApi.GetList(criteria);
That should do what you're asking for (grab the content specifically that is a member of a Taxonomy while only being of a specific SmartForm config). It's worth noting you don't need the second criteria piece (XmlConfigurationId) if your Taxonomy only contains that XmlConfiguration.
For Information, this is what I came up with. Noted Brian Oliver's comment on List but using patterns from other devs, can refactor later.
To clarify, we are creating classes from the XSDs generated from the smart forms, so have smart form types to play with. Your use may be simpler that ours.
public IEnumerable<T> GetListOfSmartFormFromTaxonomy<T>(long taxonomyId, bool isRecursive = false) where T : class
{
long smartFormId = GetSmartFormIdFromType(typeof(T));
// checks here for smartformid=0
ContentManager contentManager = new ContentManager();
ContentTaxonomyCriteria criteria = new ContentTaxonomyCriteria();
// Smart Form Type
criteria.AddFilter(ContentProperty.XmlConfigurationId, CriteriaFilterOperator.EqualTo, smartFormId);
// Taxonomy
criteria.AddFilter(taxonomyId, isRecursive);
List<ContentData> contentDataList = contentManager.GetList(criteria);
IEnumerable<T> smartFormList = ConvertToSmartFormList<T>(pressReleaseDataList);
return smartFormList;
}
private IEnumerable<T> ConvertToSmartFormList<T>(List<ContentData> contentDataList) where T : class
{
List<T> smartFormList = new List<T>();
if (contentDataList != null && contentDataList.Count > 0)
{
foreach (ContentData contentData in contentDataList)
{
if (contentData.IsSmartFormContent())
{
T smartForm = GetDeserializedContent<T>(contentData.Html);
if (smartForm != null)
{
PropertyInfo property = smartForm.GetType().GetProperty("ContentId");
if (property != null)
{
property.SetValue(smartForm, contentData.Id, null);
}
smartFormList.Add(smartForm);
}
}
}
}
return smartFormList;
}
private long GetSmartFormIdFromType(Type smartFormType)
{
SmartFormConfigurationManager manager = new SmartFormConfigurationManager();
SmartFormConfigurationCriteria criteria = new SmartFormConfigurationCriteria();
// Note: Smart Form Title must match the type's name, i.e. no spaces, for this to work
criteria.AddFilter(SmartFormConfigurationProperty.Title, CriteriaFilterOperator.EqualTo, smartFormType.Name);
List<SmartFormConfigurationData> configurationData = manager.GetList(criteria);
if (configurationData == null || configurationData.Count == 0)
{
return 0;
}
return configurationData.First().Id;
}

My Nintex Custom Action not reading in Workflow Variable in SingleLineInput

I've written a custom workflow action that takes in several values, mostly using the SingleLineInput control.
When I assign literal values, I have no issues, but when I try to assign a Workflow Variable, I don't get the actual value of the variable, I get the literal text - something like {WorkflowVariable:XmlValue} - assuming my variable was names XmlValue.
I'm not sure what I could possibly be doing wrong. Any ideas?
Here's code snippets:
The javascript for retrieving the value from the SingleLineInput
function TPAWriteConfig() {
configXml.selectSingleNode("/NWActionConfig/Parameters/Parameter[#Name='FieldValue']/PrimitiveValue/#Value").text = getRTEValue('<%=fieldValue.ClientID%>');
SaveErrorHandlingSection();
return true;
}
The server control:
<Nintex:ConfigurationProperty ID="ConfigurationProperty3" runat="server" FieldTitle="Field Value" RequiredField="True">
<TemplateControlArea>
<Nintex:SingleLineInput runat="server" id="fieldValue"></Nintex:SingleLineInput>
</TemplateControlArea>
</Nintex:ConfigurationProperty>
From my adapter class:
private const string FieldValueProperty = "FieldValue";
NWActionConfig config = new NWActionConfig(this);
config.Parameters[2] = new ActivityParameter();
config.Parameters[2].Name = FieldValueProperty;
config.Parameters[2].PrimitiveValue = new PrimitiveValue();
config.Parameters[2].PrimitiveValue.Value = string.Empty;
config.Parameters[2].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
From the activity class:
public static DependencyProperty FieldValueProperty = DependencyProperty.Register("FieldValue", typeof (string),
typeof (
WriteOnePdfFieldActivity));
public string FieldValue
{
get { return (string) GetValue(FieldValueProperty); }
set { SetValue(FieldValueProperty, value); }
}
I feel a little silly answering my own question, but for the sake of anyone else having the same issues. Here's how it works:
If you're putting a literal value in the field, just use the value
If you're using any other kind of assignment, do a lookup based on the value.
The code below demonstrates:
var fieldValue = FieldValue.StartsWith("{") ? ctx.AddContextDataToString(FieldValue, true) : FieldValue;
This extract the value from the workflow context. Hope this helps.

Reflection - Iterate object's properties recursively within my own assemblies (Vb.Net/3.5)

I wonder if anyone can help me - I've not done much with reflection but understand the basic principles.
What I'm trying to do:
I'm in the process of developing a class that gathers a lot of information about the local system, network, etc... to be used for automated bug reporting. Instead of having to change my test harness every time I add a new property, I'd (ideally) like to be able to serialise the lot as an XML string and just display that in a textbox.
Unfortunately, the Framework won't use the default XML serializer on read-only properties (which almost all of mine are) as they wouldn't deserialize properly
[Not sure I agree with the assumption that anything serialized must be de-serializable - MS says this is a feature "by design" which I suppose I can understand - Perhaps a tag to indicate that it should be serialized anyway would be advantageous?]
The initial approach was to make properties gettable and settable (with a throw exception on the setter) but the amount of work tidying this up afterwards seems a little excessive and I would want the properties to be read-only in the final version.
What I need help with:
My current plan is to use reflection to recursively iterate through each (public) property of my topmost gathering class. The problem is, the samples I've seen don't handle things recursively. Additionally, I only want to inspect an object's properties if it's in one of my assemblies - Otherwise just call .ToString on it.
If I don't have the inspection limited to my assembly, I assume I'll get (say) a string which then contains a Length which in turn will have .Tostring method...
For the purposes of this project, I can almost guarantee no circular references within my code and as this will only be used as a development tool so I'm not too concerned about it running amok now and then.
I'd appreciate some examples/advice.
Many thanks in advance.
This will hopefully get you started. It prints a tree directly to the console so you'll need to adjust to output XML. Then change the IsMyOwnType method to filter out the assemblies you're interested in, right now it only cares about types in the same assembly as itself.
Shared Sub RecurseProperties(o As Object, level As Integer)
For Each pi As PropertyInfo In o.GetType().GetProperties()
If pi.GetIndexParameters().Length > 0 Then Continue For
Console.Write(New String(" "c, 2 * level))
Console.Write(pi.Name)
Console.Write(" = ")
Dim propValue As Object = pi.GetValue(o, Nothing)
If propValue Is Nothing Then
Console.WriteLine("<null>")
Else
If IsMyOwnType(pi.PropertyType) Then
Console.WriteLine("<object>")
RecurseProperties(propValue, level+1)
Else
Console.WriteLine(propValue.ToString())
End If
End If
Next
End Sub
Shared Function IsMyOwnType(t As Type) As Boolean
Return t.Assembly Is Assembly.GetExecutingAssembly()
End Function
you extension version on c# to use on any object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Extensions
{
public static class ObjectExtension
{
public static string ToStringProperties(this object o)
{
return o.ToStringProperties(0);
}
public static string ToStringProperties(this object o, int level)
{
StringBuilder sb = new StringBuilder();
string spacer = new String(' ', 2 * level);
if (level == 0) sb.Append(o.ToString());
sb.Append(spacer);
sb.Append("{\r\n");
foreach (PropertyInfo pi in o.GetType().GetProperties())
{
if (pi.GetIndexParameters().Length == 0)
{
sb.Append(spacer);
sb.Append(" ");
sb.Append(pi.Name);
sb.Append(" = ");
object propValue = pi.GetValue(o, null);
if (propValue == null)
{
sb.Append(" <null>");
} else {
if (IsMyOwnType(pi.PropertyType))
{
sb.Append("\r\n");
sb.Append(((object)propValue).ToStringProperties(level + 1));
} else{
sb.Append(propValue.ToString());
}
}
sb.Append("\r\n");
}
}
sb.Append(spacer);
sb.Append("}\r\n");
return sb.ToString();
}
private static bool IsMyOwnType(Type t)
{
return (t.Assembly == Assembly.GetExecutingAssembly());
}
}
}

Is it possible to pass a variable's name along with the value, when passing through functions?

I want to know if it's possible to retrieve the variables name from when it was passed into a certain function. For example, if I call parseId(myId) to a function with the signature parseId(id), i can obviously retrieve the value of 'id'. However, is there any way I can retrieve 'myId' as a string (without passing it as another value)?
Specifically in vb.net, but I'm interested in how it would work in any given language.
This is all just random thoughts.. feel free to dismiss or not ;-p
Re your comment about use with stored procedures... if you want to go that route, I wouldn't mess around with the local variable names; that is an implementation detail. However, you could expose those details on an interface method and use the names from there, since that is more formalised - for example (C#):
interface ICustomerRepository {
Customer GetById(int id); // perhaps an attribute to name the sproc
}
You can use similar expression-tree parsing (as discussed here) to get the name and value of the parameter, for example:
var repoWrapper = new Repo<ICustomerRepository>();
int custId = 12345;
var cust = repoWrapper.Execute(r => r.GetById(custId));
Here we'd want to resolve the argument to GetById as "id" (not "custId"), with value 12345. This is actually exactly what my protobuf-net RPC code does ;-p (just don't ask me to translate it to VB - it is hard enough to write it in a language you know well...)
No, you can't do that in the normal sense. What are you really trying to accomplish with this?
You can do this in .NET 3.5 and above using expression trees; I'll knock up a C# example, and try to run it through reflector for VB...
C#:
static void Main()
{
int i = 17;
WriteLine(() => i);
}
static void WriteLine<T>(Expression<Func<T>> expression)
{
string name;
switch (expression.Body.NodeType)
{
case ExpressionType.MemberAccess:
name = ((MemberExpression)expression.Body).Member.Name;
break;
default:
throw new NotSupportedException("Give me a chance!");
}
T val = expression.Compile()();
Console.WriteLine(name + "=" + val);
}
The VB is below, but note that the VB compiler seems to use different names (like $VB$Local_i, not i):
Sub Main()
Dim i As Integer = 17
WriteLine(Function() i)
End Sub
Private Sub WriteLine(Of T)(ByVal expression As Expression(Of Func(Of T)))
If (expression.Body.NodeType <> ExpressionType.MemberAccess) Then
Throw New NotSupportedException("Give me a chance!")
End If
Console.WriteLine((DirectCast(expression.Body, MemberExpression).Member.Name
& "=" & Convert.ToString(expression.Compile.Invoke)))
End Sub