SPFieldUserValue : Value does not fall within the expected range - sharepoint-2010

Following piece of code returning following error not sure where is the problem,
Exception Details: System.ArgumentException: Value does not fall within the expected range.
public static SPUser convertStringToSPUser(string struser)
{
SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, struser);
SPUser objSPUser = userValue.User;
return objSPUser;
}
My string is something like, "S, Rishi".

In order to create an instance of SPFieldUserValue you should Pass a string with the following format:
[int];#[domain]\[username]
The easiest way to get that value from a list item is:
ListItem[field_GUID].ToString();

Related

SQLSTATE[22007]: Invalid datetime forma

I try to save some data that it brings me from my view, which is a table, but I don't know why it throws me that error with the insert.
result of insert
this is my view:
table of view
this is my controller:
$checked_array = $_POST['id_version'];
foreach ($request['id_version'] as $key => $value) {
if (in_array($request['id_version'][$key], $checked_array))
{
$soft_instal = new Software_instalacion;
$soft_instal->id_instalacion = $instalaciones->id;
$soft_instal->id_historial = $historial->id;
$soft_instal->id_usuario = $request->id_usuario;
$soft_instal->id_version = $_POST['id_version'][$key];
$soft_instal->obs_software = $_POST['obs_software'][$key];
$soft_instal->id_tipo_venta = $_POST['id_tipo_venta'][$key];
$soft_instal->save();
}
}
id_tipo_venta seems to be an empty string which is apparently not valid.
You can try debugging what you get in :
var_dump($_POST['id_tipo_venta'][$key]);
die;
Your database field expects to receive an integer. Therefore, using the intval() function can solve your problem.
Indeed, I think your code returns an alphanumeric string.
Therefore, the code below will return 0 in all cases if no version is returned (not set, string or simply null):
$soft_instal->id_tipo_venta = intval($_POST['id_tipo_venta'][$key]);
On the other hand, intval() will always convert to int, so a decimal will be converted, example :
intval("1.1") // returns 1
intval("v1.1") // returns 0
If this is not the desired behavior, maybe you should think about changing your database type.
EDIT :
Of course, you can also set the value as null if you prefer to 0. You must allow nullable values in your database.
id_tipo_venta can not be empty, try with some number or change type column to varchar in the database

Setting a variable to linq query with no results

