0% found this document useful (0 votes)
23 views11 pages

TP Photos

Uploaded by

yikom vasu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views11 pages

TP Photos

Uploaded by

yikom vasu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

public class RouteConfig

{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}

public class PhotoController : Controller


{
//Le model
private PhotosContext db = new PhotosContext();
// GET: Photo
public ActionResult Index()
{
return View(db.Photos.ToList());
}

public ActionResult Details(int? id)


{
if(id==null)
{
return RedirectToAction(
"DisplayError",
new { message = "No id for the request"});
}

Photo photo = db.Photos.Find(id);

if (photo == null)
{
return RedirectToAction(
"DisplayError",
new { message = "No photo for that id" });
}
return View(photo);
}

public ActionResult DisplayError(string message)


{
ViewData["message"] = message;

return View();
}

public FileContentResult GetImage(int id)


{
Photo photo = db.Photos.Find(id);
Response.ContentType = photo.ImageMimeType;

if (photo != null)
{
return new FileContentResult(
photo.PhotoFile, photo.ImageMimeType);
}
else
return null;
}

public ActionResult GetPhotoByTitle(string title)


{
if (title == null)
{
return RedirectToAction(
"DisplayError",
new { message = "No title for the request" });
}

//Recherche par Title


var query = from ph in db.Photos
where ph.Title == title
select ph;

var photo = query.FirstOrDefault();

if (photo == null)
{
return RedirectToAction(
"DisplayError",
new { message = "No photo for that title" });
}
//On va envoyer la vue Détails avec le model photo
return View("Details", photo);
}

//Gerer l'action Create


[HttpGet]
public ActionResult Create()
{
Photo photo = new Photo();
photo.CreatedDate = DateTime.Now;
return View("Create", photo);
}

[HttpPost]
public ActionResult Create(Photo photo,
HttpPostedFileBase image)
{
photo.CreatedDate = DateTime.Now;

if(!ModelState.IsValid)
{
//Le model state encpsule l'etat de validation du model
// foreach( var item in ModelState.Keys)
// {
// Response.Write(item +" "+ModelState[item].Errors[0].ErrorMessage+"<br/>");
return View("Create", photo);
// }
}
else
{
if(image!=null)
{
photo.ImageMimeType = image.ContentType;
photo.PhotoFile = new byte[image.ContentLength];
image.InputStream.Read(photo.PhotoFile,0, image.ContentLength);

}
db.Photos.Add(photo);
db.SaveChanges();
}

return RedirectToAction("Index");
}
}
}

Models

namespace WebApplicationPhotos.Models
{
public class Comment
{
public int CommentId { get; set; }
public int PhotoId { get; set; }
[Required]
[StringLength(250)]
public string UserName { get; set; }
[DataType(DataType.MultilineText)]
public string Subject { get; set; }
public string Body { get; set; }

public virtual Photo Photo { get; set; }


}
}

namespace WebApplicationPhotos.Models
{
//Initialisateur de base de données
public class PhotDBInitializer :
DropCreateDatabaseAlways<PhotosContext>
{
public byte[] getFileBytes(string path)
{
//Ouvrire le fichier path en mode read
FileStream
fileOnDisk =
new
FileStream(HttpRuntime.AppDomainAppPath + path,
FileMode.Open);
byte[] fileBytes;

BinaryReader reader = new BinaryReader(fileOnDisk);


fileBytes = reader.ReadBytes((int)fileOnDisk.Length);
return fileBytes;
}

protected override void Seed(PhotosContext context)


{
base.Seed(context);

var photo = new Photo()


{
Title = "Test Photo",
Description = " Une description",
UserName = "El Aoufi",
PhotoFile = getFileBytes("\\Images\\flower.jpg"),
ImageMimeType = "image/jpeg",
CreatedDate = DateTime.Now

};

//Ajouter la photos à la base de données


context.Photos.Add(photo);
context.SaveChanges();

var comment = new Comment()


{
PhotoId = 1,
UserName = "El Mqadem",
Subject = "Test de commentaire",
Body = "Tbhis comment should appear in Photo 1"

};

//Ajouter le commentaire à la base de données


context.Comments.Add(comment);
context.SaveChanges();
}

}
}

