protected void CalculateOwnVehicles(ushort buildingID, ref Building data, TransferManager.TransferReason material, ref int count, ref int cargo, ref int capacity, ref int outside)
 {
     VehicleManager instance = Singleton<VehicleManager>.instance;
     ushort num = data.m_ownVehicles;
     int num2 = 0;
     while (num != 0)
     {
     if ((TransferManager.TransferReason)instance.m_vehicles.m_buffer [(int)num].m_transferType == material)
     {
         VehicleInfo info = instance.m_vehicles.m_buffer [(int)num].Info;
         int a;
         int num3;
         info.m_vehicleAI.GetSize (num, ref instance.m_vehicles.m_buffer [(int)num], out a, out num3);
         cargo += Mathf.Min (a, num3);
         capacity += num3;
         count++;
         if ((instance.m_vehicles.m_buffer [(int)num].m_flags & (Vehicle.Flags.Importing | Vehicle.Flags.Exporting)) != Vehicle.Flags.None)
         {
             outside++;
         }
     }
     num = instance.m_vehicles.m_buffer [(int)num].m_nextOwnVehicle;
     if (++num2 > 16384)
     {
         CODebugBase<LogChannel>.Error (LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);
         break;
     }
     }
 }
Exemplo n.º 2
0
        public void TestFileShareSnapshotsCopyToBase()
        {
            int fileCount = 3;

            string        snapshotFile   = "snapshotFile";
            DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);

            sourceDataInfo.IsFileShareSnapshot = true;
            DMLibDataHelper.AddMultipleFiles(sourceDataInfo.RootNode, snapshotFile, fileCount, 1024);

            SourceAdaptor.Cleanup();
            SourceAdaptor.CreateIfNotExists();
            SourceAdaptor.GenerateData(sourceDataInfo);

            CloudFileDataAdaptor fileAdaptor = (SourceAdaptor as CloudFileDataAdaptor);

            CloudFileDirectory SourceObject = SourceAdaptor.GetTransferObject(sourceDataInfo.RootPath, sourceDataInfo.RootNode) as CloudFileDirectory;
            CloudFileDirectory DestObject   = fileAdaptor.fileHelper.FileClient.GetShareReference(fileAdaptor.ShareName).GetRootDirectoryReference();


            // transfer File and finished succssfully
            Task <TransferStatus> task = TransferManager.CopyDirectoryAsync(
                SourceObject,
                DestObject,
                DMLibTestContext.IsAsync,
                new CopyDirectoryOptions()
            {
                Recursive = true
            },
                new DirectoryTransferContext()
            {
                ShouldOverwriteCallbackAsync = TransferContext.ForceOverwrite
            });

            Test.Assert(task.Wait(15 * 60 * 100), "Tansfer finished in time.");
            Test.Assert(task.Result.NumberOfFilesFailed == 0, "No Failed File.");
            Test.Assert(task.Result.NumberOfFilesSkipped == 0, "No Skipped File.");
            Test.Assert(task.Result.NumberOfFilesTransferred == fileCount, string.Format("Transferred file :{0} == {1}", task.Result.NumberOfFilesTransferred, fileCount));

            // verify that Files in Share Snapshot is transferred
            IEnumerable <IListFileItem> sourceFiles = SourceObject.ListFilesAndDirectories(HelperConst.DefaultFileOptions);

            foreach (IListFileItem item in sourceFiles)
            {
                if (item is CloudFile)
                {
                    CloudFile srcFile  = item as CloudFile;
                    CloudFile destFile = DestObject.GetFileReference(srcFile.Name);
                    srcFile.FetchAttributes();
                    destFile.FetchAttributes();
                    Test.Assert(srcFile.Properties.ContentMD5 == destFile.Properties.ContentMD5, string.Format("File {0} MD5 :{1} == {2}", srcFile.Name, srcFile.Properties.ContentMD5, destFile.Properties.ContentMD5));
                }
            }
        }
