//test
        public string httpRequest(string url)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.Timeout = 3000; //3s

            string responseString = ""; //resp string

            try
            {
                WebResponse response = httpWebRequest.GetResponse();

                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);

                string responseFromServer = reader.ReadToEnd();

                reader.Close();
                response.Close();

                responseString = responseFromServer;
            }
            catch (System.Net.WebException)
            {
                _status = FetchResult.ConnectionError;
                return "";
            }

            _status = FetchResult.Success;
            return responseString;
        }
Ejemplo n.º 2
0
        protected override FetchResult <BatchReportVM> _fetch(int?Skip, int?Count, NgControllerInstruct[] filters)
        {
            using (var l = new MessagesModuleLogic()) {
                var query = l.GetFilteredQueryable <tblMessageBatch>(filters);
                int count = query.Count();
                query = query.OrderByDescending(x => x.FinishedOn).ThenByDescending(x => x.CreatedOn);
                if (Skip != null)
                {
                    query = query.Skip(Skip.Value);
                }
                if (Count != null)
                {
                    query = query.Take(Count.Value);
                }
                var queryResult = query.ToList().Select(x => PocoConstructor.MakeFromObj(x, BatchReportVM.tblMessageBatchPR));

                return(FetchResult <BatchReportVM> .Succes(queryResult, count));
            }
        }
Ejemplo n.º 3
0
        void UpdateCachedAssets()
        {
            // Update only if the view is visible.
            bool isViewVisible = IsViewLoaded && View.Window != null;

            if (!isViewVisible)
            {
                return;
            }

            // The preheat window is twice the height of the visible rect.
            var visibleRect = new CGRect(CollectionView.ContentOffset, CollectionView.Bounds.Size);
            var preheatRect = visibleRect.Inset(0f, -0.5f * visibleRect.Height);

            // Update only if the visible area is significantly different from the last preheated area.
            nfloat delta = NMath.Abs(preheatRect.GetMidY() - previousPreheatRect.GetMidY());

            if (delta <= CollectionView.Bounds.Height / 3f)
            {
                return;
            }

            // Compute the assets to start caching and to stop caching.
            var rects       = ComputeDifferenceBetweenRect(previousPreheatRect, preheatRect);
            var addedAssets = rects.added
                              .SelectMany(rect => CollectionView.GetIndexPaths(rect))
                              .Select(indexPath => FetchResult.ObjectAt(indexPath.Item))
                              .Cast <PHAsset> ()
                              .ToArray();

            var removedAssets = rects.removed
                                .SelectMany(rect => CollectionView.GetIndexPaths(rect))
                                .Select(indexPath => FetchResult.ObjectAt(indexPath.Item))
                                .Cast <PHAsset> ()
                                .ToArray();

            // Update the assets the PHCachingImageManager is caching.
            imageManager.StartCaching(addedAssets, thumbnailSize, PHImageContentMode.AspectFill, null);
            imageManager.StopCaching(removedAssets, thumbnailSize, PHImageContentMode.AspectFill, null);

            // Store the preheat rect to compare against in the future.
            previousPreheatRect = preheatRect;
        }
Ejemplo n.º 4
0
        public FetchResult <Flight> FetchFlights(string whereClause = null, SqlParameter[] sqlParams = null)
        {
            JoinableDatabaseTable flightSourceTable = new JoinableDatabaseTable("flights");

            flightSourceTable.AddAttribute("flights.Id");
            flightSourceTable.AddAttribute("depAirport.Country");
            flightSourceTable.AddAttribute("depAirport.City");
            flightSourceTable.AddAttribute("destAirport.Country");
            flightSourceTable.AddAttribute("destAirport.City");
            flightSourceTable.AddAttribute("TimeOfDeparture");
            flightSourceTable.AddAttribute("TimeOfArrival");
            flightSourceTable.AddAttribute("SeatRows");
            flightSourceTable.AddAttribute("SeatsPerRow");

            flightSourceTable.CreateJoin("airports", "DepartureAirportId", "Id", "depAirport");
            flightSourceTable.CreateJoin("airports", "DestinationAirportId", "Id", "destAirport");

            ObjectRelationalMapper <Flight> flightsMapper = new ObjectRelationalMapper <Flight>(Config.DB_CONNECTION_STRING, flightSourceTable);

            FetchResult <Flight> flightsFetched = flightsMapper.Fetch(attr => {
                Airport departureAp   = new Airport(attr["depAirport.Country"].ToString(), attr["depAirport.City"].ToString());
                Airport destinationAp = new Airport(attr["destAirport.Country"].ToString(), attr["destAirport.City"].ToString());

                return
                (new Flight((int)attr["flights.Id"],
                            (DateTime)attr["TimeOfDeparture"],
                            (DateTime)attr["TimeOfArrival"],
                            departureAp, destinationAp,
                            (int)attr["SeatRows"],
                            (int)attr["SeatsPerRow"]));
            }, whereClause, sqlParams);

            if (!flightsFetched.HasError)
            {
                foreach (Flight flight in flightsFetched.RetrievedItems)
                {
                    flight.TakenSeatNumbers = FetchTakenSeats(flight.Id);
                }
            }

            return(flightsFetched);
        }
Ejemplo n.º 5
0
        public void testWrite1()
        {
            // Create a small bundle, an early commit
            byte[] bundle = makeBundle("refs/heads/aa", db.Resolve("a").Name, null);

            // Then we clone a new repo from that bundle and do a simple test. This
            // makes sure
            // we could Read the bundle we created.
            Core.Repository newRepo     = createBareRepository();
            FetchResult     fetchResult = fetchFromBundle(newRepo, bundle);

            Core.Ref advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/aa");

            Assert.AreEqual(db.Resolve("a").Name, advertisedRef.ObjectId.Name);
            Assert.AreEqual(db.Resolve("a").Name, newRepo.Resolve("refs/heads/aa").Name);
            Assert.IsNull(newRepo.Resolve("refs/heads/a"));

            // Next an incremental bundle
            bundle = makeBundle(
                "refs/heads/cc",
                db.Resolve("c").Name,
                new GitSharp.Core.RevWalk.RevWalk(db).parseCommit(db.Resolve("a").ToObjectId()));

            fetchResult   = fetchFromBundle(newRepo, bundle);
            advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/cc");
            Assert.AreEqual(db.Resolve("c").Name, advertisedRef.ObjectId.Name);
            Assert.AreEqual(db.Resolve("c").Name, newRepo.Resolve("refs/heads/cc").Name);
            Assert.IsNull(newRepo.Resolve("refs/heads/c"));
            Assert.IsNull(newRepo.Resolve("refs/heads/a")); // still unknown

            try
            {
                // Check that we actually needed the first bundle
                Core.Repository newRepo2 = createBareRepository();
                fetchResult = fetchFromBundle(newRepo2, bundle);
                Assert.Fail("We should not be able to fetch from bundle with prerequisites that are not fulfilled");
            }
            catch (MissingBundlePrerequisiteException e)
            {
                Assert.IsTrue(e.Message.IndexOf(db.Resolve("refs/heads/a").Name) >= 0);
            }
        }