I have a table that holds links to websites about particular theaters. I want to retrieve the first link for a given theater. My code to set the variable:
Dim link As String = TheaterLinks.Where(Function(x) x.TheaterID = TheaterID).FirstOrDefault().Link
If there are no results (some theaters won't have any links), then I get:
Object reference not set to an instance of an object.
How do I do this? I tried:
Dim link As String = Links.Where(Function(x) x.TheaterID = TheaterID.DefaultIfEmpty().First().Link
But I can't figure out what to put inside DefaultIfEmpty(). I tried DefaultIfEmpty("") and DefaultIfEmpty(blankstringvariable) but then I get:
Value of type 'String' cannot be converted to type 'TheaterLink'.
The problem is that FirstOrDefault() is allowed to return null, in which case accessing Link property would throw an exception.
If you use VB.NET 14, add question mark for automatic null checking:
Dim link As String = TheaterLinks.Where(Function(x) x.TheaterID = TheaterID).FirstOrDefault()?.Link
(see ?.Link instead of .Link)
Otherwise, do it in two stages: first, get the object using FirstOrDefault, then null-check it manually with an If statement.
For my original example, I just had to add a question mark:
Dim link As String = Links.Where(Function(x) x.ID = id).FirstOrDefault()?.Link
I tried doing this in my model and got a "Nullable object must have a value" error, so I did the two-stage approach:
Dim eventDate = Events.Where(Function(x) x.ID = id).FirstOrDefault()?.EventDate
If eventDate.HasValue Then
'some code
Else
'some code
End If

How can we extract all messages from processing report in json-schema validator

I am using json-schema validator for validating json data. if any error occur it will generate a report. But I want to show the error to the user the report is too big so I want to show only error messages.
This is my report
----------reports-------------
com.github.fge.jsonschema.report.ListProcessingReport: failure
--- BEGIN MESSAGES ---
error: instance failed to match at least one required schema among 4
level: "error"
schema: {"loadingURI":"#","pointer":"/properties/question-groups/items"}
instance: {"pointer":"/question-groups/0"}
domain: "validation"
keyword: "anyOf"
nrSchemas: 4
reports: {"/properties/question-groups/items/anyOf/0":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/multiple-choice/properties/evaluation-key/properties/options/items"},"instance":{"pointer":"/question-groups/0/evaluation-key/options/0"},"domain":"validation","keyword":"allOf","message":"instance failed to match all required schemas (matched only 0 out of 1)","matched":0,"nrSchemas":1,"reports":{"/definitions/multiple-choice/properties/evaluation-key/properties/options/items/allOf/0":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/multiple-choice/properties/evaluation-key/properties/options/items/allOf/0/properties/score"},"instance":{"pointer":"/question-groups/0/evaluation-key/options/0/score"},"domain":"validation","keyword":"type","message":"instance type (string) does not match any allowed primitive type (allowed: [\"integer\"])","found":"string","expected":["integer"]}]}}],"/properties/question-groups/items/anyOf/1":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/text/properties/evaluation-key"},"instance":{"pointer":"/question-groups/0/evaluation-key"},"domain":"validation","keyword":"additionalProperties","message":"object instance has properties which are not allowed by the schema: [\"options\"]","unwanted":["options"]},{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/text/properties/evaluation-key"},"instance":{"pointer":"/question-groups/0/evaluation-key"},"domain":"validation","keyword":"required","message":"object has missing required properties ([\"scorers\"])","required":["scorers"],"missing":["scorers"]},{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/text/properties/type"},"instance":{"pointer":"/question-groups/0/type"},"domain":"validation","keyword":"enum","message":"instance value (\"multiple-choice\") not found in enum (possible values: [\"text\"])","value":"multiple-choice","enum":["text"]}],"/properties/question-groups/items/anyOf/2":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/numeric/properties/evaluation-key"},"instance":{"pointer":"/question-groups/0/evaluation-key"},"domain":"validation","keyword":"additionalProperties","message":"object instance has properties which are not allowed by the schema: [\"options\"]","unwanted":["options"]},{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/numeric/properties/evaluation-key"},"instance":{"pointer":"/question-groups/0/evaluation-key"},"domain":"validation","keyword":"required","message":"object has missing required properties ([\"scorers\"])","required":["scorers"],"missing":["scorers"]},{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/numeric/properties/type"},"instance":{"pointer":"/question-groups/0/type"},"domain":"validation","keyword":"enum","message":"instance value (\"multiple-choice\") not found in enum (possible values: [\"numeric\"])","value":"multiple-choice","enum":["numeric"]}],"/properties/question-groups/items/anyOf/3":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/table"},"instance":{"pointer":"/question-groups/0"},"domain":"validation","keyword":"anyOf","message":"instance failed to match at least one required schema among 2","nrSchemas":2,"reports":{"/definitions/table/anyOf/0":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/table/anyOf/0"},"instance":{"pointer":"/question-groups/0"},"domain":"validation","keyword":"required","message":"object has missing required properties ([\"cells\"])","required":["cells","evaluation-key","group-id","question-text","type"],"missing":["cells"]}],"/definitions/table/anyOf/1":[{"level":"error","schema":{"loadingURI":"#","pointer":"/definitions/table/anyOf/1"},"instance":{"pointer":"/question-groups/0"},"domain":"validation","keyword":"required","message":"object has missing required properties ([\"cells\",\"matching-unit\"])","required":["cells","evaluation-key","group-id","matching-unit","question-text","type"],"missing":["cells","matching-unit"]}]}}]}
--- END MESSAGES ---
How can I get only error messages, any suggestions will be help full.
Thank you
somu
You can read the report as a JsonNode and get what ever parameter you need from that.
ProcessingReport report;
ProcessingMessage message;
report = schema.validate(jsonData);
Iterator itr = report.iterator();
while(itr.hasNext())
{
message = (ProcessingMessage) itr.next();
System.out.println("Message" + message.asJson().get("message").asText());
System.out.println("Reports" + message.asJson().get("reports").asText());
}
You should iterate over all messages and choose only errors comparing getLogLevel() with LogLevel.ERROR. That works for me
Iterator<ProcessingMessage> itr = report.iterator();
while(itr.hasNext())
{
ProcessingMessage message = (ProcessingMessage) itr.next();
if(message.getLogLevel().equals(LogLevel.ERROR)){
System.out.println(message.toString());
}
}
You can use the following method
String getErrorsList(ProcessingReport report, boolean onlyErrors) {
StringBuilder jsonValidationErrors = new StringBuilder();
for (ProcessingMessage processingMessage : report) {
if(onlyErrors && LogLevel.ERROR.equals(processingMessage.getLogLevel())) {
jsonValidationErrors.append(processingMessage.getMessage()).append("\n\r");
} else if(!onlyErrors) {
jsonValidationErrors.append(processingMessage.getMessage()).append("\n\r");
}
}
return jsonValidationErrors.toString();
}

