How can I speed up my MVC asp.net website? - c#

Hi Everyone I am working on my first MVC 3 website built in C# in asp.net I am having some trouble with with the speed of the website as it takes over 45 seconds to expand or contract the tables that show the database.
I have included my code for the reportTemplate which has my jquery on it
I have been trying to figure out how to use cache but I am worried that the data will not be up to date when the managers need up to date data
#{
ViewBag.Title = "ReportTemplate";
}
<script language="javascript" type="text/javascript">
$(document).ready(function () {
toggle = function (className) {
$('.' + className).toggle('fast');
}
});
</script>
<h2>ReportTemplate</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
INVESTMENT AREA
</th>
<th>
MAJOR PROGRAM
</th>
<th>
MANAGER
</th>
<th>
PROJECT
</th>
<th>
SPA
</th>
<th>
PA
</th>
</tr>
#{
string investment_area = "";
string major_program = "";
string manager = "";
string project = "";
string spa = "";
string pa = "";
string iaClass = "";
string mpClass = "";
string manClass = "";
string pjClass = "";
string spaClass = "";
string paClass = "";
}
#foreach (var item in Model)
{
iaClass = item.investment_area.Substring(0, 2);
mpClass = item.major_program;
manClass = item.manager;
pjClass = item.project;
spaClass = item.spa;
paClass = item.pa;
if (investment_area != item.investment_area)
{
<tr>
<td class = "ndeTable ui-widget-header pointer border" onclick="toggle('#iaClass')" colspan="6">
#item.investment_area
</td>
</tr>
}
investment_area = item.investment_area;
if (major_program != item.major_program)
{
<tr class="#iaClass">
<td style = "width :200px"></td>
<td class = "ndeTable pointer border" onclick="toggle('#mpClass')" colspan="5">
#item.major_program
</td>
</tr>
}
major_program = item.major_program;
if (manager != item.manager)
{
<tr class = "#iaClass #mpClass">
<td></td>
<td style = "width : 100px"></td>
<td class = "ndeTable pointer border" onclick="toggle('#manClass')" colspan="4">
#item.manager
</td>
</tr>
}
manager = item.manager;
if (project != item.project)
{
<tr class = "#iaClass #mpClass #manClass">
<td></td>
<td></td>
<td style = "width : 200px"></td>
<td class = "ndeTable pointer border" onclick = "toggle('#pjClass')" colspan="3">
#item.project
</td>
</tr>
}
project = item.project;
if (spa != item.spa)
{
<tr class = "#iaClass #mpClass #manClass #pjClass">
<td></td>
<td></td>
<td></td>
<td style = "width : 325px"></td>
<td class = "ndeTable pointer border" onclick = "toggle('#spaClass')" colspan = "2">
#item.spa
</td>
</tr>
}
spa = item.spa;
<tr class = "#iaClass #mpClass #manClass #pjClass #spaClass">
<td></td>
<td></td>
<td></td>
<td></td>
<td style = "width: 200px"></td>
<td class = "ndeTable pointer border" onclick = "toggle('#paClass')" colspan = "1">
#item.pa
</td>
</tr>
pa = item.pa;
}
</table>
I am going to continue trying to optimize the code in the meantime but if anyone has any tips or tricks I can use I would be very thankful as this has been troubling me for the past couple days and 45 secs for a small database is ridiculous. Thank you for your time.
Cheers,
James

Fire up sql profiler/sql trace and check out how many queries you are doing during single http request that creates the page. Queries are often the one to blame for performance issues. It's nearly impossible that solely rendering the view takes so much time.

It might happen that you have too many records that you are trying to display in the table. You should use paging. Take a look at datatables.net It is a nice jquery plugin that will help you with paging. Make sure that you are using server side processing. Of course, you will have to change a lot in your code (both server side and client side).

Which browser are you working with? Older browsers don't have the Javascript performance of the newer ones and with the number of panels you could be simultaneously exposing or hiding that is undoubtedly the cause of your issue.
I agree with the answer that deals with paging, that would be a good option reduce the amount of data you are presenting in one go or you must reduce the number of elements you are revealing simultaneously. Javascript execution isn't instant and on the old browsers it's really slow.