Ejemplo n.º 6
0
        public Task HandleAsync(FetchResult fetchResult)
        {
            if (fetchResult.ContentType == ContentType.Json)
            {
                if (fetchResult.DeserializedObject != null)
                {
                    var jsonSerializerSetting = new JsonSerializerSettings();
                    jsonSerializerSetting.Converters.Add(new StringEnumConverter());
                    jsonSerializerSetting.Formatting = Formatting.Indented;

                    var json = JsonConvert.SerializeObject(fetchResult.DeserializedObject, jsonSerializerSetting);
                    Console.WriteLine(json);
                }
            }
            else if (fetchResult.ContentType == ContentType.Html)
            {
                Console.WriteLine(fetchResult.Content);
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 7
0
        /// <exception cref="NGit.Errors.MissingObjectException"></exception>
        /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        private void Checkout(Repository clonedRepo, FetchResult result)
        {
            Ref head = result.GetAdvertisedRef(branch);

            if (branch.Equals(Constants.HEAD))
            {
                Ref foundBranch = FindBranchToCheckout(result);
                if (foundBranch != null)
                {
                    head = foundBranch;
                }
            }
            if (head == null || head.GetObjectId() == null)
            {
                return;
            }
            // throw exception?
            if (head.GetName().StartsWith(Constants.R_HEADS))
            {
                RefUpdate newHead = clonedRepo.UpdateRef(Constants.HEAD);
                newHead.DisableRefLog();
                newHead.Link(head.GetName());
                AddMergeConfig(clonedRepo, head);
            }
            RevCommit commit   = ParseCommit(clonedRepo, head);
            bool      detached = !head.GetName().StartsWith(Constants.R_HEADS);
            RefUpdate u        = clonedRepo.UpdateRef(Constants.HEAD, detached);

            u.SetNewObjectId(commit.Id);
            u.ForceUpdate();
            if (!bare)
            {
                DirCache         dc = clonedRepo.LockDirCache();
                DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc, commit.Tree);
                co.Checkout();
                if (cloneSubmodules)
                {
                    CloneSubmodules(clonedRepo);
                }
            }
        }
Ejemplo n.º 8
0
        public NGitPullResultAdapter(PullCommand pullCommand)
        {
            var stringWriter = new StringWriter();
            var textMonitor  = new  TextProgressMonitor(stringWriter);

            pullCommand.SetProgressMonitor(textMonitor);

            var pullResponse = pullCommand.Call();

            Success = pullResponse.IsSuccessful();

            var parsed = pullResponse.ToString()
                         .Replace("with base", Environment.NewLine + "with base")
                         .Replace("using", Environment.NewLine + "using");

            Msg = stringWriter.ToString() + newLine + " ......... " + newLine
                  + parsed;

//			string fetchedFrom = pullResponse.GetFetchedFrom();
//			Msg += newLine + "fetchedFrom: " + fetchedFrom;

            FetchResult fetchResult = pullResponse.GetFetchResult();
//
//			var trackingRefUpdates = fetchResult.GetTrackingRefUpdates ();
//			foreach (var trackingRefUpdate in trackingRefUpdates) {
//				var oldObjectId = trackingRefUpdate.GetOldObjectId ().Name;
//				var newObjectId = trackingRefUpdate.GetNewObjectId ().Name;
//				Msg += newLine + "Old object id: " + oldObjectId;
//				Msg += newLine + "New object id: " + newObjectId;
//
//				var refResult = trackingRefUpdate.GetResult ();
//				Msg += newLine + "refResult: " + refResult;
//			}

            var msg = fetchResult.GetMessages();

            if (!string.IsNullOrEmpty(msg))
            {
                Msg += newLine + "Result: " + newLine + msg;
            }
        }
Ejemplo n.º 9
0
 public RemoteFetchData Fetch(RemoteRowHeader header, out Guid[] bookmarks, int count, bool skipCurrent, ProcessCallInfo callInfo)
 {
     try
     {
         var          channel = GetServiceInterface();
         IAsyncResult result  = channel.BeginFetchSpecific(CursorHandle, callInfo, header, count, skipCurrent, null, null);
         result.AsyncWaitHandle.WaitOne();
         FetchResult fetchResult = channel.EndFetchSpecific(result);
         bookmarks = fetchResult.Bookmarks;
         return(fetchResult.FetchData);
     }
     catch (FaultException <DataphorFault> fault)
     {
         throw DataphorFaultUtility.FaultToException(fault.Detail);
     }
     catch (CommunicationException ce)
     {
         ReportCommunicationError();
         throw new ServerException(ServerException.Codes.CommunicationFailure, ErrorSeverity.Environment, ce);
     }
 }
Ejemplo n.º 10
0
        // Tax Codes for lines on Transactions

        public static ListPage <TaxCode> Map(FetchResult <TaxCodeModel> codes, TaxCodesListArgs args)
        {
            var items = codes.value.Select(code => new TaxCode
            {
                Category    = args.CodeCategory,
                Code        = code.taxCode,
                Description = code.description
            }).ToList();
            var listPage = new ListPage <TaxCode>
            {
                Items = items,
                Meta  = new ListPageMeta
                {
                    Page       = (int)Math.Ceiling((double)args.Skip / args.Top) + 1,
                    PageSize   = 100,
                    TotalCount = codes.count,
                }
            };

            return(listPage);
        }
Ejemplo n.º 11
0
        public async Task <FetchResult <User> > GetUserAsync(int userId)
        {
            var fetchResult = new FetchResult <User>();

            try
            {
                fetchResult.Result = await _appDbContext.Users.GetUserAsync(userId);

                if (fetchResult.Result == null)
                {
                    _logger.LogDebug($"[{ErrorCode.UserService001}] User with Id:{userId} does not exist.");
                    fetchResult.Errors.Add(new Error(ErrorCode.UserService001, $"User with Id:{userId} does not exist."));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"[{ErrorCode.UserService002}] {ex.Message}");
            }

            return(fetchResult);
        }
Ejemplo n.º 12
0
        public FetchResult <IEnumerable <string> > GetHints(string word, Guid indexPk)
        {
            FetchResult <IEnumerable <string> > result;

            try
            {
                word.RequireNotNullOrEmpty(nameof(word));

                if (word.Length > CodeIndexBuilder.HintWordMaxLength)
                {
                    word = word.Substring(0, CodeIndexBuilder.HintWordMaxLength);
                }

                result = new FetchResult <IEnumerable <string> >
                {
                    Result = CodeIndexSearcher.GetHints(word, indexPk),
                    Status = new Status
                    {
                        Success = true
                    }
                };

                Log.LogDebug($"Get Hints For '{word}' successful");
            }
            catch (Exception ex)
            {
                result = new FetchResult <IEnumerable <string> >
                {
                    Status = new Status
                    {
                        Success    = false,
                        StatusDesc = ex.ToString()
                    }
                };

                Log.LogDebug(ex, $"Get Hints For '{word}' failed");
            }

            return(result);
        }
Ejemplo n.º 13
0
        public async Task <FetchResult <NpvVariable> > GetNpvVariableById(int id)
        {
            var fetchResult = new FetchResult <NpvVariable>();

            try
            {
                fetchResult.Data = await _appDbContext.NpvVariables.GetNpvVariableById(id);

                if (fetchResult.Data == null)
                {
                    // do logging here
                    fetchResult.Errors.Add(new Error(ErrorCodes.NpvVariableServiceError005, "NPV Variable does not exists."));
                }
            }
            catch (Exception ex)
            {
                // do logging here
                fetchResult.Errors.Add(new Error(ErrorCodes.NpvVariableServiceError003));
            }

            return(fetchResult);
        }
Ejemplo n.º 14
0
 private void TryDetectContentType(FetchResult fetchResult)
 {
     if (fetchResult != null && fetchResult.Exceptions.Count == 0)
     {
         if (fetchResult.RequestTask.ResultContentType == ContentType.Auto)
         {
             try
             {
                 JToken.Parse(fetchResult.Content);
                 fetchResult.ContentType = ContentType.Json;
             }
             catch
             {
                 fetchResult.ContentType = ContentType.Html;
             }
         }
         else
         {
             fetchResult.ContentType = fetchResult.RequestTask.ResultContentType;
         }
     }
 }
Ejemplo n.º 15
0
        public IEnumerable <SeatNumber> FetchTakenSeats(int flightId)
        {
            DatabaseTable seatsTable = new DatabaseTable("seats");

            seatsTable.AddAttribute("PosX");
            seatsTable.AddAttribute("PosY");
            seatsTable.AddAttribute("Id");
            seatsTable.AddAttribute("FlightId");
            seatsTable.AddAttribute("PassengerId");

            ObjectRelationalMapper <SeatNumber> seatNumberMapper = new ObjectRelationalMapper <SeatNumber>(Config.DB_CONNECTION_STRING, seatsTable);

            string whereClause = "FlightId = " + flightId;
            FetchResult <SeatNumber> fetchResultSeatNumbers = seatNumberMapper.Fetch(attr => new SeatNumber((int)attr["PosX"], (int)attr["PosY"]), whereClause);

            if (fetchResultSeatNumbers.HasError)
            {
                return(new SeatNumber[0]);
            }

            return(fetchResultSeatNumbers.RetrievedItems);
        }
Ejemplo n.º 16
0
        private static GitSharp.Core.Ref guessHEAD(FetchResult result)
        {
            // Some transports allow us to see where HEAD points to. If that is not so,
            // we'll have to guess.
            GitSharp.Core.Ref head = result.GetAdvertisedRef(Constants.HEAD);
            if (head != null)
            {
                return(head);
            }

            var availableHeads = result.AdvertisedRefs.Where(r => r.Name.StartsWith(Constants.R_HEADS));

            // master is our preferred guess, so if it's advertised, return that.
            GitSharp.Core.Ref guessedHead = result.GetAdvertisedRef(Constants.R_HEADS + Constants.MASTER);
            if (guessedHead == null && availableHeads.Count() > 0)
            {
                // if master is not advertised, return any other head.
                guessedHead = availableHeads.First();
            }

            return(guessedHead);
        }
Ejemplo n.º 17
0
        /// <exception cref="System.Exception"></exception>
        private Git SetUpRepoWithRemote()
        {
            Repository remoteRepository = CreateWorkRepository();
            Git        remoteGit        = new Git(remoteRepository);

            // commit something
            WriteTrashFile("Test.txt", "Hello world");
            remoteGit.Add().AddFilepattern("Test.txt").Call();
            initialCommit = remoteGit.Commit().SetMessage("Initial commit").Call();
            WriteTrashFile("Test.txt", "Some change");
            remoteGit.Add().AddFilepattern("Test.txt").Call();
            secondCommit = remoteGit.Commit().SetMessage("Second commit").Call();
            // create a master branch
            RefUpdate rup = remoteRepository.UpdateRef("refs/heads/master");

            rup.SetNewObjectId(initialCommit.Id);
            rup.ForceUpdate();
            Repository   localRepository = CreateWorkRepository();
            Git          localGit        = new Git(localRepository);
            StoredConfig config          = localRepository.GetConfig();
            RemoteConfig rc = new RemoteConfig(config, "origin");

            rc.AddURI(new URIish(remoteRepository.Directory.GetPath()));
            rc.AddFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
            rc.Update(config);
            config.Save();
            FetchResult res = localGit.Fetch().SetRemote("origin").Call();

            NUnit.Framework.Assert.IsFalse(res.GetTrackingRefUpdates().IsEmpty());
            rup = localRepository.UpdateRef("refs/heads/master");
            rup.SetNewObjectId(initialCommit.Id);
            rup.ForceUpdate();
            rup = localRepository.UpdateRef(Constants.HEAD);
            rup.Link("refs/heads/master");
            rup.SetNewObjectId(initialCommit.Id);
            rup.Update();
            return(localGit);
        }
Ejemplo n.º 18
0
        protected override FetchResult <MessageScheduleVM> _fetch(int?Skip, int?Count, NgControllerInstruct[] filters)
        {
            using (var l = new MessagesModuleLogic()) {
                IQueryable <tblMessageSchedule> baseQuery = null;

                //Special instructions filtration.
                //this SHOULD be incapsulated sometime.
                //Special instructions is query filters that not relies on main enitity POCO parametrs
                //such as tblMessageSchedule in this case, and we need special logick to handle it,
                var specialInstructions = filters == null ? null : filters.Where(x => x.isSpecial);
                NgControllerInstruct filter;
                if (specialInstructions != null &&
                    (filter = specialInstructions.FirstOrDefault(x => x.key == "TemplateName")) != null)
                {
                    baseQuery = l.GetFilteredQueryable <tblTemplate>
                                    (new[] {
                        new NgControllerInstruct {
                            key = "Name", op = filter.op, val = filter.val
                        }
                    }).SelectMany(x => x.tblMessageSchedules);
                }

                var query = l.GetFilteredQueryable(filters, baseQuery);
                int count = query.Count();
                query = query.OrderByDescending(x => x.ScheduleDate);
                if (Skip != null)
                {
                    query = query.Skip(Skip.Value);
                }
                if (Count != null)
                {
                    query = query.Take(Count.Value);
                }
                var queryResult = query.ToList().Select(x => PocoConstructor.MakeFromObj(x, MessageScheduleVM.tblMessageSchedulePR));

                return(FetchResult <MessageScheduleVM> .Succes(queryResult, count));
            }
        }
Ejemplo n.º 19
0
        public async Task <List <Item> > FetchAllAsync(SearchState initialState, CancellationToken cancellationToken)
        {
            var ret = new List <Item>();
            // UPDATE: if server sends 'itemListSupported', we pass it in the SearchState
            FetchResult result = await FetchAsync(initialState, cancellationToken);

            while (result.State != FetchState.ENDED)
            {
                switch (result.State)
                {
                case FetchState.ITEMS:
                    ret.Add(result.Item);
                    break;

                case FetchState.PENDING:
                    await Task.Delay(100, cancellationToken);

                    break;

                // UPDATE: handle ITEMLIST
                case FetchState.ITEMLIST:
                    ret.AddRange(result.ItemList);
                    break;

                case FetchState.ENDED:
                    break;

                default:
                    Console.WriteLine($"Unsupported FetchState value encountered: {result.State.ToString()}");
                    Console.WriteLine("Ending fetch cycle early.");
                    return(ret);
                }

                result = await FetchAsync(result.NextSearchState, cancellationToken);
            }

            return(ret);
        }
Ejemplo n.º 20
0
        private void PopulateFlightList()
        {
            FetchResult <Flight> flightsFetched = dbAccess.FetchFlights();

            if (flightsFetched.HasError)
            {
                MessageBox.Show("Leider ist ein Fehler beim Abrufen der Flüge aufgetreten.\r\n\r\n Details:\r\n" + flightsFetched.ErrorDetails, "Fehler");
            }
            else
            {
                _flights.Clear();

                foreach (Flight flight in flightsFetched.RetrievedItems)
                {
                    _flights.Add(flight);
                }
            }

            if (lvwFlights.Items.Count > 0)
            {
                lvwFlights.SelectedIndex = 0;
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Executes the
 /// <code>Clone</code>
 /// command.
 /// </summary>
 /// <returns>
 /// the newly created
 /// <code>Git</code>
 /// object with associated repository
 /// </returns>
 /// <exception cref="NGit.Api.Errors.InvalidRemoteException">NGit.Api.Errors.InvalidRemoteException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.TransportException">NGit.Api.Errors.TransportException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException
 ///     </exception>
 public override Git Call()
 {
     try
     {
         URIish      u          = new URIish(uri);
         Repository  repository = Init(u);
         FetchResult result     = Fetch(repository, u);
         if (!noCheckout)
         {
             Checkout(repository, result);
         }
         return(new Git(repository));
     }
     catch (IOException ioe)
     {
         throw new JGitInternalException(ioe.Message, ioe);
     }
     catch (URISyntaxException)
     {
         throw new InvalidRemoteException(MessageFormat.Format(JGitText.Get().invalidRemote
                                                               , remote));
     }
 }
Ejemplo n.º 22
0
        public void FetchTest()
        {
            Config config = new Config();

            config.Zone = Zone.ZONE_CN_East;
            Mac           mac           = new Mac(AccessKey, SecretKey);
            BucketManager bucketManager = new BucketManager(mac, config);
            string        resUrl        = "http://devtools.qiniu.com/qiniu.png";
            FetchResult   ret           = bucketManager.Fetch(resUrl, Bucket, "qiniu-fetch.png");

            if (ret.Code != (int)HttpCode.OK)
            {
                Assert.Fail("fetch error: " + ret.ToString());
            }
            Console.WriteLine(ret.ToString());

            ret = bucketManager.Fetch(resUrl, Bucket, null);
            if (ret.Code != (int)HttpCode.OK)
            {
                Assert.Fail("fetch error: " + ret.ToString());
            }
            Console.WriteLine(ret.ToString());
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Executes the
 /// <code>Clone</code>
 /// command.
 /// </summary>
 /// <exception cref="NGit.Api.Errors.JGitInternalException">if the repository can't be created
 ///     </exception>
 /// <returns>
 /// the newly created
 /// <code>Git</code>
 /// object with associated repository
 /// </returns>
 public virtual Git Call()
 {
     try
     {
         URIish      u          = new URIish(uri);
         Repository  repository = Init(u);
         FetchResult result     = Fetch(repository, u);
         Checkout(repository, result);
         return(new Git(repository));
     }
     catch (IOException ioe)
     {
         throw new JGitInternalException(ioe.Message, ioe);
     }
     catch (InvalidRemoteException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
     catch (URISyntaxException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
 }
Ejemplo n.º 24
0
        public FetchResult <Booking> FetchBookings(string whereClause = null, SqlParameter[] sqlParams = null)
        {
            JoinableDatabaseTable bookingSourceTable = new JoinableDatabaseTable("bookings");

            bookingSourceTable.AddAttribute("bookings.Id");
            bookingSourceTable.AddAttribute("bookings.PassengerId");
            bookingSourceTable.AddAttribute("passengers.Title");
            bookingSourceTable.AddAttribute("passengers.FirstName");
            bookingSourceTable.AddAttribute("passengers.LastName");
            bookingSourceTable.AddAttribute("bookings.FlightId");
            bookingSourceTable.AddAttribute("depAirport.Country");
            bookingSourceTable.AddAttribute("depAirport.City");
            bookingSourceTable.AddAttribute("destAirport.Country");
            bookingSourceTable.AddAttribute("destAirport.City");
            bookingSourceTable.AddAttribute("flights.TimeOfDeparture");
            bookingSourceTable.AddAttribute("flights.TimeOfArrival");
            bookingSourceTable.AddAttribute("flights.SeatRows");
            bookingSourceTable.AddAttribute("flights.SeatsPerRow");
            bookingSourceTable.AddAttribute("seats.PosX");
            bookingSourceTable.AddAttribute("seats.PosY");
            bookingSourceTable.AddAttribute("bookings.IsWaiting");

            Join j = bookingSourceTable.CreateJoin("seats", "bookings.PassengerId", "PassengerId", null, JoinTypes.Left);

            j.CustomCondition = "AND bookings.FlightId = seats.FlightId";

            bookingSourceTable.CreateJoin("passengers", "bookings.PassengerId", "Id");
            bookingSourceTable.CreateJoin("flights", "bookings.FlightId", "Id");
            bookingSourceTable.CreateJoin("airports", "flights.DepartureAirportId", "Id", "depAirport");
            bookingSourceTable.CreateJoin("airports", "flights.DestinationAirportId", "Id", "destAirport");

            ObjectRelationalMapper <Booking> bookingMapper = new ObjectRelationalMapper <Booking>(Config.DB_CONNECTION_STRING, bookingSourceTable);

            FetchResult <Booking> fetchResult = bookingMapper.Fetch(CreateBookingInstance, whereClause, sqlParams);

            return(fetchResult);
        }
Ejemplo n.º 25
0
        private Ref FindBranchToCheckout(FetchResult result)
        {
            Ref foundBranch = null;
            Ref idHEAD      = result.GetAdvertisedRef(Constants.HEAD);

            foreach (Ref r in result.GetAdvertisedRefs())
            {
                string n = r.GetName();
                if (!n.StartsWith(Constants.R_HEADS))
                {
                    continue;
                }
                if (idHEAD == null)
                {
                    continue;
                }
                if (r.GetObjectId().Equals(idHEAD.GetObjectId()))
                {
                    foundBranch = r;
                    break;
                }
            }
            return(foundBranch);
        }
Ejemplo n.º 26
0
        public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, params string[] parentCommitsHashes)
        {
            var fetchResult = new FetchResult {
                IsSuccess = true, NewChangesetCount = 0
            };
            var latestChangesetId = GetLatestChangesetId();

            if (lastChangesetIdToFetch != -1)
            {
                latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch);
            }
            // TFS 2010 doesn't like when we ask for history past its last changeset.
            if (MaxChangesetId >= latestChangesetId)
            {
                return(fetchResult);
            }
            List <ITfsChangeset> fetchedChangesets;

            do
            {
                fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch).ToList();
                if (!fetchedChangesets.Any())
                {
                    return(fetchResult);
                }

                var objects = new Dictionary <string, GitObject>(StringComparer.InvariantCultureIgnoreCase);
                Trace.WriteLine(
                    RemoteRef + ": Getting changesets from " + (MaxChangesetId + 1) + " to " + latestChangesetId + " ...", "info");
                foreach (var changeset in fetchedChangesets)
                {
                    fetchResult.NewChangesetCount++;
                    if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch)
                    {
                        return(fetchResult);
                    }
                    string parentCommitSha = null;
                    if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
                    {
                        fetchResult.IsSuccess = false;
                        return(fetchResult);
                    }
                    var log = Apply(MaxCommitHash, changeset, objects);
                    if (parentCommitSha != null)
                    {
                        log.CommitParents.Add(parentCommitSha);
                    }
                    if (changeset.Summary.ChangesetId == mergeChangesetId)
                    {
                        foreach (var parent in parentCommitsHashes)
                        {
                            log.CommitParents.Add(parent);
                        }
                    }
                    var commitSha = ProcessChangeset(changeset, log);
                    fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId;
                    // set commit sha for added git objects
                    foreach (var commit in objects)
                    {
                        if (commit.Value.Commit == null)
                        {
                            commit.Value.Commit = commitSha;
                        }
                    }
                    DoGcIfNeeded();
                }
            } while (fetchedChangesets.Any() && latestChangesetId > fetchResult.LastFetchedChangesetId);
            return(fetchResult);
        }
Ejemplo n.º 27
0
        private async Task <Dictionary <string, CPlayerUpdate> > ScanSingleCompetitor(CompetitorData competitorData,
                                                                                      ScanType scanType)
        {
            var list = new Dictionary <string, CPlayerUpdate>();

            try
            {
                var requestTime = DateTime.UtcNow;
                var fetchResult = await _innerPageParser.GetCompetitorPlayerStatBlock(competitorData.Id);

                var responseTime   = DateTime.UtcNow;
                var defaultRawData = fetchResult.HtmlDocument;

                if (defaultRawData == null)
                {
                    return(null);
                }

                string chosenLeague = string.Empty;
                var    seasonDic    =
                    ParseFunctions.ParseSeasonsSelect(defaultRawData.DocumentNode.SelectNodes("//select/optgroup/."), out chosenLeague);
                if (seasonDic == null)
                {
                    return(null);
                }

                var rawData = defaultRawData;
                if (scanType == ScanType.DailyGames &&
                    seasonDic.ContainsKey(competitorData.NextScan.CompetitionData.Name))
                {
                    requestTime = DateTime.UtcNow;
                    fetchResult =
                        await
                        _innerPageParser.GetCompetitorPlayerStatBlock(competitorData.Id,
                                                                      seasonDic[competitorData.NextScan.CompetitionData.Name].Key);

                    responseTime = DateTime.UtcNow;

                    rawData = fetchResult.HtmlDocument;
                    if (rawData == null)
                    {
                        return(null);
                    }
                }

                var table = rawData.DocumentNode.SelectSingleNode("//table[contains(@class,table)]");
                if (table == null)
                {
                    return(null);
                }

                var seasonId = table.GetAttributeValue("data-season_id", "");

                var season = seasonDic.FirstOrDefault(x => x.Value.Key == seasonId);

                var coachesNodes = defaultRawData.DocumentNode.SelectNodes("//table[@class='table squad']//tbody//tr//td[@class='name large-link']/a");

                if (coachesNodes != null)
                {
                    foreach (var coachNode in coachesNodes)
                    {
                        string coachPageLink = GetCoachPageLink(coachNode);

                        if (!string.IsNullOrWhiteSpace(coachPageLink))
                        {
                            FetchResult coachFetchResult = await _innerPageParser.GetCochCardBlock(coachPageLink);

                            HtmlDocument coachPageDoc = coachFetchResult.HtmlDocument;

                            string   nationality;
                            string   coachFullName;
                            DateTime?bornDate;
                            ParseCoachPersonalDetails(coachPageDoc, out nationality, out bornDate, out coachFullName);

                            CPlayerUpdate coachUpdate = GetCoachUpdate(competitorData, nationality, coachFullName, bornDate);

                            if (coachUpdate != null)
                            {
                                list.Add(coachPageLink, coachUpdate);
                            }
                        }
                    }
                }


                var dataRows = rawData.DocumentNode.SelectNodes("//tbody/tr");
                if (dataRows == null)
                {
                    return(null);
                }

                var index = 1;

                foreach (var row in dataRows)
                {
                    try
                    {
                        string link           = null;
                        var    cAthleteUpdate = ParsePlayerCareerInSquadByCompetition(competitorData, season, row,
                                                                                      scanType, out link, chosenLeague);
                        if (cAthleteUpdate != null)
                        {
                            if (string.IsNullOrEmpty(link))
                            {
                                link = index.ToString();
                                index++;
                            }

                            if (!list.ContainsKey(link))
                            {
                                var currentCompetition = scanType == ScanType.DailyGames && competitorData.NextScan != null
                                    ? competitorData.NextScan.CompetitionData : competitorData.CompetitionData;
                                cAthleteUpdate.WebRequestTime  = requestTime;
                                cAthleteUpdate.WebResponseTime = responseTime;
                                cAthleteUpdate.UsedProxy       = fetchResult.UsedProxy;
                                list.Add(link, cAthleteUpdate);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            catch (Exception exception)
            {
            }

            return(list);
        }
Ejemplo n.º 28
0
        public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, params string[] parentCommitsHashes)
        {
            var fetchResult = new FetchResult{IsSuccess = true};
            foreach (var changeset in FetchChangesets())
            {
                AssertTemporaryIndexClean(MaxCommitHash);
                var log = Apply(MaxCommitHash, changeset);
                if (changeset.IsMergeChangeset)
                {
                    var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this);
                    var shaParent = Repository.FindCommitHashByChangesetId(parentChangesetId);
                    if (shaParent == null)
                        shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit);
                    if (shaParent != null)
                    {
                        log.CommitParents.Add(shaParent);
                    }
                    else
                    {
                        if (stopOnFailMergeCommit)
                        {
                            fetchResult.IsSuccess = false;
                            fetchResult.LastFetchedChangesetId = MaxChangesetId;
                            return fetchResult;
                        }
            //TODO : Manage case where there is not yet a git commit for the parent changset!!!!!
                        stdout.WriteLine("warning: this changeset " + changeset.Summary.ChangesetId +
                        " is a merge changeset. But it can't have been managed accordingly because one of the parent changeset "
                        + parentChangesetId + " is not present in the repository! If you want to do it, fetch the branch containing this changeset before retrying...");
                    }
                }
                if (changeset.Summary.ChangesetId == mergeChangesetId)
                {
                    foreach (var parent in parentCommitsHashes)
                    {
                        log.CommitParents.Add(parent);
                    }
                }

                if (ExportMetadatas)
                {
                    if (changeset.Summary.Workitems.Any())
                    {
                        string workitems = string.Empty;
                        foreach (var workitem in changeset.Summary.Workitems)
                            workitems += "\n" + GitTfsConstants.GitTfsWorkItemPrefix + workitem.Id + " associate";
                        log.Log += workitems;
                    }

                    if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment))
                        log.Log += "\n" + GitTfsConstants.GitTfsPolicyOverrideCommentPrefix + changeset.Summary.PolicyOverrideComment;

                    if (!string.IsNullOrWhiteSpace(changeset.Summary.CodeReviewer))
                        log.Log += "\n" + GitTfsConstants.GitTfsCodeReviewerPrefix + changeset.Summary.CodeReviewer;

                    if (!string.IsNullOrWhiteSpace(changeset.Summary.SecurityReviewer))
                        log.Log += "\n" + GitTfsConstants.GitTfsSecurityReviewerPrefix + changeset.Summary.SecurityReviewer;

                    if (!string.IsNullOrWhiteSpace(changeset.Summary.PerformanceReviewer))
                        log.Log += "\n" + GitTfsConstants.GitTfsPerformanceReviewerPrefix + changeset.Summary.PerformanceReviewer;
                }

                var commitSha = Commit(log);
                UpdateTfsHead(commitSha, changeset.Summary.ChangesetId);
                StringBuilder metadatas = new StringBuilder();
                if(changeset.Summary.Workitems.Any())
                {
                    string workitemNote = "Workitems:\n";
                    foreach(var workitem in changeset.Summary.Workitems)
                    {
                        workitemNote += String.Format("[{0}] {1}\n    {2}\n", workitem.Id, workitem.Title, workitem.Url);
                    }
                    metadatas.Append(workitemNote);
                }

                if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment))
                    metadatas.Append("\nPolicy Override Comment:" + changeset.Summary.PolicyOverrideComment);

                if (!string.IsNullOrWhiteSpace(changeset.Summary.CodeReviewer))
                    metadatas.Append("\nCode Reviewer:" + changeset.Summary.CodeReviewer);

                if (!string.IsNullOrWhiteSpace(changeset.Summary.SecurityReviewer))
                    metadatas.Append("\nSecurity Reviewer:" + changeset.Summary.SecurityReviewer);

                if (!string.IsNullOrWhiteSpace(changeset.Summary.PerformanceReviewer))
                    metadatas.Append("\nPerformance Reviewer:" + changeset.Summary.PerformanceReviewer);
                if (metadatas.Length != 0)
                    Repository.CreateNote(commitSha, metadatas.ToString(), log.AuthorName, log.AuthorEmail, log.Date);
                DoGcIfNeeded();
            }
            return fetchResult;
        }
        public static async Task <FetchResult> LoadTask(MonoBehaviour runner, Uri uri)
        {
            FetchResult result = new FetchResult()
            {
                Asset          = null,
                FailureMessage = null
            };
            var ifNoneMatch = MREAPI.AppsAPI.AssetCache.SupportsSync ?
                              MREAPI.AppsAPI.AssetCache.GetVersionSync(uri) :
                              await MREAPI.AppsAPI.AssetCache.GetVersion(uri);

            runner.StartCoroutine(LoadCoroutine());

            // Spin asynchronously until the request completes.
            while (!result.IsPopulated)
            {
                await Task.Delay(10);
            }

            // handle caching
            if (ifNoneMatch != null && result.ReturnCode == 304)
            {
                var assets = MREAPI.AppsAPI.AssetCache.SupportsSync ?
                             MREAPI.AppsAPI.AssetCache.LeaseAssetsSync(uri) :
                             await MREAPI.AppsAPI.AssetCache.LeaseAssets(uri);

                result.Asset = assets.FirstOrDefault() as T;
            }
            else if (result.Asset != null)
            {
                MREAPI.AppsAPI.AssetCache.StoreAssets(
                    uri,
                    new UnityEngine.Object[] { result.Asset as UnityEngine.Object },
                    result.ETag);
            }

            return(result);

            IEnumerator LoadCoroutine()
            {
                DownloadHandler handler;

                if (typeof(T) == typeof(UnityEngine.AudioClip))
                {
                    handler = new DownloadHandlerAudioClip(uri, AudioType.UNKNOWN);
                }
                else if (typeof(T) == typeof(UnityEngine.Texture))
                {
                    handler = new DownloadHandlerTexture(false);
                }
                else
                {
                    result.FailureMessage = $"Unknown download type: {typeof(T)}";
                    yield break;
                }

                // Spin asynchronously until the load throttler would allow us through.
                while (AssetLoadThrottling.WouldThrottle())
                {
                    yield return(null);
                }

                using (var scope = new AssetLoadThrottling.AssetLoadScope())
                    using (var www = new UnityWebRequest(uri, "GET", handler, null))
                    {
                        if (ifNoneMatch != null)
                        {
                            www.SetRequestHeader("If-None-Match", ifNoneMatch);
                        }

                        yield return(www.SendWebRequest());

                        if (www.isNetworkError)
                        {
                            result.ReturnCode     = -1;
                            result.FailureMessage = www.error;
                        }
                        else
                        {
                            result.ReturnCode = www.responseCode;
                            result.ETag       = www.GetResponseHeader("ETag") ?? "unversioned";

                            if (www.isHttpError)
                            {
                                result.FailureMessage = $"[{www.responseCode}] {uri}";
                            }
                            else if (www.responseCode >= 200 && www.responseCode <= 299)
                            {
                                if (typeof(T).IsAssignableFrom(typeof(UnityEngine.AudioClip)))
                                {
                                    result.Asset = ((DownloadHandlerAudioClip)handler).audioClip as T;
                                }
                                else if (typeof(T).IsAssignableFrom(typeof(UnityEngine.Texture)))
                                {
                                    result.Asset = ((DownloadHandlerTexture)handler).texture as T;
                                }
                            }
                        }
                    }
            }
        }
