Check and display errors in GridView - c#

I have this codes:
private string ErrorMessage(string input)
{
{
if (!string.IsNullOrEmpty(input))
return input;
BtnImport1.Visible = false;
}
return "No value entered!";
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileNameOnServer = fileUpload.PostedFile.FileName;
string fileExt =
System.IO.Path.GetExtension(fileUpload.FileName);
if (fileUpload.PostedFile != null && fileExt == ".csv")
{
try
{
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploads"));
Label1.Text = "File name: " +
fileUpload.PostedFile.FileName + "<br>" +
fileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
BtnImport1.Visible = true;
Cancel.Visible = true;
fileUpload.Visible = false;
btnUpload.Visible = false;
}
else
{
Label1.Text = "Error - a file name must be specified/only csv files are allowed";
return;
}
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns[8]) });
myGridView.DataSource = data;
myGridView.DataBind();
}
Currently, if there are empty fields in the gridview, it will display "No value entered", but, this is only for column[1] to column [7]. If I were to upload the csv file with column[8] and column[0] containing no value, the debugger would stop as there is an error. How do I avoid this? Please help!

Change this line:
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns[8]) });
To this:
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns.Length<=8?"":columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns.Length<=8?"":columns[8]) });
UPDATE: Expanding my answer to answer second question.
Change your ErroMessage method to this:
private string ErrorMessage(string input, string dataTypeExpected="string")
{
switch (dataTypeExpected)
{
case "string": if (!string.IsNullOrEmpty(input))
return input;
break;
case "int":
int result=-1;
if (int.TryParse(input, out result))
return result.ToString();
else return "Error: value must be an integer";
}
return "No value entered!";
}
And also change the var data... part to this (pay attention how I pass columns[7] & columns[8] to the ErrorMessage method):
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns.Length<=8?"":columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7],"int"), Registration = ErrorMessage(columns.Length<=8?"":columns[8],"int") });
Explanation: I rewrote the ErrorMessage function to receive an extra optional parameter (defaulted to "string") called dataTypeExpected. You can use that parameter to indicate the data type that the input parameter should be in. If the data passed in is an empty string or a string that does not contain digits and you specify the dataTypeExpected parameter to be "int" (as I did above), the error message will say "Error: value must be an integer";
Notice that I removed the line BtnImport1.Visible = false; from the ErrorMessage method because you are executing that line once for every time the ErrorMessage is called when you only need to execute it once. So, move that line to some place else.

Related

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request

I have a controller with a method that returns result, when i step through debugging i get DenyAnyGet on JsonRequestBehavior. Any idea what could be an issue? I need some assistance please mates. The GetData method uses SortByColumnWithOrder below and maybe i am missing something and fix my table as well to allow data to filter not null. As i thought before it was the reason, but getting DenyGet i am bit confused now.
public ActionResult GetData()
{
//Server side Parameter.
JsonResult result = new JsonResult();
try
{
// Initilization
string search = Request.Form.GetValues("search[value]")[0];
// string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
// Loading.
List<EventsManagementTb> data = this.LoadData();
// Total record count.
int totalRecords = data.Count;
// Verification.
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
{
// Apply search
data = data.Where(l=>l.TrainingType.ToLower().Contains(search.ToLower())
|| l.TrainingDescription.ToLower().Contains(search.ToLower())
|| l.Price.ToString().ToLower().Contains(search.ToLower())
|| l.Venue.ToLower().Contains(search.ToLower())
|| l.Facilitator.ToLower().Contains(search.ToLower())
|| l.WhoAttend.ToLower().Contains(search.ToLower())
|| l.RSVP.ToLower().Contains(search.ToLower())).ToList();
}
// Sorting
data = this.SortByColumnWithOrder(order, orderDir, data);
// Filter record data.
int recFilter = data.Count;
// Apply pagination.
data = data.Skip(startRec).Take(pageSize).ToList();
result = this.Json(new { draw = Request["draw"], recordsTotal = totalRecords, recordsFiltered = recFilter, data = data }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;// This gets hits here.
}
private List<EventsManagementTb> SortByColumnWithOrder(string order, string orderDir, List<EventsManagementTb> data)
{
// Initialization.
List<EventsManagementTb> lst = new List<EventsManagementTb>();
try
{
// Sorting
switch (order)
{
case "0":
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.TrainingType).ToList()
: data.OrderBy(l => l.TrainingType).ToList();
break;
case "1":
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.TrainingDescription).ToList()
: data.OrderBy(l => l.TrainingDescription).ToList();
break;
case "2":
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.Price).ToList()
: data.OrderBy(l => l.Price).ToList();
break;
case "3":
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.Venue).ToList()
: data.OrderBy(l => l.Venue).ToList();
break;
case "4":
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.Facilitator).ToList()
: data.OrderBy(l => l.Facilitator).ToList();
break;
case "5":
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.WhoAttend).ToList()
: data.OrderBy(l => l.WhoAttend).ToList();
break;
default:
lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(l => l.RSVP).ToList()
: data.OrderBy(l => l.RSVP).ToList();
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return lst;
}
private List<EventsManagementTb> LoadData()
{
List<EventsManagementTb> lst = new List<EventsManagementTb>();
try
{
string line = string.Empty;
string srcFilePath = "content/files/EventsManagementTb.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
//Read file
while ((line = sr.ReadLine()) != null)
{
EventsManagementTb tb = new EventsManagementTb();
string[] info = line.Split(',');
// Setting
tb.TrainingType = info[0].ToString();
tb.TrainingDescription = info[1].ToString();
tb.Price = Convert.ToInt32(info[2].ToString());
tb.Venue = info[3].ToString();
tb.Facilitator = info[4].ToString();
tb.WhoAttend = info[5].ToString();
tb.RSVP = info[6].ToString();
// Adding
lst.Add(tb);
}
sr.Dispose();
sr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return lst;
}
}

