nUnit : throw HttpResponseException and access embedded HttpResponseMessage - exception

Assert.Throws<HttpResponseException>(() => ApiController.Post("query-params-string", "request-body-json"));
Now I'd like to view the contents of HttpResponseException.Response.StatusCode
Any way to do this ?

HttpResponseException ex = Assert.Throws<HttpResponseException>(() => ApiController.Post("query-params-string", "request-body-json"));<br>
Assert.AreEqual(ex.Response.StatusCode, HttpStatusCode.NotFound);

Related

why insert query is not working in laravel 5

I am new to Laravel 5 and MVC. I can not figure out why is my INSERT query not running but JUST directing me to search page. below is my code.
edit: the database connection is proper and I can view data on page via same database
public function insert()
{
DB::table('patients')->insert(
array('name' => 'fakhir', 'email' => 'hello#email.com')
);
return view('patients/search');
}
Try '->where', let me know what you get.
public function insert()
{
DB::table('patients')->where('#')->insert(
array('name' => 'fakhir', 'email' => 'hello#email.com')
);
return view('patients/search');
}
have you tried to adding with eloquent ? I think firstly, You should try to adding with eloquent.
You test it in this way
Patients::create(['name'=>'fakhir','email'=>'hello#email.com']);

Create a folder inside another with parents argument in java desktop application

I am trying to create a folder inside another folder by setting the id of parents property, but the folder is not created inside it.I need a solution for a java desktop application but i cant found the right syntax for the parents property in order to perform my post request correctly (HttpPost object is the org.apache.http.client.methods.HttpPost)
HttpPost post2 = new HttpPost("https://www.googleapis.com/drive/v2/files");
post2.addHeader("Content-Type", "application/json");
post2.addHeader("Authorization","Bearer XXXXXX");
JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("title", userid);
jsonObject2.addProperty("parents", "['kind': 'drive#parentReference',
{'id': '"+MY_PARENT_FILE_ID+"'}]");
jsonObject2.addProperty("mimeType", "application/vnd.google-apps.folder");
post2.setEntity(new StringEntity(jsonObject2.toString()));
HttpResponse response2 = httpClient.execute(post2);
Can anyone tell me what I am doing wrong, or suggest a solution?
I use the Google API Ruby Client gem found at https://github.com/google/google-api-ruby-client.
authenticated_client_and_drive
is a method that returns and authenticated client and drive instance. Essentially, you make a post request to https://accounts.google.com/o/oauth2/token with a token that looks like:
{'refresh_token' => USERS_EXISTING_REFRESH_TOKEN,
'client_id' => 'YOUR_CLIENT_ID',
'client_secret' => 'YOUR_CLIENT_SECRET',
'grant_type' => 'refresh_token'}
Then it's as simple as implementing a method like:
def create_folder_within_folder(title, parent_folder_id)
# INPUTS: a folder title (string) and parent_folder_id (string)
# OUTPUT: the file_id (string) of the newly created folder
#client, #drive = authenticated_client_and_drive
#folder = #drive.files.insert.request_schema.new({
'title' => title,
'description' => 'Your Description Here',
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => [{"id" => parent_folder_id}]
})
#result = #client.execute(
:api_method => #drive.files.insert,
:body_object => #folder)
return #result.data.id
end
Hope this points you in the right direction!

zend framework 2, return the rendered contents of a view inside a JSON Model

I am trying to create a JsonModel with an item in the variables 'html' containing the current rendered view. I would like to add this code to an event:
rather than this method: How to render ZF2 view within JSON response? which is in the controller, I would like to automate the process by moving it to an Event
I have the strategy in my module.config.php:
'strategies' => array(
'ViewJsonStrategy',
)
I have set up a setEventManager in the controller:
$events->attach(MvcEvent::EVENT_RENDER, function ($e) use ($controller) {
$controller->setRenderFormat($e);
}, -20);
Is this the best event to attach it to? would the RENDER_EVENT be better?
Now I would like to change the render of the page based on !$this->getRequest()->isXmlHttpRequest(), (commented out for debug)
public function setRenderFormat($e)
{
//if(!$this->getRequest()->isXmlHttpRequest())
//{
$controller = $e->getTarget();
$controllerClass = get_class($controller);
//Get routing info
$controllerArr = explode('\\', $controllerClass);
$currentRoute = array(
'module' => strtolower($controllerArr[0]),
'controller' => strtolower(str_replace("Controller", "", $controllerArr[2])),
'action' => strtolower($controller->getEvent()->getRouteMatch()->getParam('action'))
);
$view_template = implode('/',$currentRoute);
$viewmodel = new \Zend\View\Model\ViewModel();
$viewmodel->setTemplate($view_template);
$htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($viewmodel, $viewmodel);
$jsonModel = new JsonModel();
$jsonModel->setVariables(array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1,2,3,4,5,6)
));
return $jsonModel;
//}
}
Strangely, (or not) this code works and produces the $jsonModel, however is doesn't overwite the normal HTML view with the json, but the same code (without the event) in a controller method, overwrites perfectly.
p.s Is there a better method to do the whole concept?
p.p.s how can I obtain the current View Template from within the controller, without resorting to 8 lines of code?
Thanks in advance!
Aborgrove
you are returning the view model from an event I thinks this doesn't have any effect in current viewmanager view model, fetch the current viewmodel from viewmanager and call setTerminal(true). or replace the created jsonmodel using the viewmanager