Value does not fall within the expected range in SharePoint 2010

I am doing below things,
On Feature Activation, I'm creating a new list with 1 sample row in it.
I'm using our internal API to create a custom list which uses FieldRef.
Sytax is like, FieldRef(string staticName, string displayName, SPFieldType, ... )
And I have created a column like
public static FieldRef SalesPerson = new FieldRef("SalesPersonName", "Person Name", SPFieldType.Text);
In my web part, I'm fetching this list's items.
SPQuery query = new SPQuery();
query.ViewFields = string.Format("
IList returnlist = null;
SPList spList = spWeb.Lists.TryGetList(ListName);
if (spList != null)
{
SPListItemCollection listitems = spList.GetItems(query);
returnlist = new List(listitems.Count); //This Gives Correct Number Of Count
foreach (SPListItem item in listitems)
{
returnlist.Add(new MyClass()
{
_SalesPersonName = item[FIELDS.SalesPerson.DisplayName].ToString();
}
}
}
And This Gives Below Error :
Server Error in '/' Application.
Value does not fall within the expected range.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Value does not fall within the expected range.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Strange "Expected invocation on the mock at least once, but was never performed" error when I am setting up the Mock

I'm getting this error from Moq via NUnit, and it doesn't make much in the way of sense to me.
"Expected invocation on the mock at least once, but was never performed: x => x.DeleteItem(.$VB$Local_item)"
"at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable1 setups, IEnumerable1 actualCalls, Expression expression, Times times, Int32 callCount)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify[T](Mock mock, Expression1 expression, Times times, String failMessage)
at Moq.Mock1.Verify(Expression`1 expression)
at PeekABookEditor.UnitTests.ItemBrowsing.Can_Delete_Item() in C:\Projects\MyProject\MyProject.UnitTests\Tests\ItemBrowsing.vb:line 167"
Very similar code works well in C#, so the error might be minor and syntactical on my part.
Here's my code:
<Test()> _
Public Sub Can_Delete_Item()
'Arrange: Given a repository containing some item...
Dim mockRepository = New Mock(Of IItemsRepository)()
Dim item As New Item With {.ItemID = "24", .Title = "i24"}
mockRepository.Setup(Function(x) x.Items).Returns(New Item() {item}.AsQueryable())
'Act ... when the user tries to delete that product
Dim controller = New ItemsController(mockRepository.Object)
Dim result = controller.Delete(24)
'Assert ... then it's deleted, and the user sees a confirmation
mockRepository.Verify(Sub(x) x.DeleteItem(item))
result.ShouldBeRedirectionTo(New With {Key .action = "List"})
Assert.AreEqual(DirectCast(controller.TempData("message"), String), "i24 was deleted")
End Sub
The guilty line appears to be "mockRepository.Verify(Sub(x) x.DeleteItem(item))"
Any thoughts on how to fix this?
Working C# code isn't the exact same, but here it is:
[Test]
public void Can_Delete_Product()
{
// Arrange: Given a repository containing some product...
var mockRepository = new Mock<IProductsRepository>();
var product = new Product { ProductID = 24, Name = "P24"};
mockRepository.Setup(x => x.Products).Returns(
new[] { product }.AsQueryable()
);
// Act: ... when the user tries to delete that product
var controller = new AdminController(mockRepository.Object);
var result = controller.Delete(24);
// Assert: ... then it's deleted, and the user sees a confirmation
mockRepository.Verify(x => x.DeleteProduct(product));
result.ShouldBeRedirectionTo(new { action = "Index" });
controller.TempData["message"].ShouldEqual("P24 was deleted");
}
In your VB test method, you create Item with a string ItemID = "24", but you call the controller.Delete method with an integer value of 24.
Check your controller code and see if the type discrepancy results in the item not being identified correctly, so either DeleteItem is not called at all, or is called with a different Item.