Loop optimization (Multi level Menu) ASP.NET - asp.net-mvc

I'm trying create a function to generate HTML file for multi-language menu. The code can work but only problem is its taking too long to compile. The flow is, this function will be called in the Global.asax file (process before start the program)
I suspect it caused by the looping process. So please advice me about the optimization. Thank you in advance. Here is the code.
public static void GenerateMenu(string strPath)
{
string[] tempCateHTML = new string[] { "_temp_menu_en.cshtml", "_temp_menu_bm.cshtml", "_temp_menu_ch.cshtml" }; //temporary file names
string[] cateHTML = new string[] { "_menu_en.cshtml", "_menu_bm.cshtml", "_menu_ch.cshtml" };
for (int i = 0; i < 3; i++)
{
using (EFContext ctx = new EFContext())
{
List<int> parentId = new List<int>();
List<Category> parentCategory = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = 0").ToList();
StringWriter sWriter = new StringWriter();
using (HtmlTextWriter wt = new HtmlTextWriter(sWriter))
{
foreach (Category cate in parentCategory)
{
string[] columnParent = new string[] { cate.Category_Name, cate.Category_NameBM, cate.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li); //<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A); //<a>
wt.Write(columnParent[i]);
wt.RenderEndTag();//</a>
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
List<Category> childCategoryL1 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", cate.CategoryID).ToList();
foreach (Category root in childCategoryL1)
{
string[] columnChild1 = new string[] { root.Category_Name, root.Category_NameBM, root.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild1[i]);
wt.RenderEndTag();//</a>
List<Category> childCategoryL2 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", root.CategoryID).ToList();
if (childCategoryL2.Count > 0)
{
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
foreach (Category child1 in childCategoryL2)
{
string[] columnChild2 = new string[] { child1.Category_Name, child1.Category_NameBM, child1.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild2[i]);
wt.RenderEndTag();//</a>
List<Category> childCategoryL3 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", child1.CategoryID).ToList();
if (childCategoryL3.Count > 0)
{
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
foreach (Category child2 in childCategoryL3)
{
string[] columnChild3 = new string[] { child2.Category_Name, child2.Category_NameBM, child2.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild3[i]);
wt.RenderEndTag();//</a>
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
}
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
}
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
wt.RenderEndTag();//</li>
}
}
string menuHTML = sWriter.ToString();
string filePath = Path.Combine(strPath, #"Views\Shared\CacheData\CateMenu\");
new FileInfo(filePath).Directory.Create(); //create new folder
var menuPath = String.Format("{0}{1}", filePath, tempCateHTML[i]); //create multiple HTML files for multiple language
using (FileStream fs = new FileStream(menuPath, FileMode.Append, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(menuHTML);
sw.Flush();
sw.Close();
fs.Close();
}
if (!File.Exists(filePath + cateHTML[i]))
{
using (File.Create(filePath + cateHTML[i]))
{
//create dummy file if the file doesnt exists
}
}
File.Replace(menuPath, filePath + cateHTML[i], filePath + cateHTML[i] + ".bac");
}
}
}
it's a long process. So really Thank you for the time

Actuall I've already found the solution for my problem. The solution was built tree menu based on this method. Thank you for the help.

Related

How to refactor the connectionString in my Entity Framework & ASP.NET MVC project?

I have a large number of stored procedures to work with and I have to work with Entity Framework.
I got for example this controller where I'm just calling the database to show my table:
public class CarguioController : Controller
{
public ActionResult Index(int? page)
{
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
// establece conneciĆ³n
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#MODO";
param1.SqlDbType = SqlDbType.Int;
param1.Value = 2;
SqlCommand cmdProcedure = new SqlCommand(#"Almacen.[PRC_Carguio]", conn);
cmdProcedure.Parameters.Add(param1);
conn.Open();
cmdProcedure.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmdProcedure.ExecuteReader();
List<CarguioViewModel> lst = new List<CarguioViewModel>();
int pageNumber = page ?? 1;
int pageSize = 8;
if (dr.HasRows)
{
while (dr.Read())
{
lst.Add(new CarguioViewModel
{
Carguio_ID = dr.GetInt32(0),
Vehiculos_ID = dr.GetInt32(1),
ManifiestoCarga_ID = dr.GetInt32(2),
Guia_ID = dr.GetInt32(3),
Programaciones_ID = dr.GetInt32(4),
Numero = dr.GetInt32(5),
NroMobil = dr.GetString(6),
Fecha = dr.GetDateTime(7),
Usuarios_ID = dr.GetInt32(8),
Sucursales_IS = dr.GetInt32(9)
});
//display retrieved record
}
return View(lst.ToPagedList(pageNumber, pageSize));
}
else
{
Console.WriteLine("No data found.");
}
dr.Close();
conn.Close();
}
return View();
}
}
As you can see, I have to connect with the SQL Server database many times. Maybe you have done a similar job with ASP.NET MVC projects or have any idea to refactor my code?
I have more than 30 tables and everyone has more a Crud and other functions.
I've been searching for this but there is just the same example.
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
You can get create in General Utility class to read the connection, so that It is stay in one place in the code and read connection value from the Genral Utility class wherever you need it.
void Main()
{
string cn = GeneralUtility.getConnectionString();
}
public class GeneralUtility
{
public static string getConnectionString()
{
string cs = "";
try
{
cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
catch (Exception ex)
{
throw new Exception("Connection String Error " + ex.Message.ToString());
}
return cs;
}
}
I added a new element called ADO.Net Entity Data Model, where I retrieve all my Stored Procedures, It is helpful
I added a new element called ADO.Net Entity Data Model
Well, now my code is shorter than before:
public ActionResult Index(int? page)
{
List<CarguioModel> lst = new List<CarguioModel>();
int pageNumber = page ?? 1;
int pageSize = 8;
using (MarviBKPEntities prcAlm = new MarviBKPEntities())
{
List<PRC_Carguio_Result> prc = prcAlm.PRC_Carguio(2, null, null, null, null, null, null, null, null, null, null).ToList();
return View(prc.ToPagedList(pageNumber, pageSize));
}
return View();
}
Whta do you think? Could it cause some bad performance?

Delete a context record from grid in kendo UI using LINQ

Hi Im using kendo ui grid in my project.
This is my code to insert records in database.
public static void Insert(StudentViewModel student)
{
student.StudentId = All().OrderByDescending(p => p.StudentId).First().StudentId + 1;
//All().Insert(0, student);
UniRegEntities uniRegEntities = new UniRegEntities();
Student stu =new Student();
stu.FName = student.FirstName;
stu.LName = student.LastName;
stu.Gender = uniRegEntities.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
stu.Id = student.StudentId;
uniRegEntities.Students.Add(stu);
uniRegEntities.SaveChanges();
}
And this is my update statement.
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToUpdate = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
studentToUpdate.FName = student.FirstName;
studentToUpdate.LName = student.LastName;
studentToUpdate.Gender = context.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
context.SaveChanges();
}
Anyone can suggest me the delete method?
You can either get an entity from the DB and then delete it or create one and then delete it.
So:
var e = // Get
ctx.DeleteObject(e);
ctx.SaveChanges();
or
var e = new Foo() { FooId = id };
ctx.Entity.Attach(e);
ctx.DeleteObject(e);
ctx.SaveChanges();
Applied to your situation:
You are getting a record so you want to use DeleteObject()
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToDelete = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
context.Students.DeleteObject(studentToUpdate);
context.SaveChanges();
}
context.Students.Remove(context.students.Single(x=>x.Id==student.Id));
Can you please try with below code snippet?
using (var db= new AppContext(ConnectionStr))
{
try
{
con.Configuration.AutoDetectChangesEnabled = false;
var o = new Student { StudentId = student.StudentId };
db.Students.Attach(o);
db.Students.Remove(o);
db.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message);
}
finally
{
con.Configuration.AutoDetectChangesEnabled = true;
}
}

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I am having trouble exporting data to Excel. The following seems to render the gridview into my View, instead of prompting the user to open with Excel, which I have installed on my machine.
Public ActionResult ExportToExcel()
{
var products = this.Repository.Products.ToList();
var grid = new GridView();
grid.DataSource = from p in products
select new
{
Id = p.Id,
Name = p.Name
};
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View("MyView");
}
What am I doing wrong?
I have tried your code and it works just fine.
The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):
public ActionResult ExportToExcel()
{
var products = new System.Data.DataTable("teste");
products.Columns.Add("col1", typeof(int));
products.Columns.Add("col2", typeof(string));
products.Rows.Add(1, "product 1");
products.Rows.Add(2, "product 2");
products.Rows.Add(3, "product 3");
products.Rows.Add(4, "product 4");
products.Rows.Add(5, "product 5");
products.Rows.Add(6, "product 6");
products.Rows.Add(7, "product 7");
var grid = new GridView();
grid.DataSource = products;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View("MyView");
}
You can call helper class in any controller
//view
#Html.ActionLink("Export to Excel", "Excel")
//controller Action
public void Excel()
{
var model = db.GetModel()
Export export = new Export();
export.ToExcel(Response, model);
}
//helper class
public class Export
{ public void ToExcel(HttpResponseBase Response, object clientsList)
{
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = clientsList;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
Step 1: View page code
<input type="button" id="btnExport" value="Export" class="btn btn-primary" />
<script>
$(document).ready(function () {
$('#btnExport').click(function () {
window.location = '/Inventory/ExportInventory';
});
});
</script>
Step 2: Controller Code
public ActionResult ExportInventory()
{
//Load Data
var dataInventory = _inventoryService.InventoryListByPharmacyId(pId);
string xml=String.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(dataInventory.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, dataInventory);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
xml = xmlDoc.InnerXml;
}
var fName = string.Format("Inventory-{0}", DateTime.Now.ToString("s"));
byte[] fileContents = Encoding.UTF8.GetBytes(xml);
return File(fileContents, "application/vnd.ms-excel", fName);
}
using (MemoryStream mem = new MemoryStream())
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Add a row to the cell table.
Row row;
row = new Row() { RowIndex = 1 };
sheetData.Append(row);
// In the new row, find the column location to insert a cell in A1.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
{
refCell = cell;
break;
}
}
// Add the cell to the cell table at A1.
Cell newCell = new Cell() { CellReference = "A1" };
row.InsertBefore(newCell, refCell);
// Set the cell value to be a numeric value of 100.
newCell.CellValue = new CellValue("100");
newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "text.xlsx");
}
I have done this before, I think you need to remove the ActionResult. Make it a void and remove the return View(MyView). this is the solution
I used a list in my controller class to set data into grid view. The code works fine for me:
public ActionResult ExpExcl()
{
List<PersonModel> person= new List<PersonModel>
{
new PersonModel() {FirstName= "Jenny", LastName="Mathew", Age= 23},
new PersonModel() {FirstName= "Paul", LastName="Meehan", Age=25}
};
var grid= new GridView();
grid.DataSource= person;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition","attachement; filename=data.xls");
Response.ContentType="application/excel";
StringWriter sw= new StringWriter();
HtmlTextWriter htw= new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View();
}
The modest way to export excel in MVC is using Microsoft CloseXml. I wrote a simple function for exporting my query result as excel sheet:
using ClosedXML.Excel;
...
public ActionResult ToExcel(List<Dictionary<string, string>> data, Dictionary<string, string> columnMap, string fileName, string sheetName)
{
var dtDataBuffer = new System.Data.DataTable("buffer");
foreach (string col in columnMap.Values)
{
dtDataBuffer.Columns.Add(col, typeof(string));
}
foreach (var row in data)
{
List<string> rowData = new List<string> { };
foreach (string col in columnMap.Keys)
{
rowData.Add(row[col]);
}
dtDataBuffer.Rows.Add(rowData.ToArray());
}
var memoryStream = new MemoryStream();
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add(dtDataBuffer, sheetName);
worksheet.Rows().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
worksheet.Rows().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
worksheet.Columns().AdjustToContents();
workbook.SaveAs(memoryStream);
}
return File(memoryStream.ToArray(), "application/vnd.ms-excel", fileName);
}
And this is a usage example (in practice I use my own class to run query and generate data. You can find it here for Oracle and SQL Server):
public ActionResult myReportExport(){
var data=List<Dictionary<string, string>>(){
{{"Column1_Index","Column1_Value"},{"Column2_Index","Column2_Value"},...}
...
};
return ToExcel(data, new Dictionary<string, string> {
{ "Column1_Index", "Column1 Title" } ,
{ "Column2_Index", "Column2 Title" } ,
...
},
"myFileName.xlsx",
"my sheet name"
);
}