namespace WebApplicationPhotos.Models
{
public class Photo
{
[Required]
[DisplayName("Id")]
public int PhotoId { get; set; }
[Required]
public string Title { get; set; }

[DisplayName("Photo")]
public byte[] PhotoFile { get; set;}
public string ImageMimeType { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[DataType(DataType.DateTime)]
[DisplayName("Created date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yy}")]
public DateTime CreatedDate { get; set; }
public string UserName { get; set; }

public virtual ICollection<Comment> comments { get; set; }


}
}

namespace WebApplicationPhotos.Models
{
public class PhotosContext : DbContext
{
public PhotosContext() :
base()
{

}
public DbSet<Photo> Photos { get; set; }
public DbSet<Comment> Comments { get; set; }
}
}

Views

@model WebApplicationPhotos.Models.Photo

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
@using (Html.BeginForm("Create","Photo",FormMethod.Post ,new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Photo</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.PhotoFile, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="image" />
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>

View Details
@model WebApplicationPhotos.Models.Photo

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
</head>
<body>
<div>
<h4>Photo</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>

<dd>
@Html.DisplayFor(model => model.Title)
</dd>

<dt>
@Html.DisplayNameFor(model => model.PhotoFile)
</dt>

<dd>
@if (Model.PhotoFile != null)
{
<img src='@Url.Action("GetImage","Photo",new { id= Model.PhotoId})'

alt="description ...." />

}
</dd>

<dt>
@Html.DisplayNameFor(model => model.ImageMimeType)
</dt>

<dd>
@Html.DisplayFor(model => model.ImageMimeType)
</dd>

<dt>
@Html.DisplayNameFor(model => model.Description)
</dt>

<dd>
@Html.DisplayFor(model => model.Description)
</dd>

<dt>
@Html.DisplayNameFor(model => model.CreatedDate)
</dt>

<dd>
@Html.DisplayFor(model => model.CreatedDate)
</dd>

<dt>
@Html.DisplayNameFor(model => model.UserName)
</dt>

<dd>
@Html.DisplayFor(model => model.UserName)
</dd>

</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.PhotoId }) |
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>

View DisplayError

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DisplayError</title>
</head>
<body>
<div>

<h1> @ViewData["message"]</h1>
</div>
</body>
</html>

View index
@model IEnumerable<WebApplicationPhotos.Models.Photo>

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table border="1" class="table">
<tr>
<th>

</th>
<th>
@Html.DisplayNameFor(model => model.PhotoId)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>

<th>
@Html.DisplayNameFor(model => model.ImageMimeType)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.CreatedDate)
</th>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
<th>
photo
</th>

</tr>

@foreach (var item in Model) {


<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.PhotoId }) |
@Html.ActionLink("Details", "Details", new { id = item.PhotoId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.PhotoId })
</td>
<td>
@Html.DisplayFor(modelItem => item.PhotoId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ImageMimeType)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreatedDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@if(item.PhotoFile != null)
{
<img
src='@Url.Action("GetImage","Photo",new { id=item.PhotoId})'
width="50"
height="50"
alt="description ...."
/>

}
</td>

</tr>
}

</table>

<p>
@Html.ActionLink("Create New", "Create")
</p>
</body>
</html>

namespace WebApplicationMVC1.Controllers
{
public class HomeController : Controller
{
//Represente le model - la base de données
tachesDataContext db =
new tachesDataContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=tachesDB;Integrated Security=True");
// GET: Home
public ActionResult Index()
{
//Ramener l'ensemble des taches
/* var query = from tache in db.Taches
select tache;*/

//Un traitement
//la liste des taches constituent le modele de la vue
return View(db.Taches.ToList());
}

// afficher un formulaire pour saisir une nouvelle tache


// reponse à l'action Create
public ActionResult Create()
{
return View();
}

// Enregistrer la nouvelle tache dans la BD


public ActionResult CreateNew(string tache, int duree)
{
//Un traitement
Taches ta = new Taches();
ta.tache = tache;
ta.duree = duree;
ta.dateEntree = DateTime.Now;
ta.complete = false;
//Sauvegarder la tache....
db.Taches.InsertOnSubmit(ta);
db.SubmitChanges();
return RedirectToAction("Index");
}

// Marquer une tache comme complete


public ActionResult Complete(int id)
{
var query = from ta in db.Taches
where ta.IdTache == id
select ta;

Taches tache=query.FirstOrDefault();
if (tache != null)
tache.complete = true;

db.SubmitChanges();
//Un traitement
return RedirectToAction("Index");
}
}
}

You might also like