Related

RazorEngine.Templating.TemplateCompilationException: Errors while compiling a Template. ASP.NET core 3

Using RazorEngine to compile the HTML getting error as
RazorEngine.Templating.TemplateCompilationException: Errors while compiling a Template.
Please try the following to solve the situation:
* If the problem is about missing/invalid references or multiple defines either try to load
the missing references manually (in the compiling appdomain!) or
Specify your references manually by providing your own IReferenceResolver implementation.
See https://antaris.github.io/RazorEngine/ReferenceResolver.html for details.
Currently all references have to be available as files!
* If you get 'class' does not contain a definition for 'member':
try another modelType (for example 'null' to make the model dynamic).
NOTE: You CANNOT use typeof(dynamic) to make the model dynamic!
Or try to use static instead of anonymous/dynamic types.
private string RunCompile(string rootPath, string templateName, EmailViewModel model, string templateKey = null)
{
string result = string.Empty;
if (string.IsNullOrEmpty(rootPath) || string.IsNullOrEmpty(templateName) || model == null) return result;
string templateFilePath = Path.Combine(rootPath, templateName);
if (File.Exists(templateFilePath))
{
string template = File.ReadAllText(templateFilePath);
if (string.IsNullOrEmpty(templateKey))
{
templateKey = Guid.NewGuid().ToString();
}
result = Engine.Razor.RunCompile(template, templateKey, typeof(EmailViewModel), model);
}
return result;
}
HTML template
#model ViewModel.EmailViewModel
<table bgcolor="white" align="left" border="0" cellspacing="0" cellpadding="0" style="color:#5E5E5E;font-size:14px;font-family:Proxima Nova,Century Gothic,Arial,Verdana,sans-serif;width:100%;border:1px solid #F0F0F0; padding: 32px;">
<tbody>
<tr align="center">
<td style="padding-top:30px;padding-bottom:32px;">
<img src="https://ok6static.oktacdn.com/bc/image/fileStoreRecord?id=fs01fviisxo2dNOCM2p7" alt="monash university logo"/>
</td>
</tr>
<tr>
<td style="padding-top:24px;">
<div style="font-family:Consolas,Courier New,Courier,monospace;text-align:left;margin:10px;">
<h1>
Thank you for the registration
</h1>
</div>
</td>
</tr>
<tr>
<td style="padding-top:24px;">
<div style="font-family:Consolas,Courier New,Courier,monospace;text-align:left;margin:10px;">
<p>Please click on the below link to confirm email address</p>
</div>
</td>
</tr>
<tr>
<td style="padding-top:24px;">
<div style="font-family:Consolas,Courier New,Courier,monospace;text-align:left;margin:10px;">
#Model.Message
</div>
</td>
</tr>
</tbody>
</table>
I had the same issue. And resolved it with removing string #model ViewModel.EmailViewModel

why onClick Event of C# not working in <td> of table tag