Ejemplo n.º 30
0
 public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, params string[] parentCommitsHashes)
 {
     var fetchResult = new FetchResult{IsSuccess = true};
     foreach (var changeset in FetchChangesets())
     {
         AssertTemporaryIndexClean(MaxCommitHash);
         var log = Apply(MaxCommitHash, changeset);
         if (changeset.IsMergeChangeset)
         {
             var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this);
             var shaParent = Repository.FindCommitHashByCommitMessage("git-tfs-id: .*;C" + parentChangesetId + "[^0-9]");
             if (shaParent == null)
                 shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit);
             if (shaParent != null)
             {
                 log.CommitParents.Add(shaParent);
             }
             else
             {
                 if (stopOnFailMergeCommit)
                 {
                     fetchResult.IsSuccess = false;
                     fetchResult.LastFetchedChangesetId = MaxChangesetId;
                     return fetchResult;
                 }
     //TODO : Manage case where there is not yet a git commit for the parent changset!!!!!
                 stdout.WriteLine("warning: found merge changeset " + changeset.Summary.ChangesetId +
                                     " but unable to manage it due to lack of local commit for changeset " + parentChangesetId +
                                     "! Fetch the corresponding branch before...");
             }
         }
         if (changeset.Summary.ChangesetId == mergeChangesetId)
         {
             foreach (var parent in parentCommitsHashes)
             {
                 log.CommitParents.Add(parent);
             }
         }
         var commitSha = Commit(log);
         UpdateTfsHead(commitSha, changeset.Summary.ChangesetId);
         if(changeset.Summary.Workitems.Any())
         {
             string workitemNote = "Workitems:\n";
             foreach(var workitem in changeset.Summary.Workitems)
             {
                 workitemNote += String.Format("[{0}] {1}\n    {2}\n", workitem.Id, workitem.Title, workitem.Url);
             }
             Repository.CreateNote(commitSha, workitemNote, log.AuthorName, log.AuthorEmail, log.Date);
         }
         DoGcIfNeeded();
     }
     return fetchResult;
 }
