ToJSON method not found - which namespace is required? - asp.net-mvc

I want to log .net WEB API request-response to newly created file. So, I have implemented NLog mechanism in my project which works great. but still below code's .ToJSON() line doesn't get resolved. I can't figure out which namespace is required to use it. is there anything missing out?
I'm referring these two articles but still can't figure out.
1) http://www.codeproject.com/Articles/1028416/RESTful-Day-sharp-Request-logging-and-Exception-ha
2) http://www.strathweb.com/2012/06/using-nlog-to-provide-custom-tracing-for-your-asp-net-web-api/
.net namespaces
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Tracing;
using System.Net.Http;
using System.Text;
if (level != TraceLevel.Off)
{
if (traceAction != null && traceAction.Target != null)
{
category = category + Environment.NewLine + "Action Parameters : " + traceAction.Target.ToJSON(); //this ToJSON doesn't get resolved. which namespace should I include?
}
var record = new TraceRecord(request, category, level);
if (traceAction != null) traceAction(record);
Log(record);
}

There is no such method. The example from codeproject.com shows you how to make it yourself:
using System.Web.Script.Serialization;
using System.Data;
using System.Collections.Generic;
using System;
namespace WebApi.Helpers
{
public static class JSONHelper
{
/// <summary>
/// Extened method of object class, Converts an object to a json string.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJSON(this object obj)
{
var serializer = new JavaScriptSerializer();
try
{
return serializer.Serialize(obj);
}
catch(Exception ex)
{
return "";
}
}
}
}

A better way is to use JSON.Net. It is most likely already referenced in your project and System.Web.Extensions.dll is ancient nowadays (its performance is terrible):
public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
{
if (level != TraceLevel.Off)
{
if (traceAction != null && traceAction.Target != null)
{
category = category + Environment.NewLine + "Action Parameters : " + JsonConvert.SerializeObject(traceAction.Target);
}
var record = new TraceRecord(request, category, level);
if (traceAction != null) traceAction(record);
Log(record);
}
}

Related

Push Notifications using signalR in ASP.NET MVC

I'm still learning ASP.NET MVC architecture and if any of my questions parts seem awful, sorry for the inconvenience that happened.
I want to add push notifications to my ASP.NET MVC web application which I have never used before.
I followed this article:
http://demo.dotnetawesome.com/push-notification-system-with-signalr
I'm using Entity Framework, and added the database connection string to my web.config file.
I used to create database connection via a class:
public class zSqlDb: DbContext
{
public zSqlDb(): base("Data Source=YEA-LAPTOP;Initial Catalog=db_ptweb;Integrated Security=True")
{
}
}
So in this article, he creates a class and there writes code to save data changes in the database.
This is the code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Microsoft.AspNet.SignalR;
namespace PushNotification
{
public class NotificationComponent
{
//Here we will add a function for register notification (will add sql dependency)
public void RegisterNotification(DateTime currentTime)
{
string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
string sqlCommand = #"SELECT [ContactID],[ContactName],[ContactNo] from [dbo].[Contacts] where [AddedOn] > #AddedOn";
//you can notice here I have added table name like this [dbo].[Contacts] with [dbo], it's mandatory when you use Sql Dependency
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlCommand, con);
cmd.Parameters.AddWithValue("#AddedOn", currentTime);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
cmd.Notification = null;
SqlDependency sqlDep = new SqlDependency(cmd);
sqlDep.OnChange += sqlDep_OnChange;
//we must have to execute the command here
using (SqlDataReader reader = cmd.ExecuteReader())
{
// nothing need to add here now
}
}
}
void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
//or you can also check => if (e.Info == SqlNotificationInfo.Insert) , if you want notification only for inserted record
if (e.Type == SqlNotificationType.Change)
{
SqlDependency sqlDep = sender as SqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
//from here we will send notification message to client
var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
notificationHub.Clients.All.notify("added");
//re-register notification
RegisterNotification(DateTime.Now);
}
}
public List<Contact> GetContacts(DateTime afterDate)
{
using (MyPushNotificationEntities dc = new MyPushNotificationEntities())
{
return dc.Contacts.Where(a => a.AddedOn > afterDate).OrderByDescending(a => a.AddedOn).ToList();
}
}
}
}
But I did to add records to the database by using the controller. So will this change the definition of the push notification process? If yes then I want to know how to match this code with mine.

How to detect IIS events in windows event logs and detemine its application pool according to this code?

I try to make a listener on windows event logs, but I need to recognize IIS events in it and determine its application pool.
could I do that according to this code ??? by process id for example or any thing else.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.DirectoryServices;
using Microsoft.Web;
using Microsoft.Web.Administration;
namespace EventLogEnt
{
class Program
{
static AutoResetEvent signal;
static void Main(string[] args)
{
// create new log
signal = new AutoResetEvent(false);
EventLog myNewLog = new EventLog("Application", "TIS3", "Outlook");
myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten);
myNewLog.EnableRaisingEvents = true;
myNewLog.WriteEntry("Test message", EventLogEntryType.Information);
signal.WaitOne();
Console.ReadKey();
}
public static void MyOnEntryWritten(object source, EntryWrittenEventArgs e)
{
Console.WriteLine(e.Entry.Message);
Console.WriteLine("the entry type: " + e.Entry.EntryType);
Console.WriteLine("---------------------------------------------");
signal.Set();
}
}
}

