private LocalStateMachineEngine.ActionResult Create() { if (!m_ControlState.ItemID.IsNullOrEmpty()) { return(new LocalStateMachineEngine.ActionResult(new ApplicationException("Create error: a trailer is selected"), "Create")); } try { Partner _Partner = Partner.FindForUser(EDC, SPContext.Current.Web.CurrentUser); if (_Partner == null) { return(LocalStateMachineEngine.ActionResult.NotValidated("CreateuserMustBeExternalPartner".GetShepherdLocalizedString())); } Trailer _drv = new Trailer() { Trailer2PartnerTitle = _Partner }; LocalStateMachineEngine.ActionResult _rr = Update(_drv); if (!_rr.ActionSucceeded) { return(_rr); } EDC.Trailer.InsertOnSubmit(_drv); EDC.SubmitChangesSilently(RefreshMode.OverwriteCurrentValues); } catch (Exception ex) { return(new LocalStateMachineEngine.ActionResult(ex, "Create")); } return(LocalStateMachineEngine.ActionResult.Success); }
public void SetActionState(ActionState newActionState) { switch (currentActionState) { case ActionState.Free: lastSavePosition = transform.position; break; case ActionState.Falling: timeFalling = 0.0f; fallingSave.gameObject.SetActive(false); break; case ActionState.Hooked: lastSavePosition = transform.position; break; } switch (newActionState) { case ActionState.Free: gameObject.layer = LayerList.Player; player.hook.ResetAnchorPoints(); canDash = true; break; case ActionState.Falling: player.hook.ResetAnchorPoints(); gameObject.layer = LayerList.PlayerFalling; rigidbody2D.velocity = Vector2.zero; fallingSave.gameObject.SetActive(true); break; case ActionState.Dashing: gameObject.layer = LayerList.PlayerDashing; canDash = false; timeDashing = 0.0f; Vector2 dashDirection = (Vector2)crosshair.transform.localPosition - boxCollider2D.offset; dashTime = dashDirection.magnitude / dashSpeed; dashingDirection = dashDirection.normalized; Trailer.AddTrailer(spriteRenderer, dashTime, 0.05f, 1.0f, 10.0f, 0.1f); break; case ActionState.Swinging: gameObject.layer = LayerList.PlayerDashing; break; case ActionState.Pulling: gameObject.layer = LayerList.PlayerDashing; break; case ActionState.Repositioning: gameObject.layer = LayerList.PlayerDashing; canDash = false; timeRepositioning = 0.0f; break; } currentActionState = newActionState; }
public Trailer buildStandaardTrailer() { var T = new Trailer(); var lst = new List <Axle> { new Axle { AsType = AsType.VoorAs, Id = 1, SequenceNumber = 1, Size = 10, Afstand = 100, WheelBaseFactor = 1 }, new Axle { AsType = AsType.AchterAs, Id = 2, SequenceNumber = 2, Size = 10, Afstand = 3000, WheelBaseFactor = 1 } }; T.Axles = lst; return(T); }
//GET public ActionResult EditMovie(int?MovieId, int?TrailerId) { // send the Movie of the id that send to a EDIT view if ((TrailerId == null) || (MovieId == null)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Trailer Trailer = db.Trailer.Find(TrailerId); if (Trailer == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } foreach (var Movie in Trailer.Movies) { if (Movie.ID == MovieId) { return(View(Movie)); } } return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); }
public IActionResult Add(AddTrailerViewModel addtrailerViewModel) { if (ModelState.IsValid) { Trailer newTrailer = new Trailer { SerialNumber = addtrailerViewModel.SerialNumber, Make = addtrailerViewModel.Make, Model = addtrailerViewModel.Model, DotInsp = addtrailerViewModel.DotInsp, Plate = addtrailerViewModel.Plate, RegDate = addtrailerViewModel.RegDate, Year = addtrailerViewModel.Year, TrailerNumber = addtrailerViewModel.TrailerNumber }; //add to tractorData context.Trailers.Add(newTrailer); //always save changes context.SaveChanges(); return(Redirect("/Trailer")); } ; return(View(addtrailerViewModel)); }
// remove Trailer // GET public ActionResult DeleteTrailer(int?TrailerId, int?ActorId) { // delete the trailer from trailer table and from Actor table Actor Actor = db.Actor.Find(ActorId); Trailer Trailer = null; foreach (var item in Actor.Trailers) { if (item.ID == TrailerId) { Trailer = item; } } Actor.Trailers.Remove(Trailer); db.Trailer.Remove(Trailer); db.SaveChanges(); if (TrailerId == null || ActorId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(RedirectToAction("Details" + "/" + ActorId)); //after we delete we return to the normal page with the Actor ID and other Details about him with other movies }
// remove Movie public ActionResult DeleteMovie(int?MovieId, int?TrailerId) { //delete the Movie from the Movie table and the disc table Trailer Trailer = db.Trailer.Find(TrailerId); Movie Movie = null; foreach (var item in Trailer.Movies) { if (item.ID == MovieId) { Movie = item; } } Trailer.Movies.Remove(Movie); db.Movie.Remove(Movie); db.SaveChanges(); int ActorId = db.Trailer.Find(Movie.TrailerID).ActorID; if (TrailerId == null || MovieId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(RedirectToAction("Details" + "/" + ActorId)); }
public async Task <IActionResult> PutTrailer(int id, Trailer trailer) { if (id != trailer.trailerID) { return(BadRequest()); } _context.Entry(trailer).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrailerExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <Trailer> > PostTrailer(Trailer trailer) { _context.trailer.Add(trailer); await _context.SaveChangesAsync(); return(CreatedAtAction("GetTrailer", new { id = trailer.trailerID }, trailer)); }
private void Awake() { trailer = this; pool = new GameObject("Pool"); pool.transform.parent = transform; }
public IActionResult Add(AddOrderViewModel addOrderViewModel) { if (ModelState.IsValid) { Order newOrder = new Order() { OrderNumber = addOrderViewModel.OrderNumber, DueDate = addOrderViewModel.DueDate, //Driver = null, //matches the TrailerForLoad = context.Trailers.Where(x => x.TrailerID == addOrderViewModel.TrailerID).Single(), CustomerOrders = context.Customers.Single(x => x.CustomerID == addOrderViewModel.CustomerID), //Driver = context.Employees.ToList() }; context.Orders.Add(newOrder); trailerSelected = context.Trailers.Where(x => x.TrailerID == addOrderViewModel.TrailerID).Single(); //newOrder.TrailerForLoad = trailerSelected; trailerSelected.TrailerStatus = "Unavailable"; context.SaveChanges(); return(Redirect("/Order")); } return(View(addOrderViewModel)); }
public IActionResult Edit(EditOrderViewModel editOrderViewModel) { //trailerSelected = context.Trailers.Where(x => x.TrailerID == editOrderViewModel.TrailerForLoadID).Single(); Order order = context.Orders.FirstOrDefault(o => o.OrderID == editOrderViewModel.OrderID); Trailer newTrailer = context.Trailers.FirstOrDefault(t => t.TrailerID == editOrderViewModel.TrailerForLoadID); Trailer oldTrailer = context.Trailers.FirstOrDefault(t => t.TrailerID == order.TrailerForLoadID); order.OrderNumber = editOrderViewModel.OrderNumber; order.CustomerOrdersID = editOrderViewModel.CustomerOrdersID; //if (order.TrailerForLoadID != trailerSelected.TrailerID){ // order.TrailerForLoad.TrailerStatus = "Available"; // trailerSelected.TrailerStatus = "Unavailable"; //} if (oldTrailer.TrailerID != newTrailer.TrailerID) { oldTrailer.TrailerStatus = "Available"; newTrailer.TrailerStatus = "Unavailable"; } order.TrailerForLoadID = newTrailer.TrailerID; //editOrderViewModel.TrailerForLoadID; //save changes context.SaveChanges(); return(Redirect("/")); }
//Get: Trailer/ShowMatch public ActionResult ShowMatch(int?pnID) { if (!Request.IsAuthenticated) { return(RedirectToAction("Login", "Account")); } if (pnID == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Trailer oCurrentTrailer = oApplicationDBContext.Trailers.Find(pnID); if (oCurrentTrailer == null) { return(HttpNotFound()); } IEnumerable <Trailer> oTrailerQuery = from oTrailer in oApplicationDBContext.Trailers where oTrailer.NextLoadLocation == oCurrentTrailer.CurrentLoadDestination where oTrailer.CurrentLoadETA == oCurrentTrailer.CurrentLoadETA where oTrailer.ApplicationUserID != oCurrentTrailer.ApplicationUserID select oTrailer; return(View(oTrailerQuery.ToList())); }
public ActionResult AddTrailer(List<string> lifestyles = null, string name = "", string image = "", int tw = 0, int gtw = 0, string hitchClass = "", string shortDesc = "", string message = "") { // Save the category List<string> error_messages = new List<string>(); Trailer trailer = new Trailer(); try { trailer = TrailerModel.Save(lifestyles, 0, name, image, tw, gtw, hitchClass, shortDesc, message); } catch (Exception e) { error_messages.Add(e.Message); } // Make sure we didn't catch any errors if (error_messages.Count == 0 && trailer.trailerID > 0) { return RedirectToAction("Trailers"); } else { ViewBag.name = name; ViewBag.lifestyles = lifestyles; ViewBag.image = image; ViewBag.tw = tw; ViewBag.gtw = gtw; ViewBag.hitchClass = hitchClass; ViewBag.shortDesc = shortDesc; ViewBag.message = message; ViewBag.error_messages = error_messages; } List<DetailedCategories> cats = ProductCat.GetLifestyles(); ViewBag.cats = cats; return View(); }
/// <summary> /// The GetTrailerAndHandleTimeout /// </summary> /// <returns>The <see cref="Task"/></returns> private async Task GetTrailerAndHandleTimeout() { HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Get, $"api/movies/d8663e5e-7494-4f81-8739-6e0de1bea7ee/trailers/{Guid.NewGuid()}"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); try { using (HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { Stream stream = await response.Content.ReadAsStreamAsync(); response.EnsureSuccessStatusCode(); Trailer trailer = stream.ReadAndDeserializeFromJson <Trailer>(); } } catch (OperationCanceledException ocException) { Console.WriteLine($"An operation was cancelled with message {ocException.Message}."); // additional cleanup, ... } }
async Task RunAsync() { //client.BaseAddress = new Uri("http://tamasdeep1624-eval-test.apigee.net/proxyfleetapi"); Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; int CarrierID = (int)localSettings.Values["CarrierID"]; Trailer trailer = new Trailer { CarrierId = CarrierID, LicensePlate = license.Text, Make = make.Text, Vin = vinnum.Text, TrailerType = trailertype.Text, Year = year.Text, Model = model.Text }; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("apikey", "NbqYQDjspLDvorREUZAnyHZyCC3GoPGs"); string json = JsonConvert.SerializeObject(trailer); Debug.WriteLine(json); HttpContent content; HttpResponseMessage response; content = new StringContent(json, Encoding.UTF8, "application/json"); Debug.WriteLine(client.DefaultRequestHeaders); response = await client.PostAsync("http://tamasdeep1624-eval-test.apigee.net/proxyfleetapi/api/Trailers", content); if (response.IsSuccessStatusCode) { success.Text = "Successfully Added Trailers"; } Debug.WriteLine(response); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var result = new List <Trailer>(); JObject root = JObject.Load(reader); var trailers = root["items"].Children <JObject>(); foreach (var item in trailers) { var snippets = item["snippet"].ToArray(); Trailer trailer = new Trailer(); trailer.Description = snippets[2].Children().First().ToString(); trailer.PublishedAt = DateTime.Parse(snippets[0].Children().First().ToString()); var thumbnails = snippets[4].Children <JObject>(); var mediumThumbnail = thumbnails["medium"].ToArray().First()["url"]; trailer.ThumbnailUrl = mediumThumbnail.ToString(); trailer.VideoId = item["id"].ToArray().Children().Skip(1).First().ToString(); result.Add(trailer); } return(result); }
public void Edit(Trailer entity) { _context.Trailers.Attach(entity); var entry = _context.Entry(entity); entry.State = EntityState.Modified; _context.SaveChanges(); }
public async Task <IActionResult> Edit(int id, [Bind("TrailerID,Description,Model")] Trailer trailer) { if (id != trailer.TrailerID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(trailer); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrailerExists(trailer.TrailerID)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } return(View(trailer)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Img,Descripcion,LibroId")] Trailer trailer) { if (id != trailer.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(trailer); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrailerExists(trailer.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["LibroId"] = new SelectList(_context.Libros, "Id", "Descripcion", trailer.LibroId); return(View(trailer)); }
public async Task <IActionResult> Edit(int id, [Bind("TrailerId,Number,Massa,TireId")] Trailer trailer) { if (id != trailer.TrailerId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(trailer); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrailerExists(trailer.TrailerId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["TireId"] = new SelectList(_context.Tires, "TireId", "Name", trailer.TireId); return(View(trailer)); }
public void TruckTrailerTest() { var truck1 = new Truck { Id = "1" }; var truck2 = new Truck { Id = "2" }; var trailer = new Trailer(); var carPark = new CarPark { Cars = new ObservableCollection <Car> { truck1, truck2 } }; MEFValidationRules.RegisterType(typeof(TruckTrailerValidator)); var gr = carPark.EntityGraph(CarPark.Shape); truck1.Trailer = trailer; Assert.IsFalse(truck1.HasValidationErrors); Assert.IsFalse(truck2.HasValidationErrors); truck2.Trailer = trailer; Assert.IsTrue(truck1.HasValidationErrors); Assert.IsTrue(truck2.HasValidationErrors); MEFValidationRules.UnregisterType(typeof(TruckTrailerValidator)); }
public bool CustomUpdate(float time) { for (int i = 0; i < trailerParts.Count; i++) { TrailerPart trailerPart = trailerParts[i]; trailerPart.spriteRenderer.transform.localScale -= Vector3.one * scaleDecreasePerSecond * time; if (trailerPart.CustomUpdate(time)) { trailerParts.Remove(trailerPart); Trailer.GiveTrailerPart(trailerPart); Debug.Log("Test"); } } if ((timeLastPart -= time) <= 0.0f) { TrailerPart trailerPart = Trailer.TakeTrailerPart(); trailerPart.Init(originalRenderer, lifeTime); trailerPart.transform.parent = transform; trailerParts.Add(trailerPart); timeLastPart = partDistance; } if ((duration -= time) <= 0.0f) { return(true); } return(false); }
public AddTrailerViewModel(AddVehicleViewModel vehicle, Trailer defaultTrailer = null, Cargo defaultCargo = null) { this.Vehicle = vehicle; this.Trailers = Constants.AllTrailers; this.Cargos = Constants.AllCargo; this.Title = "Trailer"; if (vehicle.SelectedVehicleType.vtype == "War Rig") { this.Trailers.Add(new Trailer { ttype = "War Rig", cost = 0, slots = 0 }); this.SelectedTrailer = this.Trailers.Last(); } else { this.SelectedTrailer = this.Trailers.FirstOrDefault(x => x.ttype == defaultTrailer?.ttype) ?? Trailers[0]; } // default to none this.SelectedCargo = this.Cargos.FirstOrDefault(x => x.ctype == defaultCargo?.ctype) ?? Cargos[0]; this.CanSelectTrailer = this.SelectedTrailer?.ttype != "War Rig"; this.Id = Guid.NewGuid(); }
async Task RunAsync() { //client.BaseAddress = new Uri("http://tamasdeep1624-eval-test.apigee.net/proxyfleetapi"); Address carrierAddress = new Address { Name = "ABC trucking", Streetname = "162 West Point", City = "Scarborough", Email = "*****@*****.**", Postalcode = "h0h0h0", Province = "ON", Phone = "6476081234" }; Carrier carrier = new Carrier { Address = carrierAddress, Ctpat = "5784878", Mc = "787878", Cvor = "784512478", Usdot = "784521" }; Trailer trailer = new Trailer { Carrier = carrier, LicensePlate = license.Text, Make = make.Text, Vin = vinnum.Text, TrailerType = trailertype.Text, Year = year.Text, Model = model.Text, Location = carrier.Address.City + ", " + carrier.Address.Province }; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("apikey", "NbqYQDjspLDvorREUZAnyHZyCC3GoPGs"); string json = JsonConvert.SerializeObject(trailer); Debug.WriteLine(json); HttpContent content; HttpResponseMessage response; content = new StringContent(json, Encoding.UTF8, "application/json"); Debug.WriteLine(client.DefaultRequestHeaders); response = await client.PostAsync("http://tamasdeep1624-eval-test.apigee.net/proxyfleetapi/api/Trailers", content); if (response.IsSuccessStatusCode) { success.Text = "Successfully Added Trailers"; } Debug.WriteLine(response); }
public async Task <IActionResult> PutTrailer([FromRoute] int id, [FromBody] Trailer trailer) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != trailer.Id) { return(BadRequest()); } _context.Entry(trailer).State = EntityState.Modified; try { _context.Update(trailer); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrailerExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public TrailerDto Get(int id) { //Repo dependencies IRepo <Trailer> trailerRepo = this.unitOfWork.TrailerRepo; IRepo <Location> locationRepo = this.unitOfWork.LocationRepo; //Get trailer from repo Trailer trailer = trailerRepo.Get(id); //Ensure trailer exists if (trailer == null) { throw new DoesNotExistException(); } //Get location from repo Location location = locationRepo.Get(trailer.LocationId); //Create dto TrailerDto dto = Mapper.Map <TrailerDto>(trailer); if (location != null) { dto.Location = Mapper.Map <LocationDto>(location); } //Return dto return(dto); }
public void Create(Guid senderId, Vehicle vehicle, Trailer trailer) { var request = Request.Create(senderId, vehicle, trailer); requestRepository.Add(request); persistenceContext.SaveChanges(); }
public async Task <IActionResult> CreateTrailer(Guid movieId, [FromBody] Models.TrailerForCreation trailerForCreation) { // model validation if (trailerForCreation == null) { return(this.BadRequest()); } if (!this.ModelState.IsValid) { // return 422 - Unprocessable Entity when validation fails return(new UnprocessableEntityObjectResult(this.ModelState)); } Trailer trailer = this.mapper.Map <Trailer>(trailerForCreation); Trailer createdTrailer = await this.trailersRepository.AddTrailer(movieId, trailer); // no need to save, in this type of repo the trailer is // immediately persisted. // map the trailer from the repository to a shared model trailer return(this.CreatedAtRoute("GetTrailer", new { movieId, trailerId = createdTrailer.Id }, this.mapper.Map <Models.Trailer>(createdTrailer))); }
private void m_SaveButton_Click(object sender, EventArgs e) { try { Partner _prtn = Element.GetAtIndex <Partner>(EDC.Partner, m_PartnerTitle.SelectedValue); Trailer _nd = null; if (m_ItemID.Value.IsNullOrEmpty()) { _nd = new Trailer(); EDC.Trailer.InsertOnSubmit(_nd); } else { _nd = Element.GetAtIndex <Trailer>(EDC.Trailer, m_ItemID.Value); } _nd.AdditionalComments = this.m_Comments.Text; _nd.Tytuł = this.m_TruckTitle.Text; _nd.Trailer2PartnerTitle = _prtn; EDC.SubmitChanges(); SPUtility.Redirect(Request.Params["Source"], SPRedirectFlags.Default, HttpContext.Current); } catch (Exception ex) { ReportException("m_SaveButton_Click", ex); } }
protected void Page_Load(object sender, EventArgs e) { if (m_PartnerTitle.Items.Count == 0) { Trailer _trl = null; m_ItemID.Value = Request.Params["ID"]; if (!m_ItemID.Value.IsNullOrEmpty()) { _trl = Element.GetAtIndex <Trailer>(EDC.Trailer, m_ItemID.Value); m_Comments.Text = _trl.AdditionalComments; m_TruckTitle.Text = _trl.Tytuł; } Partner _Partner = Partner.FindForUser(EDC, SPContext.Current.Web.CurrentUser); if (_Partner == null) { m_PartnerTitle.AddPartner(true, _trl == null ? null : _trl.Trailer2PartnerTitle, EDC); } else { m_PartnerTitle.AddPartner(false, _Partner, EDC); } } this.m_CancelButton.Click += new EventHandler(m_CancelButton_Click); this.m_SaveButton.Click += new EventHandler(m_SaveButton_Click); }
/// <summary> /// Sets the current trailer. /// </summary> /// <param name="repository">Repository.</param> /// <param name="trailer">Trailer.</param> public static void SetCurrentTrailer(Repository repository, Trailer trailer) { var profile = repository.Profiles.FirstOrDefault(); profile.CurrentTrailerNumber = trailer.TrailerNumber; repository.SaveChanges(); }
internal Message( BasicHeader basicHeader, ApplicationHeader applicationHeader, UserHeader userHeader, TextBlock text, Trailer trailer) { if (basicHeader == null) { throw new ParserException("The Basic Header Block is mandatory."); } this.BasicHeader = basicHeader; this.ApplicationHeader = applicationHeader; this.UserHeader = userHeader; this.Text = text; this.Trailer = trailer; }
public Message() : base(new QuickFix.BeginString("FIXT.1.1")) { m_header = new Header(this); m_trailer = new Trailer(this); getHeader().setField( new QuickFix.ApplVerID("7") ); }
public Message() : base(new QuickFix.BeginString("FIX.4.2")) { m_header = new Header(this); m_trailer = new Trailer(this); }
public Message( QuickFix.MsgType msgType ) : base(new QuickFix.BeginString("FIX.4.2"), msgType) { m_header = new Header(this); m_trailer = new Trailer(this); }
//------------------------------------------------------------------------------------------- // Search and Download Trailerfiles via TMDB (mostly YouTube) //------------------------------------------------------------------------------------------- internal static void SearchAndDownloadTrailerOnlineTMDB(DataRow[] r1, int index, bool loadAllTrailers, bool interactive, string overridestoragepath) { //LogMyFilms.Debug("(SearchAndDownloadTrailerOnlineTMDB) - mastertitle : '" + MyFilms.r[index][MyFilms.conf.StrTitle1] + "'"); //if (Helper.FieldIsSet(MyFilms.conf.StrTitle2)) LogMyFilms.Debug("(SearchAndDownloadTrailerOnlineTMDB) - secondary title : '" + MyFilms.r[index][MyFilms.conf.StrTitle2] + "'"); //LogMyFilms.Debug("(SearchAndDownloadTrailerOnlineTMDB) - Cleaned Title : '" + MediaPortal.Util.Utils.FilterFileName(MyFilms.r[index][MyFilms.conf.StrTitle1].ToString().ToLower()) + "'"); string titlename = Helper.TitleWithoutGroupName(r1[index][MyFilms.conf.StrTitle1].ToString()); string titlename2 = (Helper.FieldIsSet(MyFilms.conf.StrTitle2)) ? Helper.TitleWithoutGroupName(r1[index][MyFilms.conf.StrTitle2].ToString()) : ""; string collectionname = Helper.TitleFirstGroupName(r1[index][MyFilms.conf.StrTitle1].ToString()); string path; #region Retrieve original directory of mediafiles try { path = r1[index][MyFilms.conf.StrStorage].ToString(); if (path.Contains(";")) path = path.Substring(0, path.IndexOf(";", StringComparison.Ordinal)); //path = Path.GetDirectoryName(path); //if (path == null || !Directory.Exists(path)) //{ // LogMyFilms.Warn("Directory of movie '" + titlename + "' doesn't exist anymore - check your DB"); // return; //} if (path.Contains("\\")) path = path.Substring(0, path.LastIndexOf("\\", StringComparison.Ordinal)); // LogMyFilms.Debug("(SearchAndDownloadTrailerOnlineTMDB) get media directory name: '" + path + "'"); } catch (Exception) { LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() error with directory of movie '" + titlename + "' - check your DB"); return; } #endregion string imdb = ""; #region get imdb number sor better search match if (!string.IsNullOrEmpty(r1[index]["IMDB_Id"].ToString())) imdb = r1[index]["IMDB_Id"].ToString(); else if (!string.IsNullOrEmpty(r1[index]["URL"].ToString())) { string urLstring = r1[index]["URL"].ToString(); var cutText = new Regex("" + @"tt\d{7}" + ""); var m = cutText.Match(urLstring); if (m.Success) imdb = m.Value; } #endregion int year; #region get local language string language = CultureInfo.CurrentCulture.Name.Substring(0, 2); // LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB - detected language = '" + language + "'"); #endregion LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - movie '" + titlename + "', media directory '" + path + "', language '" + language + "'"); var api = new Tmdb(MyFilms.TmdbApiKey, language); // var tmdbConf = api.GetConfiguration(); int selectedMovieId = 0; #region search matching TMDB movie id if (imdb.Contains("tt")) { TmdbMovie movie = api.GetMovieByIMDB(imdb); if (movie.id > 0) { selectedMovieId = movie.id; } } if (selectedMovieId == 0) // no movie found by imdb search { TmdbMovieSearch moviesfound; if (int.TryParse(r1[index]["Year"].ToString(), out year)) { moviesfound = api.SearchMovie(titlename, 1, "", null, year); if (moviesfound.results.Count == 0) moviesfound = api.SearchMovie(titlename, 1, null); } else { moviesfound = api.SearchMovie(r1[index][MyFilms.conf.StrTitle1].ToString(), 1, null); if (moviesfound.results.Count == 0 && titlename2.Length > 0) { if (int.TryParse(r1[index]["Year"].ToString(), out year)) { moviesfound = api.SearchMovie(titlename2, 1, "", null, year); if (moviesfound.results.Count == 0) moviesfound = api.SearchMovie(titlename2, 1, null); } } } if (moviesfound.results.Count == 1) { selectedMovieId = moviesfound.results[0].id; } else { LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - Movie Search Results: '" + moviesfound.total_results.ToString() + "' for movie '" + titlename + "'"); if (!interactive) return; else { if (moviesfound.results.Count == 0) { while(selectedMovieId == 0) { selectedMovieId = SearchTmdbMovie(titlename, titlename, titlename2, year, language, false); if (selectedMovieId == -1) return; // cancel search } } else { var choiceMovies = new List<TmdbMovie>(); var dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU); if (dlg == null) return; dlg.Reset(); dlg.SetHeading(GUILocalizeStrings.Get(10798992)); // Select movie ... foreach (TmdbMovie movieResult in moviesfound.results) { dlg.Add(movieResult.title + " (" + movieResult.release_date + ")"); choiceMovies.Add(movieResult); } dlg.DoModal(GUIWindowManager.ActiveWindow); if (dlg.SelectedLabel == -1) return; selectedMovieId = choiceMovies[dlg.SelectedLabel].id; } } } } #endregion if (selectedMovieId == 0) { LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB - no movie found - no trailers added to DL queue - returning"); if (interactive) GUIUtils.ShowNotifyDialog(GUILocalizeStrings.Get(10798995)); // No matching movie found ! return; } #region search trailers for movie var trailersfound = new List<Youtube>(); TmdbMovieTrailers trailers = api.GetMovieTrailers(selectedMovieId, language); // trailers in local language if (trailers.youtube.Count > 0) trailersfound.AddRange(trailers.youtube); LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - '" + trailers.youtube.Count + "' trailers found in local language ('" + language + "')"); if (language != "en") { trailers = api.GetMovieTrailers(selectedMovieId, "en"); // engish trailers if (trailers.youtube.Count > 0) trailersfound.AddRange(trailers.youtube); LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - '" + trailers.youtube.Count + "' trailers found in language 'en'"); } if (trailersfound.Count == 0) { LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - no trailers found - returning"); if (interactive) GUIUtils.ShowNotifyDialog(GUILocalizeStrings.Get(10798996)); // no trailers found ! } else { LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - '" + trailersfound.Count + "' trailers found"); var dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU); if (dlg == null) return; Youtube selectedTrailer = null; string selectedTrailerUrl = ""; string selectedQuality = ""; if (interactive) { #region build menu with available trailers var choiceView = new List<Youtube>(); dlg.Reset(); dlg.SetHeading(GUILocalizeStrings.Get(10798993)); // Select trailer ... dlg.Add("<" + GUILocalizeStrings.Get(10798997) + ">"); // load all choiceView.Add(new Youtube()); foreach (Youtube trailer in trailersfound) { dlg.Add(trailer.name + " (" + trailer.size + ")"); choiceView.Add(trailer); } //dlg.Add(GUILocalizeStrings.Get(10798711)); //search youtube trailer with onlinevideos //choiceView.Add("youtube"); dlg.DoModal(GUIWindowManager.ActiveWindow); if (dlg.SelectedLabel == -1) return; if (dlg.SelectedLabel > 0) { selectedTrailer = choiceView[dlg.SelectedLabel]; LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - selectedTrailer = '" + selectedTrailer.name + " (" + selectedTrailer.size + ")'"); } #endregion } #region select trailer format and quality in OV player factory if (selectedTrailer != null) { Dictionary<string, string> availableTrailerFiles = MyFilmsPlugin.Utils.OVplayer.GetYoutubeDownloadUrls("http://www.youtube.com/watch?v=" + selectedTrailer.source); var choiceView = new List<string>(); dlg.Reset(); dlg.SetHeading(GUILocalizeStrings.Get(10798994)); // Select quality ... foreach (KeyValuePair<string, string> availableTrailerFile in availableTrailerFiles) { dlg.Add(availableTrailerFile.Key); choiceView.Add(availableTrailerFile.Value); // this is the download URL } dlg.DoModal(GUIWindowManager.ActiveWindow); if (dlg.SelectedLabel == -1) return; selectedTrailerUrl = choiceView[dlg.SelectedLabel]; selectedQuality = dlg.SelectedLabelText; } #endregion #region download trailer string destinationDirectory; if (overridestoragepath != null) { string newpath = Path.Combine(overridestoragepath + @"MyFilms\", path.Substring(path.LastIndexOf("\\") + 1)); newpath = Path.Combine(newpath, "Trailer"); destinationDirectory = newpath; } else { destinationDirectory = Path.Combine(path, "Trailer"); } if (selectedTrailerUrl.Length > 0 && selectedTrailer != null) { var trailer = new Trailer(); trailer.MovieTitle = titlename; trailer.Trailername = selectedTrailer.name; trailer.OriginalUrl = "http://www.youtube.com/watch?v=" + selectedTrailer.source; trailer.SourceUrl = selectedTrailerUrl; trailer.Quality = selectedQuality; trailer.DestinationDirectory = destinationDirectory; // Path.Combine(Path.Combine(path, "Trailer"), (MediaPortal.Util.Utils.FilterFileName(titlename + " (trailer) " + selectedTrailer.name + " (" + dlg.SelectedLabelText.Replace(" ", "") + ")" + extension))); MyFilms.AddTrailerToDownloadQueue(trailer); LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - start loading single trailer '" + selectedTrailer.name + "' from URL: '" + selectedTrailerUrl + "'"); if (interactive) GUIUtils.ShowNotifyDialog(GUILocalizeStrings.Get(1079703)); // trailer addd to DL queue } else { for (int i = 0; i < trailersfound.Count; i++) { if (i < 2 || loadAllTrailers) { Dictionary<string, string> availableTrailerFiles = MyFilmsPlugin.Utils.OVplayer.GetYoutubeDownloadUrls("http://www.youtube.com/watch?v=" + trailersfound[i].source); string url = null; string quality = null; if (availableTrailerFiles != null && availableTrailerFiles.Count > 0) { //url = availableTrailerFiles.Last().Value; //quality = availableTrailerFiles.Last().Key; KeyValuePair<string, string> highestQualitySelection = MyFilmsPlugin.Utils.OVplayer.GetPreferredQualityOption(availableTrailerFiles, "FHD"); url = highestQualitySelection.Value; quality = highestQualitySelection.Key; LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - selected trailer with quality = '" + quality ?? "" + "', url = '" + url ?? "" + "'"); } else { LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - no download Url found - adding trailer without DL links for later processing from queue"); } var trailer = new Trailer(); trailer.MovieTitle = titlename; trailer.Trailername = trailersfound[i].name; trailer.OriginalUrl = "http://www.youtube.com/watch?v=" + trailersfound[i].source; trailer.SourceUrl = url; trailer.Quality = quality; trailer.DestinationDirectory = destinationDirectory; // filename: (MediaPortal.Util.Utils.FilterFileName(titlename + " (trailer) " + trailersfound[i].name + " (" + quality.Replace(" ", "") + ")" + extension)) LogMyFilms.Debug("SearchAndDownloadTrailerOnlineTMDB() - add trailer '#" + i + "'"); MyFilms.AddTrailerToDownloadQueue(trailer); } } } #endregion } #endregion }
/// <summary> /// Imports movies and trailers records into the code-first database, using two json files as source. /// </summary> /// <param name="jsonMovies"></param> /// <param name="jsonTrailers"></param> public void ImportMoviesAndTrailers(string jsonMovies, string jsonTrailers) { this.db.Configuration.ValidateOnSaveEnabled = false; var movies = GetMovies(jsonMovies); var trailers = GetTrailers(jsonTrailers); var actors = new Dictionary<string, Models.Actor>(); var genres = new Dictionary<string, Genre>(); var counta = 0; foreach (var currentMovie in movies) { var first = trailers.FirstOrDefault(x => x.title == currentMovie.title); var trailerUrl = first == null ? EmergencyTrailer : first.videoURL; var trailer = new Trailer() { Url = trailerUrl }; this.db.Trailers.Add(trailer); decimal result = 0M; decimal.TryParse(currentMovie.rating, out result); var movieToAdd = new Movie() { Description = currentMovie.plot, Title = currentMovie.title, ImageUrl = currentMovie.urlPoster, Rating = result, CountRating = rnd.Next(200, 1000), ReleaseDate = currentMovie.releaseDate.ToDateTime().Sqlize(), Restriction = RestrictionMapping.ContainsKey(currentMovie.rated.ToLower()) ? RestrictionMapping[currentMovie.rated.ToLower()] : Restrictions.NotRestricted, Duration = currentMovie.runtime == null || currentMovie.runtime.Length == 0 ? 90 : int.Parse(currentMovie.runtime[0].Split(' ')[0]) }; Console.WriteLine("Movie added"); trailer.ReleaseDate = movieToAdd.ReleaseDate.AddMonths(-6); this.db.Movies.Add(movieToAdd); if (currentMovie.actors != null) { var addedActorsCount = 0; foreach (var currentActor in currentMovie.actors) { var currentActorNames = currentActor.actorName.Split(' '); var firstname = currentActorNames[0]; var lastname = currentActorNames[currentActorNames.Length == 1 ? 0 : 1]; if (!actors.ContainsKey(firstname + " " + lastname)) { var actorToAdd = new Models.Actor() { FirstName = firstname, LastName = lastname, FullName = currentActor.actorName }; actors.Add(actorToAdd.FirstName + " " + actorToAdd.LastName, actorToAdd); this.db.Actors.Add(actorToAdd); addedActorsCount++; } movieToAdd.Actors.Add(actors[firstname + " " + lastname]); if(addedActorsCount == 4) { break; } } } foreach (var currentGenre in currentMovie.genres) { if (!genres.ContainsKey(currentGenre)) { var newGenre = new Genre() { Name = currentGenre }; genres.Add(currentGenre, newGenre); this.db.Genres.Add(genres[currentGenre]); } movieToAdd.Genres.Add(genres[currentGenre]); genres[currentGenre].Movies.Add(movieToAdd); } movieToAdd.Trailers.Add(trailer); this.db.Movies.Add(movieToAdd); if (counta++ % 5 == 4) { this.db.SaveChanges(); Console.Clear(); Console.SetCursorPosition(0, 0); Console.WriteLine(counta + " items added"); } } Console.WriteLine("data from from json imported."); }
public void Add(Trailer entity) { _context.Trailers.Add(entity); _context.SaveChanges(); }