Ejemplo n.º 31
0
 public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, params string[] parentCommitsHashes)
 {
     var fetchResult = new FetchResult{IsSuccess = true};
     var fetchedChangesets = FetchChangesets();
     int count = 0;
     var objects = new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase);
     foreach (var changeset in fetchedChangesets)
     {
         count++;
         string parentCommitSha = null;
         if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
         {
             fetchResult.NewChangesetCount = count;
             fetchResult.IsSuccess = false;
             fetchResult.LastFetchedChangesetId = MaxChangesetId;
             return fetchResult;
         }
         var log = Apply(MaxCommitHash, changeset, objects);
         if (parentCommitSha != null)
             log.CommitParents.Add(parentCommitSha);
         if (changeset.Summary.ChangesetId == mergeChangesetId)
         {
             foreach (var parent in parentCommitsHashes)
             {
                 log.CommitParents.Add(parent);
             }
         }
         var commitSha = ProcessChangeset(changeset, log);
         // set commit sha for added git objects
         foreach (var commit in objects)
         {
             if (commit.Value.Commit == null)
                 commit.Value.Commit = commitSha;
         }
         DoGcIfNeeded();
     }
     fetchResult.NewChangesetCount = count;
     return fetchResult;
 }
 private void updateError(FetchResult status)
 {
     switch (status)
     {
         case FetchResult.ConnectionError:
             statusLabel.Text = "There is no connection to the VK servers";
             break;
         case FetchResult.BadData:
             statusLabel.Text = "Bad data";
             break;
     }
 }