Object reference not set to an instance of an object MVC 5

I'm new to MVC working on 3-tier MVC project and i am using a ready database.
now i need to write a query using linq in Business Layer to bring list of doctors like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DoctorsSheet.DataAccess;
namespace DoctorsSheet.Business
{
class Doctor : IDoctor
{
DoctorsSheetDBEntities db = new DoctorsSheetDBEntities();
public IQueryable<Doctors> GetDoctors()
{
var doctors = from d in db.Doctors
select d;
return doctors.AsQueryable<Doctors>();
}
}
}
and when i call GetDoctors() from DoctorsController
it tell me Object reference not set to an instance of an object
this is the Controller :
public ActionResult Index()
{
var doctors = obj.GetDoctors().AsQueryable<Doctors>();
return View(doctors);
}
please help me how to fix it.
Make your class public -
public class Doctor : IDoctor
And then initiate obj variable as shown below and then use obj.
IDoctor obj = new Doctor();
NOTE: As #Sippy explained there is no need for you to use GetDoctors().AsQueryable<Doctors>();.

How to use .cs Class DataFunctions Inside MVC Controller Classes

I have an asp.net web application, now i am trying to convert it to ASP.NET MVC. The problem is my old project has some .cs classes i, Example one class that handle all user data operations , one handle database operations , one will handle some priority properties like... I had included those classes in mvc Project , i had created a new Folder named Project_Class and copy all of my classes to it, my problem is how to access these classes in mvc controller class, how can i call a function of this class in mvc controller class.
I had include a sample .cs class structure below
**class1.cs**
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Xml;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace xyz.abc
{
public class AssignValues:SSS
{
Process Objdb;
SqlCommand sqlcom;
SqlConnection sqlcon;
private int _EId;
private int _CId;
XmlDocument PXML, OutputXML;
XmlElement Root, ParameterElement, InputParamIdNode, OperatorIdNode, OutputParamIdNode, OutputParamValueNode, ConditionStatusNode, ModeNode, InputTypeNode, OutputTypeNode, InputRegisterIdNode, InputRegisterHeaderIdNode, OutputRegisterIdNode, OutputRegisterHeaderIdNode, UIdNode, orderNode;
public int iCount = 0;
public int EId
{
set
{
_EId = value;
}
get
{
return _EId;
}
}
public int CId
{
set
{
_CId = value;
}
get
{
return _CId;
}
}
public AssignValues()
{
}
public AssignValues(SqlCommand SqlComm,SqlConnection SqlConn)
{
Objdb = new Process();
sqlcom=SqlComm;
sqlcon = SqlConn;
}
public string check()
{
string x="hai";
return x
}
}
}
my Controller class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XYZ.ABC.Controllers;
using XYZ.ABC;
namespace XYZ.ABC.Controllers
{
public class XYZ_Controller :Controller
{
public ActionResult XYZ_Checklist()
{
return View();
}
}
}
i want to call "public string check()" method in my controller class,is it possible? ,i am newbie in mvc, please help me to solve this.
You can simply call that in your MVC controller class
Follow the steps
1) Include the namespace of the class in MVC controller class
2) Inherit old class in Your MVC Controller
Public Class MVCCOntrollerclassname: Class1
3) Create object of the .cs class
like
class1 c=new class1();
4) Create a constructor of MVC controller class
like
MVCCOntrollerclassname()
{
c.methodname();
}
Note : You say you are migrating asp.net to MVC , so if you have any asp.net dll then must change it as MVC Compitable dll
The MVC Framework just instantiates your Controller class and invokes an action method using some defined configuration or convention. So with that in mind ask yourself the question how would I invoke this method if you instantiated the controller yourself and called XYZ_Checklist().
The answer may look something like this:
public ActionResult XYZ_Checklist()
{
var assignValues = new AssignValues();
var result = assignValues.check();
// Do something here with the result ...
return View();
}
That's the short and simple answer. Once you start to understand that the framework isn't magic and is simply calling your code, you can start to delve into better ways to arrange your code (IoC/DI, etc.).
Hope this helps!

An error occured while executing the query. Please check the stack trace for more detail

I am trying to query a customer in qbo with a name that has an ' for example (Joe's Shop) and getting the above error.
here is the code.
IEnumerable<Customer> customers = customerQueryService.Where(c => c.DisplayName =="Joe's Shop");
if (customers.Count()!=0 )
{
customer = customers.First();
}
return customer;
Please use backslash to escape the single quote.
"Joe\'s Shop"
Thanks
using Intuit.Ipp.Core;
using Intuit.Ipp.Data;
using Intuit.Ipp.LinqExtender;
using Intuit.Ipp.QueryFilter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
static class SampleCalls
{
public static Customer QueryCustomerByDisplayName(ServiceContext context, string displayName) {
displayName = displayName.Replace("'", "\\'"); //Escape special characters
QueryService<Customer> customerQueryService = new QueryService<Customer>(context);
return customerQueryService.Where(m => m.DisplayName == displayName).FirstOrDefault();
}
}

Resources