Datasource order changed while sorting and grouping in server side - asp.net-mvc

We have tried asp sorting and grouping the datasource the order will be changed. But in client side working fine. We have attached code snippet below.
List<accs> acc = new List<accs>();
acc.Add(new accs() { Account = "4320", Content = "Invest" });
acc.Add(new accs() { Account = "4290", Content = "rewrw" });
acc.Add(new accs() { Account = "4290", Content = "test11" });
var list = acc.OrderBy(x => x.Content);
var t = list.GroupBy(p => p.Account, p => p.Content, (key, g) => new { Account = key, Content = g.ToList() });
return View();
serverside output:
0-Account="4320"
1-Account="4290"
ClientSide output:
0-Account="4290"
1-Account="4320"
Please let me know if you have any solution.
Regards,
Gopi G.

Related

SharePoint 2019 CSOM not saving FieldUserValue

I'm facing a strange Issue when I'm inserting or updating an item in SharePoint2019 list which contains a user column the save completes with no errors but the user column always have empty value,
below is my code
context.Load(context.Web, web => web.Lists);
await context.ExecuteQueryAsync();
List RiskList = context.Web.Lists.GetByTitle("Risks");
context.Load(RiskList);
context.Load(RiskList, r => r.Fields);
await context.ExecuteQueryAsync();
ListItem listItem = RiskList.GetItemById(projectRisks.Id);
List<ListItemFormUpdateValue> listItemFormUpdateValue = new List<ListItemFormUpdateValue>();
if (projectRisks.AssignedTo.HasValue)
{
listItem["AssignedTo"] = new FieldUserValue() { LookupId = projectRisks.AssignedTo.Value };
}
if (projectRisks.Owner.HasValue)
{
User OwnerUser = context.Web.SiteUsers.GetById(projectRisks.Owner.Value);
context.Load(OwnerUser);
await context.ExecuteQueryAsync();
listItem["Owner"] = new FieldUserValue() { LookupId = OwnerUser.Id };
}
listItemFormUpdateValue.Add(new ListItemFormUpdateValue() { FieldName = "Category", FieldValue = GetSPSelectedChoiceValue(context, RiskList, "Category", projectRisks.CategoryName).Result });
listItemFormUpdateValue.Add(new ListItemFormUpdateValue() { FieldName = "Status", FieldValue = GetSPSelectedChoiceValue(context, RiskList, "Status", projectRisks.StatusName).Result });
listItem["Contingency_x0020_plan"] = projectRisks.ContingencyPlan;
listItem["Cost"] = projectRisks.Cost;
listItem["Cost_x0020_Exposure"] = string.Empty;
listItem["Description"] = projectRisks.Description;
listItem["DueDate"] = projectRisks.DueDate;
listItem["Exposure"] = projectRisks.Exposure;
listItem["Impact"] = projectRisks.Impact;
listItem["Mitigation_x0020_plan"] = projectRisks.MitigationPlan;
listItem["Probability"] = projectRisks.Probability;
listItem["Title"] = projectRisks.Name;
listItem.ValidateUpdateListItem(listItemFormUpdateValue, false, string.Empty);
listItem.Update();
await context.ExecuteQueryAsync();
as you can see in the AssignTo and in Owner Columns no mater how I try to save the users values the list will take the default value which is null.
I have made sure that there is values in the assigned to and Owner properties and I have tried using the ListItemFormUpdateValue but with no luck.
Thanks in advance

Looping through custom fields to populate dynamic fields in Zapier

I'm not sure how to loop through the custom fields when adding a dynamic field via the web script editor.
When I test I can see the fields are being returned in the console
Where the number of fields is different with each instance of our app.
This is the code I'm using to return the data.
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content)._embedded;
return results;
});
I assume I need to loop through each of the fields, pull out the ID and name and then put them back as an array of objects?
Something like this, only problem is nothing is being returned?
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content).results._embedded;
var cFields = [];
for (var i = 0; i < results.length; i++) {
cFields.push({'id': results.customFields[i].label});
}
return cFields;
});
Any pointers?
I worked this out in the end. I think the problem was more because of my lack of coding knowledge. Not sure if this is the best answer but it worked.
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content)._embedded;
let customFields = [];
for (let i = 0; i < results.customFields.length; i++) {
let customFieldsObj = {};
customFieldsObj['key'] = results.customFields[i].id;
customFieldsObj['label'] = results.customFields[i].label;
let helpText = results.customFields[i].type + ' Field';
customFieldsObj['helpText'] = helpText.toUpperCase();
customFields.push(customFieldsObj);
}
return customFields;
});

