Lambda expressions to JSON array - arrays

List<string> _columns = new List<string>() { "Kurator", "Filial", "Klient", "Saldo", "Docs", "no_Docs", "Change", "Status" };
var columns = cols.Select(p => new {
data = p.ColumnName });
Tis gives me an array of objects JsonResult: data:Kurator, data:Filial etc.
Here is data = constant. How i can use it dynamically from another List???
So i need data from two list of objects
List<string> list1 = new List<string>() { "lst1-1", "lst1-2", "lst1-3" };
List<string> list2 = new List<string>() { "lst2-1", "lst2-2", "lst2-3" };
var columns = cols.Select(p => new {
lst1-1= lst2-1 });
To get in return Json(columns, JsonRequestBehavior.AllowGet);
columns = array of (lst1-1:lst2-1,lst1-2:lst2-1, lst1-3:lst2-1)
i`m already break my head!!!

try this:
var columns = from l1 in list1.Select((val, index) => new { val, index })
from l2 in list2.Select((val, index) => new { val, index })
where l1.index == l2.index
select l1.val + " : " + l2.val;

Related

Adding Google Classroom ID based on user enrollment code

I have a spreadsheet where a user can list classes and Google Classroom enrollment codes, represented by the array userClassCodes. This array is allowed to contain blank values when the range contains blank cells. This array is represented in the following way:
[ ['class name 01', 'class code 01'], ['class name 02', 'class code 02'], ...]
I am using the Google Classroom API to get a list of the sheet user's enrollment codes and course IDs. I would like to iterate through the userClassCodes array and add the class ID to the array when there is a matching class code in the API response. If there is no match, I would like to preserve the entry in the array and add a blank value for the course ID.
I am having trouble properly constructing an array that will achieve the desired output. Here is my current code:
function googleClassroomImport() {
var userClassCodes = SpreadsheetApp.getActive().getRange("Sheet1!A1:B25").getValues();
var newArray = [];
var options = {
teacherId: 'me',
courseStates: 'ACTIVE',
pageSize: 50
};
var response = Classroom.Courses.list(options);
response.courses.forEach(function (course) {
for (let i = 0; i < userClassCodes.length; i++) {
if (userClassCodes[i][1] == course.enrollmentCode) {
newArray.push([userClassCodes[i][0], userClassCodes[i][1], course.id]);
}
else {
newArray.push([userClassCodes[i][0], userClassCodes[i][1], ""]);
}
}
});
console.log(newArray);
}
Try this:
function googleClassroomImport() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const rg = sh.getRange("A1:B25");
const vs = rg.getValues().filter(r => r[0] && r[1]).filter(e => e);
const arr = vs.map(r => r[1]);
var options = { teacherId: 'me', courseStates: 'ACTIVE', pageSize: 50 };
var response = Classroom.Courses.list(options);
response.courses.forEach(course => {
let idx = arr.indexOf(course.enrollmentCode);
if (~idx) {
vs[idx].push(course.id);
} else {
vs[idx].push('');
}
});
console.log(newArray);
}

(I'm not uploading any file) The request message is too big. the server does not allow messages larger than 2097152

I have a simple list with 108 items, this code was working until today, but some how stop working with the message in the Title.
I'm only passing a simple CAML but I canĀ“t ride of this error.
Anyone have a Suggestion? this is annoying.
private static int GetLookupCity(string city)
{
var oList = Ctx.Web.Lists.GetByTitle("City");
var camlQuery = new CamlQuery
{
ViewXml = "<View><Query><Where><Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">" + city + "</Value></Eq></Where></Query></View>"
};
var listItems = oList.GetItems(camlQuery);
Ctx.Load(listItems,
items => items.Include(
item => item["ID"],
item => item["Title"]));
Ctx.ExecuteQuery();
foreach (var oListItem in listItems)
{
FieldLookupValue lv = new FieldLookupValue
{
LookupId = int.Parse(oListItem["ID"].ToString())
};
return lv.LookupId;
}
Ctx.Dispose();
return 0;
}
I I'm using this in an Excel Addin, so It's not thread safe. The only way I can put this work was to use the Garbage Collector in all methods.
private static int GetLookupCity(string city)
{
var oList = Ctx.Web.Lists.GetByTitle("City");
var camlQuery = new CamlQuery
{
ViewXml = "<View><Query><Where><Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">" + city + "</Value></Eq></Where></Query></View>"
};
var listItems = oList.GetItems(camlQuery);
Ctx.Load(listItems,
items => items.Include(
item => item["ID"],
item => item["Title"]));
Ctx.ExecuteQuery();
GC.Collect();
var queryable = listItems.ToList().FirstOrDefault();
FieldLookupValue lv = new FieldLookupValue
{
LookupId = int.Parse(queryable[0]["ID"].ToString())
};
return lv.LookupId;
Ctx.Dispose();
GC.Collect();
return 0;
}

combine two array as key value pair

I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data
You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);
Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END

Pass in arrays for x and y values to use in pie Chart in MVC?

Using the built-in Chart in Web Helpers, I was able to bind my data to build a chart, but only if it was a bar chart. I want to make a pie chart. Every example shows creating an array for x and y values by hard-coding them. For example,
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" })
I went through probably the longest way possible to get my information set up in two arrays and it isn't working. There is no error, it just displays a white screen. When debugging, the values come through just as expected. Here is my controller:
var query = string.Format("Select C.* from Cards C Left Join CardDecks CD ON CD.CardID = C.CardID Where DeckID = {0}", id);
var cardlist = db.Cards.SqlQuery(query).ToList();
var piearray = cardlist.Select(t => t.MainType.Title).ToList();
var pievalues = piearray.GroupBy(c => c, (a, b) => string.Format("{0} {1}", b.Count(), a)).ToArray();
string first = " ";
string second = " ";
string xvalues = " ";
string yvalues = " ";
List<String> xx = new List<string>();
List<String> yy = new List<string>();
foreach (var item in pievalues)
{
first = item.ToString().Substring(0, item.IndexOf(" "));
second = item.ToString().Substring(item.IndexOf(" ") + 1);
xx.Add(first);
yy.Add(second);
}
for (int i = 0; i < xx.Count; i++)
{
if (i == xx.Count - 1)
{
xvalues = xvalues + xx[i];
}
else
{
xvalues = xvalues + xx[i] + " , ";
}
}
string[] XValue = xvalues.Split(',');
for (int i = 0; i < yy.Count; i++)
{
if (i == yy.Count - 1)
{
yvalues = yvalues + yy[i];
}
else
{
yvalues = yvalues + yy[i] + " , ";
}
}
string[] YValue = yvalues.Split(',');
var myChart = new Chart(width: 200, height: 200)
.AddSeries(chartType: "Pie", xValue: XValue, xField: "X Field",
yValues: YValue , yFields: "Y Fields").Write();
var vm = new ViewDeck();
vm.Chart = myChart;
//More vm.views = view
return View(vm);
Here is part of my Model:
public Chart Chart { get; set; }
Here is part of my View:
#Model.Chart
I would like to avoid using 3rd party plug-ins. Any help is appreciated. :)
I ended up changing to HighCharts... after I finally got this working it turned out that it looked horrible and there wasn't much in the way of styling. I have some if statements to check the number in the array, it's the only way I found I could build the pie chart objects. It is a bit different when using line or bar charts because you can copy x and y values independently. In the pie chart structure, you have to build new object [] with the string name and int number. If you knew how many categories you were going to have and just needed the numbers to be dynamic you don't have to worry about an array count. Here is an example with array count:
if (arrayCount == 3)
{
Highcharts chart = new Highcharts("chart")
.InitChart(new DotNet.Highcharts.Options.Chart { PlotShadow = false })
.SetTitle(new Title { Text = "Card Type Distribution" })
.SetSeries(new Series
{
Type = ChartTypes.Pie,
Data = new Data(new object[]
{
new object[] { XValue[0], YValue[0] },
new object[] { XValue[1], YValue[1] },
new object[] { XValue[2], YValue[2]}
})
});

Telerik ComboBox with picture

I need a picture in combobox but I have only path
var files = Url.Content("~/Content/skin/Simple.png");
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(files.Select(f => new SelectListItem { Selected = false, Text = f.ToString(), Value = "" }))
)
thank you but if I need to show all pictures in folder
string searchFolder = Url.Content("~/Content/skin/");
var filters = new[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
var files = Some Class.GetFilesFrom(searchFolder, filters, false);
there are my full code
controller
public ActionResult Combo()
{
return View();
}
model
public class Combo
{
public static string[] GetFilesFrom(string searchFolder, string[] filters, bool isRecursive)
{
var filesFound = new List<String>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.ToArray();
}
}
and View
#using TETRA.RS.WWW.UI.Models
#{
string searchFolder = Url.Content("~/Content/skin/");
var filters = new[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
var files = Combo.GetFilesFrom(searchFolder, filters, false);
}
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(files.Select(f => new SelectListItem { Selected = false, Text = f, Value = "" }))
)
And I see only full path in combobox
And I do not Know how many pictures in a folder
There are different ways of adding images to an item selectable from a radcombobox, each has their benefits and the most suitable can only be defined by your requirements.
The easiest way is to assign a value to the ImageUrl attribute.
(Telerik Documentation: http://www.telerik.com/help/aspnet-ajax/combobox-appearance-item-images.html)
Alternatively you could modify the item template. (Telerik Demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx)
I have used Kendo UI
I have a folder with pictures and I don't Know how much there are
I need to get all the pictures and use in comboBox
Method finds all pictures
public static string[] GetFilesFrom(string searchFolder, string[] filters, bool isRecursive)
{
var filesFound = new List<string>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.Select(Path.GetFileName).ToArray();
}
SettingsController
public ActionResult Theme()
{
return View();
}
public JsonResult ThemeJson()
{
string searchFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content\\themes\\skin");
var filters = new[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
var files = Tools.GetFilesFrom(searchFolder, filters, false);
return Json(files.Select(f => new { Id = f, Name = Path.GetFileNameWithoutExtension(f) }));
}
and View
#using Kendo.Mvc.UI
#(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { })
.DataSource(source => source.Read(read => read.Action("ThemeJson", "Settings").Type(HttpVerbs.Post)))
.Filter("startswith")
.Height(300)
.Template("<img src=\"" + Url.Content("~/Content/themes/skin/") + "${data.Id}\" alt=\"${data.Id}\" />" +
"<dl>" +
"Name theme: ${ data.Name }" +
"</dl>")
)
also you need add reference kendo.all.min.js and Kendo.Mvc.UI

Resources