I'm trying to display IEnumerable int values in JQGrid. As seen below column gmu is IEnumerable int but does not show correctly in the grid. Instead of the values, this is what shows in the grid for that gmu column:
System.Linq.Enumerable+WhereSelectEnumerableIterator2[<>f__AnonymousType25[System.Int32,System.String,System.Int32,System.Int32,System.Int32],System.Int32]
var result = from x in test
group x by new { x.dau, x.population_estimate, x.year } into p
select new
{
dau = p.Key.dau,
population_estimate = p.Key.population_estimate,
year = p.Key.year,
gmu = p.Select(x => x.gmu)
};
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = results.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var pageResults = result.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from pageResult in pageResults
select new
{
//id = pageResult.id,
cell = new[] {
pageResult.year.ToString(),
pageResult.dau.ToString(),
pageResult.gmu.ToString(),
pageResult.population_estimate.ToString(),
}
}).ToArray()
};
You just need to add "ToArray()" after "Select" in your Linq statement.
gmu = String.Join<int>(", ", p.Select(x => x.gmu))
What's happening is that, when it goes to render your IEnumerable object, .NET is implicitly invoking the "ToString()" function (it's not smart enough to actually enumerate the object on its own initiative), resulting in what you see.
Related
I'm making a master details and I've come to a problem on how not to accept existing invoiceno. I've tried modalstate...if else and all but it's not preventing it. I have two tables...invoice and invoicedesc where I enter two inputs in one view page at the same time and it will return to index once confirmed. However, if there's a duplicate internalinvoiceno, once I press the details button, it will crash cause collide. I'm trying if else with list where right but any help right now will do.
Create code in home controller
[HttpPost]
public ActionResult CreateInvoice(string invoiceDetailsList, string internalInvoiceNo, string invoiceNo, DateTime invoiceDate, string customerName, int year, int month, string amount, string foreignAmount, string userCreated, string userModified, int accMonth, int accYear, string accStatus, string status, string paidStatus, string principal, DateTime dateCreated, DateTime dateModified, string el1, string invoiceType, string currrencyType, string exchangeRate, string gstChecked, DateTime paymentSchedule, string paymentMode, string cashAdvance)
{
List<Desc> detailsList = JsonConvert.DeserializeObject<List<Desc>>(invoiceDetailsList);
var addingmaster = new College();
{
addingmaster.InternalInvoiceNo = internalInvoiceNo;
addingmaster.InvoiceNo = invoiceNo;
addingmaster.InvoiceDate = Convert.ToDateTime(invoiceDate);
addingmaster.CustomerName = customerName;
addingmaster.Year = year;
addingmaster.Month = month;
addingmaster.Amount = Convert.ToDecimal(amount);
addingmaster.ForeignAmount = Convert.ToDecimal(foreignAmount);
addingmaster.UserCreated = userCreated;
addingmaster.UserModified = userModified;
addingmaster.AccMonth = accMonth;
addingmaster.AccYear = accYear;
addingmaster.AccStatus = accStatus;
addingmaster.Status = status;
addingmaster.PaidStatus = paidStatus;
addingmaster.Principal = principal;
addingmaster.DateCreated = Convert.ToDateTime(dateCreated);
addingmaster.DateModified = Convert.ToDateTime(dateModified);
addingmaster.EL1 = el1;
addingmaster.InvoiceType = invoiceType;
addingmaster.CurrencyType = currrencyType;
addingmaster.ExchangeRate = Convert.ToDecimal(exchangeRate);
addingmaster.GSTChecked = gstChecked;
addingmaster.PaymentSchedule = Convert.ToDateTime(paymentSchedule);
addingmaster.PaymentMode = paymentMode;
addingmaster.CashAdvance = cashAdvance;
db.klsm_Invoice.Add(addingmaster);
db.SaveChanges();
}
foreach (var item in detailsList)
{
Desc addingdetails = new Desc();
addingdetails.InternalInvoiceNo = item.InternalInvoiceNo;
addingdetails.InvoiceNo = item.InvoiceNo;
addingdetails.DescNo = item.DescNo;
addingdetails.Principal = item.Principal;
addingdetails.ChargeCode = item.ChargeCode;
addingdetails.Quantity = item.Quantity;
addingdetails.Description = item.Description;
addingdetails.UnitPrice = item.UnitPrice;
addingdetails.Amount = item.Amount;
addingdetails.ForeignAmount = item.ForeignAmount;
addingdetails.EL1 = item.EL1;
addingdetails.EL2 = item.EL2;
addingdetails.ShortName = item.ShortName;
addingdetails.InvoiceType = item.InvoiceType;
addingdetails.PONumber = item.PONumber;
addingdetails.Batch = item.Batch;
addingdetails.CCVBatch = item.CCVBatch;
addingdetails.PaidAmount = item.PaidAmount;
addingdetails.Paid = item.Paid;
addingdetails.TT = item.TT;
addingdetails.BankCode = item.BankCode;
//addingdetails.Id = item.Id;
db.klsm_InvoiceDesc.Add(addingdetails);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
I have constructed a Grid in Vaadin 14 using a parser to extract from files as shown below:
Grid<String[]> grid = new Grid<>();
try {
List<String[]> entries = reader.readAll();
// Assume the first row contains headers
String[] headers = entries.get(0);
for (int i = 0; i < headers.length-1; i++) {
final int columnIndex = i;
String header = headers[i];
String humanReadableHeader = SharedUtil.camelCaseToHumanFriendly(header);
grid.addColumn(str -> str[columnIndex]).setHeader(humanReadableHeader).setSortable(true).setWidth("100px");
}
grid.setItems(entries.subList(1, entries.size()));
What I want to do next is add a CheckBox to every row that would return a visualization of the data in the corresponding row. So my question is two-fold:
Is there a function that already exists to emulate this behavior via clicking anywhere on a row?
If not, what would be the best way to initialize a Grid to accommodate this?
Simply add a component column:
Grid<String[]> grid = new Grid<>();
try {
List<String[]> entries = reader.readAll();
// Assume the first row contains headers
String[] headers = entries.get(0);
for (int i = 0; i < headers.length-1; i++) {
final int columnIndex = i;
String header = headers[i];
String humanReadableHeader = SharedUtil.camelCaseToHumanFriendly(header);
grid.addColumn(str -> str[columnIndex]).setHeader(humanReadableHeader).setSortable(true).setWidth("100px");
}
// Here goes your checkbox column
grid.addComponentColumn(item -> {
// Create the checkbox
}).setHeader("<the header>");
grid.setItems(entries.subList(1, entries.size()));
I want to pass a list of Ids to a stored procedure using Simple.Data.
My stored procedure is...
CREATE TYPE IntValue AS TABLE (Value INT)
GO
CREATE PROCEDURE testTableSproc
#items IntValue READONLY
AS
SELECT * FROM #items
So far I've tried...
public class IntValue
{
public int Value { get; set; }
}
var db = Database.OpenNamedConnection("MyConnection")
var array = new int[] {1, 2, 3};
List<IntValue> results = db.testTableSproc(items: array);
also
List<IntValue> results = db.testTableSproc(
items: array.Select(x => new IntValue{ Value = x}).ToArray());
Any solutions or confirmation that this is not supported?
Figured it out - Simple.Data accepts DataTable as a type.
var db = ConnectionFactory.GetConnection();
var tbl = new DataTable("items");
tbl.Columns.Add("Value");
var row1 = tbl.NewRow();
row1["Value"] = 1;
tbl.Rows.Add(row1);
var row2 = tbl.NewRow();
row2["Value"] = 2;
tbl.Rows.Add(row2);
var row3 = tbl.NewRow();
row3["Value"] = 3;
tbl.Rows.Add(row3);
List<IntValue> results = db.testTableSproc(items: tbl);
The syntax for working with DataTables is quite clunky but it can be refactored out of sight.
Can any1 explain how we can create Excel WITHOUT using INTEROP in c# window service.
So that I can apply styles also to the generating excel as I wish.
Rigin
You can use one of the Excel libraries. I use this C# Excel library.
See also this sample of code:
http://www.easyxls.com/manual/FAQ/export-to-excel-in-dot-net.html
You can create both XLS or XLSX documents.
You can create excel in windows services like below:
public static void GenerateExcel(DataTable DT, string fullFileName, string rptHeader, string SheetName)
{
try
{
var file = new FileInfo(fullFileName);
string currentFileName = System.IO.Path.GetFileName(fullFileName);
ExcelPackage excel = new ExcelPackage(file);
var sheetcreate = excel.Workbook.Worksheets.Add("Sheet1");
//rptHeader = getCaption(rptHeader);
char c = 'A';
c = (char)(((int)c) + DT.Columns.Count - 1);
//sheetcreate.Cells["A1:" + c+"1"].Value = rptHeader;
sheetcreate.Cells["A1:D1"].Value = rptHeader;
sheetcreate.Cells["A1:" + c + "1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
//sheetcreate.Cells["A1:" + c + "1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#c6c6c6"));
sheetcreate.Cells[1, 1, 1, DT.Columns.Count].Merge = true;
sheetcreate.Cells[1, 1, 1, DT.Columns.Count].Style.Font.Bold = true;
int col = 0;
foreach (DataColumn column in DT.Columns)
{
sheetcreate.Cells[2, ++col].Value = column.ColumnName;
sheetcreate.Cells[2, col].Style.Font.Bold = true;
sheetcreate.Cells[2, col].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
sheetcreate.Cells[2, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
if (DT.Rows.Count > 0)
{
int row = 2;
for (int eachRow = 0; eachRow < DT.Rows.Count; ) //looping each row
{
bool havingText = false;
for (int eachColumn = 1; eachColumn <= col; eachColumn++) //looping each column in a row
{
var eachRowObject = sheetcreate.Cells[row + 1, eachColumn];
eachRowObject.Style.Fill.PatternType = ExcelFillStyle.Solid;
eachRowObject.Value = DT.Rows[eachRow][(eachColumn - 1)].ToString();
if (!havingText) //checking if 'totoa' in string and setting up 'havingText' variable to color it differently
havingText = DT.Rows[eachRow][(eachColumn - 1)].ToString().ToLower().Contains("total");
//Making all cell value to left align
eachRowObject.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
//if (CL.isDecimal(DT.Rows[eachRow][(eachColumn - 1)].ToString())) //if it is number with decimal value make it right align
//{
// eachRowObject.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
//}
//eachRowObject.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin); // adding border to each cells
//if (eachRow % 2 == 0) //alternatively adding color to each cell.
// eachRowObject.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#e0e0e0"));
//else
// eachRowObject.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#ffffff"));
}
if (havingText) //if any cell data containt 'total' color complete.
{
for (int eachColumn = 1; eachColumn <= col; eachColumn++)
{
sheetcreate.Cells[row + 1, eachColumn].Style.Fill.PatternType = ExcelFillStyle.Solid;
//sheetcreate.Cells[row + 1, eachColumn].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#86a9ef"));
}
}
eachRow++;
row++;
}
getLog("batch controller: in loop");
}
getLog("batch controller: 485");
sheetcreate.Cells.AutoFitColumns();
excel.Save();
}
catch (Exception e)
{
getLog("Error while generating excel=>"+e);
}
}
You can download EPPlus from : https://www.nuget.org/packages/EPPlus/
An array of Image Url path:
["http://cdncms.fonts.net/hero-images/FEX_Hero_Thumb.png ","http://cdncms.fonts.net/hero-images/Wilma_Hero_Thumb.png "]
asp.net mvc Controller :
public ActionResult Extract(string[] name)
{
//List<string> myList = name.ToList<string>();
for(int x = 0; x < name.Length; x++)
{
//string something = name[x];
var item = name[x];
Session["values"] = item;
}
char[] delimiter1 = new char[] { ',' }; // <-- Split on these
string[] array1 = Session["values"].ToString().Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array1)
{
string exts = Path.GetExtension(item); //illegal character
string strRealname = Path.GetFileName(item); illegal character
}
I know this problem due to the presence of [ character at the beginning and last .I have tried but not succeeded .Any idea how to remove this using split function in C#
Assuming that you have correctly identified the problem, you could do this before making it an array:
var values = Session["values"].ToString();
if(values.StartsWith("[")) values = values.Substring(1);
if(values.EndsWith("]")) values = values.Substring(0, values.Length - 1);