Returning recursive result

I currently have this in a simple MVC Api controller:
var rootFolder = Umbraco.TypedMedia(200);
return rootFolder.Children().Select(s => new MediaItem
{
Name = s.Name,
Children = s.Children.Select(e => new MediaItem
{
Name = e.Name
})
});
It works, but only return level 1 and 2.
I tried using
return rootFolder.Descendants(), which returns all results from all levels - but "flattened out", so I cannot see the structure in the output.
The output is used in a simple app, navigating a tree structure.
Any ideas, as to how I can make it recursive?
Using Descendants, the output is returned like this
[
{
"Name":"dok1"
},
{
"Name":"dok2"
},
{
"Name":"dok21"
}
]
But it should be
[
{
"Name":"dok1"
},
{
"Name":"dok2"
"Children": [
{
"Name":"dok21"
}
]
}
Not sure you really need recursion here -- the solution below (or something similar) should suffice
// Dictionary between level/depth(int) and the files on that level/depth
var fileDictionary = new Dictionary<int, List<MediaItem>>();
var children = rootFolder.Children();
var depth = 1;
while (children.Any())
{
var tempList = new List<MediaItem>();
children.ForEach(child => {
tempList.Add(child);
});
fileDictionary.Add(depth, tempList);
children = children.Children();
depth++;
}
Then, you can do something like:
foreach (var key in fileDictionary.Keys)
{
// Access the key by key.Key (key would be "depth")
// Access the values by fileDictionary[key] (values would be list of MediaItem)
}
Why not just create a recursive function like so?
IEnumerable<MediaItem> ConvertToMediaItems(IEnumerable<IPublishedContent> items)
{
return items?.Select(i => new MediaItem
{
Name = i.Name,
Children = ConvertToMediaItems(i.Children)
}) ?? Enumerable.Empty<MediaItem>();
}
Then the usage would be
var rootFolder = Umbraco.TypedMedia(200);
return ConvertToMediaItems(rootFolder.Children());
You can also make the function a local function if it's only needed in one place.

"CS0162: Warning as Error: Unreachable code detected" on Razor View

I have the following code within a script tag on my razor view:
self.regions = [];
#foreach(var region in Model.OperationRegions)
{
<text>
self.regions.push({
regionid: '#region.Region_Id',
regionname: '#region.Title',
selected: ko.observable(#(Model.RegionsList.Contains(region.Region_Id).ToString().ToLower()))
});
</text>
}
self.categories = [];
#foreach(var category in Model.Categories)
{
<text>
self.categories.push({
categoryid: '#category.Category_Id',
title: '#category.Title'
});
</text>
}
For clarity, the code outside of the foreach loops and within the text tags are Javascript and the purpose of the razor code is to populate my Javascript arrays with data from the server.
When I run this I am currently getting a server error saying "CS0162: Warning as Error: Unreachable code detected"
The error is thrown on the second "foreach" in the snippet.
Surprisingly I couldn't find another question referring to this error message on an MVC razor page so I'm posting this here.
My question is why is that line of code considered to be unreachable? I will update this question if I find anything else on my page to be relevant to the issue as I try to debug.
The error has disappeared now. I had renamed a property of my model and not recompiled before trying to load the page again. Recompiling made the error go away. I have no idea how the root cause translated to the error message shown but its fixed now in any case.
This is an extremely poor way to handle this. There's no need to build an array piece by piece like this. Just convert your list to JSON.
self.regions = #Html.Raw(Json.Encode(Model.OperationRegions.Select(region => new {
regionid = region.Region_Id,
regionname = region.Title,
selected = Model.RegionsList.Contains(region.Region_Id)
})));
The only thing this can't handle is making selected an observable. However, you can simply loop through the array and fix this:
for (var i = 0; i < self.regions.length; i++) {
self.regions[i].selected = ko.observable(self.regions[i].selected);
}
However, the better approach is to use another view model:
var OperationRegionViewModel = function (data) {
var self = {};
self.regionid = ko.observable(data.regionid);
self.regionname = ko.observable(data.regionname);
self.selected = ko.observable(data.selected);
return self;
};
Then, you can just do something like:
var regions = #Html.Raw(Json.Encode(Model.OperationRegions.Select(region => new {
regionid = region.Region_Id,
regionname = region.Title,
selected = Model.RegionsList.Contains(region.Region_Id)
})));
self.regions = $.map(regions, new OperationRegionViewModel);
Or, even better build your JSON all at once:
var json = #Html.Raw(Json.Encode(new {
regions = Model.OperationRegions.Select(r => new { ... }),
categories = Model.Categories.Select(c => new { ... }),
// etc
});
Then, inject this all into your view model:
var viewModel = (function (json) {
// other stuff
self.regions = $.map(json.regions, new OperationRegionViewModel);
self.categories = $.map(json.categories, new CategoryViewModel);
// etc
})(json);