Ejemplo n.º 33
0
        public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null, params string[] parentCommitsHashes)
        {
            var fetchResult = new FetchResult {
                IsSuccess = true, NewChangesetCount = 0
            };
            var latestChangesetId = GetLatestChangesetId();

            if (lastChangesetIdToFetch != -1)
            {
                latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch);
            }
            // TFS 2010 doesn't like when we ask for history past its last changeset.
            if (MaxChangesetId >= latestChangesetId)
            {
                return(fetchResult);
            }
            IEnumerable <ITfsChangeset> fetchedChangesets;

            do
            {
                fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch);
                if (!fetchedChangesets.Any())
                {
                    return(fetchResult);
                }

                var objects = BuildEntryDictionary();
                foreach (var changeset in fetchedChangesets)
                {
                    fetchResult.NewChangesetCount++;
                    if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch)
                    {
                        return(fetchResult);
                    }
                    string parentCommitSha = null;
                    if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
                    {
                        fetchResult.IsSuccess = false;
                        return(fetchResult);
                    }
                    var parentSha = (renameResult != null && renameResult.IsProcessingRenameChangeset) ? renameResult.LastParentCommitBeforeRename : MaxCommitHash;
                    var isFirstCommitInRepository = (parentSha == null);
                    var log = Apply(parentSha, changeset, objects);
                    if (changeset.IsRenameChangeset && !isFirstCommitInRepository)
                    {
                        if (renameResult == null || !renameResult.IsProcessingRenameChangeset)
                        {
                            fetchResult.IsProcessingRenameChangeset  = true;
                            fetchResult.LastParentCommitBeforeRename = MaxCommitHash;
                            return(fetchResult);
                        }
                        renameResult.IsProcessingRenameChangeset  = false;
                        renameResult.LastParentCommitBeforeRename = null;
                    }
                    if (parentCommitSha != null)
                    {
                        log.CommitParents.Add(parentCommitSha);
                    }
                    if (changeset.Summary.ChangesetId == mergeChangesetId)
                    {
                        foreach (var parent in parentCommitsHashes)
                        {
                            log.CommitParents.Add(parent);
                        }
                    }
                    var commitSha = ProcessChangeset(changeset, log);
                    fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId;
                    // set commit sha for added git objects
                    foreach (var commit in objects)
                    {
                        if (commit.Value.Commit == null)
                        {
                            commit.Value.Commit = commitSha;
                        }
                    }
                    DoGcIfNeeded();
                }
            } while (fetchedChangesets.Any() && latestChangesetId > fetchResult.LastFetchedChangesetId);
            return(fetchResult);
        }