I'm trying to dynamically generate onClick event in tag by concatenating strings and im getting the result i want, but when I click on element then event is not working. I thought that may be not support onClick event and tried other ways like putting onClick in , etc, but nothing works. please help me here.
my html code:
<table class="downloadTable">
<tr>
<th class="sn">SN</th>
<th class="assi">Notes Title</th>
<th class="pby">Subject</th>
<th class="ld">Posted by</th>
<th class="dp">Posted date</th>
</tr><%=getNotesData()%>
</table>
my C# coding:
public string getAssignmentData()
{
string data = "";
string CS = ConfigurationManager.ConnectionStrings["_logdb"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
string query = "Select * from _tbNotes";
SqlCommand comm = new SqlCommand(query, conn);
conn.Open();
using (SqlDataReader drd = comm.ExecuteReader())
{
if (drd.HasRows)
{
while (drd.Read())
{
int id = 1;
string title = drd.GetString(1);
string sub = drd.GetString(2);
string auth = drd.GetString(3);
data += "<tr OnClick=\"_storeDetails(4)\"><td>" + id + "</td><td>" + title + "</td><td>" + sub + "</td><td>" + auth + "</td></tr>";
id++;
}
}
}
return data;
}
}
Function that im calling onClick()
protected void _storeDetails(int uid)
{
Session["AssignmentNo"] = uid;
Response.Redirect("~/ViewAssignment.aspx");
}
resulting browser code:
<table class="massi tb">
<tbody>
<tr>
<th class="sn">SN</th>
<th class="assi">Assignment Title</th>
<th class="pby">Posted By</th>
<th class="pd">Post Date</th>
<th class="ld">Last Submit Date</th>
</tr>
<tr onclick="_storeDetails(4)">
<td>1</td>
<td>Java assignment 1</td>
<td>java</td>
<td>tanvi</td>
</tr>
<tr onclick="_storeDetails(4)">
<td>1</td>
<td>vector graphics</td>
<td>web development</td>
<td>pandey</td>
</tr>
<tr onclick="_storeDetails(4)">
<td>1</td>
<td>Advance java assignment 2</td>
<td>Advance Java</td>
<td>Tenvi Gautam</td>
</tr>
<tr>
<td>1</td>
<td onclick="_storeDetails">Java assignment 1</td>
<td>java</td>
<td>tanvi</td>
</tr>
</tbody>
please help me what im doing wrong here. also if any alternative you doing this same work then tell me.
That will not work because this:
<tr onclick="_storeDetails(4)">
means to call the funtion _storeDetails on the client side. Therefore, the function must be a javascript function.
Your storeDetails is a method on the server side. You need to do it like this instead:
<tr onclick="javascript:__doPostBack('_storeDetails','4');">
Then in the server side, you need this code:
if (this.IsPostBack)
{
if (Request["__EVENTTARGET"] == "_storeDetails")
{
// This can fail if you pass a value which is not an integer
// You can use TryParse instead if you want.
int param = int.Parse(Request["__EVENTARGUMENT"]);
_storeDetails(param);
}
}
You're trying to call a server-side function from client-side code, which in your example is not going to work. You have a few options:
Do a postback and set the desired control as the source. You need to create a client javascript function:
<tr onclick="_storeDetails(4)">
<script type="text/javascript">
function _storeDetails(parameter)
{
__doPostBack('_storeDetailsClick', parameter)
}
</script>
You could then handle postback in Page_Load().
Use Web Methods:
[WebMethod]
public static void StoreDetails(int uid)
{
}
Call it in JavaScript:
PageMethods.SetName(parameterValue, onSuccess, onFail);
You need to initialize page methods:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Do it all client-side. Of course this depends on what you're doing with the posted data.

C# modifying strings

I'm working on an application in which I retrieve data from a database to be displayed in a table in my cshtml. One of the fields I'm calling is a date field. The data for it in the database is stored in the following format: MMDDYY i.e; 091504. For reasons I need not get into, the data has to be stored in that format in the database. I'm trying to figure out how I can modify its display to show 09/15/04 instead of 091504.
#model IEnumerable<BillingApp.Models.SERV_CHARGE_INT_RATE_NSF_PENALTY>
<table id="Test" class="tablesorter">
<thead>
<tr>
<th>Effective Date</th>
</tr>
</thead>
#if (Model.Count() == 0)
{
<tbody>
<tr>
<td colspan="4">
No Records match search criteria
</td>
</tr>
</tbody>
}
else{
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.EFFECTIVE_DATE)
</td>
</tr>
}
</tbody>
</table>
If you use a DateTime object, you can try using [DisplayFormat] in your model.
Ex :
[DisplayFormat(DataFormatString = "{MM/dd/yy}")]
public DateTime EFFECTIVE_DATE { get; set }
If you are using a string instead of DateTime, you could consider converting the data type by using #ByteBlast's solution :
DateTime.ParseExact(item.EFFECTIVE_DATE, "MMddyy", CultureInfo.CurrentCulture);
There are many ways to handle this.
One would be to have your model class parse the dates coming out of the database into actual DateTime objects and then use those throughout your application (probably the best choice, if you need to do anything else with the dates).
Another would be to slice up the string when displaying it, if all you need to do is display the date. Something along the lines of this:
#foreach (var item in Model)
{
<tr>
<td>
#(item.EFFECTIVE_DATE.Substring(0,2))/#(item.EFFECTIVE_DATE.Substring(2,2))/#(item.EFFECTIVE_DATE.Substring(4,2))
</td>
</tr>
}

