While calling out web service method I get error as follow:
GenericException
An unexpected error occured.
Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Where[TSource](IEnumerable1 source, Func2 predicate)
at QuotingGate.CalcsLV.Casco.Standard.Ergo.Calculate(VehicleQuotingParameters parameters, CascoQuote& quote) in c:\Projects\xxx\WebServices\QuotingGate\CalcsLV\Casco\Standard\Ergo.cs:line 152
at QuotingGate.CalcsBase.CalculatorBase`4.Quote(In parameters) in c:\Projects\xxx\WebServices\QuotingGate\CalcsBase\Base.cs:line 138
On Ergo.cs line 152 there is linq query like that:
var territory = from c in prices.premiums where c.tariffParam3 == "LV" select c;
Googled and find many cases where there was Single instead of SingleOrDefault.. but in my case its linq and relay does not matter is there any result or not, right ?
Prices are set here :
...
policyDataKASKORetParam1 prices = null;
prices = ws.GetCascoQuotesUnregistered(quote,
parameters.Vehicle.VIN,
parameters.Vehicle.Make,
parameters.Vehicle.Model,
parameters.Vehicle.ManufactureDate.Value.Year,
parameters.Vehicle.Value.Value,
parameters.Vehicle.EngineCapacity ?? 0,
parameters.Insurance.StartDate.Value,
parameters.Insurance.Currency.ToString(), irJaunakLiet, parameters.Client.Code, parameters.Vehicle.OwnerCode, irDefinetieServisi);
enter code here
...
and the method it calls:
public policyDataKASKORetParam1 GetCascoQuotesUnregistered(CascoQuote quote, string vin, string make, string model, int year, int vehicleValue, int engine, DateTime policyStartDate, string currency, bool irJaunakLiet, string clientCode, string ownerCode, bool irDefinetieServisi)
{
policyDataKASKORetParam1 prices;
string personCode = string.IsNullOrWhiteSpace(Config.FixedOwnerCode) ? clientCode : Config.FixedOwnerCode;
DateTime start = policyStartDate;
DateTime issue = DateTime.Today;
prices = WS.getOfferDataKASKO(SessionKey,
personCode, // Holder Code
null,
null,
vin,
make,
model, // Model
year, // Year
engine, // Engine
string.Empty, // Usage
ownerCode, // Person Code
true,
false,
false,
false,
false,
false,
true,
false,
irJaunakLiet,
false,
irDefinetieServisi,
false, // TODO: All risks
(double)vehicleValue,
currency,
issue,
start,
null,
0d,
null,
null);
if (prices.status != 0)
quote.ErrorList.Add(new QuoteBase.Error(Errors.InsurerError, string.Format("Error message: {0}", prices.statusText)));
return prices;
}
Basically the last method calls out Web Service method.. So all together can i assume that the Web service dose not return me anything or can there be some other possibility's why it ends up null. (Don't know how to debug it, its running on remote server.. tried WCF tracing but without any results.. )
The Problem is in another country and business people are telling me that All the Web service should work so they are saying me that prices.premiums are not null.. but without debugging, cant really argue with them. Should i make a some kinda Client to run the Web Service and run it on my local machine ? Or is there some kinda another possibility to see the values of running instance ?
Also they say that Web Service hasn't been changed - also i know 100% that my code has not been changed, and all that worked fine like 10 days ago..
(PS I'm Junior who's mentor has left.. ~4 month experiences only )
From MSDN, here's the signature of the Where extension method:
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
As you can see, source is the parameter that corresponds to the collection and your error message indicates 'Parameter name: source' so my guess is that prices.premiums is null.
Related
I have written code to extract tables and name value pairs from pdf using Amazon Textract. I followed this example:
https://docs.aws.amazon.com/textract/latest/dg/async-analyzing-with-sqs.html
which was in sdk for java version 1.1.
I have refactored it for version 2.
This is an async process that only applies to multi page documents. When i get back the results it is pretty accurate for first page. But the consecutive pages are mostly empty rows. The documents i parse are scanned so the quality is not great. However if i take a jpg of individual pages and use the one page operation, i.e. AnalyzeDocumentRequest, each page comes out good. Also Amazon Textract tryit service renders the pages correctly.
So the error must be in my code but can't see where.
As you see it all happens in here :
GetDocumentAnalysisRequest documentAnalysisRequest = GetDocumentAnalysisRequest.builder().jobId(jobId)
.maxResults(maxResults).nextToken(paginationToken).build();
response = textractClient.getDocumentAnalysis(documentAnalysisRequest);
and i can't really do any intervention.
The most likely place I could make a mistake would be in the util file that gathers the page and table blocks i.e. here:
PageModel pageModel = tableUtil.getTableResults(blocks);
But that works perfectly for the first page, and i could also see in the response object above, that the number of blocks returned are much less.
Here is the full code:
private DocumentModel getDocumentAnalysisResults(String jobId) throws Exception {
int maxResults = 1000;
String paginationToken = null;
GetDocumentAnalysisResponse response = null;
Boolean finished = false;
int pageCount = 0;
DocumentModel documentModel = new DocumentModel();
// loops until pagination token is null
while (finished == false) {
GetDocumentAnalysisRequest documentAnalysisRequest = GetDocumentAnalysisRequest.builder().jobId(jobId)
.maxResults(maxResults).nextToken(paginationToken).build();
response = textractClient.getDocumentAnalysis(documentAnalysisRequest);
// Show blocks, confidence and detection times
List<Block> blocks = response.blocks();
PageModel pageModel = tableUtil.getTableResults(blocks);
pageModel.setPageNumber(pageCount++);
Map<String,String> keyValues = formUtil.getFormResults(blocks);
pageModel.setKeyValues(keyValues);
documentModel.getPages().add(pageModel);
paginationToken = response.nextToken();
if (paginationToken == null)
finished = true;
}
return documentModel;
}
Has anyone else encountered this issue?
Many thanks
if the response has NextToken, then you need to recall textract and pass in the NextToken to get the next batch of Blocks.
I am not sure how to do this in Java but here is the python example from AWS repo
https://github.com/aws-samples/amazon-textract-serverless-large-scale-document-processing/blob/master/src/jobresultsproc.py
For my solution, I did a simple if response['NextToken'] then recall method and concat the response['Blocks'] to my current list.
Put request is handled very well as far as I have observed but something goes wrong after an updated hotel object is passed to HotelManager layer from HotelRepository.
That's the error: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
here is the code in HotelRepository:
public async Task<int> UpdateHotel(Hotel hotel)
{
var sql = "UPDATE Hotels " +
"SET name = #name, city = #city " +
"WHERE Id = #id";
var updatedHotel = new Hotel()
{
Name = hotel.Name,
City = hotel.City,
Id = hotel.Id
};
using (var connection = new SqlConnection(CONNECTION_STRING))
{
return await connection.ExecuteAsync(sql, updatedHotel);
}
}
At first I though it was about the spaces in the sql commands. I realized I did not add any spaces after the ends of the lines so I fixed that but I guess that's not the issue since I still get the same error.
The other routes work well.
Hotel object in the request contains id, name, and city.
Do you know what's wrong?
That's the error: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
You can try to install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package to add support for Newtonsoft.Json based features, and check if it can help fix above issue.
services.AddControllersWithViews().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Scenario: Deactivate the user whose login date is less than 42 from today. I have an user whose last login date is 1/22/2020(US Date format)/22/1/2020 5:12 pm. Here I wrote a batch apex for deactivating. My code has executed successfully and my batch status is completed but the user record is not deactivating.
Here is the code:
global class User_Deactivation implements Database.Batchable<SObject>
{
dateTime dt = date.today()-42;
public String query = 'SELECT Name, LastLoginDate, Id From User WHERE IsActive = true AND LastLoginDate=:dt ';
global Database.querylocator start(Database.BatchableContext bc)
{
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc,List<User> scope)
{
List<User> userList = new List<User>();
for(User s:scope)
{
User u =(user)s;
userList.add(u);
}
if(userList.size() > 0)
{
for(User usr : userList)
{
usr.isActive = false;
}
}
update userList;
}
global void finish(Database.BatchableContext bc)
{
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :BC.getJobId()];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Job Status: ' + a.Status);
mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
please help me out on this
Multiple things you can improve here, where do I begin...
Initialisation(?) piece
dateTime dt = date.today()-42;
String query = 'SELECT Name, LastLoginDate, Id From User WHERE IsActive = true AND LastLoginDate=:dt';
Do you need Date or DateTime match? The way you wrote it it'll match only people who logged in exactly at midnight. System.debug(dt); would say 2020-01-23T00:00:00.000Z. It shouldn't be an equals sign, should be "less than" or "less or equal".
Or even better - you can make it bit more clear what you want to do, bit more "semantic" so the poor guy who's going to maintain it can understand it without extra comments. This reads more natural and uses the SOQL date literals, special "constants" to simplify your logic: SELECT Id, LastLoginDate FROM User WHERE isActive = true AND LastLoginDate != LAST_N_DAYS:42
What is this section of code anyway. It's not really static variables, it's not a constructor... I think it'll behave as a constructor. Be very, very careful with constructors for batches. The state of the class at the end of the constructor gets saved (serialised) and restored every time the class is scheduled to run. It's tempting to put some initialisation code into constructor, maybe read some custom settings, precalculate stuff... But then you'll be in for nasty surprise when admin adds new custom setting and the batch doesn't pick it up. In your case it's even worse, I'd suspect it'll serialise the dt and your today() will be frozen in time, not what you expected. To be safe move all initialisation logic to start()
And I'd even say whoever gave you the requirement didn't think it through. When you make new user they get a link they need to click in next 72h. If they didn't do it (maybe it was sent late Friday and they want to login on Monday) - this thing will dutifully kill their access at Friday night without giving them any chance to login. You need some "grace period". Maybe something like WHERE isActive = true AND (LastLoginDate < :x OR (LastLoginDate = null AND CreatedDate < :x))
start()
Queries in strings work and that's how a lot of batch documentation is written but they are poor practice. Where possible use a compiled query, in brackets. You get minimal improvement in execution (precompiled), you get compile-time warnings when you mess up (better than a runtime error which you might not notice if you don't monitor jobs). And most importantly - if somebody wants to delete a field - SF will detect a dependency and stop him/her. Use return Database.getQueryLocator([SELECT ...]); wherever you can.
execute()
Your scope already is a list of users, why do you do extra casts to User? Why do you add them to a helper list? Why 2 loops?
for(User u : scope){
u.isActive = false;
}
update users;
and you're done?
P.S. Why "global" all over the place?
In my .NET application, I recently had to make some changes in the database structure and upon changing code I have run into this error message.
The line used to say _categoryID = new Guid(Request.QueryString["CategoryID"].ToString()); which worked fine to retrieve a list of products based on the categoryid, but now I had to add a top level category called Market, and I used int instead of Guid in the database, because to me using Guid is a pain.
But now when I change the line I mentioned to _marketID = new Int32(Request.QueryString["MarketID"].ToString()); I get the error.
Here is the chunk of code :
#region Variables
Int32 _marketID;
#endregion
if ( Request.QueryString [ "MarketID" ] != null )
{
_marketID = new Int32(Request.QueryString["MarketID"].ToString());
ViewState["MarketID"] = _marketID;
BindDataToUI ( );
CreateFilterInSession ( );
}
Try this instead :
_marketID = Convert.ToInt32(Request.QueryString["MarketID"]);
note : no need to use ToString() for querystring values, they're all natively strings anyway.
Strange things happen...
I was forced to move to a new developer machine (Windows Server 2008 R2 to 2012).
The exact same code doesn't work on the new machine.
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
MembershipUserCollection retvalue = new MembershipUserCollection();
string ldapConnectionString = _configuration.GetConnectionString();
using (DirectoryEntry de
= new DirectoryEntry(ldapConnectionString, _configuration.SearchAccount, _configuration.SearchAccountPassword, AuthenticationTypes.ServerBind))
{
string filter = string.Format("(&(objectClass=Person)(CUSTOMemail={0}))", emailToMatch);
DirectorySearcher ds = new DirectorySearcher(de, filter, new[] { "cn", "CUSTOMemail" }, SearchScope.Subtree);
SearchResultCollection collection = ds.FindAll();
totalRecords = collection.Count;
int pagesCount = (totalRecords > pageSize) ? (int)Math.Ceiling((double)(totalRecords / pageSize)) : 1;
if (pageIndex > pagesCount - 1)
throw new IndexOutOfRangeException("PageIndex exceeds max PageIndex");
for (int i = pageIndex * pageSize; i < totalRecords; i++)
{
DirectoryEntry userDirectoryEntry = collection[i].GetDirectoryEntry();
string userName = userDirectoryEntry.Properties["cn"].Value as string;
string providerUserKey = userDirectoryEntry.Path;
string email = userDirectoryEntry.Properties["CUSTOMemail"].Value as string;
MembershipUser mu = new MembershipUser(
providerName: Name,
name: userName,
providerUserKey: providerUserKey,
email: email,
passwordQuestion: null,
comment: null,
isApproved: true,
isLockedOut: false,
creationDate: DateTime.MinValue,
lastLoginDate: DateTime.MinValue,
lastActivityDate: DateTime.MinValue,
lastPasswordChangedDate: DateTime.MinValue,
lastLockoutDate: DateTime.MinValue);
retvalue.Add(mu);
}
}
return retvalue;
}
The code fails when it is trying to read the CUSTOMemail property. System properties (such as "cn") work.
The IIS settings are exactly the same although this shouldn't matter as the binding process works. The domain membership (I read various threads about that) didn't change and does not matter because it's an edirectory and I'm using a dedicated user to bind anyway.
I can filter on the property (see above) and view all the properties' names. A network trace shows me that the properties and their values are transmitted over the wire so everything I need is there. And using an LDAP explorer like JXplorer shows me the complete DirectoryEntry (including values).. however my C# code doesn't get along with it. I'm absolutely puzzled as to why it works on one virtual machine and not on the other one.
I'm intrigued by the fact that all the data is transmitted over the wire (so the directory definitely has no permissions issues here) but my C# code is unable to extract the values out of it :(
I know this is an old question, but since I busted my brains about the same thing for a bit, I figured its worthwhile for anyone who's gotten this far...
The problem lies in the way DirectoryServices caches the schema, if it attempts to load a custom attribute (any attribute not familiar to DirectoryServices via the domain its connected to)
(hotfix specifically for Windows 8/2012)
Its actually documented in a KB article
http://support.microsoft.com/kb/2802148 that also includes the hotfix that should solve your problem (if you haven't solved it already)
Is it possible this runs as a different user on the two different VM's? In which case a possible permissions issue? Does your user on the second VM has sufficient permissions?