namespace ActionMailSample.Controllers
{
public class MailController : MailerBase
{
//
// GET: /Mail/
public EmailResult SampleEmail()
{
From = "ExampleEmail#this.com";
To.Add("ExampleEmail#there.com");
Subject = "tha pikseis kolopsaro";
return Email();<---ERROR no overload for method Email takes 0 arguments.
}
}
}
You must enter the same name of the EmailResult and the viewmodel that came from the view where is the form to send.
public class MailController : MailerBase
{
public EmailResult SampleEmail(mail_ViewModel model)
{
To.Add("destination#email.com");
From = "from#email.com";
Subject = "Subject of Email";
return Email("SampleEmail", model);
}
}
Dont forget when you create the view, append .txt or .html to Plain or Html email.
The name of this view in plain text will be SampleEmail.txt that will become the filename SampleEmail.txt.cshtml
In the view (SampleEmail.txt.cshtml) you can put something like this:
#model TEST.Models.mail_ViewModel
#{
Layout = null;
}
Contact from Website
Name: #Html.Raw(Model.Nome)
Email: #Html.Raw(Model.Email)
Subject: #Html.Raw(Model.Subject)
Message: #Html.Raw(Model.Message)
Hope this helped.
The method Email() expects one or more parameters. Consult the documentation for the Email() function to see what is expected and supply this information.
Related
in my app I've generated an url like this:
http://www.test.com/?mail=test%40gmail.ba&code=71147ff9-87ae-41fc-b53f-5ecb3dbe5a01
The way how I generated Url is posted below:
private string GenerateUrl(string longUrl, string email, string confirmCode)
{
try
{
// By the way this is not working (Home/MailConfirmed) I'm getting message
// Requested URL: /Home/MailConfirmed
// The resource cannot be found.
string url = longUrl + "/Home/MailConfirmed";
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["mail"] = email;
query["code"] = confirmCode;
uriBuilder.Query = query.ToString();
uriBuilder.Port = -1;
url = uriBuilder.ToString();
return url;
}
catch (Exception ex)
{
return "Error happened: " + ex.Message;
}
}
In longUrl I'm passing www.test.com, in email I'm passing
test#gmail.com and so on..
There are informations about my website:
www.test.com
mail:test#gmail.com
confirmcode:71147ff9-87ae-41fc-b53f-5ecb3dbe5a01
And in my HomeController.cs there is a method which should took parameters out of query string - url and pass it to the method which should activate users account by getting user by mail (mail is unique) and comparing this guid with guid in database. So I'm wondering how can I call this method?
So my method looks like this:
public JsonResult MailConfirmed(string mail, string confirmCode)
{
try
{
// Here I will get user and update it in DB
return Json("success", JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json("fail", JsonRequestBehavior.AllowGet);
}
}
So my question is how is possiblee for user to click on following link and to get an my method invoked.. ?
Thanks a lot
Cheers
In order to navigate to your MailConfirmed(), your url would need to be
http://www.test.com/Home/MailConfirmed?mail=test%40gmail.ba&confirmcode=71147ff9-87ae-41fc-b53f-5ecb3dbe5a01
Note the segments for the controller and action names, and code=xxx should be confirmcode=xxx to match the name of the parameter in the method.
You can simplify your code (and delete your GenerateUrl() method) by making use of UrlHelper methods to generate the url).
To generate the above url, all you need in your controller method is
string url = Url.Action("MailConfirmed", "Home",
new { mail = email, confirmcode = confirmCode },
this.Request.Url.Scheme);
I am implementing Jersey based REST API and using swagger to generate HTML based documentation for the same. I am using swagger's annotations to read and scan the resources to generate documentation. I have specified response for each resource using #ApiResponse annotation as below:
#Path("/hello")
#Api(value = "Hello World" )
public class HelloRest
{
#GET
#ApiOperation(value="Hello world", httpMethod="GET")
#ApiResponses(value={ #ApiResponse(code = 200, message = "Success", response = WebservicesErrorResponse.class, reference = "C:/Desktop/hello.json")
#ApiResponse(code = 404, message = "Not found", response = WebservicesErrorResponse.class)})
#Produces({"application/json", "application/xml"})
public Response helloWorld()
{
return Response.status(WebservicesCommonTypes.SUCCESS).entity("Hello rest API").build();
}
}
It is working fine and it is generating HTML based documentation as below:
As it shows the complete structure (Model and example value) of response if response code is 404. And in example value, it is not showing the values, only showing the type for each parameter for the model.
I want to show the sample example schema for the response so that client can understand that what would be the exact response for each response. I researched on it and I found that there is one attribute:
#ApiResponse(reference = "") - Specifies a reference to the response type. The specified reference can be either local or remote and will be used as-is, and will override any specified response() class.
I tried it and I give it a path for my sample.json file as below:
#ApiResponse(code = 200, message = "Success", response = WebServicesErrorResponse, reference = "http://localhost:9001/myinstanceofapplication/html/api-doc/hello.json")
and I also tried to give another path that is local path like below:
#ApiResponse(code = 200, message = "Success", response = WebservicesErrorResponse.class, reference = "C:/Desktop/hello.json")
but when swagger generate document for it then it gives following:
It is showing C:/Desktop/hello.json is not defined!
I have researched and tried lot many solutions but couldn't able to give proper reference to it. I found that this is an issue by https://github.com/swagger-api/swagger-ui/issues/1700 and https://github.com/swagger-api/swagger-js/issues/606.
So how can I use reference attribute of #ApiResponse to that swagger could show the sample XML/JSON swagger UI. My model class is below:
#XmlRootElement(name="response")
#XmlAccessorType(XmlAccessType.FIELD)
public class WebservicesErrorResponse
{
#XmlElement
private int code;
#XmlElement
private String message;
public WebservicesErrorResponse(){ }
public WebservicesErrorResponse(int code, String message)
{
this.code = code;
this.message = message;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
}
and I want to show following sample XML in the swagger UI:
<?xml version="1.0"?>
<response>
<code>200</code>
<message>success</message>
</response>
You need to annotate your model class (not the API resource/method!) with the #ApiModel and #ApiModelProperty annotations as described here.
For what you want to achieve, it would probably be enough to annotate your model members as follows:
#ApiModelProperty(example = "200")
#XmlElement
private int code;
#ApiModelProperty(example = "success")
#XmlElement
private String message;
If that doesn't work, try putting the annotation on the getters (I'm not really familiar with the XML side of this, have only done it for JSON).
I've been Following this post To get my head around Lazy field of T, Which I think I understand, But I'm having trouble getting associated Field Data for a Part loaded this way
Aim - To show photo of blog post author on a blog post.
I want to add a content part "Content Author"
The part Editor should appear as a drop down list of orchard users.
(regardless of the content owner cms users should be able to pick the author)
I have added an image upload field to the User Content Type
I want to show the image of the user on the front end in the view for the Content Author Part
For the first part I have created the content type and used the lazy Filed of UserPart to get the username. However when I try and get the associated fields for the UserPart. There dosent seem to be any.
public class ContentAuthorRecord : ContentPartRecord
{
public virtual string AuthorEmail { get; set; }
}
public class ContentAuthorPart : ContentPart<ContentAuthorRecord>
{
internal readonly LazyField<UserPart> Owner = new LazyField<UserPart>();
public string AuthorEmail
{
get { return Record.AuthorEmail; }
set { Record.AuthorEmail = value; }
}
public UserPart Author
{
get { return Owner.Value; }
set { Owner.Value = value; }
}
public string AuthorName
{
get
{
if (Author == null)
return "Riders for health";
else
{
return Author.UserName;
}
}
}
}
public class ContentAuthorHandler :ContentHandler
{
private readonly IContentManager _contentManager;
public ContentAuthorHandler(IRepository<ContentAuthorRecord> repository, IContentManager contentManager)
{
_contentManager = contentManager;
OnActivated<ContentAuthorPart>(SetUpCustomPart);
Filters.Add(StorageFilter.For(repository));
}
private void SetUpCustomPart(ActivatedContentContext content, ContentAuthorPart part)
{
// Setup the getter of the lazy field
part.Owner.Loader(() => _contentManager.Query<UserPart, UserPartRecord>().List().FirstOrDefault(x => x.Email == part.AuthorEmail));
}
}
I would expect to be able to access the field with something like
(ImageUploadField.Fields.ImageUploadField)Author.Fields.FirstOrDefault(x
=> x.Name == "Photo");
form the within the part class
( although this makes every thing a bit brittle, hard coding a field name, but I'm not sure how eles to go about it)
Further Info
I have a HeaderPart with a Image field added via the cms (not in code) in the display handler I fetch the field like this
protected override DriverResult Display(HeaderPart part, string displayType, dynamic shapeHelper)
{
if (part.HeaderType == HeaderType.Full_width_hero_image)
{
var field = (ImageUploadField) part.Fields.FirstOrDefault(f => f.Name == "HeaderImage");
if (field != null)
{
return ContentShape("Parts_Header_ImageHero",
() => shapeHelper.Parts_Header_ImageHero(ImagePath: field.ImagePath, ImageTitle: field.FileName));
}
return null;
}
if (part.HeaderType == HeaderType.Full_width_hero_video)
{
return ContentShape("Parts_Header_VideoHero", () => shapeHelper.Parts_Header_VideoHero(VideoUrl: part.VideoUrl));
}
if (part.HeaderType == HeaderType.Body_width_video)
{
return ContentShape("Parts_Header_VideoBody", () => shapeHelper.Parts_Header_VideoBody(VideoUrl: part.VideoUrl));
}
return null;
}
This works, But I can do the same for a part loaded into a lazy field.
Cast to dynamic first, then the syntax becomes much simpler: ((dynamic)part.ContentItem).NameOfTheType.NameOfTheField.NameOfTheProperty
If you have added the fields to the User content type via the CMS interface, it may have added the fields to a different part to the one you expect. If you are adding fields to the User content type, by default it will have added the fields to a new part called 'User', not 'UserPart'. Try to following to search all parts in the content item:
(ImageUploadField.Fields.ImageUploadField)Author.ContentItem.Parts
.SelectMany(p => p.Fields).FirstOrDefault(f => f.Name == "Photo");
or directly from the 'User' part:
(ImageUploadField.Fields.ImageUploadField)Author.ContentItem.Parts
.First(p => p.PartDefinition.Name == p.ContentItem.ContentType).Fields
.FirstOrDefault(f => f.Name == "Photo");
I'm using Struts2. I have two web forms that have the same code. I would like to eliminate one form. Here is the structure of my Struts project.
\Web Pages
form.jsp
\WEB-INF
\Content
error.jsp
form.jsp
success.jsp
\Source Packages
\action
MyAction.java
MyAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.*;
public class MyAction extends ActionSupport {
#Action(value = "foo", results = {
#Result(name = "input", location = "form.jsp"),
#Result(name = "success", location = "success.jsp"),
#Result(name = "error", location = "error.jsp")
})
public String execute() throws Exception {
if (user.length() == 1) {
return "success";
} else {
return "error";
}
}
private String user = "";
public void validate() {
if (user.length() == 0) {
addFieldError("user", getText("user required"));
}
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
I tried to eliminate form.jsp under \Web Pages by adding a new action method to MyAction.java.
#Action(value="bar", results = {
#Result(name = "success", location = "form.jsp"),
})
public String another() {
return "success";
}
But I got the following error when I go to http : //localhost .../bar.action
HTTP Status 404 - No result defined for action action.MyAction and result input
Your MyAction has an implementation of validate(), which means it is validation aware.
What's happening is that you're calling another, but validate() is kicking in (as it's in the interceptor stack). Validation is failing, and therefore sending to INPUT result, which is not defined in another.
You should
Add #SkipValidation to the another method if you don't want validation there
Add the INPUT result to another() if you want a default input result
On a more general note, when you get that kind of error (No result defined for action X and result input) it usually means you're either having validation errors, parameter population errors (eg: an exception in preparable).
I have a simple bean, like that:
package models;
import play.data.validation.Constraints;
public class Upload
{
#Constraints.Required
#Constraints.MinLength(4)
#Constraints.MaxLength(40)
public String name;
#Constraints.Required
public String inputFile;
}
and form, like that:
#form(action = routes.Application.submit(), 'enctype -> "multipart/form-data") {
#inputText(
uploadForm("name"),
'_label -> "Name"
)
#inputFile(
uploadForm("inputFile"),
'_label -> "Queries"
)
}
What is the best way to validate inputFile?
Is it possible do to that with annotations?
#Required constraint does not work at all.
I want it to be selected + add some limitation on size.
make your form like:
<input type="file" name="inputFile">
In you submit method add this:
// from official documentation
public static Result submit() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart file = body.getFile("inputFile");
if (inputFile != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
// method the check size
if(!validateFileSize){
return redirect(routes.Application.index()); // error in file size
}
return ok("File uploaded");
} else {
// here comes the validation
flash("error", "Missing file");
return redirect(routes.Application.index());
}
}
Something like the following, maybe?
MultipartFormData body = request().body().asMultipartFormData();
if (!body.getFiles().isEmpty()) {
// do your work
}