Ejemplo n.º 34
0
        public JsonResult GetRepeatModes()
        {
            var items = ScheduleRepeatModeHelper.GetAllowedRepeatModeNames();

            return(NgResultToJsonResult(FetchResult <string> .Succes(items, items.Length)));
        }
Ejemplo n.º 35
0
        public static async Task <FetchResult> LoadTask(MonoBehaviour runner, Uri uri)
        {
            // acquire the exclusive right to load this asset
            if (!await MREAPI.AppsAPI.AssetCache.AcquireLoadingLock(uri))
            {
                throw new TimeoutException("Failed to acquire exclusive loading rights for " + uri);
            }

            FetchResult result = new FetchResult()
            {
                Asset          = null,
                FailureMessage = null
            };
            var ifNoneMatch = MREAPI.AppsAPI.AssetCache.SupportsSync
                                ? MREAPI.AppsAPI.AssetCache.TryGetVersionSync(uri)
                                : await MREAPI.AppsAPI.AssetCache.TryGetVersion(uri);

            // if the cached version is unversioned, i.e. the server doesn't support ETags, don't bother making request
            if (ifNoneMatch == Constants.UnversionedAssetVersion)
            {
                var assets = MREAPI.AppsAPI.AssetCache.SupportsSync
                                        ? MREAPI.AppsAPI.AssetCache.LeaseAssetsSync(uri)
                                        : await MREAPI.AppsAPI.AssetCache.LeaseAssets(uri);

                result.Asset = assets.FirstOrDefault() as T;

                MREAPI.AppsAPI.AssetCache.ReleaseLoadingLock(uri);
                return(result);
            }

            runner.StartCoroutine(LoadCoroutine());

            // Spin asynchronously until the request completes.
            while (!result.IsPopulated)
            {
                await Task.Delay(10);
            }

            // handle caching
            if (!string.IsNullOrEmpty(ifNoneMatch) && result.ReturnCode == 304)
            {
                var assets = MREAPI.AppsAPI.AssetCache.SupportsSync
                                        ? MREAPI.AppsAPI.AssetCache.LeaseAssetsSync(uri)
                                        : await MREAPI.AppsAPI.AssetCache.LeaseAssets(uri);

                result.Asset = assets.FirstOrDefault() as T;
            }
            else if (result.Asset != null)
            {
                MREAPI.AppsAPI.AssetCache.StoreAssets(
                    uri,
                    new UnityEngine.Object[] { result.Asset },
                    result.ETag);
            }

            MREAPI.AppsAPI.AssetCache.ReleaseLoadingLock(uri);
            return(result);

            IEnumerator LoadCoroutine()
            {
                DownloadHandler handler;

                if (typeof(T) == typeof(UnityEngine.AudioClip))
                {
                    handler = new DownloadHandlerAudioClip(uri, AudioType.UNKNOWN);
                }
                else if (typeof(T) == typeof(UnityEngine.Texture))
                {
                    handler = new DownloadHandlerTexture(false);
                }
                else
                {
                    result.FailureMessage = $"Unknown download type: {typeof(T)}";
                    yield break;
                }

                // Spin asynchronously until the load throttler would allow us through.
                while (AssetLoadThrottling.WouldThrottle())
                {
                    yield return(null);
                }

                using (var scope = new AssetLoadThrottling.AssetLoadScope())
                    using (var www = new UnityWebRequest(uri, "GET", handler, null))
                    {
                        if (!string.IsNullOrEmpty(ifNoneMatch))
                        {
                            www.SetRequestHeader("If-None-Match", ifNoneMatch);
                        }

                        yield return(www.SendWebRequest());

                        if (www.isNetworkError)
                        {
                            result.ReturnCode     = -1;
                            result.FailureMessage = www.error;
                        }
                        else
                        {
                            result.ReturnCode = www.responseCode;
                            result.ETag       = www.GetResponseHeader("ETag") ?? Constants.UnversionedAssetVersion;

                            if (www.isHttpError)
                            {
                                result.FailureMessage = $"[{www.responseCode}] {uri}";
                            }
                            else if (www.responseCode >= 200 && www.responseCode <= 299)
                            {
                                if (typeof(T).IsAssignableFrom(typeof(UnityEngine.AudioClip)))
                                {
                                    result.Asset = ((DownloadHandlerAudioClip)handler).audioClip as T;
                                }
                                else if (typeof(T).IsAssignableFrom(typeof(UnityEngine.Texture)))
                                {
                                    result.Asset = ((DownloadHandlerTexture)handler).texture as T;
                                }
                            }
                        }
                    }
            }
        }
