Search Results

Search found 111 results on 5 pages for 'notfound'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • How can I properly handle 404s in ASP.NET MVC?

    - by Brian
    I am just getting started on ASP.NET MVC so bear with me. I've searched around this site and various others and have seen a few implementations of this. EDIT: I forgot to mention I am using RC2 Using URL Routing: routes.MapRoute( "Error", "{*url}", new { controller = "Errors", action = "NotFound" } //404s ); The above seems to take care of requests like this (assuming default route tables setup by initial MVC project): "/blah/blah/blah/blah" Overriding HandleUnknownAction() in the controller itself: //404s - handle here (bad action requested protected override void HandleUnknownAction(string actionName) { ViewData["actionName"] = actionName; View("NotFound").ExecuteResult(this.ControllerContext); } However the previous strategies do not handle a request to a Bad/Unknown controller. For example, I do not have a "/IDoNotExist", if I request this I get the generic 404 page from the web server and not my 404 if I use routing + override. So finally, my question is: Is there any way to catch this type of request using a route or something else in the MVC framework itself? OR should I just default to using Web.Config customErrors as my 404 handler and forget all this? I assume if I go with customErrors I'll have to store the generic 404 page outside of /Views due to the Web.Config restrictions on direct access. Anyway any best practices or guidance is appreciated.

    Read the article

  • Windows Phone - failing to get a string from a website with login information

    - by jumantyn
    I am new to accessing web services with Windows Phone 7/8. I'm using a WebClient to get a string from a php-website. The site returns a JSON string but at the moment I'm just trying to put it into a TextBox as a normal string just to test if the connection works. The php-page requires an authentication and I think that's where my code is failing. Here's my code: WebClient client = new WebClient(); client.Credentials = new NetworkCredential("myUsername", "myPassword"); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(new Uri("https://www.mywebsite.com/ba/php/jsonstuff.php")); void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { try { string data = e.Result; this.jsonText.Text = data; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } This returns first a WebException and then a TargetInvocationException. If I replace the Uri with for example "http://www.google.com/index.html" the jsonText TextBox gets filled with html text from Google (oddly enough, this also works even when the WebClient credentials are still set). So is the problem in the setting of the credentials? I couldn't find any good results when searching for guides on how to access php-pages with credentials, only without them. Then I found a short mention somewhere to use the WebClient.Credentials property. But should it work some other way? Update: here's what I can get out of the WebException (sorry for the bad formatting): System.Net.WebException: The remote server returned an error: NotFound. ---System.Net.WebException: The remote server returned an error: NotFound. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<c_DisplayClasse.b_d(Object sendState) at System.Net.Browser.AsyncHelper.<c_DisplayClass1.b_0(Object sendState) --- End of inner exception stack trace --- at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)

    Read the article

  • Is there a way to restart a cursor? Oracle

    - by Solid1Snake1
    I am trying to do something such as: for(int i = 0; i<10; i++) { for(int j = 0; j<10; j++) { Blah; } } //As you can see each time that there is a different i, j starts at 0 again. Using cursors in Oracle. But if I'm correct, after I fetch all rows from a cursor, it will not restart. Is there a way to do this? Here is my sql: CREATE OR REPLACE PROCEDURE SSACHDEV.SyncTeleappWithClientinfo as teleCase NUMBER; CURSOR TeleAppCursor is Select distinct(casenbr) from TeleApp; CURSOR ClientInfoCursor is Select casenbr from clientinfo where trim(cashwithappyn) is null; BEGIN open TeleAppCursor; open ClientInfoCursor; LOOP fetch TeleAppCursor into teleCase; EXIT when TeleAppCursor%NOTFOUND; LOOP fetch ClientInfoCursor into clientCase; EXIT when ClientInfoCursor%NOTFOUND; if clientCase = teleCase then update ClientInfo set cashwithappyn = (select cashwithappyn from teleapp where casenbr = clientCase) where casenbr = clientCase; break; end if; END LOOP; END LOOP; END; I did check online and was unable to find anything on this.

    Read the article

  • asp.net mvc postback

    - by user266909
    I have a controller with the following two Edit methods. The edit form displays correctly with all additional dropdown lists from the FormViewModel. However, when I changed some field values and submitted the form. None of the changed fields were saved. The fields in the postbask collection have default or null values. I have another edit form which update another table. On submit, the changed values are saved. Does anyone know why? // GET: /Transfers/Edit/5 public ActionResult Edit(int id) { Transfer transfer = myRepository.GetTransfer(id); if (transfer == null) return View("NotFound"); return View(new TransferFormViewModel(transfer)); } // // POST: /Transfers/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, Transfer collection) { Transfer transfer = vetsRepository.GetTransfer(id); if (transfer == null) return View("NotFound"); else { try { UpdateModel(transfer); vetsRepository.Save(); return RedirectToAction("Details", new { id = transfer.TransfersID }); } catch { ModelState.AddModelErrors(transfer.GetRuleViolations()); return View(new TransferFormViewModel(transfer)); } } }

    Read the article

  • Dovecot Virtual Users Not Authenticating

    - by blankabout
    We have a standard Postfix/Dovecot installation working perfectly with real users but cannot work out how to add virtual users, all virtual user login attempts fail with authentication errors. Following are snippets from the configuration files: /etc/postfix/main.cf: virtual_mailbox_domains = virtualexample.com virtual_mailbox_base = /var/spool/vhosts virtual_mailbox_recipients = hash:/etc/postfix/virtual_mailbox_recipients /etc/dovecot/dovecot.conf: !include conf.d/*.conf /etc/dovecot/conf.d/10-auth.conf auth_mechanisms = cram-md5 digest-md5 plain passdb { driver = passwd-file # Path for passwd-file. Also set the default password scheme. args = scheme=cram-md5 /etc/cram-md5.pwd } /etc/cram-md5.pwd [email protected]{MD5}$1$uIMvzy92$9Xt67B/qw4u6txkkxzne80 This is a snippet from the log when a login attempt is made: auth: Debug: Loading modules from directory: /usr/lib64/dovecot/auth auth: Debug: Module loaded: /usr/lib64/dovecot/auth/libauthdb_ldap.so auth: Debug: Module loaded: /usr/lib64/dovecot/auth/libdriver_sqlite.so auth: Debug: Module loaded: /usr/lib64/dovecot/auth/libmech_gssapi.so auth: Debug: passwd-file /etc/cram-md5.pwd: Read 1 users auth: Debug: auth client connected (pid=21990) auth: Debug: client in: AUTH#0111#011CRAM-MD5#011service=imap#011lip=1.1.1.1#011rip=2.2.2.2#011lport=143#011rport=51774 auth: Debug: client out: CONT#0111#011PDI1Njc0NjQ1NzQ3MTY0NTkuMTM0MTIxNzkwN0BncDM+ auth: Debug: client in: CONT auth: Debug: passwd-file([email protected],2.2.2.2): lookup: [email protected] file=/etc/cram-md5.pwd auth: Debug: client out: OK#0111#[email protected] auth: Debug: master in: REQUEST#0111630404609#01121990#0111#011b66b5f46b520a08e1d19d3d249be7073 auth: Debug: passwd([email protected],2.2.2.2): lookup auth: passwd([email protected],2.2.2.2): unknown user auth: Error: userdb([email protected],2.2.2.2): user not found from userdb passwd auth: Debug: master out: NOTFOUND#0111630404609 imap: Error: Authenticated user not found from userdb, auth lookup id=1630404609 (client-pid=21990 client-id=1) imap-login: Internal login failure (pid=21990 id=1) (auth failed, 1 attempts): user=, method=CRAM-MD5, rip=2.2.2.2, lip=1.1.1.1, mpid=21993 auth: Debug: auth client connected (pid=22010) auth: Debug: client in: AUTH#0111#011CRAM-MD5#011service=imap#011lip=1.1.1.1#011rip=2.2.2.2#011lport=143#011rport=51775 auth: Debug: client out: CONT#0111#011PDcxMDkwNDY1NTQzODUzMDkuMTM0MTIxNzkyOEBncDM+ auth: Debug: client in: CONT auth: Debug: passwd-file([email protected],2.2.2.2): lookup: [email protected] file=/etc/cram-md5.pwd auth: Debug: client out: OK#0111#[email protected] auth: Debug: master in: REQUEST#011343539713#01122010#0111#011e47b1345784e2845d59e794afa9a6bbe auth: Debug: passwd([email protected],2.2.2.2): lookup auth: passwd([email protected],2.2.2.2): unknown user auth: Error: userdb([email protected],2.2.2.2): user not found from userdb passwd auth: Debug: master out: NOTFOUND#011343539713 imap: Error: Authenticated user not found from userdb, auth lookup id=343539713 (client-pid=22010 client-id=1) imap-login: Internal login failure (pid=22010 id=1) (auth failed, 1 attempts): user=, method=CRAM-MD5, rip=2.2.2.2, lip=1.1.1.1, mpid=22011 It would appear that the user lookup is not working, even tho' the log suggests that Dovecot is using the /etc/cram-md5.pwd file and the user is configured in that same file. There are of course dozens of examples of using virtual users with Dovecot, but all the ones we have found either refer to Dovecot 1.x (we are using 2.x), using only virtual users (we must use real AND virtual users) or want to use a MySQL db, we need to use a text file. Some hints about where we are going wrong would be very much appreciated.

    Read the article

  • Problems migrating an EBS backed instance over AWS Regions

    - by gshankar
    Note: I asked this question on the EC2 forums too but haven't received any love there. Hopefully the ServerFault community will be more awesome. The new AWS Sydney region opening up is something that we've been waiting for for a long time but I'm having a lot of trouble migrating our instances over from N. California. I managed to migrate 1 instance over using CloudyScripts to move a snapshot and then firing up a new instance in the Sydney region. This was a very new instance so both the source and destination were running on a Ubuntu 12.04 LTS server and I had no issues there. However, the rest of our instances are all Ubuntu 10.04 LTS and with these, I'm having a lot of problems. I've tried following: 1- following the AWS whitepaper on moving instances which was given to us at the recent Customer Appreciation Day in Sydney where the new region was launched. The problem with this approach was with the last step (Step 19) here you register the image: ec2-register -s snap-0f62ec3f -n "Wombat" -d "migrated Wombat" --region ap-southeast-2 -a x86_64 --kernel aki-937e2ed6 --block-device-mapping "/dev/sdk=ephemeral0" I keep getting this error: Client.InvalidAMIID.NotFound: The AMI ID 'ami-937e2ed6' does not exist which I think is due to the kernel_id not existing in the Sydney region? 2- Using CloudyScripts to move a snapshot and then creating a new volume and attaching to a new instance in Sydney This results in the instance just hanging on boot and failing the status checks. I can't SSH in or look at the server log I suspect that my issue is with finding the right kernel_id for the volume in the new region. However I can't seem to work out how to go about finding this kernel_id, the ones I've tried (from the original instance) don't result in the Client.InvalidAMIID.NotFound: The AMI ID 'ami-937e2ed6' error and any other kernel_id just won't boot. I've tried both 12.04 and 10.04 versions of Ubuntu. Nothing seems to work, I've been banging my head against a wall for a while now, please help! New (broken) instance i-a1acda9b ami-9b8611a1 aki-31990e0b Source instance i-08a6664e ami-b37e2ef6 aki-937e2ed6 p.s. I also tried following this guide on updating my Ubuntu LTS version to 12.04 before doing the migration but it didn't seem to work either, still getting stuck on updating the kernel_id http://ubuntu-smoser.blogspot.com.au/2010/04/upgrading-ebs-instance.html

    Read the article

  • Welcome to www.badapi.net, a REST API with badly-behaved endpoints

    - by Elton Stoneman
    Originally posted on: http://geekswithblogs.net/EltonStoneman/archive/2014/08/14/welcome-to-www.badapi.net-a-rest-api-with-badly-behaved-endpoints.aspxI've had a need in a few projects for a REST API that doesn't behave well - takes a long time to respond, or never responds, returns unexpected status codes etc.That can be very useful for testing that clients cope gracefully with unexpected responses.Till now I've always coded a stub API in the project and run it locally, but I've put a few 'misbehaved' endpoints together and published them at www.badapi.net, and the source is on GitHub here: sixeyed/badapi.net.You can browse to the home page and see the available endpoints. I'll be adding more as I think of them, and I may give the styling of the help pages a bit more thought...As of today's release, the misbehaving endpoints available to you are:GET longrunning?between={between}&and={and} - Waits for a (short) random period before returningGET verylongrunning?between={between}&and={and} -Waits for a (long) random period before returningGET internalservererror    - Returns 500: Internal Server ErrorGET badrequest - Returns 400: BadRequestGET notfound - Returns 404: Not FoundGET unauthorized - Returns 401: UnauthorizedGET forbidden - Returns 403: ForbiddenGET conflict -Returns 409: ConflictGET status/{code}?reason={reason} - Returns the provided status code Go bad.

    Read the article

  • System Slow After Uprading Ubuntu

    - by Aragon N
    i have an ubuntu network machine which has release of 10.04.1 LTS Lucid. on this system i have apache, postgresql and django. for some app. development i have to install php and php-curl... due to being on network, i have exported wmvare machine to internet and firstly i have upgraded system and then install php5 packages on it. After all replacing it with its old place, i have considered that the new system query is some slow according to another. Old system query time : 140 ms New system query time : 9.11 s i have checked /etc/network interface and it seems there is no problem. i have checked /etc/resolv.conf and it seems ok i have checked /etc/nsswitch.conf and only host section is different from old one which old system has hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4 and then i have checked time host -t A services.myapp.com and i got real 0m0.355s user 0m0.010s sys 0m0.020s and now what can i have to check for boosting my system as before?

    Read the article

  • Managing service references and endpoint configurations for Silverlight applications

    Youve written your service. Youve written your Silverlight application. You Add Service Reference to your application and got the client proxy code. Your app works on your machine and you push it out. FAIL. NotFound. Crap. You forgot that your service reference had your local URI endpoint in there and when you moved it to staging and/or production it failed. You start cursing Microsoft and the Silverlight team and add to the threads in the forums or perhaps initiate a new wishlist item for the...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • ASP.NET MVC validation problem

    - by ile
    ArticleRepostitory.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using CMS.Model; using System.Web.Mvc; namespace CMS.Models { public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } public class ArticleRepository { private DB db = new DB(); // // Query Methods public IQueryable<ArticleDisplay> FindAllArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public IQueryable<ArticleDisplay> FindTodayArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where article.Date == DateTime.Today select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public Article GetArticle(int id) { return db.Articles.SingleOrDefault(d => d.ArticleID == id); } public IQueryable<ArticleDisplay> DetailsArticle(int id) { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where id == article.ArticleID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } // // Insert/Delete Methods public void Add(Article article) { db.Articles.InsertOnSubmit(article); } public void Delete(Article article) { db.Articles.DeleteOnSubmit(article); } // // Persistence public void Save() { db.SubmitChanges(); } } } ArticleController.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using CMS.Models; using CMS.Model; namespace CMS.Controllers { public class ArticleController : Controller { ArticleRepository articleRepository = new ArticleRepository(); ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository(); // // GET: /Article/ public ActionResult Index() { var allArticles = articleRepository.FindAllArticles().ToList(); return View(allArticles); } // // GET: /Article/Details/5 public ActionResult Details(int id) { var article = articleRepository.DetailsArticle(id).Single(); if (article == null) return View("NotFound"); return View(article); } // // GET: /Article/Create public ActionResult Create() { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); Article article = new Article() { Date = DateTime.Now, CategoryID = 1 }; return View(article); } // // POST: /Article/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } // // GET: /Article/Edit/5 public ActionResult Edit(int id) { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); var article = articleRepository.GetArticle(id); return View(article); } // // POST: /Article/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection collection) { Article article = articleRepository.GetArticle(id); try { // TODO: Add update logic here UpdateModel(article, collection.ToValueProvider()); articleRepository.Save(); return RedirectToAction("Details", new { id = article.ArticleID }); } catch { return View(article); } } // // HTTP GET: /Article/Delete/1 public ActionResult Delete(int id) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); else return View(article); } // // HTTP POST: /Article/Delete/1 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id, string confirmButton) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); articleRepository.Delete(article); articleRepository.Save(); return View("Deleted"); } } } View/Article/Create.aspx: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CMS.Model.Article>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Create</h2> <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="Title">Title:</label> <%= Html.TextBox("Title") %> <%= Html.ValidationMessage("Title", "*") %> </p> <p> <label for="Content">Content:</label> <%= Html.TextArea("Content", new { id = "Content" })%> <%= Html.ValidationMessage("Content", "*")%> </p> <p> <label for="Date">Date:</label> <%= Html.TextBox("Date") %> <%= Html.ValidationMessage("Date", "*") %> </p> <p> <label for="CategoryID">Category:</label> <%= Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["categories"])%> </p> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> If I remove DropDownList from .aspx file then validation (on date only because no other validation exists) works, but of course I can't create new article because one value is missing. If I leave dropdownlist and try to insert wrong date I get following error: System.InvalidOperationException: The ViewData item with the key 'CategoryId' is of type 'System.Int32' but needs to be of type 'IEnumerable'. If I enter correct date than the article is properly inserted. There's one other thing that's confusing me... For example, if I try manually add the categoyID: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here // Manually add category value article.CategoryID = 1; articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } ..I also get the above error. There's one other thing I noticed. If I add partial class Article, when returning to articleRepository.cs I get error that 'Article' is an ambiguous reference between 'CMS.Models.Article' and 'CMS.Model.Article' Any thoughts on this one?

    Read the article

  • Silverlight Application

    - by Avijit Singh
    I have prepared a Silverlight application and my database is in the server. Its running smoothly for small set of data but for large data set giving an error : Remote Serve returned an error:notFound. How can i resolve it,please any one solve this problem. I have build it in ASP.NET with C#. So kindly provide the solution in C# if possible.

    Read the article

  • I'm trying to match some numbers in a string using a regexpressions and am having difficulty with th

    - by Ryan
    here is the line i'm trying to parse [\\?\Volume{d3f7f470-526b-11df-92eb-001a647802d2}\] 85 90 NotFound I'm basically just trying to get the numbers that are outside of the brackets and ignore anything in between the brackets. My original syntax worked until I realized that sometimes there would be numbers in the brackets (I was just using "([0-99]{2})") any help would be greatly appreciated. Thanks

    Read the article

  • How to detect some Activex in Javascript ?

    - by Rebol Tutorial
    I have an activex plugin here: http://reboltutorial.com/plugins/logo-badge/ I tried by adapting the script http://forums.devarticles.com/javascript-development-22/detecting-activex-objects-installed-in-ie-11041.html to <script> //if RPluginIE is not installed if( !document.RPluginIE){ document.loction.href = "Notfound.html" } </script> but it doesn't work. How to detect for any activex ?

    Read the article

  • ASP.NET MVC - dropdown list post handling problem

    - by ile
    I've had troubles for a few days already with handling form that contains dropdown list. I tried all that I've learned so far but nothing helps. This is my code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using CMS; using CMS.Model; using System.ComponentModel.DataAnnotations; namespace Portal.Models { public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } public class HomePageViewModel { public HomePageViewModel(IEnumerable<ArticleDisplay> summaries, Article article) { this.ArticleSummaries = summaries; this.NewArticle = article; } public IEnumerable<ArticleDisplay> ArticleSummaries { get; private set; } public Article NewArticle { get; private set; } } public class ArticleRepository { private DB db = new DB(); // // Query Methods public IQueryable<ArticleDisplay> FindAllArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID orderby article.Date descending select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public IQueryable<ArticleDisplay> FindTodayArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where article.Date == DateTime.Today select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public Article GetArticle(int id) { return db.Articles.SingleOrDefault(d => d.ArticleID == id); } public IQueryable<ArticleDisplay> DetailsArticle(int id) { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where id == article.ArticleID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } // // Insert/Delete Methods public void Add(Article article) { db.Articles.InsertOnSubmit(article); } public void Delete(Article article) { db.Articles.DeleteOnSubmit(article); } // // Persistence public void Save() { db.SubmitChanges(); } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Portal.Models; using CMS.Model; namespace Portal.Areas.CMS.Controllers { public class ArticleController : Controller { ArticleRepository articleRepository = new ArticleRepository(); ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository(); // // GET: /Article/ public ActionResult Index() { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); Article article = new Article() { Date = DateTime.Now, CategoryID = 1 }; HomePageViewModel homeData = new HomePageViewModel(articleRepository.FindAllArticles().ToList(), article); return View(homeData); } // // GET: /Article/Details/5 public ActionResult Details(int id) { var article = articleRepository.DetailsArticle(id).Single(); if (article == null) return View("NotFound"); return View(article); } // // GET: /Article/Create //public ActionResult Create() //{ // ViewData["categories"] = new SelectList // ( // articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" // ); // Article article = new Article() // { // Date = DateTime.Now, // CategoryID = 1 // }; // return View(article); //} // // POST: /Article/Create [ValidateInput(false)] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } // // GET: /Article/Edit/5 public ActionResult Edit(int id) { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); var article = articleRepository.GetArticle(id); return View(article); } // // POST: /Article/Edit/5 [ValidateInput(false)] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection collection) { Article article = articleRepository.GetArticle(id); try { // TODO: Add update logic here UpdateModel(article, collection.ToValueProvider()); articleRepository.Save(); return RedirectToAction("Details", new { id = article.ArticleID }); } catch { return View(article); } } // // HTTP GET: /Article/Delete/1 public ActionResult Delete(int id) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); else return View(article); } // // HTTP POST: /Article/Delete/1 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id, string confirmButton) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); articleRepository.Delete(article); articleRepository.Save(); return View("Deleted"); } [ValidateInput(false)] public ActionResult UpdateSettings(int id, string value, string field) { // This highly-specific example is from the original coder's blog system, // but you can substitute your own code here. I assume you can pick out // which text field it is from the id. Article article = articleRepository.GetArticle(id); if (article == null) return Content("Error"); if (field == "Title") { article.Title = value; UpdateModel(article, new[] { "Title" }); articleRepository.Save(); } if (field == "Content") { article.Content = value; UpdateModel(article, new[] { "Content" }); articleRepository.Save(); } if (field == "Date") { article.Date = Convert.ToDateTime(value); UpdateModel(article, new[] { "Date" }); articleRepository.Save(); } return Content(value); } } } and view: <%@ Page Title="" Language="C#" MasterPageFile="~/Areas/CMS/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Portal.Models.HomePageViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <div class="naslov_poglavlja_main">Articles Administration</div> <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm("Create","Article")) {%> <div class="news_forma"> <label for="Title" class="news">Title:</label> <%= Html.TextBox("Title", "", new { @class = "news" })%> <%= Html.ValidationMessage("Title", "*") %> <label for="Content" class="news">Content:</label> <div class="textarea_okvir"> <%= Html.TextArea("Content", "", new { @class = "news" })%> <%= Html.ValidationMessage("Content", "*")%> </div> <label for="CategoryID" class="news">Category:</label> <%= Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["categories"], new { @class = "news" })%> <p> <input type="submit" value="Publish" class="form_submit" /> </p> </div> <% } %> <div class="naslov_poglavlja_main"><%= Html.ActionLink("Write new article...", "Create") %></div> <div id="articles"> <% foreach (var item in Model.ArticleSummaries) { %> <div> <div class="naslov_vijesti" id="<%= item.ArticleID %>"><%= Html.Encode(item.ArticleTitle) %></div> <div class="okvir_vijesti"> <div class="sadrzaj_vijesti" id="<%= item.ArticleID %>"><%= item.ArticleContent %></div> <div class="datum_vijesti" id="<%= item.ArticleID %>"><%= Html.Encode(String.Format("{0:g}", item.ArticleDate)) %></div> <a class="news_delete" href="#" id="<%= item.ArticleID %>">Delete</a> </div> <div class="dno"></div> </div> <% } %> </div> </asp:Content> When trying to post new article I get following error: System.InvalidOperationException: The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'. I really don't know what to do cause I'm pretty new to .net and mvc Any help appreciated! Ile EDIT: I found where I made mistake. I didn't include date. If in view form I add this line I'm able to add article: <%=Html.Hidden("Date", String.Format("{0:g}", Model.NewArticle.Date)) %> But, if I enter wrong datetype or leave title and content empty then I get the same error. In this eample there is no need for date edit, but I will need it for some other forms and validation will be necessary. EDIT 2: Error happens when posting! Call stack: App_Web_of9beco9.dll!ASP.areas_cms_views_article_create_aspx.__RenderContent2(System.Web.UI.HtmlTextWriter __w = {System.Web.UI.HtmlTextWriter}, System.Web.UI.Control parameterContainer = {System.Web.UI.WebControls.ContentPlaceHolder}) Line 31 + 0x9f bytes C#

    Read the article

  • smbclient -L host works. ping host doesn't work. What is missing

    - by DrorCohen
    I upgrade my ubuntu desktop to 13.10. When I say upgrade I mean installed on a new partition from scratch (old partition is available if To the problem: I'm trying to ping a host (Drobo-FS server) by it's netbios name. I get "Unknown Host". However running smbclient -l HostName - give me all the output in the world. Stracing the ping I can it tries to use resolv.conf (expected fail) and then when accessing mdns stuff it fails (no mdns.allow file) and exits. Here's the host line from /etc/nsswitch.conf: hosts: files wins mdns4_minimal [NOTFOUND=return] dns mdns4 I've added wins right after files (and also tried before dns. Nothing helps. Reboot after every change. What am I missing?

    Read the article

  • How to configure ubuntu ldap client to get password policies from server?

    - by Rafaeldv
    I have a ldap server on CentOS, 389-ds. I configured the client, ubuntu 12.04, to authenticate on that base and it works very well. But it don't gets the password policies from server. For example, if i set the policy to force user to change the password on first login, ubuntu ignores it and logs him in, always. How can i setup the client to get the policies? Here are the client files: /etc/nsswitch.conf passwd: files ldap group: files ldap shadow: files ldap hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4 networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis sudoers: ldap files common-auth auth [success=2 default=ignore] pam_unix.so nullok_secure auth [success=1 default=ignore] pam_ldap.so use_first_pass auth requisite pam_deny.so auth required pam_permit.so auth optional pam_cap.so common-account account [success=2 new_authtok_reqd=done default=ignore] pam_unix.so account [success=1 default=ignore] pam_ldap.so account requisite pam_deny.so account required pam_permit.so common-password password requisite pam_cracklib.so retry=3 minlen=8 difok=3 password [success=2 default=ignore] pam_unix.so obscure use_authtok try_first_pass sha512 password [success=1 user_unknown=ignore default=die] pam_ldap.so use_authtok try_first_pass password requisite pam_deny.so password required pam_permit.so password optional pam_gnome_keyring.so common-session session [default=1] pam_permit.so session requisite pam_deny.so session required pam_permit.so session optional pam_umask.so session required pam_unix.so session optional pam_ldap.so session optional pam_ck_connector.so nox11 session optional pam_mkhomedir.so skel=/etc/skel umask=0022 /etc/ldap.conf base dc=a,dc=b,dc=c uri ldaps://a.b.c/ ldap_version 3 rootbinddn cn=directory manager pam_password md5 sudoers_base ou=SUDOers,dc=a,dc=b,dc=c pam_lookup_policy yes pam_check_host_attr yes nss_initgroups_ignoreusers avahi,avahi-autoipd,backup,bin,colord,daemon,games,gnats,hplip,irc,kernoops,libuuid,lightdm,list,lp,mail,man,messagebus,news,proxy,pulse,root,rtkit,saned,speech-dispatcher,sshd,sync,sys,syslog,usbmux,uucp,whoopsie,www-data /etc/ldap/ldap.conf BASE dc=a,dc=b,dc=c URI ldaps://a.b.c/ ssl on use_sasl no tls_checkpeer no sudoers_base ou=SUDOers,dc=a,dc=b,dc=c sudoers_debug 2 pam_lookup_policy yes pam_check_host_attr yes pam_lookup_policy yes pam_check_host_attr yes TLS_CACERT /etc/ssl/certs/ca-certificates.crt TLS_REQCERT never

    Read the article

  • Windows domain full hostnames cannot be resolved resulting in intranet not working

    - by OpethR
    the domain: is foo.bar.local full hostname is: bla.foo.bar.local short hostname is: bla I installed winbind. here is my smb.conf: name resolve order = lmhosts host wins bcast here is my nsswitch.conf: hosts: files mdns4_minimal [NOTFOUND=return] dns wins mdns4 when I try to ping full hostname, I get: "ping: unknown host" when I ping short hostname it works and shows me PING bla.foo.bar.local (10.11.20.135) 56(84) bytes of data. 64 bytes from bla.foo.bar.local (10.11.20.135): icmp_req=1 ttl=62 time=49.7 ms *notice that it manages to get the full hostname!? :S now the only reason I need it is cuz I'm trying to reach intranet websites. when I type short hostname "bla" in firefox address bar, it automatically changes it to the full hostname (which is good, right?!) but then it says: Server not found Firefox can't find the server at bla.foo.bar.local. what am I doing wrong? it's driving me nutz. so if you are wandering then yes, it is company intranet I'm trying to reach from ubuntu. If I use my crappy winxp everything is working perfectly well.

    Read the article

  • Building MySQL with boost on windows

    - by user13177919
    As you've probably heard already MySQL needs boost to build. However, in the good ol' MySQL tradition, the above link does give you only the instructions on how to build it on linux. And completely ignores the fact that there're other OSes too that people develop on. To fill in that gap, I've compiled a small step by step guide on how to do it on windows. Note that I always, as a principle, build out-of-source. The typical setup I have is : bzr clone lp:~mysql/mysql-server/5.7 mysql-trunkcd mysql-trunkmkdir bldcd bldcmake -DWITH_DEBUG=1 -DMYSQL_PROJECT_NAME=mysql-trunk ..devenv /build debug mysql-trunk.sln This has been tested to work on a 32 bit compile using VS2013 on a Windows7 64 bit build. Note that you'll need other things too (bison, eventually openssl etc) that I will assume you already have set up. Steps: Download Boost 1.55.0. It's the *only* version that is known to work currently. Extract boost_1_55_0/ from the zip to c:\boost\boost_1_55_0 Go to Control Panel/System/Environment variables and set WITH_BOOST=C:\boost\boost_1_55_0 in User variables. Make sure you restart your open command line terminal windows after this !  If you're upgrading from non-boost build, remove your bld/ directory and create a new one. run cmake as you'd typically do. You should get: -- Local boost dir C:/boost/boost_1_55_0 -- Local boost zip LOCAL_BOOST_ZIP-NOTFOUND -- BOOST_VERSION_NUMBER is #define BOOST_VERSION 105500 -- BOOST_INCLUDE_DIR C:/boost/boost_1_55_0 Build as normal (devenv /build debug ...). It should work.

    Read the article

  • Building a JMX client in a servlet installed on the Deployment Manager

    - by Trevor
    Hi guys, I'm building a monitoring application as a servlet running on my websphere 7 ND deployment manager. The tool uses JMX to query the deployment manager for various data. Global Security is enabled on the dmgr. I'm having problems getting this to work however. My first attempt was to use the websphere client code: String sslProps = "file:" + base +"/properties/ssl.client.props"; System.setProperty("com.ibm.SSL.ConfigURL", sslProps); String soapProps = "file:" + base +"/properties/soap.client.props"; System.setProperty("com.ibm.SOAP.ConfigURL", pp); Properties connectProps = new Properties(); connectProps.setProperty(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP); connectProps.setProperty(AdminClient.CONNECTOR_HOST, dmgrHost); connectProps.setProperty(AdminClient.CONNECTOR_PORT, soapPort); connectProps.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "true"); AdminClient adminClient = AdminClientFactory.createAdminClient(connectProps) ; This results in the following exception: Caused by: com.ibm.websphere.management.exception.ConnectorNotAvailableException: ADMC0016E: The system cannot create a SOAP connector to connect to host ssunlab10.apaceng.net at port 13903. at com.ibm.ws.management.connector.soap.SOAPConnectorClient.getUrl(SOAPConnectorClient.java:1306) at com.ibm.ws.management.connector.soap.SOAPConnectorClient.access$300(SOAPConnectorClient.java:128) at com.ibm.ws.management.connector.soap.SOAPConnectorClient$4.run(SOAPConnectorClient.java:370) at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118) at com.ibm.ws.management.connector.soap.SOAPConnectorClient.reconnect(SOAPConnectorClient.java:363) ... 22 more Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:519) at java.net.Socket.connect(Socket.java:469) at java.net.Socket.<init>(Socket.java:366) at java.net.Socket.<init>(Socket.java:209) at com.ibm.ws.management.connector.soap.SOAPConnectorClient.getUrl(SOAPConnectorClient.java:1286) ... 26 more So, I then tried to do it via RMI, but adding in the sas.client.properties to the environment, and setting the connectort type in the code to CONNECTOR_TYPE_RMI. Now though I got a NameNotFoundException out of CORBA: Caused by: javax.naming.NameNotFoundException: Context: , name: JMXConnector: First component in name JMXConnector not found. [Root exception is org.omg.CosNaming.NamingContextPackage.NotFound: IDL:omg.org/CosNaming/NamingContext/NotFound:1.0] To see if it was an IBM issue, I tried using the standard JMX connector as well with the same result (substitute AdminClient for JMXConnector in the above error) * JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/JMXConnector"); Hashtable h = new Hashtable(); String providerUrl = "corbaloc:iiop:" + dmgrHost + ":" + rmiPort + "/WsnAdminNameService"; h.put(Context.PROVIDER_URL, providerUrl); // Specify the user ID and password for the server if security is enabled on server. String[] credentials = new String[] { "***", "***" }; h.put("jmx.remote.credentials", credentials); // Establish the JMX connection. JMXConnector jmxc = JMXConnectorFactory.connect(url, h); // Get the MBean server connection instance. mbsc = jmxc.getMBeanServerConnection(); At this point, in desperation I wrote a wsadmin sccript to run both the RMI and SOAP methods. To my amazement, this works fine. So my question is, why does the code not work in a servlet installed on the dmgr ? regards, Trevor

    Read the article

  • Writing Unit Tests for ASP.NET Web API Controller

    - by shiju
    In this blog post, I will write unit tests for a ASP.NET Web API controller in the EFMVC reference application. Let me introduce the EFMVC app, If you haven't heard about EFMVC. EFMVC is a simple app, developed as a reference implementation for demonstrating ASP.NET MVC, EF Code First, ASP.NET Web API, Domain-Driven Design (DDD), Test-Driven Development (DDD). The current version is built with ASP.NET MVC 4, EF Code First 5, ASP.NET Web API, Autofac, AutoMapper, Nunit and Moq. All unit tests were written with Nunit and Moq. You can download the latest version of the reference app from http://efmvc.codeplex.com/ Unit Test for HTTP Get Let’s write a unit test class for verifying the behaviour of a ASP.NET Web API controller named CategoryController. Let’s define mock implementation for Repository class, and a Command Bus that is used for executing write operations.  [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } The code block below provides the unit test for a HTTP Get operation. [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        The GetCategories method is provided below: private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } In the unit test method Get_All_Returns_AllCategory, we specify setup on the mocked type ICategoryrepository, for a call to GetCategoryWithExpenses method returns dummy data. We create an instance of the ApiController, where we have specified the Request property of the ApiController since the Request property is used to create a new HttpResponseMessage that will provide the appropriate HTTP status code along with response content data. Unit Tests are using for specifying the behaviour of components so that we have specified that Get operation will use the model type IEnumerable<CategoryWithExpense> for sending the Content data. The implementation of HTTP Get in the CategoryController is provided below: public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; } Unit Test for HTTP Post The following are the behaviours we are going to implement for the HTTP Post: A successful HTTP Post  operation should return HTTP status code Created An empty Category should return HTTP status code BadRequest A successful HTTP Post operation should provide correct Location header information in the response for the newly created resource. Writing unit test for HTTP Post is required more information than we write for HTTP Get. In the HTTP Post implementation, we will call to Url.Link for specifying the header Location of Response as shown in below code block. var response = Request.CreateResponse(HttpStatusCode.Created, category); string uri = Url.Link("DefaultApi", new { id = category.CategoryId }); response.Headers.Location = new Uri(uri); return response; While we are executing Url.Link from unit tests, we have to specify HttpRouteData information from the unit test method. Otherwise, Url.Link will get a null value. The code block below shows the unit tests for specifying the behaviours for the HTTP Post operation. [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } In the above code block, we have written two unit methods, Post_Category_Returns_CreatedStatusCode and Post_EmptyCategory_Returns_BadRequestStatusCode. The unit test method Post_Category_Returns_CreatedStatusCode  verifies the behaviour 1 and 3, that we have defined in the beginning of the section “Unit Test for HTTP Post”. The unit test method Post_EmptyCategory_Returns_BadRequestStatusCode verifies the behaviour 2. For extracting the data from response, we call Content.ReadAsStringAsync().Result of HttpResponseMessage object and deserializeit it with Json Convertor. The implementation of HTTP Post in the CategoryController is provided below: // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); } The unit test implementation for HTTP Put and HTTP Delete are very similar to the unit test we have written for  HTTP Get. The complete unit tests for the CategoryController is given below: [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        [Test] public void Get_CorrectCategoryId_Returns_Category() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(1);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);     var category = JsonConvert.DeserializeObject<CategoryWithExpense>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(1, category.CategoryId, "Got wrong number of Categories"); } [Test] public void Get_InValidCategoryId_Returns_NotFound() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(5);     // Assert     Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);            } [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } [Test] public void Put_Category_Returns_OKStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Put(category.CategoryId,category);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);    } [Test] public void Delete_Category_Returns_NoContentStatusCode() {     // Arrange              commandBus.Setup(c => c.Submit(It.IsAny<DeleteCategoryCommand >())).Returns(new CommandResult(true));     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act               var response = controller.Delete(1);     // Assert     Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);   } private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } }  The complete implementation for the Api Controller, CategoryController is given below: public class CategoryController : ApiController {       private readonly ICommandBus commandBus;     private readonly ICategoryRepository categoryRepository;     public CategoryController(ICommandBus commandBus, ICategoryRepository categoryRepository)     {         this.commandBus = commandBus;         this.categoryRepository = categoryRepository;     } public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; }   // GET /api/category/5 public HttpResponseMessage Get(int id) {     var category = categoryRepository.GetCategoryWithExpenses().Where(c => c.CategoryId == id).SingleOrDefault();     if (category == null)     {         return Request.CreateResponse(HttpStatusCode.NotFound);     }     return Request.CreateResponse(HttpStatusCode.OK, category); }   // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }   // PUT /api/category/5 public HttpResponseMessage Put(int id, CategoryModel category) {     if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         return Request.CreateResponse(HttpStatusCode.OK, category);     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }       // DELETE /api/category/5     public HttpResponseMessage Delete(int id)     {         var command = new DeleteCategoryCommand { CategoryId = id };         var result = commandBus.Submit(command);         if (result.Success)         {             return new HttpResponseMessage(HttpStatusCode.NoContent);         }             throw new HttpResponseException(HttpStatusCode.BadRequest);     } } Source Code The EFMVC app can download from http://efmvc.codeplex.com/ . The unit test project can be found from the project EFMVC.Tests and Web API project can be found from EFMVC.Web.API.

    Read the article

  • Deployment Error: Silverlight 4.0 w/WCF RIA Services in ASP.NET MVC 2 App

    - by Dennis Ward
    I've got an MVC 2 App with an RIA Services link to a Silverlight Application. On my local machine, all is well, but when I deploy to Discount ASP servers, neither the MVC controller nor the WCF RIA services called from silverlight function: A silverlight datagrid gets a load error: System.ServiceModel.DomainServices.Client.DomainOperationException: Load operation failed for query... The remote server returned an error NotFound. In the MVC page where I had a simple table that worked prior to adding an EF model and DomainDataSource, I now get the error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. This is very similar to an issue I had before, but after upgrading from the betas of WCF/Silverlight 4, but the fix I had added there doesn't seem to work any longer. The link for that issue is: SL4/MVC2/WCF RIA Services = Load Error I'm really struggling with deploying, and could use some help if anybody can shed any light on this. Thanks! Dennis

    Read the article

  • How to use WIX to deploy and run WCF service

    - by Giampaolo
    Hi I am trying to make an installer which deploys my wcf service, at the moment it is creating the virtual directory, but when i try connect my app to it, i get a CommunicationException was unhandled by user code The remote server returned an error: NotFound. I notice that if i create a virtual directory manually that it will connect and work, so i'm assuming IIS is doing something behind my back which is making it work. This is the code i am using to create the virtual directory,please note this is inside a iis:WebSite tag if more information is needed please let me know. <iis:WebVirtualDir Id="VAWebService" Directory="VAWebService" Alias="VAWebService" > <iis:WebApplication Id="VAWebService" Name="VAWebService" AllowSessions="yes" WebAppPool="VA_AppPool" /> <iis:WebDirProperties Id="MyWebSite_Properties" AnonymousAccess="yes" WindowsAuthentication="no" DefaultDocuments="service1.svc" AccessSSL="yes" AccessSSL128="yes" AccessSSLMapCert="yes" AccessSSLNegotiateCert="yes" AccessSSLRequireCert="yes" Read="yes" Write="yes" Execute="yes" Script="yes" /> </iis:WebVirtualDir> Does any one know how to fix this? any help would be appreciated. Thanks

    Read the article

  • Random "Not Found" error with Silverlight accessing ASP.NET Web Services

    - by user245822
    I'm developing an application with Silverlight 3 and ASP.NET Web Services, which uses Linq to SQL to get data from my SQL Server database. Randomly when the user causes an action to get information from any of my web service methods, Silverlight throws the exception "The remote server returned an error: NotFound.", of type "CommunicationException", with the InnerException status of "System.Net.WebExceptionStatus.UnknownError". Almost 10% of requests gets this error. If the user tries to get the same information again, normally the request has no erros and the user gets the data. When debugging in Visual Studio only Silverlight stops on the exception, and I see no reason for the web service not being found.

    Read the article

  • ASP.NET MVC: How to serve content while returning status code 404?

    - by Marek
    I would like to serve a user friendly "not found" page in my ASP.NET MVC application while providing a 404 status code. (based on this answer) I already have the mechanism how to catch an invalid route and the custom 404 page is served by my ErrorController/Handle404 action. My current implementation of Handle404: public ActionResult Handle404() { Response.StatusCode = 404; return View("NotFound"); } Currently, IIS serves the page as 404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable. (the standard IIS page, not my user friendly content) How can I include the 404 status code in the result served by the Handle404 action while still serving the content?

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >