Sequence contains no elements when using count on LINQ Query - linq

IEnumerable<EntityReference> children = (
from c in OrgContext.CreateQuery<Account>()
where
c.ParentAccountId != null && c.ParentAccountId.Id.Equals(parentGuid)
select
c.ToEntityReference()).ToList();
return children.Count() > 0 ? null : new List<EntityReference>();
Throws a "Sequence contains no elements" error. How can I reliably check if the sequence is empty before trying to count the elements? (I'd expect Count to simply return 0)

This error for me was caused by visual studio using an old build instead of my current build. I don't know why it does this, but I've had it happen in visual studio 2012 and 2013. Just deleting the bin folder fixed it.
In your case, I think the problem is that you're using the Count() method instead of the Count property.

Related

Importing flat file into SSIS gives problems because non-consistent deliminater

I am facing a problem importing a flat file into SSIS.
The file is seperated by "|" and has deliminater as ";;". However the deliminator is inconsistent. Sometimes, at the and of the rows, there is only ";" or nothing "". When importing to SSIS I get the result
Column 1 Column 2 Column 3 Column 4 Column 5
a b c d e;|a1|b1|c1|d1|e1
This should instead look like
Column 1 Column 2 Column 3 Column 4 Column 5
a b c d e
a1 b1 c1 d1 e1
And the problem arrises because in the first row there is only one or none ";".
Note this is an example, many of the rows are correct and have ";;" as deliminator. I am only pointing out the problem.
The .csv file would look like
Column 1|Column 2|Column 3|Column 4|Column 5;;
a|b|c|d|e;
a1|b1|c1|d1|e1;;
and should instead look like
Column 1|Column 2|Column 3|Column 4|Column 5;;
a|b|c|d|e;;
a1|b1|c1|d1|e1;;
The data set is very big with almost 600.000 rows and 50 columns.
The first problem I face is when I import the file, since SSIS standard DataType reading is string [DT_STR]. with a length of 50. Since sometimes there are multiple rows with wrong deliminators, I get a very long strings in the last column cell. I Use Visual Studio, and in the Advanced Editor I changed the length to something very big.
Advanced editor in Visual studio were I have changed the length
So the question is, how do I in SSIS and Visual Studio Community separate the values in some cells in one column and split op these into a entire new row (with the already defined column variables).
I have tried manually to find all the cases where there is a error and changed this in the .csv file. After this SSIS works. However this is not a durable solution because I am getting a new file every month.
I have tried reading suggestions as:
Split a single column of data with comma delimiters into multiple columns in SSIS
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/49a764e7-1a6f-4a6f-9c92-2462ffa3add2/regarding-ssis-split-multi-value-column-into-multiple-records?forum=sqlintegrationservices
but their problem is not he same, since they have a column value the replicate, and I want a entire new row.
Thanks for any help,
ss
!! EDIT trying using the answers from J Weezy and R M: !!
I try to create a script task and follow that solution.
In Visual Studio, I add a script task using a Script Component and I choose "Transformation". Under Input Columns I choose all.
After this i direct the flat file source to the script component and run the code. Running the script like this (where the script component doesn't do anything) works.
Then I enter "Edit Script" in the script component, and under public override void Input0_ProcessInputRow(Input0Buffer Row) I enter (using the help from R M):
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
public static string[] SplitLine(string input)
{
Regex lineSplit = new Regex("[0-9]\;$", RegexOptions.Compiled);
List<string> list = new List<string>();
string curr = null;
foreach (Match match in lineSplit.Matches(input))
{
curr = match.Value;
if (0 == curr.Length)
{
list.Add("");
}
list.Add(curr.TrimStart(';'));
}
return list.ToArray();
}
}
However this doesn't work (I am not even allowed to execute the task).
I have never worked with c# before so everything is new to me. As i understand the code, it search each line to find the pattern where there is numbers in front of only one ";" at the end, hence it will not find those lines which ends with numbers following by ";;" (two ;).
When there is a match, one ";" is added.
Please let me know, what I am not understanding and doing wrong.
Maybe it is also wrong to put the script component after the flat file source, because adding ";" will not result in a new line, which is what I want.
Inconsistent row delimiters is bad data and there really is no way to correct for this in either the connection manager or the data flow. Fixing bad data within the data flow is not what SSIS was designed for. Your best bet is to do one of the two following:
Work with the data source provider to fix the issue on their end
Create a script task to first modify the file to correct the bad data
From there, you will be able to process the file normally in SSIS.
Update 1:
If the only problem is a duplicate delimiter (;;), then read in the row and use the Replace(";;",";"); function. If you have either multiple duplicate or invalid end of row delimiters, then you are better served by using StringBuilder(). For a solution on using StringBuilder(), see the weblink below.
https://stackoverflow.com/a/49949787/4630376
Update 2:
One thing that I just remembered, you will need to adjust for handling only those characters that are outside of double quotes, assuming that double quotes exist within the file as the text qualifier. This is important because without it you will remove any characters that are within quotes, which may be valid data.
I would agree with J Weezy to create a script task to correct the bad data. In the script task you could possibly use regex to deal with the “;” and “;;” issue. The script task may be your only way of dealing with the the “;” and “;;” issue.
While the below code in its current form will not work for your case, it possibly could be changed to work for your case. I have used it to deal with processing a text\csv file to correct formatting issues with each line of data. Note I got this from another post on Stackoverflow.
public static string[] SplitLine(string input)
{
Regex lineSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
List<string> list = new List<string>();
string curr = null;
foreach (Match match in lineSplit.Matches(input))
{
curr = match.Value;
if (0 == curr.Length)
{
list.Add("");
}
list.Add(curr.TrimStart(','));
}
return list.ToArray();
}

Assignment of arrays in Intel Fortran

I had an old Fortran 90 code with the following command:
data1(1:100) = data_all(:)
where data_all is a bigger array then data1.
Since I know that this is not a robust syntax, it worked good when using Visual Studio 2008.
I recently switched to Visual Studio 2013, and I am not able to use this code anymore, since it tries to fill the 101th position of data1.
What are the correct Compiler options to accept that?
Probably something like this:
data1(1:100) = data_all(1:100)
If data1 is 100 elements then
data1 = data_all(1:100)
If you want others then:
data1 = data_all(istart:(istart + (SIZE(data1) - 1))

Parameters for Jump to Report in VS 2010

I have a report in Visual Studio 2010 with two fields that have jump to's. Both jump to the same report. However, one of them only requires 3 parameters to be passed whereas the other field requires 4. How can I keep the same report that is being jumped to for both fields? I can't figure out a way to not have to pass the Date parameter. I know I can create a separate dataset and a separate report, but I'd like to avoid that if possible.
SELECT SalesData.SBLOC, SalesData.SBCUST, SalesData.RMNAME, SalesData.SBITEM, SalesData.IFPRVN, SalesData.SBITD1, SalesData.SBDIV, SalesData.SBCLS,
SalesData.SBQSHP, SalesData.AVC, SalesData.SBEPRC, SalesData.SBINV, SalesData.SBORD, SalesData.SBTYPE, SalesData.SBINDT, SalesData.RMSTAT
FROM SalesData INNER JOIN
FiscalCalendar ON SalesData.SBINDT = FiscalCalendar.FiscalDate
WHERE (FiscalCalendar.FiscalYear = '2013') AND (SalesData.SBLOC IN (#Location)) AND (SalesData.SBTYPE = 'O') AND (FiscalCalendar.FiscalMonthName IN (#FiscalMonthName)) AND (FiscalCalendar.FiscalWeekNum IN (#FiscalWeekNum)) AND (FiscalCalendar.FiscalDate IN (#FiscalDate))

Can Visual Studio 2010 do conditional breakpoints on a type

I would like to set a conditional breakpoint in Visual Studio based on what a type is assigned as.
var resident = user.Resident ? new ResidentUser() : new NonResidentUser();
I would like my breakpoint to hit when resident is of type NonResidentUser.
Simple, in this case you can do condition = user.Residen == false, but in other cases you could do residen.GetType() == typeof(NonResidentUser).
You should be able to do that - set the condition to be resident.GetType() == typeof(NoneResidentUser).
OK, it seems that putting !user.Resident in the conditional window will fire when I want and therefore the type will be of NonResidentUser.

SubSonic 3 Linq Join Problems

using the linqtemplates, I tried getting the linq syntax close to what is in the docs
var query = from c in db.CountyLookups
join s in db.StateLookUps on
c.StateLookupID equals
s.StateLookupID
where c.Name2 == countyName &&
s.Abbr == stateAbbr
select new
{
Latitude = c.Latitude,
Longitude = c.Longitude
};
var result = query.SingleOrDefault();
but when .SingleOrDefault() is called, I get a yellow screen of darn that says:
System.NotSupportedException: The member 'StateLookupID' is not supported
the stack trace ends up at:
SubSonic.Linq.Structure.TSqlFormatter.VisitMemberAccess(MemberExpression m)
the StateLookupID column has underscores in the database and is a regular int pk/fk.
what am I doing wrong?
So apparently VisitMemberAccess has no idea what to do with an int, only string and datetime (starting on line 152 of SubSonic.Linq.Structure.TSqlFormatter). I don't know why this would be called on a join, since a join is usually between an int pk/fk (or guid if you like).
I ended up scrapping the linq query in favor of SubSonic.Query.Select. Here is my new code that works:
var query = db.Select.From<CountyLookup>()
.InnerJoin<StateLookUp>()
.Where(CountyLookupTable.Name2Column)
.IsEqualTo(countyName)
.And(StateLookUpTable.AbbrColumn)
.IsEqualTo(stateAbbr);
I then call ExecuteTypedList and map the results back to my model class. Works like buttah. Just wanted to use linq in this case.
I get this error when I've added properties to my models (the IsValid property as mentioned in ASP.Net MVC 1.0, thanks Rob).
I've had this problem on and off for a bit, and I think I've got it nailed down to the query builder trying to build a query for something that should be done in code, not TSQL.
When it tries to generate the SQL, it descends down the path to generate the TSQL via VisitMemberAccess on a complex type (maybe a another model) but it only knows how to perform operations on datetimes and strings in VisitMemberAccess. I'm sorry if this is a bit incoherent, but I'm trying to get my head around it.
To get around this consider using something like LinqKit AsExpandable prior to any operation which will do the TSQL generation. I've tried this on a simple OrderBy which was going BANG and it appears to work but i have no idea yet what it will do to performance.
Actually I take that back I overcame my problem problem by doing
Stuff.All().Where(x=>x.Someid == id).ToArray()
.AsQueryable()
.Where(x=>x.SomeProp.SomeFlag == true);
It is crud, but it works.
This still appears to be a problem; namely in simple cases such as:
var list = from lang in db.Languages
join site in db.SiteConfigLanguages on
lang.Code equals site.LanguageCode
select lang;
This should evaluate to simple SQL (although pointless in this example):
SELECT Language.* FROM Language LEFT JOIN SiteConfigLanguage ON Language.Code = SiteConfigLanguage.LanguageCode;
It fails inside the same VisitMemberAccess function as (in this case) Language is not a recognisable declaring type (i.e. String or DateTime). It is very similar to the description #matware provided above however it sounds as though the "IsValid" member is pure C# code whereas in this case lang.Code is simply a reference to a column in the database.
I'm currently investigating workarounds as this is only a portion of the larger LINQ query which is failing for me; if I find anything I will post it here. Otherwise, any other solutions/workarounds to this problem known?
UPDATE: Ignore me here; this is simply due to me missing a simple line on the LINQ statement; you need to make sure that you use the "into" keyword to complete things!
i.e.
var list = from lang in db.Languages
join site in db.SiteConfigLanguages on
lang.Code equals site.LanguageCode into sl
from siteLang in sl.DefaultIfEmpty()
select lang;
I've got another error mind you but at least this particular exception is solved. The next one looks a bit nastier unfortunately (inside System.Linq library).

Resources