Ejemplo n.º 36
0
        public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null, params string[] parentCommitsHashes)
        {
            var fetchResult = new FetchResult { IsSuccess = true, NewChangesetCount = 0 };
            var latestChangesetId = GetLatestChangesetId();
            if (lastChangesetIdToFetch != -1)
                latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch);
            // TFS 2010 doesn't like when we ask for history past its last changeset.
            if (MaxChangesetId >= latestChangesetId)
                return fetchResult;
            IEnumerable<ITfsChangeset> fetchedChangesets;
            do
            {
                fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch);
                if(!fetchedChangesets.Any())
                    return fetchResult;

                var objects = BuildEntryDictionary();
                foreach (var changeset in fetchedChangesets)
                {
                    fetchResult.NewChangesetCount++;
                    if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch)
                        return fetchResult;
                    string parentCommitSha = null;
                    if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
                    {
                        fetchResult.IsSuccess = false;
                        return fetchResult;
                    }
                    var parentSha = (renameResult != null && renameResult.IsProcessingRenameChangeset) ? renameResult.LastParentCommitBeforeRename : MaxCommitHash;
                    var isFirstCommitInRepository = (parentSha == null);
                    var log = Apply(parentSha, changeset, objects);
                    if (changeset.IsRenameChangeset && !isFirstCommitInRepository)
                    {
                        if (renameResult == null || !renameResult.IsProcessingRenameChangeset)
                        {
                            fetchResult.IsProcessingRenameChangeset = true;
                            fetchResult.LastParentCommitBeforeRename = MaxCommitHash;
                            return fetchResult;
                        }
                        renameResult.IsProcessingRenameChangeset = false;
                        renameResult.LastParentCommitBeforeRename = null;
                    }
                    if (parentCommitSha != null)
                        log.CommitParents.Add(parentCommitSha);
                    if (changeset.Summary.ChangesetId == mergeChangesetId)
                    {
                        foreach (var parent in parentCommitsHashes)
                            log.CommitParents.Add(parent);
                    }
                    var commitSha = ProcessChangeset(changeset, log);
                    fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId;
                    // set commit sha for added git objects
                    foreach (var commit in objects)
                    {
                        if (commit.Value.Commit == null)
                            commit.Value.Commit = commitSha;
                    }
                    DoGcIfNeeded();
                }
            } while (fetchedChangesets.Any() && latestChangesetId > fetchResult.LastFetchedChangesetId);
            return fetchResult;
        }