Why foreach returns one row inside extension method?

Why foreach returns one row inside extension method?These codes run properly inside normal method.What could be reason for return one column?
public static MvcHtmlString DropDownWithOpt(this HtmlHelper html)
{
IList<Countries> c = new List<Countries>
{
new Countries{ Country = "Georgia", Cities = new List<Cities>
{
new Cities{ City="Batumi"},
new Cities{ City="Tbilisi"},
new Cities{ City="Zugdidi"}
}},
new Countries{ Country = "Turkey", Cities = new List<Cities>
{
new Cities{ City="Istanbul"},
new Cities{ City="Ankara"}
}}
};
var select = new TagBuilder("select");
var group = new TagBuilder("optgroup");
var option = new TagBuilder("option");
foreach (var item in c)
{
group.Attributes["label"] = item.Country;
foreach (var ci in item.Cities)
{
option.Attributes["value"] = ci.City.ToString();
option.SetInnerText(ci.City);
}
}
select.InnerHtml = group.ToString(TagRenderMode.SelfClosing) + option.ToString();
return MvcHtmlString.Create(select.ToString(TagRenderMode.Normal));
}
Because inside the loop you are overwriting it
you may use
Attributes.Add (key, value)

Blackberry - get contacts list

I wanted to get the list of all names and their corresponding email address from the contact list in blackberry JDE 4.7 can anyone help with the code for getting the above mentioned things..
Thanks in advance...
try this code:
public Scr() {
Vector v = getContacts();
Enumeration iterator = v.elements();
while (iterator.hasMoreElements()) {
String[] contact = (String[]) iterator.nextElement();
for (int i = 0; i < contact.length; i++)
add(new LabelField(contact[i]));
}
}
private Vector getContacts() {
Vector result = new Vector();
try {
BlackBerryContactList contactList = (BlackBerryContactList) PIM
.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration enumx = contactList.items();
while (enumx.hasMoreElements()) {
BlackBerryContact c = (BlackBerryContact) enumx.nextElement();
String[] contact = new String[2];
if (contactList.isSupportedField(BlackBerryContact.NAME)) {
String[] name = c.getStringArray(BlackBerryContact.NAME, 0);
String firstName = name[Contact.NAME_GIVEN];
String lastName = name[Contact.NAME_FAMILY];
contact[0] = firstName + " " + lastName;
}
if (contactList.isSupportedField(BlackBerryContact.EMAIL)) {
StringBuffer emails = new StringBuffer();
int emailCount = c.countValues(BlackBerryContact.EMAIL);
for (int i = 0; i < emailCount; i++) {
String email = c.getString(BlackBerryContact.EMAIL, i);
if (email != null) {
emails.append(email.trim());
emails.append("; ");
}
}
contact[1] = emails.toString();
}
result.addElement(contact);
}
} catch (PIMException ex) {
ex.printStackTrace();
}
return result;
}

Resources