display image devexpress gridview, is this a rocket science?

Let say I have ViewModel which I use in devexpress gridview. Inside that view I display my data in devexpress gridview like this
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "myGridView";
settings.KeyFieldName = "Id";
....
var column = settings.Columns.Add("Id", "Id");
column = settings.Columns.Add("Title", "MyTitle");
...
}).Bind(Model).GetHtml()
My Model is of IEnumerable
and everything is ok with this code up.
Now I want to display image inside that gridview before or after Id column.
So I found that this should be done with Html.DevExpress().BinaryImage()
But I'm stuck here for a while now.
First to describe my viewmodel and how my images are stored.
My Model have List<Photo> collection. I'm getting images as FileContentResult.
So I know I should use this Html.DevExpress().BinaryImage() but I dont know.
Here is example which I should follow.
column = settings.Columns.Add("", "Photos");
Html.DevExpress().BinaryImage(
imageSettings =>
{
//imageSettings.Name = "Photo";
imageSettings.Width = 100;
imageSettings.Height = 100;
})
.Bind(((System.Data.Linq.Binary)DataBinder.Eval(Model, "Photo")).ToArray())
.Render();
Update:
I think I should try with this solution. Problem here is that I want to display in my grid first image from the Photos collection. I tried with with code below but with no luck. No errors.
var photoColumn = settings.Columns.Add("Photos[0].ImageData", "Foto");
photoColumn.Visible = true;
photoColumn.Width = 20;
photoColumn.FieldName = "Photo.ImageData";
photoColumn.ColumnType = MVCxGridViewColumnType.BinaryImage;
DevExpress.Web.ASPxEditors.BinaryImageEditProperties properties = (DevExpress.Web.ASPxEditors.BinaryImageEditProperties)photoColumn.PropertiesEdit;
properties.ImageHeight = 50;
properties.ImageWidth = 50;
You do not need to use BinaryImage within the GridView directly, because MVCxGridViewColumnType supports BinaryImage.
Related link - GridView - How to load binary image within BinaryImage column
Please, also review the Grid View - Templates demo that demonstrates how to use the BinaryImage within the data rows.
In you case it is necessary to customize DataItemTemplate and customize BinaryImage inside it as follows:
settings.Columns.Add(column => {
column.SetDataItemTemplateContent(c => {
Html.DevExpress().BinaryImage(
imageSettings => {
imageSettings.Name = "Photo" + c.KeyValue;
imageSettings.Width = 50;
imageSettings.Height = 50;
})
.Bind(Here_Your_Code_To_Retrieve_Image_From_Current_DataItem)
.Render();
});
});
Here is one that worked for me.
settings.Columns.Add(column =>
{
column.SetDataItemTemplateContent(c =>
{
Html.DevExpress().BinaryImage(
imageSettings =>
{
imageSettings.Name = "PhotographOfCommodity" + c.KeyValue;
imageSettings.Width = 50;
imageSettings.Height = 50;
})
.Bind(DataBinder.Eval(c.DataItem, "PhotographOfCommodity")).Render();
});
});
HOPE THIS HELPS

Resources