Ejemplo n.º 37
0
        public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, params string[] parentCommitsHashes)
        {
            var fetchResult = new FetchResult { IsSuccess = true, NewChangesetCount = 0 };
            var latestChangesetId = GetLatestChangesetId();
            if (lastChangesetIdToFetch != -1)
                latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch);
            // TFS 2010 doesn't like when we ask for history past its last changeset.
            if (MaxChangesetId >= latestChangesetId)
                return fetchResult;
            List<ITfsChangeset> fetchedChangesets;
            do
            {
                fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch).ToList();
                if(!fetchedChangesets.Any())
                    return fetchResult;

                var objects = BuildEntryDictionary();
                Trace.WriteLine(
                    RemoteRef + ": Getting changesets from " + (MaxChangesetId + 1) + " to " + latestChangesetId + " ...", "info");
                foreach (var changeset in fetchedChangesets)
                {
                    fetchResult.NewChangesetCount++;
                    if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch)
                        return fetchResult;
                    string parentCommitSha = null;
                    if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
                    {
                        fetchResult.IsSuccess = false;
                        return fetchResult;
                    }
                    var log = Apply(MaxCommitHash, changeset, objects);
                    if (parentCommitSha != null)
                        log.CommitParents.Add(parentCommitSha);
                    if (changeset.Summary.ChangesetId == mergeChangesetId)
                    {
                        foreach (var parent in parentCommitsHashes)
                            log.CommitParents.Add(parent);
                    }
                    var commitSha = ProcessChangeset(changeset, log);
                    fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId;
                    // set commit sha for added git objects
                    foreach (var commit in objects)
                    {
                        if (commit.Value.Commit == null)
                            commit.Value.Commit = commitSha;
                    }
                    DoGcIfNeeded();
                }
            } while (fetchedChangesets.Any() && latestChangesetId > fetchResult.LastFetchedChangesetId);
            return fetchResult;
        }