HtmlAgility problem

i am trying to extract some data between divs.
<div class="movie_general"><div class="img"><a href="/Movies.html" title="Watch Movie">
Fore example if i want the link "/Movies.html" i used:
string hrefValue = doc.DocumentNode
.Descendants("div")
.Where(x => x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a").Attributes["href"].Value)
.FirstOrDefault();
MessageBox.Show(hrefValue);
but i get a NullReferenceException at Where(x => x.Attributes["class"].Value == "movie_general")
What am i doing wrong?
It happens because the Linq provider must iterate through all other nodes in the document to check if it matches your search. This document must have at least one div which does not have a class attribute. So, the error happens by trying to read the Value property of an attribute which does not exist.
Replace this
.Where(x => x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a").Attributes["href"].Value)
with this
.Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a") != null && x.Element("a").Attributes["href"] != null ? x.Element("a").Attributes["href"].Value : string.Empty)
If you already know the class and that the a tag is subordinate to that, why not just grab it directly using:
HtmlDocument doc = new HtmlDocument();
doc.Load("C:\\temp\\stackhtml.html");
string link = doc.DocumentNode.SelectSingleNode("//div[#class='movie_general']//a").GetAttributeValue("href", "unkown");
Console.WriteLine(link);
Console.ReadLine();
and the result:
I added closing div tags to your example so that I could scrape it and dumped it in a file on my c drive:
<div class="movie_general">
<div class="img">
<a href="/Movies.html" title="Watch Movie">
</div>
</div>

How do I get the collection of Model State Errors in ASP.NET MVC?

How do I get the collection of errors in a view?
I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.
P.S. I'm using the Spark View Engine but the idea should be the same.
So I figured I could do something like...
<if condition="${ModelState.Errors.Count > 0}">
DisplayErrorSummary()
</if>
....and also...
<input type="text" value="${Model.Name}"
class="?{ModelState.Errors["Name"] != string.empty} error" />
....
Or something like that.
UPDATE
My final solution looked like this:
<input type="text" value="${ViewData.Model.Name}"
class="text error?{!ViewData.ModelState.IsValid &&
ViewData.ModelState["Name"].Errors.Count() > 0}"
id="Name" name="Name" />
This only adds the error css class if this property has an error.
<% ViewData.ModelState.IsValid %>
or
<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>
and for a specific property...
<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection
To just get the errors from the ModelState, use this Linq:
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
Condensed version of #ChrisMcKenzie's answer:
var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
This will give you one string with all the errors with comma separating
string validationErrors = string.Join(",",
ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToArray());
Putting together several answers from above, this is what I ended up using:
var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToList();
validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.
Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.
<%= Html.ShowAllErrors(mykey) %>
HtmlHelper:
public static String ShowAllErrors(this HtmlHelper helper, String key) {
StringBuilder sb = new StringBuilder();
if (helper.ViewData.ModelState[key] != null) {
foreach (var e in helper.ViewData.ModelState[key].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Here is the VB.
Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())
If you don't know what property caused the error, you can, using reflection, loop over all properties:
public static String ShowAllErrors<T>(this HtmlHelper helper) {
StringBuilder sb = new StringBuilder();
Type myType = typeof(T);
PropertyInfo[] propInfo = myType.GetProperties();
foreach (PropertyInfo prop in propInfo) {
foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Where T is the type of your "ViewModel".
Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:
var errors =
from item in ModelState
where item.Value.Errors.Count > 0
select item.Key;
var keys = errors.ToArray();
Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error