Create a Model by hand - asp.net-mvc

I need to be able to access the value "_CustomUserID" from other controllers within the application. I created a class but not sure how to return the value to be used by the Controller.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web.Security;
using System.DirectoryServices;
namespace myfirstapplication.Models
{
public static class ActiveDirectory
{
public static UserPrincipal GetCustomID()
{
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://10.1.1.1:389";
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.PropertiesToLoad.Add("CustomUserID");
deSearch.SearchScope = SearchScope.Subtree;
deSearch.Filter = "(&(objectCategory=user)(SAMAccountName=" + Membership.GetUser().UserName + "))";
SearchResult results = deSearch.FindOne();
string _CustomUserID = (String)results.Properties["CustomUserID"][0];
}
}
}

Change the method signature into string like this :
public static string GetCustomID()
{
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://10.1.1.1:389";
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.PropertiesToLoad.Add("CustomUserID");
deSearch.SearchScope = SearchScope.Subtree;
deSearch.Filter = "(&(objectCategory=user)(SAMAccountName=" + Membership.GetUser().UserName + "))";
SearchResult results = deSearch.FindOne();
Return (String)results.Properties["CustomUserID"][0];
}
//then in your controller all u have to say is :
string _customerId = ActiveDirectory.GetCustomID();
thanks hope this helps!

Related

Unable to generate path to save image in iOS

I created a delegate on iOS (it works on Android) to save an image using the CrossDownloadManager plugin. I copied the code from the Xamarin documentation but when I run the method, "path" returns an empty string:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YHTS.iOS;
using Foundation;
using UIKit;
using System.IO;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: Dependency(typeof(ImageSaver_IOS))]
namespace YHTS.iOS
{
public class ImageSaver_IOS : IImageSaver
{
public ImageSaver_IOS() { }
public string Save(string imageName)
{
string fileName = (new NSUrl(imageName, false)).LastPathComponent;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
return path;
}
}
}

ToJSON method not found - which namespace is required?

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);
}
}

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