KnockoutJS doesn't bind fields that have been autocompleted

I'm using an external file where I get company data. The autocomplete works just fine, inputs get filled. But when I save the page into my database all the autocompleted fields don't get bind.
public Save(saveorder: Boolean): void {
let order: Order = ko.toJS(OrderPage.Instance().Order);
let date = OrderPage.Instance().Order.DateAccepted;
let removefromorderlines: Array<number> = [];
OrderPage.Instance().j$.each(order.OrderLines, (index: number, orderline: OrderLine) => {
// Check if there are any orderlines that don't have a modelid
if (orderline.ArticleModelId == null) {
removefromorderlines.push(index);
}
});
let previousindex: any = 0;
$.each(removefromorderlines, (index: number, orderlineindex: number) => {
order.OrderLines.splice(orderlineindex - previousindex, 1);
previousindex++;
});
if (saveorder == true) {
OrderPage.Instance().ToggleDisableButton('btnSaveOrder', true);
webApi.Execute(HttpRequestType.Post, '/Order/SaveOrder', order, OrderPage.Instance().OnSaveSuccess, OrderPage.Instance().OnSaveError);
}
The data that is missing is inside of 'Order'. The data gets picked up as soon as I change anything about the inputs. I've tried to use "valueUpdate: 'input'" but no success so far.
This is my autocomplete code:
namespace Services {
interface kvkResult {
handelsnaam: string;
dossiernummer: number;
straat: string;
huisnummer: number;
huisnummertoevoeging: string;
postcode: string;
plaats: string;
ModelId: string;
displayname: string;
ContactPersonModelId: string;
}
interface Contact {
ModelId: string;
displayname: string;
}
export class kvkFactory
{
private ctlCompanyName: string;
private ctlContainerName: string;
private ctlCoc: string;
private ctlAddress: string;
private ctlAddressNumber: string;
private ctlAddressNumberSuffix: string;
private ctlZipCode: string;
private ctlTown: string;
private ctlModelId: string;
private ctlContactPersonModelId: string;
/** Function to Fetch data from kvk api
#ctlSearch: Input control for coc organisations
#ctlAutocompleteContainer: output control to display organisations result.
#ctlCocClass: output text control for Kamer voor koophandel nummer
#ctlAddressClass: output text control for address organisation
#ctlZipCodeClass: output text contorl for zip code organisation
#ctlTownClass: output text contorl for town of settlement organisation
*/
constructor(ctlSearch: string, ctlAutocompleteContainer: string, ctlCompanyNameElement: string, ctlCocElement: string, ctlAddressElement: string, ctlAddressNumberElement: string, ctlAddressNumberSuffixElement: string, ctlZipCodeElement: string, ctlTownElement: string, ctlModelIdElement?: string, ctlContactPersonModelIdElement?: string, webapiurlforsearch?: string)
{
this.ctlCompanyName = ctlSearch;
this.ctlContainerName = ctlAutocompleteContainer;
this.ctlCompanyName = ctlCompanyNameElement;
this.ctlCoc = ctlCocElement;
this.ctlAddress = ctlAddressElement;
this.ctlAddressNumber = ctlAddressNumberElement;
this.ctlAddressNumberSuffix = ctlAddressNumberSuffixElement;
this.ctlZipCode = ctlZipCodeElement;
this.ctlTown = ctlTownElement;
this.ctlModelId = ctlModelIdElement;
this.ctlContactPersonModelId = ctlContactPersonModelIdElement;
$(this.ctlCompanyName).keyup(function () {
clearTimeout(this.typingTimer);
this.typingTimer = setTimeout(() => { kvkfactory.searchKvk(webapiurlforsearch); }, this.doneTypingInterval);
});
}
typingTimer: number;
datafound = (data: any): void =>
{
let resultobject: ResultObject<kvkResult> = data;
let companies = resultobject.Records;
$(kvkfactory.ctlContainerName).empty();
$(kvkfactory.ctlContainerName).show();
$(kvkfactory.ctlContainerName).append('<table>');
$.each(companies, function (i, item) {
let entry: kvkResult = item;
$('table', kvkfactory.ctlContainerName).append("<tr class=\"auto-complete-item\" data-modelid=\"" + entry.ModelId + " \" data-contactpersonmodelid=\"" + entry.ContactPersonModelId +" \"data-id=\"" + i + "\"><td>" + entry.handelsnaam + "</td><td>" + entry.straat + " " + entry.huisnummer + "</td><td>" + entry.postcode + "</td><td>" + entry.plaats + "</td></tr>");
});
$(kvkfactory.ctlContainerName).append('</table>');
$(".auto-complete-item").on("click", function () {
let id: string = $(this).data("id");
let contactidnumber = 1;
let contactid: string = $(this).data('contactidnumber');
let modelid: string = $(this).data("modelid");
let contacts = companies[contactidnumber];
let organisationmodelid: string[] = null;
let count: number = 0;
let company: kvkResult = companies[id];
if (kvkfactory.ctlModelId != undefined && modelid!=null ) {
$(kvkfactory.ctlModelId).val(modelid);
$(kvkfactory.ctlContactPersonModelId).val(organisationmodelid);
}
$(kvkfactory.ctlCompanyName).val(company.handelsnaam);
$(kvkfactory.ctlCoc).val(company.dossiernummer);
$(kvkfactory.ctlAddress).val(company.straat);
$(kvkfactory.ctlAddressNumber).val(company.huisnummer);
$(kvkfactory.ctlAddressNumberSuffix).val(company.huisnummertoevoeging);
$(kvkfactory.ctlZipCode).val(company.postcode);
$(kvkfactory.ctlTown).val(company.plaats);
$(kvkfactory.ctlModelId).val(company.ModelId);
$(".auto-complete-container").hide();
Materialize.updateTextFields();
});
$(document).mouseup(function (e) {
let container = $(".auto-complete-container");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
};
doneTypingInterval: number = 800;
searchKvk = (webapiurlforsearch?: string): void => {
if ($(this.ctlCompanyName).val().length >= 3) {
if (webapiurlforsearch == undefined) {
webapiurlforsearch = variables.websiteurl + "/Kvk/Getdata";
}
let val = $(this.ctlCompanyName).val();
webApi.Execute(HttpRequestType.Get, webapiurlforsearch, { name: val }, this.datafound, null);
} else {
$(".auto-complete-container").empty();
}
}
}
}
let kvkfactory: Services.kvkFactory;

Accessing string from an html template class

I'm trying to access a certain variable from another class, however I'm not able to do so. I have two buttons - the first button sets token to an html template file. The second should generate the file. The first button calls the class. The second button should call the string from the class for generation.
My first button is as follows:
private void btnTemplate_Click(object sender, EventArgs e)
{
if ((txtTitle.Text == "") && (txtSku.Text == "") && (txtPrice.Text == "") && (txtDesc.Text == "") && (txtImg.Text == ""))
{
MessageBox.Show("No row selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
OpenFileDialog SetData = new OpenFileDialog();
SetData.Filter = "HTML|*.html;";
GlobalVar.setPath = "C:\\genHtml.html";
var result = SetData.ShowDialog();
DataSet ds = new DataSet();
if (result == DialogResult.OK)
{
string fileName = SetData.FileName;
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);
}
}
}
My second button:
private void btnGenerate_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(GlobalVar.setPath);
}
catch
{
MessageBox.Show("Please select a template first", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I get an error with the string output. How can I call string 'output' for the second button?
My class is as follows:
class HtmlTemplate
{
private string _html;
public HtmlTemplate(string templatePath)
{
using (var reader = new StreamReader(templatePath))
_html = reader.ReadToEnd();
}
public string Render(object values)
{
string output = _html;
foreach (var p in values.GetType().GetProperties())
output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty);
return output;
}
}
There is not enough context to be sure, but in the case of the second button it looks like output is not declared as a variable or possibly not assigned a (correct) value.
File.WriteAllText(#GlobalVar.setPath, output);
could become
var template = new HtmlTemplate(#SetData.FileName);
File.WriteAllText(#GlobalVar.setPath, template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
or alternatively
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);

Show only result within 90 days from present date after API grabs the data

I have my code pasted below. Now I'm totally lost on where and what code to insert let's say I want to show only data which has a startdate within (date today - 90 days). Kindly help me please. Been stuck for weeks on this one.
By the way this code will run after it grabs the data from another program through API.
public DataTable FGetHasData(int iMode)
{
DataTable dtHASDataReturn = new DataTable();
DataTable dtHASData = new DataTable();
string sSorter = String.Empty;
if (iMode.Equals(0))
{
try
{
dtHASData = this.oHASData.RetrievePayments();
dtHASData.Columns[0].ColumnName = "Agency Code";
dtHASData.Columns[1].ColumnName = "Agency Name";
dtHASData.Columns[2].ColumnName = "Patient Code";
dtHASData.Columns[3].ColumnName = "Claim Code";
dtHASData.Columns[5].ColumnName = "Insurance Company Name";
dtHASData.Columns[6].ColumnName = "Amount";
dtHASData.Columns[7].ColumnName = "Document Number";
dtHASData.Columns[8].ColumnName = "To Print";
dtHASData.Columns[9].ColumnName = "Payment Type";
dtHASData.Columns[10].ColumnName = "Memo";
dtHASData.Columns[11].ColumnName = "Balance Type";
dtHASData.Columns[12].ColumnName = "RAP";
dtHASData.Columns[13].ColumnName = "Outlier";
sSorter = "periodstart";
}
catch (Exception e)
{
this.FLogTrans(e.Message.ToString());
return dtHASDataReturn;
}
}
else if (iMode.Equals(1))
{
try
{
dtHASData = this.oHASData.RetrieveRemittanceAdvices();
dtHASData.Columns[0].ColumnName = "Agency Code";
dtHASData.Columns[1].ColumnName = "Agency Name";
dtHASData.Columns[3].ColumnName = "Check Amount";
dtHASData.Columns[4].ColumnName = "Remittance Advice Memo";
dtHASData.Columns[5].ColumnName = "Insurance Company Name";
dtHASData.Columns[6].ColumnName = "Amount Paid";
dtHASData.Columns[7].ColumnName = "Net Reimbursement";
dtHASData.Columns[8].ColumnName = "Withheld";
dtHASData.Columns[9].ColumnName = "Document Number";
dtHASData.Columns[10].ColumnName = "To Print";
dtHASData.Columns[11].ColumnName = "Payment Type";
dtHASData.Columns[12].ColumnName = "Memo";
sSorter = "RADate";
}
catch (Exception e)
{
this.FLogTrans(e.Message.ToString());
return dtHASDataReturn;
}
}
DataView dvSorter = new DataView(dtHASData);
if (this.FConfigVarRetriever(4).Equals("1"))
{
int iRowsMany = int.Parse(this.FConfigVarRetriever(5));
dvSorter.Sort = sSorter + " desc";
dtHASData = dvSorter.ToTable();
if (iMode.Equals(0))
{
dtHASData.Columns[4].ColumnName = "Period Start";
}
else if (iMode.Equals(1))
{
dtHASData.Columns[2].ColumnName = "Remittance Advice Date";
}
dtHASDataReturn = dtHASData.AsEnumerable().Take(iRowsMany).CopyToDataTable();
}
else if (this.FConfigVarRetriever(4).Equals("2"))
{
dvSorter.RowFilter = sSorter + " >= '" + this.FConfigVarRetriever(6) + "'";
dvSorter.Sort = sSorter + " desc";
dtHASData = dvSorter.ToTable();
if (iMode.Equals(0))
{
dtHASData.Columns[4].ColumnName = "Period Start";
}
else if (iMode.Equals(1))
{
dtHASData.Columns[2].ColumnName = "Remittance Advice Date";
}
dtHASDataReturn = dtHASData;
}
return dtHASDataReturn;
}
You said it comes in as an IEnumerable, and I'm going to assume the class has the following structure:
public class Record
{
DateTime StartDate {get; set;}
//A whole bunch of other stuff
}
In that case, we will use a Where query to do our filtering, combined with some DateTime math and comparison:
IEnumerable<Record> results = original.Where(r => r.StartDate >= DateTime.Now.AddDays(-90));
You would then use "results" wherever you had "original" so you only act on the filtered data.
To respond to the comments:
You can put it wherever you want the filtering to take place. I would put it immediately before you actually try to use it:
dtHASData = dtHASData.Where(....); //Add here
DataView dvSorter = new DataView(dtHASData);
Its ok that it comes in as an array, those are IEnumerable so the LINQ extensions work on them.

How to continue execution of method after returning data?

I developed a Web API for performance monitoring on machines, that when calling the resource via URL, the information is printed on the browser in json format. One of the methods has a loop that gets a new data value every second.
Is it possible to "return" the value upon each iteration and display it in json on the browser, thus updating automatically with each iteration? In other words, I'm trying to create a live update mechanism, rather than waiting for the program to execute and then displaying the json once the performance data log is completed.
public List<LogInfo> LogTimedPerfData(string macName, string categoryName, string counterName,
string instanceName, string logName, long? seconds)
{
iModsDBRepository modsDB = new iModsDBRepository();
List<MachineInfo> theMac = modsDB.GetMachineByName(macName);
if (theMac.Count == 0)
return new List<LogInfo>();
else if (instanceName == null)
{
if (!PerformanceCounterCategory.Exists(categoryName, macName) ||
!PerformanceCounterCategory.CounterExists(counterName, categoryName, macName) )
{
return new List<LogInfo>();
}
}
else if (instanceName != null)
{
if (!PerformanceCounterCategory.Exists(categoryName, macName) ||
!PerformanceCounterCategory.CounterExists(counterName, categoryName, macName) ||
!PerformanceCounterCategory.InstanceExists(instanceName, categoryName, macName))
{
return new List<LogInfo>();
}
}
else if (logName == null)
{
return new List<LogInfo>();
}
// Check if entered log name is a duplicate for the authenticated user
List<LogInfo> checkDuplicateLog = this.GetSingleLog(logName);
if (checkDuplicateLog.Count > 0)
{
return new List<LogInfo>();
}
PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, theMac[0].MachineName);
if (category.CategoryName == null || category.MachineName == null)
{
return new List<LogInfo>();
}
List<LogInfo> logIt = new List<LogInfo>();
if (category.CategoryType != PerformanceCounterCategoryType.SingleInstance)
{
List<InstanceInfo> instances = modsDB.GetInstancesFromCatMacName(theMac[0].MachineName, category.CategoryName);
foreach (InstanceInfo inst in instances)
{
if (!category.InstanceExists(inst.InstanceName))
{
continue;
}
else if (inst.InstanceName.Equals(instanceName, StringComparison.OrdinalIgnoreCase))
{
PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName,
inst.InstanceName, theMac[0].MachineName);
string data = "";
List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name);
string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
string[] dataValues = new string[(int)seconds];
for (int i = 0; i < seconds; i++)
{
data = "Value " + i + ": " + perfCounter.NextValue().ToString();
dataValues[i] = data;
Thread.Sleep(1000);
}
string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
Log log = new Log
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = string.Join(",", dataValues),
UserID = currUser[0].UserID
};
this.CreateLog(log);
logIt.Add(new LogInfo
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = dataValues.ToList<string>()
});
break;
}
}
}
else
{
PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName,
"", theMac[0].MachineName);
string data = "";
List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name);
string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
string[] dataValues = new string[(int)seconds];
for (int i = 0; i < seconds; i++)
{
data = "Value " + i + ": " + perfCounter.NextValue().ToString();
dataValues[i] = data;
Thread.Sleep(1000);
}
string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
Log log = new Log
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = string.Join(",", dataValues),
UserID = currUser[0].UserID
};
this.CreateLog(log);
logIt.Add(new LogInfo
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = dataValues.ToList<string>()
});
}
return logIt;
}
You might want to do some research on SignalR there are a couple tutorials out there on pushing notifications to browsers with SignalR.
Handful of possibly helpful links:
https://github.com/SignalR/SignalR/wiki
http://www.codeproject.com/Articles/322154/ASP-NET-MVC-SIngalR-and-Knockout-based-Real-time-U
http://www.msguy.com/2011/11/real-time-push-notifications-with.html

Categories