Exemplo n.º 3
0
        protected override async Task OnCopyAsync(
            Uri sourceUri,
            IStorage destinationStorage,
            Uri destinationUri,
            IReadOnlyDictionary <string, string> destinationProperties,
            CancellationToken cancellationToken)
        {
            var azureDestinationStorage = destinationStorage as AzureStorage;

            if (azureDestinationStorage == null)
            {
                throw new NotImplementedException("Copying is only supported from Azure storage to Azure storage.");
            }

            string sourceName      = GetName(sourceUri);
            string destinationName = azureDestinationStorage.GetName(destinationUri);

            CloudBlockBlob sourceBlob      = _directory.GetBlockBlobReference(sourceName);
            CloudBlockBlob destinationBlob = azureDestinationStorage._directory.GetBlockBlobReference(destinationName);

            var context = new SingleTransferContext();

            if (destinationProperties?.Count > 0)
            {
                context.SetAttributesCallback = new SetAttributesCallback((destination) =>
                {
                    var blob = (CloudBlockBlob)destination;

                    // The copy statement copied all properties from the source blob to the destination blob; however,
                    // there may be required properties on destination blob, all of which may have not already existed
                    // on the source blob at the time of copy.
                    foreach (var property in destinationProperties)
                    {
                        switch (property.Key)
                        {
                        case StorageConstants.CacheControl:
                            blob.Properties.CacheControl = property.Value;
                            break;

                        case StorageConstants.ContentType:
                            blob.Properties.ContentType = property.Value;
                            break;

                        default:
                            throw new NotImplementedException($"Storage property '{property.Value}' is not supported.");
                        }
                    }
                });
            }

            context.ShouldOverwriteCallback = new ShouldOverwriteCallback((source, destination) => true);

            await TransferManager.CopyAsync(sourceBlob, destinationBlob, _useServerSideCopy, options : null, context : context);
        }
        public async Task doDownload(string containerName, DirectoryInfo localDir, string storageConnectionString)
        {
            try
            {
                // Connect to Azure Storage to download a container
                CloudStorageAccount account    = CloudStorageAccount.Parse(storageConnectionString);
                CloudBlobClient     blobClient = account.CreateCloudBlobClient();

                // Get the container and root directory reference
                CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
                CloudBlobDirectory rootDir       = blobContainer.GetDirectoryReference("");

                // Log
                Console.WriteLine("Directory to be downloaded is {0} and {1}", rootDir.Container.Name, rootDir.StorageUri);

                // Parallel Operations
                TransferManager.Configurations.ParallelOperations = 32;

                // Setup the transfer context and track the upoload progress
                TransferContext context = new TransferContext();
                context.FileFailed += Program.FileFailedCallback;

                context.ProgressHandler = new Progress <TransferStatus>((progress) =>
                {
                    Console.WriteLine("{0} MB downloaded", progress.BytesTransferred / (1024 * 1024));
                });

                // Download recursively
                DownloadDirectoryOptions options = new DownloadDirectoryOptions()
                {
                    Recursive = true
                };

                // Start the counter
                Stopwatch s = Stopwatch.StartNew();

                // Initiate the download from DMLib
                TransferStatus transferStatus = await TransferManager.DownloadDirectoryAsync(rootDir, localDir.ToString(), options, context);

                s.Stop();

                if (transferStatus.NumberOfFilesFailed > 0)
                {
                    Console.WriteLine("{0} files failed to transfer", transferStatus.NumberOfFilesFailed);
                }

                // Log the result
                Console.WriteLine("Download has been completed in {0} seconds", s.Elapsed.TotalSeconds);
            }
            catch (StorageException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 private void OreGeneratorOnAddCreated(TechType type)
 {
     if (TransferManager.IsAllowedToExport())
     {
         var result = TransferManager.TransferToExStorage(type);
         if (result)
         {
             return;
         }
     }
     DeepDrillerContainer.AddItemToContainer(type);
 }
Exemplo n.º 6
0
        public void Run()
        {
            var account1 = new Account {
                Id = 1
            };
            var account2 = new Account {
                Id = 2
            };
            var transferManager = new TransferManager();

            transferManager.DoDoubleTransfer(account1, account2);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Copy data between Azure storage.
        ///   1. Copy a CloudBlob
        ///   2. Cancel the transfer before it finishes with a CancellationToken
        ///   3. Store the transfer checkpoint after transfer being cancelled
        ///   4. Resume the transfer with the stored checkpoint
        /// </summary>
        private static async Task BlobCopySample()
        {
            string sourceBlobName      = "azure_blockblob.png";
            string destinationBlobName = "azure_blockblob2.png";

            // Create the source CloudBlob instance
            CloudBlob sourceBlob = Util.GetCloudBlob(ContainerName, sourceBlobName, BlobType.BlockBlob);

            // Create the destination CloudBlob instance
            CloudBlob destinationBlob = Util.GetCloudBlob(ContainerName, destinationBlobName, BlobType.BlockBlob);

            // Create CancellationTokenSource used to cancel the transfer
            CancellationTokenSource cancellationSource = new CancellationTokenSource();

            TransferCheckpoint checkpoint = null;
            TransferContext    context    = new TransferContext();

            // Cancel the transfer after there's any progress reported
            Progress <TransferProgress> progress = new Progress <TransferProgress>(
                (transferProgress) => {
                if (!cancellationSource.IsCancellationRequested)
                {
                    Console.WriteLine("Cancel the transfer.");

                    // Cancel the transfer
                    cancellationSource.Cancel();
                }
            });

            context.ProgressHandler = progress;

            // Start the transfer
            try
            {
                await TransferManager.CopyAsync(sourceBlob, destinationBlob, false /* isServiceCopy */, null /* options */, context, cancellationSource.Token);
            }
            catch (Exception e)
            {
                Console.WriteLine("The transfer is cancelled: {0}", e.Message);
            }

            // Store the transfer checkpoint
            checkpoint = context.LastCheckpoint;

            // Create a new TransferContext with the store checkpoint
            TransferContext resumeContext = new TransferContext(checkpoint);

            // Resume transfer from the stored checkpoint
            Console.WriteLine("Resume the cancelled transfer.");
            await TransferManager.CopyAsync(sourceBlob, destinationBlob, false /* isServiceCopy */, null /* options */, resumeContext);

            Console.WriteLine("CloudBlob {0} is copied to {1} successfully.", sourceBlob.Uri.ToString(), destinationBlob.Uri.ToString());
        }
Exemplo n.º 8
0
        public static async Task TransferLocalDirectoryToAzureBlobDirectory(CloudStorageAccount account)
        {
            string                   localDirectoryPath = GetDirSourcePath();
            CloudBlobDirectory       blobDirectory      = GetBlobDirectory(account);
            TransferCheckpoint       checkpoint         = null;
            DirectoryTransferContext context            = GetDirectoryTransferContext(checkpoint);
            CancellationTokenSource  cancellationSource = new CancellationTokenSource();

            Console.WriteLine("\nTransfer started...\nPress 'c' to temporarily cancel your transfer...\n");

            Stopwatch              stopWatch = Stopwatch.StartNew();
            Task                   task;
            ConsoleKeyInfo         keyinfo;
            UploadDirectoryOptions options = new UploadDirectoryOptions()
            {
                Recursive = true
            };

            try
            {
                task = TransferManager.UploadDirectoryAsync(localDirectoryPath, blobDirectory, options, context, cancellationSource.Token);
                while (!task.IsCompleted)
                {
                    if (Console.KeyAvailable)
                    {
                        keyinfo = Console.ReadKey(true);
                        if (keyinfo.Key == ConsoleKey.C)
                        {
                            cancellationSource.Cancel();
                        }
                    }
                }
                await task;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nThe transfer is canceled: {0}", e.Message);
            }

            if (cancellationSource.IsCancellationRequested)
            {
                Console.WriteLine("\nTransfer will resume in 3 seconds...");
                Thread.Sleep(3000);
                checkpoint = context.LastCheckpoint;
                context    = GetDirectoryTransferContext(checkpoint);
                Console.WriteLine("\nResuming transfer...\n");
                await TransferManager.UploadDirectoryAsync(localDirectoryPath, blobDirectory, options, context);
            }

            stopWatch.Stop();
            Console.WriteLine("\nTransfer operation completed in " + stopWatch.Elapsed.TotalSeconds + " seconds.");
            //ExecuteChoice(account);
        }
Exemplo n.º 9
0
        public void Start(TaskCompletionSource <bool> ResultOfInitSink)
        {
            if (!Assembly.GetCallingAssembly().GetName().FullName.StartsWith("ACE.Server,"))
            {
                log.Fatal("Invalid startup method.  This is an ACEmulator plugin.");
                return;
            }
            TransferConfigManager.Initialize();
            TransferManager.Initialize();

            ResultOfInitSink.SetResult(true); // report success
        }
Exemplo n.º 10
0
        private void HubOutgoingConnectionRequest(object sender, OutgoingConnectionRequestEventArgs e)
        {
            var hubConnection = (HubConnection)sender;

            var ea = new ConnectionRequestEventArgs
            {
                UserNickname  = "",
                Address       = e.Message.SenderAddress,
                HubConnection = hubConnection
            };

            OnConnectionRequest(ea);

            if (ea.Cancel)
            {
                return;
            }

            TransferConnection transfer;

            try
            {
                transfer = new TransferConnection(e.Message.SenderAddress)
                {
                    AllowedToConnect = true,
                    Source           = new Source {
                        HubAddress = hubConnection.RemoteAddressString
                    }
                };

                if (Settings.NetworkInterface != null)
                {
                    transfer.LocalAddress = new IPEndPoint(Settings.NetworkInterface, 0);
                }
            }
            catch (Exception x)
            {
                Logger.Error("Unable to create outgoing transfer thread {0}", x.Message);
                return;
            }

            TransferManager.AddTransfer(transfer);
            transfer.FirstMessages = new[]
            {
                new MyNickMessage {
                    Nickname = hubConnection.Settings.Nickname
                }.Raw,
                new LockMessage {
                    ExtendedProtocol = true
                }.Raw
            };
            transfer.StartAsync();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Stops download process and removes download
        /// </summary>
        /// <param name="di"></param>
        public void RemoveDownload(DownloadItem di)
        {
            di.Priority = DownloadPriority.Pause;
            TransferManager.StopTransfers(di);

            while (di.ActiveSegmentsCount > 0)
            {
                Thread.Sleep(0);
            }

            DownloadManager.RemoveDownload(di);
        }
        public ResourceTransferValue(TransferManager transferManager, PartResourceDefinition resourceInfo, object transferTo, object transferFrom)
        {
            this.transferManager = transferManager;
            this.resourceInfo    = resourceInfo;
            this.transferTo      = transferTo;
            this.transferFrom    = transferFrom;

            DetermineTypes();
            InitializeSuffixes();

            Status = TransferManager.TransferStatus.Inactive; // Last because the setter for Status prints some of the values calculated above to the log
        }
Exemplo n.º 13
0
        private TransactionError AcceptOrDeclineTransfer(Guid userId, Guid transferID, TransferAction action)
        {
            Guid             accountId, currencyId;
            decimal          amount;
            TransactionError error = TransferManager.AcceptTransfer(userId, transferID, action, out accountId, out currencyId, out amount);
            var account            = GetAccount(accountId);

            account.AddDeposit(currencyId, amount, true);
            account.SaveAndBroadcastChanges();
            Broadcaster.Default.Add(BroadcastBLL.CommandFactory.CreateUpdateBalanceCommand(accountId, currencyId, amount, ModifyType.Add));
            return(error);
        }
Exemplo n.º 14
0
        public static async Task CopyFromAssetToBlob(IAsset asset, string sourceConn, string targetConn, string targetContainer, string targetDirectory,
                                                     Func <string, bool> action = null)
        {
            int skipSize     = 0;
            int batchSize    = 1000;
            int currentBatch = 0;
            int i            = 0;
            int len          = asset.AssetFiles.Count();

            CloudStorageAccount sourceAccount  = CloudStorageAccount.Parse(sourceConn);
            CloudStorageAccount targertAccount = CloudStorageAccount.Parse(targetConn);

            var sourceClient        = sourceAccount.CreateCloudBlobClient();
            var sourceContainerUri  = asset.Uri.ToString();
            var sourceContainer     = sourceClient.GetContainerReference(sourceContainerUri.Substring(sourceContainerUri.LastIndexOf('/') + 1));
            var targetClient        = targertAccount.CreateCloudBlobClient();
            var targetContainerBlob = targetClient.GetContainerReference(targetContainer);
            var directory           = targetContainerBlob.GetDirectoryReference(targetDirectory);

            List <Task> tasks = new List <Task>();

            while (true)
            {
                // Loop through all Jobs (1000 at a time) in the Media Services account
                IQueryable _assetCollectionQuery = asset.AssetFiles.Skip(skipSize).Take(batchSize);
                foreach (IAssetFile assetFile in _assetCollectionQuery)
                {
                    bool isOk = true;
                    if (action != null)
                    {
                        isOk = action(assetFile.MimeType);
                    }
                    if (isOk)
                    {
                        CloudBlockBlob sourceBlockBlob = sourceContainer.GetBlockBlobReference(assetFile.Name);
                        CloudBlockBlob destBlockBlob   = directory.GetBlockBlobReference(assetFile.Name);
                        tasks.Add(TransferManager.CopyAsync(sourceBlockBlob, destBlockBlob, true));
                        currentBatch++;
                        i++;
                    }
                }
                if (currentBatch == batchSize)
                {
                    skipSize    += batchSize;
                    currentBatch = 0;
                }
                else
                {
                    break;
                }
            }
            await Task.WhenAll(tasks);
        }
 /// <summary>
 /// Checks the instance, and resaves references if necessary.
 /// </summary>
 /// <param name="instance">The instance.</param>
 public static void CheckInstance(TransferManager instance)
 {
     if (TransferManagerInstanceId == null || !TransferManagerInstanceId.HasValue)
     {
         Initialize(instance);
     }
     else if (instance.GetInstanceID() != TransferManagerInstanceId)
     {
         DeInitialize();
         Initialize(instance);
     }
 }
Exemplo n.º 16
0
 private async Task TransferLocalDirectoryToAzure(CloudBlobDirectory blobDirectory, CancellationToken cancellationToken)
 {
     await TransferLocalDirectoryToAzureStorage(
         async (uploadFolder, options, context, linkedCancellationToken) =>
     {
         return(await TransferManager.UploadDirectoryAsync(uploadFolder, blobDirectory, options, context, linkedCancellationToken));
     },
         (e) => {
         return($"'{e.Source}' => '{((CloudBlobContainer)e.Destination).Name}'");
     },
         cancellationToken);
 }
Exemplo n.º 17
0
        public void Setup()
        {
            notExistBucket = "not-exist-bucket-suwjsdjwujehdfkd-" + QCloudServer.Instance().appid;
            cosXml         = QCloudServer.Instance().cosXml;
            var config = new TransferConfig();

            config.DivisionForUpload  = 1 * 1024 * 1024;
            config.DdivisionForCopy   = 1 * 1024 * 1024;
            config.SliceSizeForCopy   = 1 * 1024 * 1024;
            config.SliceSizeForUpload = 1 * 1024 * 1024;
            transferManager           = new TransferManager(cosXml, config);
            localFilePath             = QCloudServer.CreateFile(TimeUtils.GetCurrentTime(TimeUnit.Seconds) + ".txt", 1024 * 1024 * 1);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Upload a local picture to azure storage as a cloud file.
        /// </summary>
        private static async Task FileUploadSample()
        {
            string sourceFileName      = "azure.png";
            string destinationFileName = "azure_cloudfile.png";

            // Create the destination CloudFile instance
            CloudFile destinationFile = await Util.GetCloudFileAsync(ShareName, destinationFileName);

            // Start the upload
            await TransferManager.UploadAsync(sourceFileName, destinationFile);

            Console.WriteLine("File {0} is uploaded to {1} successfully.", sourceFileName, destinationFile.Uri.ToString());
        }
Exemplo n.º 19
0
        public static async Task fileUploadAsync()
        {
            var sourceFileName      = "azure.png";
            var destinationFileName = "azure_cloudfile.png";

            // Create the destination CloudFile instance
            var destinationFile = await getCloudFileAsync(_shareName, destinationFileName);

            // Start the upload
            await TransferManager.UploadAsync(sourceFileName, destinationFile);

            Console.WriteLine("File {0} is uploaded to {1} successfully.", sourceFileName, destinationFile.Uri.ToString());
        }
        public async Task <List <BlobInfo> > CopyDirectory(
            IBlobContainer sourceContainerName,
            string sourceDirectoryPath,
            IBlobContainer destinationContainerName,
            string destinationDirectoryPath,
            IBlobStorageService.CopyDirectoryOptions?options = null)
        {
            _logger.LogInformation(
                "Copying directory from {0}/{1} to {2}/{3}",
                sourceContainerName,
                sourceDirectoryPath,
                destinationContainerName,
                destinationDirectoryPath
                );

            var sourceContainer = await GetCloudBlobContainer(sourceContainerName);

            var destinationContainer = await GetCloudBlobContainer(
                destinationContainerName,
                connectionString : options?.DestinationConnectionString
                );

            var sourceDirectory      = sourceContainer.GetDirectoryReference(sourceDirectoryPath);
            var destinationDirectory = destinationContainer.GetDirectoryReference(destinationDirectoryPath);

            var copyDirectoryOptions = new CopyDirectoryOptions
            {
                Recursive = true
            };

            var filesTransferred = new List <BlobInfo>();

            var context = new DirectoryTransferContext();

            context.FileTransferred              += (sender, args) => FileTransferredCallback(sender, args, filesTransferred);
            context.FileFailed                   += FileFailedCallback;
            context.FileSkipped                  += FileSkippedCallback;
            context.SetAttributesCallbackAsync   += options?.SetAttributesCallbackAsync;
            context.ShouldTransferCallbackAsync  += options?.ShouldTransferCallbackAsync;
            context.ShouldOverwriteCallbackAsync += options?.ShouldOverwriteCallbackAsync;

            await TransferManager.CopyDirectoryAsync(
                sourceDirectory,
                destinationDirectory,
                CopyMethod.ServiceSideAsyncCopy,
                copyDirectoryOptions,
                context
                );

            return(filesTransferred);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 高级接口上传对象
        /// </summary>
        /// <returns></returns>
        public async Task TransferUploadFile(string filePath)
        {
            CosXmlConfig config = new CosXmlConfig.Builder()
                                  .SetRegion(_cosConfig.Region) //设置一个默认的存储桶地域
                                  .Build();

            string secretId       = _cosConfig.SecretId;  //云 API 密钥 SecretId
            string secretKey      = _cosConfig.SecretKey; //云 API 密钥 SecretKey
            long   durationSecond = 600;                  //每次请求签名有效时长,单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId,
                                                                                                    secretKey, durationSecond);

            CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider);
            // 初始化 TransferConfig
            TransferConfig transferConfig = new TransferConfig();

            // 初始化 TransferManager
            TransferManager transferManager = new TransferManager(cosXml, transferConfig);

            string bucket  = _cosConfig.Bucket;    //存储桶,格式:BucketName-APPID
            string cosPath = _cosConfig.UploadKey; //对象在存储桶中的位置标识符,即称对象键

            // 上传对象
            COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);

            uploadTask.SetSrcPath(filePath); //本地文件绝对路径

            uploadTask.progressCallback = delegate(long completed, long total)
            {
                Console.WriteLine(string.Format("progress = {0:##.##}%", completed * 100.0 / total));
            };
            uploadTask.successCallback = delegate(CosResult cosResult)
            {
                COSXML.Transfer.COSXMLUploadTask.UploadTaskResult result = cosResult
                                                                           as COSXML.Transfer.COSXMLUploadTask.UploadTaskResult;
                Console.WriteLine(result.GetResultInfo());
                string eTag = result.eTag;
            };
            uploadTask.failCallback = delegate(CosClientException clientEx, CosServerException serverEx)
            {
                if (clientEx != null)
                {
                    Console.WriteLine("CosClientException: " + clientEx);
                }
                if (serverEx != null)
                {
                    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                }
            };
            await transferManager.UploadAsync(uploadTask);
        }
Exemplo n.º 22
0
        private static async Task TransferAzureBlobToAzureBlob(CloudStorageAccount account)
        {
            // From・Toの情報を取得
            CloudBlockBlob sourceBlob      = GetBlob(account);
            CloudBlockBlob destinationBlob = GetBlob(account);

            // 転送処理の実施
            Console.WriteLine("\nTransfer started...\n");
            var stopWatch = Stopwatch.StartNew();
            await TransferManager.CopyAsync(sourceBlob, destinationBlob, true, null, GetSingleTransferContext());

            stopWatch.Stop();
            Console.WriteLine("\nTransfer operation completed in " + stopWatch.Elapsed.TotalSeconds + " seconds.");
        }
Exemplo n.º 23
0
        static void UploadBlobToAzure(string file)
        {
            FileInfo        fileRef  = new FileInfo(file);
            CloudBlockBlob  destBlob = container.GetBlockBlobReference(fileRef.Name.ToLower());
            TransferContext context  = new TransferContext();
            var             task     = TransferManager.UploadAsync(fileRef.FullName, destBlob, null, context, CancellationToken.None);

            task.Wait();

            CloudQueueMessage message = new CloudQueueMessage(fileRef.Name);

            task = queue.AddMessageAsync(message);
            task.Wait();
        }
Exemplo n.º 24
0
        private static async Task TransferLocalFileToAzureBlob(CloudStorageAccount account)
        {
            // From・Toの情報を取得
            var localFilePath = GetSourcePath();
            var blob          = GetBlob(account);

            // 転送処理の実施
            Console.WriteLine("\nTransfer started...\n");
            var stopWatch = Stopwatch.StartNew();
            await TransferManager.UploadAsync(localFilePath, blob, null, GetSingleTransferContext());

            stopWatch.Stop();
            Console.WriteLine("\nTransfer operation completed in " + stopWatch.Elapsed.TotalSeconds + " seconds.");
        }
        private void AddTransactions(IEnumerable <BasicTransaction> source, IList <Transaction> target, Func <Transaction> transactionFactory)
        {
            foreach (var tran in source)
            {
                var transaction = transactionFactory();

                transaction.Amount      = tran.Amount;
                transaction.Date        = tran.Date;
                transaction.Description = tran.Memo;
                transaction.Payee       = tran.Payee;
                transaction.Included    = !TransferManager.IsTransfer(transaction);
                target.Add(transaction);
            }
        }
        public async Task UploadBlobAsync(Stream fileStream, string containerName, string blobNameToCreate)
        {
            try
            {
                var blockBlob = GetBlockBlob(containerName, blobNameToCreate);
                var context   = PrepareTransfer();

                await TransferManager.UploadAsync(fileStream, blockBlob, null, context, CancellationToken.None);
            }
            catch (Exception ex)
            {
                throw new BlobStorageException($"Container: {containerName} Blob: {blobNameToCreate} - Error while uploading blob.", ex);
            }
        }
        /// <summary>
        /// Blocks offers that should be handled by the mod.
        /// </summary>
        /// <param name="transferManager">The transfer manager.</param>
        /// <param name="material">The material.</param>
        /// <param name="offer">The offer.</param>
        public static void TransferManager_AddIncomingOffer_Override(TransferManager transferManager, TransferManager.TransferReason material, TransferManager.TransferOffer offer)
        {
            Calls++;

            if ((material == TransferManager.TransferReason.Dead && Global.CleanHearseTransferOffers) ||
                (material == TransferManager.TransferReason.Garbage && Global.CleanGarbageTruckTransferOffers) ||
                (material == TransferManager.TransferReason.Sick && Global.CleanAmbulanceTransferOffers))
            {
                Blocked++;
                return;
            }

            TransferManager_AddIncomingOffer_Original(transferManager, material, offer);
        }
Exemplo n.º 28
0
        public DataManagementWrapper(int concurrency, string clientRequestId)
        {
            TransferOptions options = new TransferOptions()
            {
                ParallelOperations = concurrency
            };

            if (!Environment.Is64BitProcess && options.MaximumCacheSize > Maximum32bitCacheSize)
            {
                options.MaximumCacheSize = Maximum32bitCacheSize;
            }

            this.manager = new TransferManager(options);
        }
Exemplo n.º 29
0
        public static async Task TransferAzureBlobToAzureBlob(CloudStorageAccount account)
        {
            CloudBlockBlob          sourceBlob         = GetBlob(account);
            CloudBlockBlob          destinationBlob    = GetBlob(account);
            TransferCheckpoint      checkpoint         = null;
            SingleTransferContext   context            = GetSingleTransferContext(checkpoint);
            CancellationTokenSource cancellationSource = new CancellationTokenSource();

            Console.WriteLine("\nTransfer started...\nPress 'c' to temporarily cancel your transfer...\n");

            Stopwatch      stopWatch = Stopwatch.StartNew();
            Task           task;
            ConsoleKeyInfo keyinfo;

            try
            {
                task = TransferManager.CopyAsync(sourceBlob, destinationBlob, true, null, context, cancellationSource.Token);
                while (!task.IsCompleted)
                {
                    if (Console.KeyAvailable)
                    {
                        keyinfo = Console.ReadKey(true);
                        if (keyinfo.Key == ConsoleKey.C)
                        {
                            cancellationSource.Cancel();
                        }
                    }
                }
                await task;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nThe transfer is canceled: {0}", e.Message);
            }

            if (cancellationSource.IsCancellationRequested)
            {
                Console.WriteLine("\nTransfer will resume in 3 seconds...");
                Thread.Sleep(3000);
                checkpoint = context.LastCheckpoint;
                context    = GetSingleTransferContext(checkpoint);
                Console.WriteLine("\nResuming transfer...\n");
                await TransferManager.CopyAsync(sourceBlob, destinationBlob, false, null, context, cancellationSource.Token);
            }

            stopWatch.Stop();
            Console.WriteLine("\nTransfer operation completed in " + stopWatch.Elapsed.TotalSeconds + " seconds.");
            //ExecuteChoice(account);
        }
Exemplo n.º 30
0
        private async Task TransferLocalDirectoryToAzureBlobDirectory(string directory)
        {
            CloudBlobDirectory blobDirectory = await GetBlobDirectory();

            if (blobDirectory == null)
            {
                return;
            }

            DirectoryTransferContext context            = GetDirectoryTransferContext();
            CancellationTokenSource  cancellationSource = new CancellationTokenSource();

            logger.Log($"Transfer started...");

            Stopwatch              stopWatch = Stopwatch.StartNew();
            Task                   task;
            ConsoleKeyInfo         keyinfo;
            UploadDirectoryOptions options = new UploadDirectoryOptions()
            {
                Recursive = true
            };

            try
            {
                task = TransferManager.UploadDirectoryAsync(directory, blobDirectory, options, context, cancellationSource.Token);

                while (!task.IsCompleted)
                {
                    if (Console.KeyAvailable)
                    {
                        keyinfo = Console.ReadKey(true);

                        if (keyinfo.Key == ConsoleKey.C)
                        {
                            cancellationSource.Cancel();
                        }
                    }
                }
                await task;
            }
            catch (Exception e)
            {
                logger.Error(string.Format("The transfer is canceled: {0}", e.Message), null);
            }

            stopWatch.Stop();
            Console.WriteLine();
            logger.Log(string.Format("Transfer operation completed in {0} seconds.", stopWatch.Elapsed.TotalSeconds));
        }
        private Task <TransferStatus> CopyDirectory(dynamic sourceObject, dynamic destObject, TransferItem item)
        {
            CopyDirectoryOptions     copyDirectoryOptions = item.Options as CopyDirectoryOptions;
            DirectoryTransferContext transferContext      = item.TransferContext as DirectoryTransferContext;
            CancellationToken        cancellationToken    = item.CancellationToken;

            if (cancellationToken == null || cancellationToken == CancellationToken.None)
            {
                return(TransferManager.CopyDirectoryAsync(sourceObject, destObject, item.IsServiceCopy, copyDirectoryOptions, transferContext));
            }
            else
            {
                return(TransferManager.CopyDirectoryAsync(sourceObject, destObject, item.IsServiceCopy, copyDirectoryOptions, transferContext, cancellationToken));
            }
        }
        /// <summary>
        /// Assigns target to vehicle.
        /// </summary>
        /// <param name="vehicleId">The vehicle identifier.</param>
        /// <param name="vehicle">The vehicle.</param>
        /// <param name="material">The material.</param>
        /// <param name="targetBuildingId">The target building identifier.</param>
        /// <param name="targetCitizenId">The target citizen identifier.</param>
        /// <returns>
        /// True on success.
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// Ambulances must use citizen assignment
        /// or
        /// Material must be specified.
        /// </exception>
        /// <exception cref="System.NotImplementedException">Ambulance dispatching not fully implemented yet.</exception>
        public static bool AssignTarget(ushort vehicleId, ref Vehicle vehicle, TransferManager.TransferReason? material, ushort targetBuildingId, uint targetCitizenId)
        {
            if (!Global.EnableExperiments)
            {
                return VehicleHelper.SetTarget(vehicleId, ref vehicle, targetBuildingId, targetCitizenId);
            }

            if (targetBuildingId == 0 && targetCitizenId == 0)
            {
                return VehicleHelper.SetTarget(vehicleId, ref vehicle, targetBuildingId, targetCitizenId);
            }

            if (vehicle.Info.m_vehicleAI is AmbulanceAI && targetCitizenId == 0)
            {
                throw new InvalidOperationException("Ambulances must use citizen assignment");
            }

            if (Global.Settings.AssignmentCompatibilityMode == ServiceDispatcherSettings.ModCompatibilityMode.UseCustomCode)
            {
                if (vehicle.Info.m_vehicleAI is AmbulanceAI)
                {
                    throw new NotImplementedException("Ambulance dispatching not fully implemented yet");
                }

                return VehicleHelper.SetTarget(vehicleId, ref vehicle, targetBuildingId, targetCitizenId);
            }

            if (material == null || !material.HasValue)
            {
                if (vehicle.Info.m_vehicleAI is HearseAI)
                {
                    material = TransferManager.TransferReason.Dead;
                }
                else if (vehicle.Info.m_vehicleAI is GarbageTruckAI)
                {
                    material = TransferManager.TransferReason.Garbage;
                }
                else if (vehicle.Info.m_vehicleAI is AmbulanceAI)
                {
                    material = TransferManager.TransferReason.Sick;
                }
                else
                {
                    throw new InvalidOperationException("Material must be specified");
                }
            }
            return VehicleHelper.StartTransfer(vehicleId, ref vehicle, material.Value, targetBuildingId, targetCitizenId);
        }
        public override void ModifyMaterialBuffer(ushort buildingID, ref Building data, TransferManager.TransferReason material, ref int amountDelta)
        {
            switch (material)
            {
                case TransferManager.TransferReason.Worker0:
                case TransferManager.TransferReason.Worker1:
                case TransferManager.TransferReason.Worker2:
                case TransferManager.TransferReason.Worker3:
                    {
                        if (data.m_customBuffer1 == 0)
                        {
                            data.m_customBuffer1 = (ushort)(120 + LevelUpHelper3.instance.GetWealthThreshhold(data.Info.m_class.m_level - 1, data.Info.m_class.GetZone()));
                        }

                        if (amountDelta > 0)
                        {
                            DistrictManager instance = Singleton<DistrictManager>.instance;
                            byte district = instance.GetDistrict(data.m_position);
                            DistrictPolicies.Taxation taxationPolicies = instance.m_districts.m_buffer[(int)district].m_taxationPolicies;
                            int taxRate = Singleton<EconomyManager>.instance.GetTaxRate(this.m_info.m_class, taxationPolicies);
                            amountDelta += (50 - taxRate * 4);
                            amountDelta = Math.Max(2, amountDelta / CalculateHomeCount(data));
                        }
                        else
                        {

                            amountDelta = Math.Min(-2, amountDelta / CalculateHomeCount(data));
                        }

                        data.m_customBuffer1 = (ushort)Mathf.Clamp(data.m_customBuffer1 + amountDelta, 1, 30000);
                        return;
                    }
                case TransferManager.TransferReason.Crime:
                    int crimeBuffer = (int)data.m_crimeBuffer;
                    amountDelta = Mathf.Clamp(amountDelta, -crimeBuffer, 65535 - crimeBuffer) / 4;
                    data.m_crimeBuffer = (ushort)(crimeBuffer + amountDelta);
                    return;
            }
            base.ModifyMaterialBuffer(buildingID, ref data, material, ref amountDelta);
        }
Exemplo n.º 34
0
        private static bool CreateVehicle(VehicleManager vMgr, out ushort vehicle, ref Randomizer r, VehicleInfo info, Vector3 position, TransferManager.TransferReason type, bool transferToSource, bool transferToTarget)
        {
            bool AttemptFlag = false;
            uint ReserveMax = (vMgr.m_vehicles.m_size - 1) - Mod.RESERVEAMOUNT;  //we subtract 1 cause game doesn't use entry 0 for a real vehicle.
            int CurrentVehicleNum = vMgr.m_vehicleCount; //vMgr.m_vehicles.ItemCount(); //found they were never different ~+\- a nanosecond.
            int m_VecCount = vMgr.m_vehicleCount;  //unly
            Mod.timesCV_CalledTotal++; //stat tracking.
            if (CurrentVehicleNum >= ReserveMax && type != TransferManager.TransferReason.Fire && type != TransferManager.TransferReason.Sick
                && type != TransferManager.TransferReason.Garbage && type != TransferManager.TransferReason.Dead
                && type != TransferManager.TransferReason.Crime && type != TransferManager.TransferReason.Bus
                && type != TransferManager.TransferReason.MetroTrain && type != TransferManager.TransferReason.PassengerTrain
                && type != TransferManager.TransferReason.DeadMove && type != TransferManager.TransferReason.CriminalMove
                && type != TransferManager.TransferReason.Taxi && type != TransferManager.TransferReason.GarbageMove
                && type != TransferManager.TransferReason.Tram && type != TransferManager.TransferReason.RoadMaintenance
                && type != TransferManager.TransferReason.Snow && type != TransferManager.TransferReason.SnowMove
                && type != TransferManager.TransferReason.Fire2 && type != TransferManager.TransferReason.ForestFire
                && type != TransferManager.TransferReason.FloodWater && type !=TransferManager.TransferReason.SickMove
                && type != TransferManager.TransferReason.Sick2 && type !=TransferManager.TransferReason.EvacuateVipA
                && type != TransferManager.TransferReason.EvacuateVipB && type != TransferManager.TransferReason.EvacuateVipC
                && type != TransferManager.TransferReason.EvacuateVipD)

            {
                Mod.timesFailedByReserve++; //stat tracking
                Mod.timesFailedToCreate++;  //stat tracking
                vehicle = 0;
                return false;
            }

            if (CurrentVehicleNum >= ReserveMax)
            {
                AttemptFlag = true;
                Mod.timesReservedAttempted++;  //stat tracking.
                if (CurrentVehicleNum == (vMgr.m_vehicles.m_size -1)) { Mod.timesLimitReached++; } //stattracking
                if (Mod.DEBUG_LOG_ON && Mod.DEBUG_LOG_LEVEL >= 3) { Helper.dbgLog(" Vehicles[" + CurrentVehicleNum.ToString() +
                    "] max reached, attempting to use reserve for a " + type.ToString() + " - " + System.DateTime.Now.ToString() +
                    " : " + DateTime.Now.Millisecond.ToString() + " counter=" + Mod.timesReservedAttempted.ToString() + " reservemax=" +
                    ReserveMax.ToString()); }
            }

            //Original Untouched Below except for attemptflag and Mod.timeFailedToCreate Counters and debug logging.
            ushort num;
            if (!vMgr.m_vehicles.CreateItem(out num, ref r))
            {
                vehicle = 0;
                if (AttemptFlag)
                {
                    Mod.timesReserveAttemptFailed++ ; //stat tracking.
                    if (Mod.DEBUG_LOG_ON && Mod.DEBUG_LOG_LEVEL >= 2) {  Helper.dbgLog(" Vehicles[" + CurrentVehicleNum.ToString() +
                        "] max reached, attempted to use reserve for a " + type.ToString() + " but Failed! " + System.DateTime.Now.ToString() + " : " +
                        DateTime.Now.Millisecond.ToString() + " counter=" + Mod.timesReservedAttempted.ToString()); }
                }

                Mod.timesFailedToCreate++;  //stat tracking
                return false;
            }

            vehicle = num;
            Vehicle.Frame frame = new Vehicle.Frame(position, Quaternion.identity);
            vMgr.m_vehicles.m_buffer[vehicle].m_flags = Vehicle.Flags.Created;
            if (transferToSource)
            {
                vMgr.m_vehicles.m_buffer[vehicle].m_flags = vMgr.m_vehicles.m_buffer[vehicle].m_flags | Vehicle.Flags.TransferToSource;
            }
            if (transferToTarget)
            {
                vMgr.m_vehicles.m_buffer[vehicle].m_flags = vMgr.m_vehicles.m_buffer[vehicle].m_flags | Vehicle.Flags.TransferToTarget;
            }
            vMgr.m_vehicles.m_buffer[vehicle].Info = info;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame0 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame1 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame2 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame3 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos0 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos1 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos2 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos3 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_sourceBuilding = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetBuilding = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_transferType = (byte)type;
            vMgr.m_vehicles.m_buffer[vehicle].m_transferSize = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_waitCounter = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_blockCounter = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextGridVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextOwnVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextGuestVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextLineVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_transportLine = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_leadingVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_trailingVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_cargoParent = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_firstCargo = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextCargo = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_citizenUnits = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_path = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_lastFrame = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_pathPositionIndex = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_lastPathOffset = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_gateIndex = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_waterSource = 0;
            info.m_vehicleAI.CreateVehicle(vehicle, ref vMgr.m_vehicles.m_buffer[vehicle]);
            info.m_vehicleAI.FrameDataUpdated(vehicle, ref vMgr.m_vehicles.m_buffer[vehicle], ref vMgr.m_vehicles.m_buffer[vehicle].m_frame0);
            vMgr.m_vehicleCount = (int)(vMgr.m_vehicles.ItemCount() - 1);
            return true;
        }
        /// <summary>
        /// Creates the specified service building.
        /// </summary>
        /// <param name="serviceBuilding">The service building.</param>
        /// <param name="material">The material.</param>
        /// <param name="dispatcherType">Type of the dispatcher.</param>
        /// <param name="targetBuildingId">The target building identifier.</param>
        /// <param name="targetCitizenId">The target citizen identifier.</param>
        /// <returns>
        /// The service vehicle.
        /// </returns>
        public static ServiceVehicleInfo Create(ServiceBuildingInfo serviceBuilding, TransferManager.TransferReason material, Dispatcher.DispatcherTypes dispatcherType, ushort targetBuildingId, uint targetCitizenId)
        {
            ushort vehicleId = 0;
            VehicleInfo info = null;

            if (!Global.EnableExperiments)
            {
                info = VehicleHelper.CreateServiceVehicle(serviceBuilding.BuildingId, material, targetBuildingId, targetCitizenId, out vehicleId);
            }
            else if (Global.Settings.CreationCompatibilityMode == ServiceDispatcherSettings.ModCompatibilityMode.UseCustomCode)
            {
                info = VehicleHelper.CreateServiceVehicle(serviceBuilding.BuildingId, material, targetBuildingId, targetCitizenId, out vehicleId);
            }
            else
            {
                info = BuildingHelper.StartTransfer(serviceBuilding.BuildingId, material, targetBuildingId, targetCitizenId, out vehicleId);
            }

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

            VehicleManager manager = Singleton<VehicleManager>.instance;

            return new ServiceVehicleInfo(vehicleId, ref manager.m_vehicles.m_buffer[vehicleId], targetBuildingId == 0, dispatcherType, targetBuildingId);
        }
        /// <summary>
        /// Starts the transfer.
        /// </summary>
        /// <param name="vehicleId">The vehicle identifier.</param>
        /// <param name="vehicle">The vehicle.</param>
        /// <param name="material">The material.</param>
        /// <param name="targetBuildingId">The target building identifier.</param>
        /// <param name="targetCitizenId">The target citizen identifier.</param>
        /// <returns>True on success.</returns>
        private static bool StartTransfer(ushort vehicleId, ref Vehicle vehicle, TransferManager.TransferReason material, ushort targetBuildingId, uint targetCitizenId)
        {
            TransferManager.TransferOffer offer = new TransferManager.TransferOffer()
            {
                Building = targetBuildingId,
                Citizen = targetCitizenId,
            };

            vehicle.m_flags &= ~Vehicle.Flags.GoingBack;
            vehicle.m_flags |= Vehicle.Flags.WaitingTarget;

            // Cast AI as games original AI so detoured methods are called, but not methods from not replaced classes.
            if (Global.Settings.AssignmentCompatibilityMode == ServiceDispatcherSettings.ModCompatibilityMode.UseInstanciatedClassMethods || !Global.Settings.AllowReflection())
            {
                vehicle.Info.m_vehicleAI.StartTransfer(vehicleId, ref vehicle, material, offer);
            }
            else if (vehicle.Info.m_vehicleAI is HearseAI)
            {
                ((HearseAI)vehicle.Info.m_vehicleAI.CastTo<HearseAI>()).StartTransfer(vehicleId, ref vehicle, material, offer);
            }
            else if (vehicle.Info.m_vehicleAI is GarbageTruckAI)
            {
                ((GarbageTruckAI)vehicle.Info.m_vehicleAI.CastTo<GarbageTruckAI>()).StartTransfer(vehicleId, ref vehicle, material, offer);
            }
            else if (vehicle.Info.m_vehicleAI is AmbulanceAI)
            {
                ((AmbulanceAI)vehicle.Info.m_vehicleAI.CastTo<AmbulanceAI>()).StartTransfer(vehicleId, ref vehicle, material, offer);
            }
            else
            {
                vehicle.Info.m_vehicleAI.StartTransfer(vehicleId, ref vehicle, material, offer);
            }

            return vehicle.m_targetBuilding == targetBuildingId && (targetCitizenId == 0 || Singleton<CitizenManager>.instance.m_citizens.m_buffer[targetCitizenId].m_vehicle == vehicleId);
        }
Exemplo n.º 37
0
 public static void CalculateGuestVehicles(CommercialBuildingAI thisAI, ushort buildingID, ref Building data, TransferManager.TransferReason material, ref int count, ref int cargo, ref int capacity, ref int outside)
 {
     Debug.LogWarning("CalculateGuestVehicles is not overridden!");
 }
        private static bool IsInfoNull(TransferManager.TransferOffer offer)
        {
            if (!offer.Active) return false;

            if (offer.Vehicle != 0)
                return VehicleManager.instance.m_vehicles.m_buffer[offer.Vehicle].Info == null;

            if (offer.Building != 0)
                return BuildingManager.instance.m_buildings.m_buffer[offer.Building].Info == null;

            return false;
        }
Exemplo n.º 39
0
 public static bool FindHospital(ResidentAI thisAI, uint citizenID, ushort sourceBuilding, TransferManager.TransferReason reason)
 {
     Debug.LogWarning("FindHospital is not overridden!");
     return false;
 }
Exemplo n.º 40
0
 public static void FindVisitPlace(ResidentAI thisAI, uint citizenID, ushort sourceBuilding, TransferManager.TransferReason reason)
 {
     Debug.LogWarning("FindVisitPlace is not overridden!");
 }
        /// <summary>
        /// Creates the service vehicle.
        /// </summary>
        /// <param name="serviceBuildingId">The service building identifier.</param>
        /// <param name="material">The material.</param>
        /// <param name="targetBuildingId">The target building identifier.</param>
        /// <param name="targetCitizenId">The target citizen identifier.</param>
        /// <param name="vehicleId">The vehicle identifier.</param>
        /// <returns>
        /// The vehicle information.
        /// </returns>
        /// <exception cref="System.NotImplementedException">Target citizen not implemented yet.</exception>
        /// <exception cref="System.InvalidOperationException">Hospital assigments reuires target citizen.</exception>
        /// <exception cref="System.ArgumentException">Unhandled material.</exception>
        /// <exception cref="ArgumentException">Unhandled material.</exception>
        public static VehicleInfo CreateServiceVehicle(ushort serviceBuildingId, TransferManager.TransferReason material, ushort targetBuildingId, uint targetCitizenId, out ushort vehicleId)
        {
            if (targetCitizenId != 0)
            {
                throw new NotImplementedException("Target citizen not implemented yet");
            }

            vehicleId = 0;

            VehicleManager manager = Singleton<VehicleManager>.instance;
            ColossalFramework.Math.Randomizer randomizer = Singleton<SimulationManager>.instance.m_randomizer;

            Building building = BuildingHelper.GetBuilding(serviceBuildingId);

            if (building.Info.m_buildingAI is HospitalAI && targetCitizenId == 0)
            {
                throw new InvalidOperationException("Hospital assigments reuires target citizen");
            }

            VehicleInfo info = manager.GetRandomVehicleInfo(ref randomizer, building.Info.m_class.m_service, building.Info.m_class.m_subService, building.Info.m_class.m_level);
            if (info == null)
            {
                Log.Debug(typeof(VehicleKeeper), "CreateVehicle", "GetRandomVehicleInfo", "no vehicle");
                return null;
            }

            bool transferToSource;
            bool transferToTarget;

            switch (material)
            {
                case TransferManager.TransferReason.Dead:
                    transferToSource = true;
                    transferToTarget = false;
                    break;

                case TransferManager.TransferReason.DeadMove:
                    transferToSource = false;
                    transferToTarget = true;
                    break;

                case TransferManager.TransferReason.Garbage:
                    transferToSource = true;
                    transferToTarget = false;
                    break;

                case TransferManager.TransferReason.GarbageMove:
                    transferToSource = false;
                    transferToTarget = true;
                    break;

                default:
                    throw new ArgumentException("Unhandled material: " + material.ToString());
            }

            if (!manager.CreateVehicle(out vehicleId, ref randomizer, info, building.m_position, material, transferToSource, transferToTarget))
            {
                Log.Debug(typeof(VehicleKeeper), "CreateVehicle", "CreateVehicle", "not created");
                return null;
            }

            info.m_vehicleAI.SetSource(vehicleId, ref manager.m_vehicles.m_buffer[vehicleId], serviceBuildingId);

            if (targetBuildingId != 0 && !AssignTarget(vehicleId, ref manager.m_vehicles.m_buffer[vehicleId], material, targetBuildingId, 0))
            {
                Log.Debug(typeof(VehicleKeeper), "CreateVehicle", "SetTarget", "target not set");
                return null;
            }

            return info;
        }
        /// <summary>
        /// Starts the transfer.
        /// </summary>
        /// <param name="serviceBuildingId">The building identifier.</param>
        /// <param name="building">The building.</param>
        /// <param name="material">The material.</param>
        /// <param name="targetBuildingId">The target building identifier.</param>
        /// <param name="targetCitizenId">The target citizen identifier.</param>
        /// <param name="vehicleId">The vehicle identifier.</param>
        /// <returns>Vehicle info for the created vehicle.</returns>
        /// <exception cref="Exception">Loop counter too high.</exception>
        public static VehicleInfo StartTransfer(ushort serviceBuildingId, ref Building building, TransferManager.TransferReason material, ushort targetBuildingId, uint targetCitizenId, out ushort vehicleId)
        {
            if (building.Info.m_buildingAI is HospitalAI && targetCitizenId == 0)
            {
                return VehicleHelper.CreateServiceVehicle(serviceBuildingId, material, targetBuildingId, targetCitizenId, out vehicleId);
            }

            Vehicle[] vehicles = Singleton<VehicleManager>.instance.m_vehicles.m_buffer;
            Citizen[] citizens = Singleton<CitizenManager>.instance.m_citizens.m_buffer;

            TransferManager.TransferOffer offer = new TransferManager.TransferOffer()
            {
                Building = targetBuildingId,
                Citizen = targetCitizenId,
            };

            // Cast AI as games original AI so detoured methods are called, but not methods from not replaced classes.
            if (Global.Settings.CreationCompatibilityMode == ServiceDispatcherSettings.ModCompatibilityMode.UseInstanciatedClassMethods || !Global.Settings.AllowReflection())
            {
                building.Info.m_buildingAI.StartTransfer(serviceBuildingId, ref building, material, offer);
            }
            else if (building.Info.m_buildingAI is CemeteryAI)
            {
                ((CemeteryAI)building.Info.m_buildingAI.CastTo<CemeteryAI>()).StartTransfer(serviceBuildingId, ref building, material, offer);
            }
            else if (building.Info.m_buildingAI is LandfillSiteAI)
            {
                ((LandfillSiteAI)building.Info.m_buildingAI.CastTo<LandfillSiteAI>()).StartTransfer(serviceBuildingId, ref building, material, offer);
            }
            else if (building.Info.m_buildingAI is HospitalAI)
            {
                ((HospitalAI)building.Info.m_buildingAI.CastTo<HospitalAI>()).StartTransfer(serviceBuildingId, ref building, material, offer);
            }
            else
            {
                building.Info.m_buildingAI.StartTransfer(serviceBuildingId, ref building, material, offer);
            }

            int count = 0;
            vehicleId = building.m_ownVehicles;
            while (vehicleId != 0)
            {
                if (vehicles[vehicleId].m_targetBuilding == targetBuildingId && (targetCitizenId == 0 || citizens[targetCitizenId].m_vehicle == vehicleId))
                {
                    return vehicles[vehicleId].Info;
                }

                if (count >= ushort.MaxValue)
                {
                    throw new Exception("Loop counter too high");
                }

                count++;
                vehicleId = vehicles[vehicleId].m_nextOwnVehicle;
            }

            return null;
        }
 private bool FindHospital(uint citizenID, ushort sourceBuilding, TransferManager.TransferReason reason)
 {
     if (reason == TransferManager.TransferReason.Dead)
     {
         if (Singleton<UnlockManager>.instance.Unlocked(UnlockManager.Feature.DeathCare))
         {
             return true;
         }
        ReleaseCitizen(citizenID);
         return false;
     }
     if (Singleton<UnlockManager>.instance.Unlocked(ItemClass.Service.HealthCare))
     {
         TransferManager.TransferOffer offer = new TransferManager.TransferOffer
         {
             Priority = 6,
             Citizen = citizenID,
             Position = Singleton<BuildingManager>.instance.m_buildings.m_buffer[sourceBuilding].m_position,
             Amount = 1,
             Active = Singleton<SimulationManager>.instance.m_randomizer.Int32(2) == 0
         };
         Singleton<TransferManager>.instance.AddOutgoingOffer(reason, offer);
         return true;
     }
        ReleaseCitizen(citizenID);
     return false;
 }
 public override void StartTransfer(uint citizenID, ref Citizen data, TransferManager.TransferReason reason, TransferManager.TransferOffer offer)
 {
     if (data.m_flags == Citizen.Flags.None || (data.Dead && reason != TransferManager.TransferReason.Dead))
     {
         return;
     }
     switch (reason)
     {
         case TransferManager.TransferReason.Sick:
             if (data.Sick && base.StartMoving(citizenID, ref data, 0, offer.Building))
             {
                 data.SetVisitplace(citizenID, offer.Building, 0u);
             }
             return;
         case TransferManager.TransferReason.Dead:
             if (data.Dead)
             {
                 data.SetVisitplace(citizenID, offer.Building, 0u);
                 if (data.m_visitBuilding != 0)
                 {
                     data.CurrentLocation = Citizen.Location.Visit;
                 }
             }
             return;
         case TransferManager.TransferReason.Worker0:
         case TransferManager.TransferReason.Worker1:
         case TransferManager.TransferReason.Worker2:
         case TransferManager.TransferReason.Worker3:
             if (data.m_workBuilding == 0)
             {
                 data.SetWorkplace(citizenID, offer.Building, 0u);
             }
             return;
         case TransferManager.TransferReason.Student1:
         case TransferManager.TransferReason.Student2:
         case TransferManager.TransferReason.Student3:
             if (data.m_workBuilding == 0)
             {
                 data.SetStudentplace(citizenID, offer.Building, 0u);
             }
             return;
         case TransferManager.TransferReason.Family0:
         case TransferManager.TransferReason.Family1:
         case TransferManager.TransferReason.Family2:
         case TransferManager.TransferReason.Family3:
             if (data.m_homeBuilding != 0 && offer.Building != 0)
             {
                 uint num = Singleton<BuildingManager>.instance.m_buildings.m_buffer[(int)data.m_homeBuilding].FindCitizenUnit(CitizenUnit.Flags.Home, citizenID);
                 if (num != 0u)
                 {
                     this.MoveFamily(num, ref Singleton<CitizenManager>.instance.m_units.m_buffer[(int)((UIntPtr)num)], offer.Building);
                 }
             }
             return;
         case TransferManager.TransferReason.Single0:
         case TransferManager.TransferReason.Single1:
         case TransferManager.TransferReason.Single2:
         case TransferManager.TransferReason.Single3:
         case TransferManager.TransferReason.Single0B:
         case TransferManager.TransferReason.Single1B:
         case TransferManager.TransferReason.Single2B:
         case TransferManager.TransferReason.Single3B:
             data.SetHome(citizenID, offer.Building, 0u);
             if (data.m_homeBuilding == 0)
             {
                ReleaseCitizen(citizenID);
             }
             return;
         case TransferManager.TransferReason.PartnerYoung:
         case TransferManager.TransferReason.PartnerAdult:
             {
                 uint citizen = offer.Citizen;
                 if (citizen != 0u)
                 {
                     CitizenManager instance = Singleton<CitizenManager>.instance;
                     BuildingManager instance2 = Singleton<BuildingManager>.instance;
                     ushort homeBuilding = instance.m_citizens.m_buffer[(int)((UIntPtr)citizen)].m_homeBuilding;
                     if (homeBuilding != 0 && !instance.m_citizens.m_buffer[(int)((UIntPtr)citizen)].Dead)
                     {
                         uint num2 = instance2.m_buildings.m_buffer[(int)homeBuilding].FindCitizenUnit(CitizenUnit.Flags.Home, citizen);
                         if (num2 != 0u)
                         {
                             data.SetHome(citizenID, 0, num2);
                             data.m_family = instance.m_citizens.m_buffer[(int)((UIntPtr)citizen)].m_family;
                         }
                     }
                 }
                 return;
             }
         case TransferManager.TransferReason.Shopping:
         case TransferManager.TransferReason.ShoppingB:
         case TransferManager.TransferReason.ShoppingC:
         case TransferManager.TransferReason.ShoppingD:
         case TransferManager.TransferReason.ShoppingE:
         case TransferManager.TransferReason.ShoppingF:
         case TransferManager.TransferReason.ShoppingG:
         case TransferManager.TransferReason.ShoppingH:
             if (data.m_homeBuilding != 0 && !data.Sick && base.StartMoving(citizenID, ref data, 0, offer.Building))
             {
                 StartJourney(citizenID, data);
                 data.SetVisitplace(citizenID, offer.Building, 0u);
                 CitizenManager instance3 = Singleton<CitizenManager>.instance;
                 BuildingManager instance4 = Singleton<BuildingManager>.instance;
                 uint containingUnit = data.GetContainingUnit(citizenID, instance4.m_buildings.m_buffer[(int)data.m_homeBuilding].m_citizenUnits, CitizenUnit.Flags.Home);
                 if (containingUnit != 0u)
                 {
                     CitizenUnit[] expr_231_cp_0 = instance3.m_units.m_buffer;
                     UIntPtr expr_231_cp_1 = (UIntPtr)containingUnit;
                     expr_231_cp_0[(int)expr_231_cp_1].m_goods = (ushort)(expr_231_cp_0[(int)expr_231_cp_1].m_goods + 100);
                 }
             }
             return;
         case TransferManager.TransferReason.Entertainment:
         case TransferManager.TransferReason.EntertainmentB:
         case TransferManager.TransferReason.EntertainmentC:
         case TransferManager.TransferReason.EntertainmentD:
             if (data.m_homeBuilding != 0 && !data.Sick && base.StartMoving(citizenID, ref data, 0, offer.Building))
             {
                 data.SetVisitplace(citizenID, offer.Building, 0u);
             }
             return;
     }
 }
        /// <summary>
        /// Sets the target and updates the games vehicle object.
        /// </summary>
        /// <param name="targetBuildingId">The target building identifier.</param>
        /// <param name="vehicle">The vehicle.</param>
        /// <param name="material">The material.</param>
        /// <returns>
        /// True if target set vehicle found path the target.
        /// </returns>
        public bool SetTarget(ushort targetBuildingId, ref Vehicle vehicle, TransferManager.TransferReason? material)
        {
            if (targetBuildingId == 0)
            {
                if (this.Target == 0 && vehicle.m_targetBuilding == 0)
                {
                    return true;
                }

                return this.DeAssign(ref vehicle, true, "SetTarget");
            }

            if (Log.LogALot)
            {
                Log.DevDebug(this, "SetTarget", this.VehicleId, targetBuildingId, this.Target, vehicle.m_targetBuilding, vehicle.m_flags);
            }

            if (VehicleHelper.AssignTarget(this.VehicleId, ref vehicle, material, targetBuildingId, 0))
            {
                this.LastAssigned = Global.CurrentFrame;
                this.FreeToCollect = false;
                this.Target = targetBuildingId;

                return true;
            }

            Log.Debug(this, "SetTarget", "Failed", this.VehicleId, targetBuildingId, this.Target, vehicle.m_targetBuilding, vehicle.m_flags);

            this.LastAssigned = 0;
            this.FreeToCollect = false;
            this.Target = 0;

            return false;
        }
 /// <summary>
 /// Starts the transfer.
 /// </summary>
 /// <param name="serviceBuildingId">The building identifier.</param>
 /// <param name="material">The material.</param>
 /// <param name="targetBuildingId">The target building identifier.</param>
 /// <param name="targetCitizenId">The target citizen identifier.</param>
 /// <param name="vehicleId">The vehicle identifier.</param>
 /// <returns>
 /// Vehicle info for the created vehicle.
 /// </returns>
 public static VehicleInfo StartTransfer(ushort serviceBuildingId, TransferManager.TransferReason material, ushort targetBuildingId, uint targetCitizenId, out ushort vehicleId)
 {
     return StartTransfer(serviceBuildingId, ref Singleton<BuildingManager>.instance.m_buildings.m_buffer[serviceBuildingId], material, targetBuildingId, targetCitizenId, out vehicleId);
 }