How to insert the file name in the database using Ado.Net? Instead of the file name null value is being inserted - sql

How to insert the file name in the database using Ado.Net? Instead of the file name null value is being inserted
CONNECTION CODE-
public bool AddBooks(LibraryManagementModel LibraryObject)
{
SqlCommand cmd = new SqlCommand("AddBooks", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#book_id", LibraryObject.Id);
cmd.Parameters.AddWithValue("#book_name", LibraryObject.Book_Name);
cmd.Parameters.AddWithValue("#author", LibraryObject.Author);
cmd.Parameters.AddWithValue("#publisher", LibraryObject.Publisher);
cmd.Parameters.AddWithValue("#date_of_publication", LibraryObject.Date_of_publication);
cmd.Parameters.AddWithValue("#year", LibraryObject.Year);
cmd.Parameters.AddWithValue("#category", LibraryObject.Category);
cmd.Parameters.AddWithValue("#price", LibraryObject.Price);
cmd.Parameters.AddWithValue("#image",LibraryObject.Image);
if (connection.State == ConnectionState.Closed)
connection.Open();
int i = cmd.ExecuteNonQuery();
connection.Close();
if (i > 1)
{
return true;
}
else
{
return false;
}
}
CONTROLLER CODE-
public ActionResult AddBooks(LibraryManagementModel LibraryObject)
{
string fileName = Path.GetFileNameWithoutExtension(LibraryObject.ImageFile.FileName);
string extension = Path.GetExtension(LibraryObject.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
LibraryObject.Image = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
LibraryObject.ImageFile.SaveAs(fileName);
if (ModelState.IsValid == true)
{
BooksDB.AddBooks(LibraryObject);
ModelState.Clear();
ViewBag.AddMsg = "<script>('Data Saved')</script>";
return RedirectToAction("Index");
}
else
{
ViewBag.AddMsg = "<script>('something went wrong')</script>";
return RedirectToAction("Index");
}
return View();
}
MODEL CODE-
public class LibraryManagementModel
{
public int Id { get; set; }
[Required]
public string Book_Name { get; set; }
[Required]
public string Author { get; set; }
[Required]
public string Publisher { get; set; }
[Required]
[DataType(DataType.Date)]
public string Date_of_publication { get; set; }
[Required]
public string Year { get; set; }
public string Category { get; set; }
public string Price{ get; set; }
[DisplayName("Upload Book Image")]
public string Image { get; set; }
public HttpPostedFileBase ImageFile { get; set; }
}

Related

In Model.State Validation is invalid

i trying to upload the multiple images using asp.netcore mvc. i made property of pic in which i save the url path of image. when compiler hits the Model.State it gives Validation invalid. i also created property image in which image url saved. that property type is IFORMFILE. i am using sql to save pic information and using model for code. when i check in model state i find the error message of pic field is required.
namespace ehouse.Controllers
{
public class AddPropertyRentController1 : Controller
{
Rentdb DB =new Rentdb();
private IWebHostEnvironment _IWebHostEnvironment;
public AddPropertyRentController1(IWebHostEnvironment IWebHostEnvironment)
{
_IWebHostEnvironment = IWebHostEnvironment;
}
public IActionResult aprent()
{
return View();
}
[HttpPost]
public IActionResult aprent([Bind] RentModel ar)
{
if (ar.imge1 != null)
{
string folder = "photos/photo/";
folder += ar.imge1.FileName + Guid.NewGuid().ToString();
ar.pic1 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge1.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge2 != null)
{
string folder = "photos/photo/";
folder += ar.imge2.FileName + Guid.NewGuid().ToString();
ar.pic2 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge2.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge3 != null)
{
string folder = "photos/photo/";
folder += ar.imge3.FileName + Guid.NewGuid().ToString();
ar.pic3 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge3.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge4 != null)
{
string folder = "photos/photo/";
folder += ar.imge4.FileName + Guid.NewGuid().ToString();
ar.pic4 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge4.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge5 != null)
{
string folder = "photos/photo/";
folder += ar.imge5.FileName + Guid.NewGuid().ToString();
ar.pic5 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge5.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge6 != null)
{
string folder = "photos/photo/";
folder += ar.imge6.FileName + Guid.NewGuid().ToString();
ar.pic6 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge6.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge7 != null)
{
string folder = "photos/photo/";
folder += ar.imge7.FileName + Guid.NewGuid().ToString();
ar.pic7 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge7.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge8 != null)
{
string folder = "photos/photo/";
folder += ar.imge8.FileName + Guid.NewGuid().ToString();
ar.pic8 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge8.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge9 != null)
{
string folder = "photos/photo/";
folder += ar.imge9.FileName + Guid.NewGuid().ToString();
ar.pic9 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge9.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge10 != null)
{
string folder = "photos/photo/";
folder += ar.imge10.FileName + Guid.NewGuid().ToString();
ar.pic10 = folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge10.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
}
try
{
if (ModelState.IsValid)
{
string res = DB.Saverecord(ar);
string pics = DB.imagedb(ar);
TempData["msg"] = res;
}
}
catch (Exception ex)
{
TempData["msg"] = ex.Message;
}
return View();
}
}
}
RentModel
using System.ComponentModel.DataAnnotations;
namespace eHouse.Models
{
public class RentModel
{
public int id { get; set; }
public string tittle { get; set; }
public string price { get; set; }
public string descrip { get; set; }
public string areaUnit { get; set; }
public int area { get; set; }
public string province { get; set; }
public string city { get; set; }W
public string stadress { get; set; }
//public string features { get; set;}
public string bathroom { get; set; }
public string furnished { get; set; }
public string p_type { get; set; }
public string bedroom { get; set; }
public int p_id { get; set; }
[Required]
public string? pic1 { get; set; }
[Required]
public IFormFile imge1 { get; set; }
[Required]
public string? pic2 { get; set; }
public IFormFile imge2 { get; set; }
[Required]
public string? pic3 { get; set; }
public IFormFile imge3 { get; set; }
[Required]
public string? pic4 { get; set; }
public IFormFile imge4 { get; set; }
[Required]
public string? pic5 { get; set; }
public IFormFile imge5 { get; set; }
[Required]
public string? pic6 { get; set; }
public IFormFile imge6 { get; set; }
[Required]
public string? pic7 { get; set; }
[Required]
public IFormFile imge7 { get; set; }
[Required]
public string? pic8 { get; set; }
public IFormFile imge8 { get; set; }
[Required]
public string? pic9 { get; set; }
public IFormFile imge9 { get; set; }
[Required]
public string? pic10 { get; set; }
public IFormFile imge10 { get; set; }
public int r_id
{
get; set;
}
}
}

How to avoid saving a value of property of form object when saving changes to db

In a crud asp.net core 2.2 web app, I need to avoid saving a property of form object to db. How do I do that?
I've tried using [Editable(false)] data annotation on the ListBin property to prevent saving property value to db.
[Table("supply_lists")]
public partial class SupplyLists
{
[Column("id")]
public int Id { get; set; }
[Column("category_id")]
public int CategoryId { get; set; }
[Required]
[Column("coursecode")]
[StringLength(200)]
public string Coursecode { get; set; }
[Required]
[Column("title")]
[StringLength(200)]
public string Title { get; set; }
[Required]
[Column("filename")]
[StringLength(200)]
public string Filename { get; set; }
[Column("isactive")]
public bool Isactive { get; set; }
[Column("date", TypeName = "smalldatetime")]
public DateTime Date { get; set; }
[Column("list_bin")]
public byte[] ListBin { get; set; }
[ForeignKey("CategoryId")]
[InverseProperty("SupplyLists")]
public virtual SupplyListCategory Category { get; set; }
}
[ModelMetadataType(typeof(MetaDataTypeModel))]
public partial class SupplyLists
{
}
public class MetaDataTypeModel
{
[Editable(false)]
public byte[] ListBin { get; set; }
[Display(Name = "Is Active")]
public bool Isactive { get; set; }
[Display(Name ="Course Code")]
public string Coursecode { get; set; }
[Display(Name = "Category")]
public int CategoryId { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
}
public class EditModel : PageModel
{
private readonly SupplyListCore22.Models.SupplyListsContext _context;
private readonly IHostingEnvironment _env;
public EditModel(SupplyListCore22.Models.SupplyListsContext context, IHostingEnvironment env)
{
_context = context;
_env = env;
}
[BindProperty]
public SupplyLists SupplyLists { get; set; }
[BindProperty]
public FileUpload FileUpload { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
SupplyLists = await _context.SupplyLists
.Include(s => s.Category).FirstOrDefaultAsync(m => m.Id == id);
if (SupplyLists == null)
{
return NotFound();
}
ViewData["CategoryId"] = new SelectList(_context.SupplyListCategory, "Id", "Category");
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
//if (!ModelState.IsValid)
//{
// return Page();
//}
_context.Attach(SupplyLists).State = EntityState.Modified;
await _context.SaveChangesAsync();
if (FileUpload.UploadSupplyList != null)
{
var fileUploadData = await utilities.utilities.ProcessFormFile(FileUpload.UploadSupplyList, ModelState);
if (ModelState.ErrorCount > 0)
{
ViewData["CategoryId"] = new SelectList(_context.SupplyListCategory, "Id", "Category");
return Page();
}
var sl = _context.SupplyLists.Find(SupplyLists.Id);
sl.ListBin = fileUploadData;
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
It set the ListBin to null in db which is not what I wanted when saving changes (I wanted to preserve the old value of ListBin in db).

json string downloaded with mising values c# webclient

I'm conding a rent car asp.net mvc application and I have a strange problem.
I used the skyscanner api to get the available cars list but the json string downloaded is always missing the attribute cars or there is cars that exist and are available.
string datacar = "";
String ch = "http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/" + ids + "/" + ide + "/" + dstart + "T" + tstart + "/" + dend + "T" + tend + "/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1";
Uri url = new Uri(ch);
// Uri url2 = new Uri("http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/27539733/27539733/2016-09-10T17:45/2016-09-17T17:45/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1");
CarModel model = new CarModel();
// for (int i = 0; i <= 20; i++)
// {
using (WebClient wc = new WebClient())
{
wc.Headers.Set("Content-Type", "application/json");
datacar = wc.DownloadString(url);
//datacar = wc.DownloadString(url2);
model = JsonConvert.DeserializeObject<CarModel>(datacar);
}
and here it is the carModel defintion
namespace carrent.Models
{
public class SubmittedQuery
{
public string market { get; set; }
public string currency { get; set; }
public string locale { get; set; }
public string pickup_place { get; set; }
public string dropoff_place { get; set; }
public string pickup_date_time { get; set; }
public string drop_off_date_time { get; set; }
public string driver_age { get; set; }
}
public class Image
{
public int id { get; set; }
public string url { get; set; }
}
public class CarClass
{
public int id { get; set; }
public int sort_order { get; set; }
public string name { get; set; }
}
public class DebugItem
{
public string type { get; set; }
public string title { get; set; }
public string content { get; set; }
}
public class CarModel
{
public SubmittedQuery submitted_query { get; set; }
public List<object> cars { get; set; }
public List<object> websites { get; set; }
public List<Image> images { get; set; }
public List<CarClass> car_classes { get; set; }
public List<DebugItem> debug_items { get; set; }
}
}
Ps: the strange thing in this problem is when I initialize an url (the url2) the code run perfectly
please guys help me to get the solution and thanks

MVC 4 EF5 Database First set Default Values in Partial Class

I'm new to MVC and trying to figure out how to set default values for partial classes. I have been searching for 2 days now, and can't get anything to work. Here is a supposed solution, but it doesn't work for me. I also tried the [DefaultValue(10)] data annotation.
Here is the auto generated partial class created from the edmx file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OTIS.Models.Admin
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Company
{
public Company()
{
this.Facilities = new HashSet<Facility>();
}
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public decimal ItemMargin { get; set; }
public decimal ServicesMargin { get; set; }
public decimal InvoiceTimeIncrement { get; set; }
public decimal CashDiscountPct { get; set; }
public decimal BaseServiceHourlyRate { get; set; }
public decimal HourlyPremiumRush { get; set; }
public decimal HourlyPremiumLate { get; set; }
public decimal HourlyPremiumCustomerMaterial { get; set; }
public int CreatedByID { get; set; }
public System.DateTime CreatedOn { get; set; }
public int ModifiedBy { get; set; }
public System.DateTime ModifiedOn { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual UserProfile UserProfile1 { get; set; }
public virtual ICollection<Facility> Facilities { get; set; }
}
}
Here is my partial class I created to add annotations.
namespace OTIS.Models.Admin
{
[MetadataType(typeof(CompanyMD))]
public partial class Company
{
//public Company()
//{
// //private System.DateTime _currentDateTime = DateTime.Now;
// ////Set Default Values
// //CreatedByID = (int)Membership.GetUser().ProviderUserKey;
// //CreatedOn = _currentDateTime;
// //ModifiedBy = (int)Membership.GetUser().ProviderUserKey;
// //ModifiedOn = _currentDateTime;
//}
public string FullAddress
{
get
{
return this.City + ", " + this.State + " " + this.PostalCode;
}
}
public class CompanyMD
{
private System.DateTime _currentDateTime = DateTime.Now;
private int _currentUser = (int)Membership.GetUser().ProviderUserKey;
[Display(Name = "Company ID")]
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Display(Name = "Address")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Zip")]
public string PostalCode { get; set; }
[Display(Name = "Address")]
public string FullAddress { get; set; }
[Display(Name = "Material Margin")]
public decimal ItemMargin { get; set; }
[Display(Name = "Overtime Margin")]
public decimal ServicesMargin { get; set; }
[Display(Name = "Invoice Hour Increment")]
public decimal InvoiceTimeIncrement { get; set; }
private decimal _cashDiscountPct;
[Display(Name = "Cash Discount %")]
[DisplayFormat(DataFormatString = "{0:P2}")]
public decimal CashDiscountPct
{
get { return _cashDiscountPct; }
set { _cashDiscountPct = value/100; }
}
[Display(Name = "Base Hourly Rate ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal BaseServiceHourlyRate { get; set; }
[Display(Name = "Rush Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal HourlyPremiumRush { get; set; }
[Display(Name = "Late Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
[DefaultValue(75)]
public decimal HourlyPremiumLate { get; set; }
[Display(Name = "Cust Material Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal HourlyPremiumCustomerMaterial { get; set; }
[Display(Name = "Created By")]
public int CreatedByID { get; set; }
//{
// get { return _currentUser; }
// set { _currentUser = value; }
//}
[Display(Name = "Created On")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
//[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime CreatedOn
{
get { return _currentDateTime; }
set { _currentDateTime = value; }
}
[Display(Name = "Modified By")]
public int ModifiedBy { get; set; }
//{
// get { return _currentUser; }
// set { _currentUser = value; }
//}
[Display(Name = "Modified On")]
public System.DateTime ModifiedOn
{
get { return _currentDateTime; }
set { _currentDateTime = value; }
}
}
}
}
And then in my controller, I instantiate a new instance of the class to initialize it, but the values I set don't get set.
//
// GET: /Company/Create
public ActionResult Create()
{
ViewBag.CreatedByID = new SelectList(db.UserProfiles, "UserId", "UserName");
ViewBag.ModifiedBy = new SelectList(db.UserProfiles, "UserId", "UserName");
Company newCompany = new Company();
return View(newCompany);
}
Sorry this is so late, but I just solved a similar scenario myself.
I think the problem is how you refer to the partial class. It should be an empty reference to the partial class with no code. EF uses this "declaration" to link your partial class to your metadata class. So, your metadata class should look like this:
namespace OTIS.Models.Admin
{
[MetadataType(typeof(CompanyMD))]
public partial class Company
{} // <-- note the close bracket!
public class CompanyMD
{
private System.DateTime _currentDateTime = DateTime.Now;
private int _currentUser = (int)Membership.GetUser().ProviderUserKey;
public string FullAddress
{
get
{
return this.City + ", " + this.State + " " + this.PostalCode;
}
}
[Display(Name = "Company ID")]
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
// ....etc.... removed for brevity
} // close metadata class
} // close namespace
Hope this helps!
I found I needed to handle this in my Repository Class in a GetNew() method that would populate the default values of a new instance of the class.

How to filter audio podcasts from iTunes Search API?

By searching for podcasts with the iTunes API (http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html) the result contains both audio and video podcasts. Is there any way to retrieve only audio podcasts from the API?
Thanks in advance :-)
From the documentation it doesn’t seem as if filtering audio and video podcasts is possible; however, you could loop through the resulting items and check whether each item is audio or video for filtering. You can do that be finding additional information from the RSS feed or by making another call to iTunes using the subscribePodcast url (see example).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using System.IO;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//Searching for Windows Weekly
string url = "https://itunes.apple.com/search?term=Windows%20Weekly&media=podcast&attibute=audio";
string json = FetchHTML(url);
JavaScriptSerializer s = new JavaScriptSerializer();
var result = s.Deserialize(json);
var audioOnly = new List();
foreach (var item in result.Results)
{
if (!IsVideo(item.TrackId))
{
audioOnly.Add(item);
}
}
foreach (var au in audioOnly)
{
Console.WriteLine(au.TrackName);
}
Console.ReadLine();
}
static bool IsVideo(string id)
{
string req = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/subscribePodcast?id=" + id + "&wasWarnedAboutPodcasts=true";
string xml = FetchHTML(req,true);
bool isVideo = false;
var re = XElement.Load(new StringReader(xml)).Elements("dict").Elements("dict");
bool next = false;
foreach (var e in re.Elements())
{
if (next)
{
//This is the is video value
isVideo = e.Name.LocalName.Trim().ToLower() == "true";
next = false;
break;
}
if (e.Value == "is-video")
{
next = true;
}
}
return isVideo;
}
static string FetchHTML(string url,bool doItAsITunes = false)
{
string htmlCode = "";
using (WebClient client = new WebClient())
{
if (doItAsITunes)
{
client.Headers.Add("user-agent", "iTunes/9.1.1");
}
htmlCode = client.DownloadString(url);
}
return htmlCode;
}
}
public class SearchResult
{
public SearchResult()
{
Results = new List();
}
public int ResultCount { set; get; }
public List Results { set; get; }
}
public class Item
{
public Item()
{
GenreIDs = new List();
Genres = new List();
}
public string WrapperType { set; get; }
public string Kind { set; get; }
public string ArtistID { set; get; }
public string CollectionID { set; get; }
public string TrackId { set; get; }
public string ArtistName { set; get; }
public string CollectionName { set; get; }
public string TrackName { set; get; }
public string CollectionCensoredName { set; get; }
public string TrackCensoredName { set; get; }
public string ArtistViewUrl { set; get; }
public string FeedUrl { set; get; }
public string TrackViewUrl { set; get; }
public string PreviewUrl { set; get; }
public string ArtworkUrl60 { set; get; }
public string ArtworkUrl100 { set; get; }
public float CollectionPrice { set; get; }
public float TrackPrice { set; get; }
public string CollectionExplicitness { set; get; }
public string TrackExplicitness { set; get; }
public string DiscCount { set; get; }
public string DiscNumber { set; get; }
public string TrackCount { set; get; }
public string TrackNumber { set; get; }
public string TrackTimeMillis { set; get; }
public string Country { set; get; }
public string Currency { set; get; }
public string PrimaryGenreName { set; get; }
public List GenreIDs { set; get; }
public List Genres { set; get; }
}
}
Yes. In regular serach you get everything:
https://itunes.apple.com/search?term=jack+johnson
But you can add some params to request for example (for your case)
&entity=song
So the request will be:
https://itunes.apple.com/search?term=jack+johnson&entity=song
For more look at Searching seaction in this docs