Hello All I added a Controller in my project like this:-
using Aero.Api.Models.ViewModels;
using Aero.Common.Interface;
using Aero.Data.Interface;
using Microsoft.Web.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Aero.Api.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/province")]
public class ProvinceController : BaseApiController
{
private IUserService _userService { get; set; }
// GET: States
public ProvinceController(IUserService userService, IMappingHelper mapper) :
base(mapper)
{
_userService = userService;
}
public List<StateProvinceModel> Get()
{
List<StateProvinceModel> states = new List<StateProvinceModel>();
StateProvinceModel stateProvince = new StateProvinceModel()
{
Id = "BC",
Value = "BC - British Columbia",
Name = "British Columbia",
Country = "Canada"
};
StateProvinceModel stateProvince1 = new StateProvinceModel()
{
Id = "QB",
Value = "QB- Quebec",
Name = "Quebec",
Country = "Canada"
};
StateProvinceModel stateProvince2 = new StateProvinceModel()
{
Id = "ON",
Value = "ON- Ontario",
Name = "Ontario",
Country = "Canada"
};
states.Add(stateProvince);
states.Add(stateProvince1);
states.Add(stateProvince2);
StateProvinceModel stateProvince3 = new StateProvinceModel()
{
Id = "IL",
Value = "IL - Illinois",
Name = "Illinois",
Country = "United States"
};
StateProvinceModel stateProvince4 = new StateProvinceModel()
{
Id = "GA",
Value = "GA-Georgia",
Name = "Georgia",
Country = "United States"
};
StateProvinceModel stateProvince5 = new StateProvinceModel()
{
Id = "NY",
Value = "NY- New York",
Name = "New York",
Country = "United States"
};
states.Add(stateProvince3);
states.Add(stateProvince4);
states.Add(stateProvince5);
return states;
}
}
}
when I try to call the Get method from browser like this:- http://localhost:44300/api/v1/province I get an error that the resource was not found. Other Urls on existing controllers work. For example a Url like this:- http://localhost:44300/api/v1/properties works perfectly fine.
Can anyone tell me what is going on ?
You should inherit your contoller class to ApiController instead of BaseApiContoller.
Ex: public class GoaAPIController : ApiController
Sir, You can Try changing The Method Name .
Related
I am trying to use object initializer to set up a custom array in vb.net, there may be only 1 entry or there could be 100 on any given instance of this array. I have been successful in completing this task in C# however can not find documentation of completing it in Vb.net
I have a model:
Public Class Artist
Public Name As String
Public Task As String
End Class
within another model we have further listed this object as part of the collection
Public Property Artists() As Artist
which brings me to the controller
.Artists = New Artist() With
{.Name = "bob", .Task = "1"}
that is successful for 1 entry; how would I add another entry under the same instance of the object such as the following in c#
Artists = new Artist[]
{
new Artist() { name = "bob", Task = "1" },
new Artist() { name = "fred", Task = "2" },
new Artist() { name = "george", Task = "3" }
}
this all falls within a with statement itself being a sub of another object which seems to rule out traditional dimensioning
Dim cB = New CB {
.StoryTitle = "Test"
.IsbnNumber = 200
.Artists = new Artists...
}
Ultimate Solution
Dim cB = New CB With {
.StoryTitle = "Test",
.IsbnNumber = 200,
.Artists = New Artist() {New Artist() With {
.Name = "bob",
.Task = "1"
}, New Artist() With {
.Name = "fred",
.Task = "2"
}, New Artist() With {
.Name = "george",
.Task = "3"
}}
}
I have been successful in completing this task in C# however can not find documentation of completing it in Vb.net
Download ILSpy, drag/drop your Exe or Dll that you successfully created with C# and save project as a VB.Net project.
I'm bilingual with C# and VB.Net but when it comes to Lambda's and LINQ in VB.Net this is how I translate between the languages.
Or an even simpler and quicker method is: http://converter.telerik.com/
C#:
Artists a = new Artist[]
{
new Artist() { name = "bob", Task = "1" },
new Artist() { name = "fred", Task = "2" },
new Artist() { name = "george", Task = "3" }
}
VB.Net:
Dim a As Artists = New Artist() {New Artist() With {
.name = "bob",
.Task = "1"
}, New Artist() With {
.name = "fred",
.Task = "2"
}, New Artist() With {
.name = "george",
.Task = "3"
}}
Your syntax is a little bit off. Try this:
Dim artists() As Artist = {
New Artist() With {.Name = "bob", .Task = "1"},
New Artist() With {.Name = "bob", .Task = "1"}
}
I am working on multi language web site. it works fine with each IP_Address, the problem is that I want to make the URL changed after it renders, in the way it shows whats the language code in the URL.
here is my route config
namespace global_vrf
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{language}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, language="" }
);
}
}
}
and this is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using global_vrf.GeoIpService;
namespace global_vrf.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string language)
{
if (language!="")
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
else if(language=="")
{
try
{
string userIpAddress = this.Request.UserHostAddress;
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
if (country_code == "FRA")
{
language = "fr-FR";
}
//and I will check the other languages here
}
catch
{
string userIpAddress = "209.95.51.176";
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
language = "en-us";
}
}
Appreciate any help. thanks
Use attribute routing in mvc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using global_vrf.GeoIpService;
namespace global_vrf.Controllers
{
RoutePrefix("Example Name")]
public class HomeController : Controller
{
public ActionResult Index(string language)
{
if (language!="")
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
else if(language=="")
{
try
{
string userIpAddress = this.Request.UserHostAddress;
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
if (country_code == "FRA")
{
language = "fr-FR";
}
//and I will check the other languages here
}
catch
{
string userIpAddress = "209.95.51.176";
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
language = "en-us";
}
}
{Sorry new to JSON}
I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)
My model is simply
public class ScheduleUsers
{
public string Resource{ get; set; }
}
On my controller
var users = new JsonArray(
new JsonObject(
new KeyValuePair<string,JsonValue>("id","1"),
new KeyValuePair<string,JsonValue>("name","User1")),
new JsonObject(
new KeyValuePair<string, JsonValue>("id", "2"),
new KeyValuePair<string, JsonValue>("name", "User2"))
);
model.Resources = users.ToString();
Why don't you just return a list of entities as a JSON result, like:
public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = new List<Car>();
// add cars to the cars collection
return this.Json(cars, JsonRequestBehavior.AllowGet);
}
}
It will be converted to JSON automatically.
I did this and this works
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
//Serialize
js.Serialize(GetResources(), sb);
public List<ScheduledResource> GetResources()
{
var res = new List<ScheduledResource>()
{
new ScheduledResource()
{
id = "1",
color = "blue",
name = "User 1"
},
new ScheduledResource()
{
id = "2",
color = "black",
name = "User 2"
},
};
return res;
}
I have a fairly basic HomeController in my application and I wrote a test class for it. After running code coverage analysis on my test class I realized I don't have any test for the default constructor.
This is my HomeController
public class HomeController : BaseController
{
private INewsRepository _newsRepository;
private INewsletterRepository _newsletterRepository;
private string _currentLanguage;
public HomeController()
{
_newsRepository = NewsRepository.Current;
_newsletterRepository = NewsletterRepository.Current;
_currentLanguage = ApplicationConfig.Current.CurrentLanguage;
}
public HomeController(INewsRepository newsRepository, INewsletterRepository newsletterRepository, string currentLanguage)
{
_newsRepository = newsRepository;
_newsletterRepository = newsletterRepository;
_currentLanguage = currentLanguage;
}
public ActionResult Index()
{
return View();
}
public ActionResult LatestNews()
{
return View(_newsRepository.ListAll().Where(n => n.LanguageKey.ToLower() == _currentLanguage.ToLower()).OrderByDescending(n => n.Date).Take(10));
}
public ActionResult LatestNewsletters()
{
return View(_newsletterRepository.ListAll().Where(n => n.LanguageKey.ToLower() == _currentLanguage.ToLower()).OrderByDescending(n => n.Date).Take(10));
}
}
And this is my test class for it:
[TestClass]
public class HomeControllerTest
{
private INewsletterRepository _mockNewsletterRepostiory = null;
private INewsRepository _mockNewsRepostiory = null;
private List<News> _fakeNewsList = new List<News> {
new News{Id = 0, Title = "some title", Date = new DateTime(1989, 2, 19), LanguageKey = "fa", Description = "some description"},
new News{Id = 1, Title = "some title", Date = new DateTime(1989, 2, 20), LanguageKey = "fa", Description = "some description"},
new News{Id = 2, Title = "some title", Date = new DateTime(1989, 2, 21), LanguageKey = "fa", Description = "some description"},
new News{Id = 3, Title = "some title", Date = new DateTime(1989, 2, 22), LanguageKey = "fa", Description = "some description"}
};
private List<Newsletter> _fakeNewsletterList = new List<Newsletter>
{
new Newsletter{ Id = 0, Description = "some description", UrlKey = "first-newsletter", Title = "some title", SendDate = null, NewsletterContents = null, LanguageKey = "fa", Date = new DateTime(1989, 2, 19) },
new Newsletter{ Id = 1, Description = "some description", UrlKey = "first-newsletter", Title = "some title", SendDate = null, NewsletterContents = null, LanguageKey = "fa", Date = new DateTime(1989, 2, 20) },
new Newsletter{ Id = 2, Description = "some description", UrlKey = "first-newsletter", Title = "some title", SendDate = null, NewsletterContents = null, LanguageKey = "fa", Date = new DateTime(1989, 2, 21) },
new Newsletter{ Id = 3, Description = "some description", UrlKey = "first-newsletter", Title = "some title", SendDate = null, NewsletterContents = null, LanguageKey = "fa", Date = new DateTime(1989, 2, 22) }
};
[TestInitialize]
public void Setup()
{
// Mock News Repository
var mockNewsRepository = MockRepository.GenerateStub<INewsRepository>();
mockNewsRepository.Stub(m => m.ListAll()).Return(_fakeNewsList.AsQueryable());
// Mock Newsletter Repository
var mockNewsletterRopository = MockRepository.GenerateStub<INewsletterRepository>();
mockNewsletterRopository.Stub(m => m.ListAll()).Return(_fakeNewsletterList.AsQueryable());
_mockNewsletterRepostiory = mockNewsletterRopository;
_mockNewsRepostiory = mockNewsRepository;
}
[TestMethod]
public void IndexReturnsView()
{
// Arrange
HomeController homeController = new HomeController(_mockNewsRepostiory, _mockNewsletterRepostiory, "fa");
// Act
ViewResult result = homeController.Index() as ViewResult;
// Assert
Assert.AreEqual("", result.ViewName);
}
[TestMethod]
public void LatestNewsReturnsCorrectObject()
{
// Arrange
HomeController homeController = new HomeController(_mockNewsRepostiory, _mockNewsletterRepostiory, "fa");
// Act
ViewResult result = homeController.LatestNews() as ViewResult;
// Assert
Assert.IsNotNull(result.ViewData.Model, "Result model is not null.");
Assert.IsTrue(_fakeNewsList.OrderByDescending(n => n.Date).SequenceEqual(result.ViewData.Model as IQueryable<News>), "Model is correct");
}
[TestMethod]
public void LatestNewslettersReturnsCorrectObject()
{
// Arrange
HomeController homeController = new HomeController(_mockNewsRepostiory, _mockNewsletterRepostiory, "fa");
// Act
ViewResult result = homeController.LatestNewsletters() as ViewResult;
// Assert
Assert.IsNotNull(result.ViewData.Model, "Result model is not null.");
Assert.IsTrue(_fakeNewsletterList.OrderByDescending(n => n.Date).SequenceEqual(result.ViewData.Model as IQueryable<Newsletter>), "Model is correct");
}
}
First of all do I really need to test this constructor?
Secondly, Is it a good practice to make the _newsRepository and the other guys public and readonly then write a test method to check their types after constructing the controller?
The only reason I'd recommend writing a test for the constructor is if you care a lot about getting as much code coverage as possible. Testing the fact that you can create an instance of the controller, and whether instances of each object created in the ctor are valid isn't a very valuable test. I'd say it's a waste of time.
So, for your first question I suggest you don't worry about unit testing the ctor. If there is a problem in the ctor then you will notice it very quickly via other unit tests, as explained in my next comment.
As for making the repository classes public and readonly, I don't recommend doing that. What you really need to focus on, regards unit tests, is functionality of the controller, especially methods that make use of the objects which are created in the ctor. That's where you need to concentrate on. Those tests will tell you whether or not these was an issue in the ctor for those objects.
I have a list of users I am retrieving from Active Directory like so
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAIN", "dc=domain,dc=org");
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "Advisors");
ViewBag.EmployeeID = new SelectList(group.Members, "EmployeeID", "DisplayName");
I would like to add two additional items to this list but do not want to create user accounts for them in Active Directory as they are not real users.
Is it possible to do something like
var items1 = new[]
{
new { EmployeeID = "1", DisplayName = "Independent" },
new { EmployeeID = "2", DisplayName = "Own" }
};
var items = Concat(group.Members, items1);
{
ViewBag.EmployeeID = new SelectList(items, "EmployeeID", "DisplayName");
}
Well, You can have a ViewModel like this:
public class EmployeeViewModel
{
public string EmployeeId { get; set; }
public string DisplayName { get; set; }
}
and than you can cast the group.Members to a list of your ViewModel, add some custom itens on this list and set this list to the ViewBag.
var members = group.Members.Select(x => new EmployeeViewModel() { EmployeeId = x.EmployeeId, DisplayName = x.DisplayName }).ToList();
members.Add(new EmployeeViewModel() { EmployeeId = "1", DisplayName = "Independent" });
members.Add(new EmployeeViewModel() { EmployeeId = "2", DisplayName = "Own" });
ViewBag.EmployeeID = new SelectList(members, "EmployeeID", "DisplayName");