Real-time searching of GridView control

In the past I've used jQuery/Ajax to capture the key press of an end user, and build up a WHERE clause to filter data on a Web form.
I'm now taking advantage of the strongly type facilitates in ASP.NET 4.5. I was wondering if anyone has a way of performing real-time filtering/searching on a Gridview.
Basically, I have three grids, all showing different information. I want the end-user to key in or select from a drop down list (generic searching) and all girds reflect those changes.
I'm not adverse to resorting back to the old method, just didn't; know if there was anything new I could use?
So you can look at this. I hope this help you.
Here is the HTML:
<input id="searchInput" value="Type To Filter">
<br/>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody id="fbody">
<tr>
<td>cat</td>
<td>one</td>
</tr>
<tr>
<td>dog</td>
<td>two</td>
</tr>
<tr>
<td>cat</td>
<td>three</td>
</tr>
<tr>
<td>moose</td>
<td>four</td>
</tr>
<tr>
<td>mouse</td>
<td>five</td>
</tr>
<tr>
<td>dog</td>
<td>six</td>
</tr>
</tbody>
</table>
And here is the JavaScript code:
$("#searchInput").keyup(function () {
// Split the current value of searchInput
var data = this.value.split(" ");
// Create a jQuery object of the rows
var jo = $("#fbody").find("tr");
if (this.value == "") {
jo.show();
return;
}
// Hide all the rows
jo.hide();
// Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
// Show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
Enter link description here

Parse data/numbers from table cells C# or VisualBasic

I have a string which contains html code from a webpage. There's a table in the code I'm interested in. I want to parse the numbers present in the table cells and put them in textboxes, each number in its own textbox. Here's the table:
<table class="tblSkills">
<tr>
<th class="th_first">Strength</th><td class="align_center">15</td>
<th>Passing</th><td class="align_center">17</td>
</tr>
<tr>
<th class="th_first">Stamina</th><td class="align_center">16</td>
<th>Crossing</th><td class="align_center"><img src='/pics/star.png' alt='20' title='20' /></td>
</tr>
<tr>
<th class="th_first">Pace</th><td class="align_center"><img src='/pics/star_silver.png' alt='19' title='19' /></td>
<th>Technique</th><td class="align_center">16</td>
</tr>
<tr>
<th class="th_first">Marking</th><td class="align_center">15</td>
<th>Heading</th><td class="align_center">10</td>
</tr>
<tr>
<th class="th_first">Tackling</th><td class="align_center"><span class='subtle'>5</span></td>
<th>Finishing</th><td class="align_center">15</td>
</tr>
<tr>
<th class="th_first">Workrate</th><td class="align_center">16</td>
<th>Longshots</th><td class="align_center">8</td>
</tr>
<tr>
<th class="th_first">Positioning</th><td class="align_center">18</td>
<th>Set Pieces</th><td class="align_center"><span class='subtle'>2</span></td>
</tr>
</table>
As you can see there are 14 numbers. To make things worse numbers like 19 and 20 are replaced by images and numbers lower than 6 have a span class.
I know I could use HTML agility pack or something similar, but I'm not yet that good to figure how to do it by myself, so I need your help.
Your HTML sample also happens to be good XML. You could use any of .net's XML reading/parsing techniques.
Using LINQ to XML in C#:
var doc = XDocument.Parse(yourHtml);
var properties = new List<string>(
from th in doc.Descendants("th")
select th.Value);
var values = new List<int>(
from td in doc.Descendants("td")
let img = td.Element("img")
let textValue = img == null ? td.Value : img.Attribute("alt").Value
select int.Parse(textValue));
var dict = new Dictionary<string, int>();
for (var i = 0; i < properties.Count; i++)
{
dict[properties[i]] = values[i];
}

Categories

Resources