예제 #1
0
        public bool UpdateContact(Repositories.Contact contact)
        {
            try
            {
                Repositories.Contact original = GetContact(contact.ContactId);

                if (original != null)
                {
                    repository.Entry(original).CurrentValues.SetValues(contact);

                    if (original.Address != null)
                        repository.Entry(original.Address).CurrentValues.SetValues(contact.Address);
                    else if (contact.Address != null)
                    {
                        original.Address = new Address();
                        repository.Entry(original.Address).CurrentValues.SetValues(contact.Address);
                    }

                    repository.SaveChanges();
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
 public DelegationSettingsForUserViewModel(Repositories.IDelegationRepository delegationRepository, IUserManagementRepository userManagementRepository, string username)
 {
     this.delegationRepository = delegationRepository;
     this.userManagementRepository = userManagementRepository;
     int totalCount;
     var allnames =
         userManagementRepository.GetUsers(0, 100, out totalCount)
         .Select(x => new SelectListItem
         {
             Text = x
         }).ToList();
     allnames.Insert(0, new SelectListItem { Text = DelegationSettingsForUserInputModel.ChooseItem, Value = "" });
     this.AllUserNames = allnames;
     
     this.UserName = username;
     if (!IsNew)
     {
         var realmSettings =
                 this.delegationRepository
                     .GetDelegationSettingsForUser(this.UserName)
                     .ToArray();
         this.DelegationSettings = realmSettings;
     }
     else
     {
         this.DelegationSettings = new DelegationSetting[0];
     }
 }
예제 #3
0
        public int AddContact(Repositories.Contact contact)
        {
            repository.Contacts.Add(contact);
            repository.SaveChanges();

            return contact.ContactId;
        }
예제 #4
0
        public ServicesManager(
            INutConfiguration configurationManager,
            Infrastructure.ConfigurationManagement.DbConfigurationSettings.Factory dbConfigurationSettingsFactory,
            IEventBus eventBus,
            IEnumerable<IReportPeriodically> pushServices,
            IEnumerable<IRemoteInvocationService> remoteInvokedServices,
            Services.IGlobalSettingsService globalSettings,
            Func<RegisteredPackagesPollingClient> packagesPollerFactory,
            Func<PollingClientCollection> pollingCollectionFactory,
            Repositories.IPackageRepository packageRepository,
            IHoardeManager hoardeManager)
        {
            _log = LogProvider.For<ServicesManager>();

            _configurationManager = configurationManager;
            _dbConfigurationSettingsFactory = dbConfigurationSettingsFactory;
            _eventBus = eventBus;
            _pushServices = pushServices;
            _remoteInvokedServices = remoteInvokedServices;
            _globalSettings = globalSettings;

            _packagesPollerFactory = packagesPollerFactory;
            _pollingCollectionFactory = pollingCollectionFactory;

            _packageRepository = packageRepository;

            _hoardeManager = hoardeManager;
        }
 public AccountService(Repositories.AccountRepository repository)
 {
     if (repository == null)
     {
         throw new ArgumentException("repository");
     }
     this.repository = repository;
 }
예제 #6
0
 public NodeServiceImpl(Repositories.IRepositoryContext context,
     Repositories.INodeRepository node,
     Repositories.ICommandRepository command)
     : base(context)
 {
     _NodeRepository = node;
     _CommandRepository = command;
 }
예제 #7
0
        public IncentiveService(Logging.ILogger logger,
			Repositories.ICouponRepository couponRepository,
			IAccountService accountService
			)
        {
            this.CouponRepository = couponRepository;
            this.Logger = logger;
            this.AccountService = accountService;
        }
 public IdentityProvidersViewModel(Repositories.IIdentityProviderRepository identityProviderRepository)
 {
     // TODO: Complete member initialization
     this.identityProviderRepository = identityProviderRepository;
     this.IdentityProviders =
         identityProviderRepository.GetAll()
         .Select(x => new IPModel { ID = x.ID, Name = x.DisplayName })
         .ToArray();
 }
        public override bool Transition(Game game, Repositories.TelephoneGameRepository repository)
        {
            if (null != game.gamePhrase)
            {
                ChangeState(game, repository);
                return true;
            }

            return false;
        }
예제 #10
0
 public static IRepository CreateRepository(Repositories type = Repositories.Vk)
 {
     switch (type)
     {
         case Repositories.Vk: return VkRepository.Instance;
         case Repositories.Facebook: return  FacebookRepository.Instance;
         default:
           return new VkRepository();
     }
 }
 public ClientCertificatesViewModel(Repositories.IClientCertificatesRepository clientCertificatesRepository)
 {
     this.clientCertificatesRepository = clientCertificatesRepository;
     this.Users =
         clientCertificatesRepository.List(-1, -1)
         .Select(x => new ClientCertificateUserInputModel
         {
             Username = x
         }).ToArray();
 }
 public RolesViewModel(Repositories.IUserManagementRepository UserManagementRepository)
 {
     this.UserManagementRepository = UserManagementRepository;
     this.Roles =
         UserManagementRepository
             .GetRoles()
             .Select(x => new RoleInputModel { Name = x })
             .OrderBy(x=>x.CanDelete)
             .ToArray();
 }
예제 #13
0
        public override bool Transition(Game game, Repositories.TelephoneGameRepository repository)
        {
            if (!game.error)
            {
                ChangeState(game, repository);
                return true;
            }

            return false;
        }
        public override bool Transition(Game game, Repositories.TelephoneGameRepository repository)
        {
            if (game.numberOfPlayers >= game.gameType.minNumberOfPlayers)
            {
                ChangeState(game, repository);
                return true;
            }

            return false;
        }
예제 #15
0
 public Employee(Repositories.Employee repEmployee)
 {
     this.Id = repEmployee.Id;
     this.FirstName = repEmployee.FirstName;
     this.LastName = repEmployee.LastName;
     this.Patronym = repEmployee.Patronym;
     this.Place = repEmployee.Place;
     this.BirthDate = repEmployee.BirthDate;
     this.DepartmentId = repEmployee.DepartmentId;
 }
예제 #16
0
 public LogServiceImpl(Repositories.IRepositoryContext context,
     Repositories.INodeLogRepository nodeLog,
     Repositories.ITaskLogRepository taskLog,
     Repositories.INodeRepository node,
     Repositories.ITaskRepository task)
     : base(context)
 {
     _NodeLogRepository = nodeLog;
     _TaskLogRepository = taskLog;
     _NodeRepository = node;
     _TaskRepository = task;
 }
        public UsersViewModel(Repositories.IUserManagementRepository UserManagementRepository, int currentPage, string filter)
        {
            Container.Current.SatisfyImportsOnce(this);

            this.UserManagementRepository = UserManagementRepository;
            this.Filter = filter;

            Init(currentPage, filter);
            if (TotalPages < CurrentPage)
            {
                Init(TotalPages, filter);
            }
        }
 public ProtocolsViewModel(Repositories.IConfigurationRepository ConfigurationRepository)
 {
     this.ConfigurationRepository = ConfigurationRepository;
     
     for (int i = 0; i < protocolMap.Count; i++)
     {
         var item = protocolMap[i];
         var id = i;
         var name = item.Item1;
         var enabled = item.Item2(this.ConfigurationRepository).Enabled;
         protocols.Add(new Protocol { ID = id, Name = name, Enabled = enabled });
     }
 }
예제 #19
0
        public GitHubApi(IHttpClient client)
        {
            this.client = client;

            client.BeforeRequest += ClientOnBeforeRequest;
            client.AfterRequest += ClientOnAfterRequest;

            Repositories = new Repositories(client);
            Gists = new Gists(client);
            Issues = new Issues(client);
            Milestones = new Milestones(client);
            Labels = new Labels(client);
            Users = new Users(client);
            Authorizations = new Authorizations(client);
            Keys = new Keys(client);
        }
        public UsersViewModel(Repositories.IUserManagementRepository UserManagementRepository, string filter)
        {
            // TODO: Complete member initialization
            this.UserManagementRepository = UserManagementRepository;
            this.Filter = filter;

            if (String.IsNullOrEmpty(filter))
            {
                Users = UserManagementRepository.GetUsers();
                Total = Showing;
            }
            else
            {
                Users = UserManagementRepository.GetUsers(filter);
                Total = UserManagementRepository.GetUsers().Count();
            }
        }
예제 #21
0
        public CartService(Logging.ILogger logger
			, Repositories.ICartRepository cartRepository
            , Services.ICatalogService catalogService
			, Services.IAccountService accountService
			, Services.IEventPublisher eventPublisherService
			, Repositories.ICommentRepository commentRepository
			)
        {
            m_LastCartItems = new System.Collections.Generic.SynchronizedCollection<CartItem>();

            this.Logger = logger;
            this.CartRepository = cartRepository;
            this.CatalogService = catalogService;
            this.AccountService = accountService;
            this.EventPublisherService = eventPublisherService;
            this.CommentRepository = commentRepository;
        }
예제 #22
0
      protected void Application_Start()
      {
         InitializeContainer();
         ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
         RegisterRoutes(RouteTable.Routes);

         _completeQueue = _container.Resolve<IMessageQueue>("Complete");

         _pollingThread = new Thread(CompletePolling);

         var repositories = new Repositories
         {
            BinaryRepository = _container.Resolve<IBinaryRepository>(),
            ImageRepository = _container.Resolve<IImageRepository>()
         };

         _pollingThread.Start(repositories);
      }
        public void Update(Repositories.IConfigurationRepository ConfigurationRepository)
        {
            var keys = ConfigurationRepository.Keys;
            try
            {
                var cert = X509.LocalMachine.My.SubjectDistinguishedName.Find(SigningCertificate, false).First();

                // make sure we can access the private key
                var pk = cert.PrivateKey;

                keys.SigningCertificate = cert;
            }
            catch (CryptographicException)
            {
                throw new ValidationException(string.Format(Resources.KeyConfigurationViewModel.NoReadAccessToPrivateKey, WindowsIdentity.GetCurrent().Name));
            }

            if (DecryptionCertificate == null)
            {
                keys.DecryptionCertificate = null;
            }
            else
            {
                try
                {
                    var cert = X509.LocalMachine.My.SubjectDistinguishedName.Find(DecryptionCertificate, false).First();

                    // make sure we can access the private key
                    var pk = cert.PrivateKey;

                    keys.DecryptionCertificate = cert;
                }
                catch (CryptographicException)
                {
                    throw new ValidationException(string.Format(Resources.KeyConfigurationViewModel.NoReadAccessToPrivateKey, WindowsIdentity.GetCurrent().Name));
                }
            }

            keys.SymmetricSigningKey = SymmetricSigningKey;

            // updates key material config
            ConfigurationRepository.Keys = keys;
        }
        public void Update(Repositories.IConfigurationRepository ConfigurationRepository)
        {
            var keys = ConfigurationRepository.Keys;
            try
            {
                var cert = X509.LocalMachine.My.SubjectDistinguishedName.Find(SigningCertificate, false).First();

                // make sure we can access the private key
                var pk = cert.PrivateKey;

                keys.SigningCertificate = cert;
            }
            catch (CryptographicException)
            {
                throw new ValidationException(WindowsIdentity.GetCurrent().Name + " does not have read access to the private key of the signing certificate you selected (see http://technet.microsoft.com/en-us/library/ee662329.aspx).");
            }

            if (DecryptionCertificate == null)
            {
                keys.DecryptionCertificate = null;
            }
            else
            {
                try
                {
                    var cert = X509.LocalMachine.My.SubjectDistinguishedName.Find(DecryptionCertificate, false).First();

                    // make sure we can access the private key
                    var pk = cert.PrivateKey;

                    keys.DecryptionCertificate = cert;
                }
                catch (CryptographicException)
                {
                    throw new ValidationException(WindowsIdentity.GetCurrent().Name + " does not have read access to the private key of the signing certificate you selected (see http://technet.microsoft.com/en-us/library/ee662329.aspx).");
                }
            }

            keys.SymmetricSigningKey = SymmetricSigningKey;

            // updates key material config
            ConfigurationRepository.Keys = keys;
        }
        public UsersViewModel(Repositories.IUserManagementRepository UserManagementRepository, string filter)
        {
            this.UserManagementRepository = UserManagementRepository;
            this.Filter = filter;

            if (String.IsNullOrEmpty(filter))
            {
                Users = UserManagementRepository.GetUsers();
                Total = Showing = Users.Count();
            }
            else
            {
                Users = UserManagementRepository.GetUsers(filter);
                Total = UserManagementRepository.GetUsers().Count();
                Showing = Users.Count();
            }

            UsersDeleteList = Users.Select(x => new UserDeleteModel { Username = x }).ToArray();
        }
예제 #26
0
        public static async Task ExtractTweetFeatures(Tweet tweet, Repositories.IOutput outpurRepo)
        {
            //Maintain the 60 second window of tweets
            MaintainTimeWindow(tweet, 60);

            string strResult = tweet.text;

            //Clean the tweet text up
            strResult = GetCleanedupTweetText(tweet.text);

            if (!string.IsNullOrEmpty(strResult))
            {
                //Process hashtags and related features (graphs and so on)
                ProcessHashtagData(tweet, strResult);

                if (outpurRepo != null)
                {
                    await outpurRepo.WriteFeatureOneOutputAsync(strResult, tweet.created_at);
                    await outpurRepo.WriteFeatureTwoOutputAsync(CalculateAverageDegree());
                }
            }
        }
예제 #27
0
 protected void InitializeContext()
 {
     Repositories.Load(new Repositories());
     Repositories.LoadContext(new EntityObjectContextTest());
 }
 public OAuthClientIndexViewModel(Repositories.IClientsRepository clientsRepository)
 {
     // TODO: Complete member initialization
     this.clientsRepository = clientsRepository;
     this.Clients = this.clientsRepository.GetAll().Select(x=>new OAuthClientIndexInputModel{Name=x.Name, ID=x.ID}).ToArray();
 }
예제 #29
0
        protected override async void OnInitialize()
        {
            var results = await repositories.Search("mvvm");

            Repositories.AddRange(results.Select(r => new RepositoryViewModel(r)));
        }
예제 #30
0
 public Services()
 {
     repository = new Repositories();
 }
        public override async Task <long> SubmitDeleteChangeRequestAsync <TId>(WheelBase entity, TId id, string requestedBy, List <ChangeRequestItemStaging> changeRequestItemStagings = null, CommentsStagingModel comment = null, List <AttachmentsModel> attachmentsStaging = null, string changeContent = null)
        {
            // validation
            if (id.Equals(default(TId)))
            {
                throw new ArgumentNullException(nameof(id));
            }
            var wheelBaseFromDb = await FindAsync(id);

            if (wheelBaseFromDb == null)
            {
                throw new NoRecordFound("No Wheel Base exist");
            }

            changeRequestItemStagings = changeRequestItemStagings ?? new List <ChangeRequestItemStaging>();
            changeRequestItemStagings.Add(new ChangeRequestItemStaging()
            {
                EntityId        = wheelBaseFromDb.Id.ToString(),
                Entity          = typeof(WheelBase).Name,
                ChangeType      = ChangeType.Delete,
                CreatedDateTime = DateTime.UtcNow,
                Payload         = Serializer.Serialize(new WheelBase()
                {
                    Id              = wheelBaseFromDb.Id,
                    Base            = wheelBaseFromDb.Base,
                    WheelBaseMetric = wheelBaseFromDb.WheelBaseMetric
                })
            });

            changeContent = string.Format("{0} / {1}"
                                          , wheelBaseFromDb.Base, wheelBaseFromDb.WheelBaseMetric);

            var changeRequestId = await base.SubmitDeleteChangeRequestAsync(wheelBaseFromDb, id, requestedBy, changeRequestItemStagings, comment, attachmentsStaging, changeContent);

            wheelBaseFromDb.ChangeRequestId = changeRequestId;
            _wheelBaseRepositoryService.Update(wheelBaseFromDb);
            Repositories.SaveChanges();

            IList <VehicleToWheelBase> existingVehicleToWheelBases =
                await
                base.Repositories.GetRepositoryService <VehicleToWheelBase>()
                .GetAsync(item => item.WheelBaseId.Equals(wheelBaseFromDb.Id) && item.DeleteDate == null);

            if (existingVehicleToWheelBases == null || existingVehicleToWheelBases.Count == 0)
            {
                var vehicleToWheelBaseSearchResult = await _vehicleToWheelBaseSearchService.SearchAsync(null, $"wheelBaseId eq {wheelBaseFromDb.Id}");

                var existingVehicleToWheelBaseDocuments = vehicleToWheelBaseSearchResult.Documents;
                if (existingVehicleToWheelBaseDocuments != null && existingVehicleToWheelBaseDocuments.Any())
                {
                    foreach (var existingVehicleToWheelBaseDocument in existingVehicleToWheelBaseDocuments)
                    {
                        //existingVehicleDocument.VehicleId must be a GUID string
                        await _vehicleToWheelBaseIndexingService.UpdateWheelBaseChangeRequestIdAsync(existingVehicleToWheelBaseDocument.VehicleToWheelBaseId, changeRequestId);
                    }
                }
            }
            else
            {
                foreach (var vehicleToWheelBase in existingVehicleToWheelBases)
                {
                    await _vehicleToWheelBaseIndexingService.UpdateVehicleToWheelBaseChangeRequestIdAsync(vehicleToWheelBase.Id.ToString(), changeRequestId);
                }
            }
            return(changeRequestId);
        }
예제 #32
0
        public override async Task <long> SubmitUpdateChangeRequestAsync <TId>(BedLength entity, TId id, string requestedBy,
                                                                               ChangeType changeType = ChangeType.None,
                                                                               List <ChangeRequestItemStaging> changeRequestItemStagings = null, CommentsStagingModel comment = null, List <AttachmentsModel> attachments = null, string changeContent = null)
        {
            if (String.IsNullOrWhiteSpace(entity?.Length))
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (String.IsNullOrWhiteSpace(entity?.BedLengthMetric))
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (id.Equals(default(TId)))
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (!entity.Id.Equals(id))
            {
                throw new ArgumentException("Invalid Bed Length Id");
            }

            var bedLengthFromDb = await FindAsync(id);

            if (bedLengthFromDb == null)
            {
                throw new NoRecordFound("No Bed Length exist");
            }

            changeRequestItemStagings = changeRequestItemStagings ?? new List <ChangeRequestItemStaging>();
            await ValidateBedLengthIsNotDuplicate(entity, ChangeType.Modify);
            await ValidateBedLengthHasNoChangeRequest(entity);
            await ValidateBedLengthLookUpHasNoChangeRequest(entity);

            entity.InsertDate = bedLengthFromDb.InsertDate;
            var existingEntity = new BedLength()
            {
                Id                      = bedLengthFromDb.Id,
                Length                  = bedLengthFromDb.Length,
                BedLengthMetric         = bedLengthFromDb.BedLengthMetric,
                ChangeRequestId         = bedLengthFromDb.ChangeRequestId,
                VehicleToBedConfigCount = bedLengthFromDb.VehicleToBedConfigCount,
                DeleteDate              = bedLengthFromDb.DeleteDate,
                InsertDate              = bedLengthFromDb.InsertDate,
                LastUpdateDate          = bedLengthFromDb.LastUpdateDate
            };

            changeRequestItemStagings.Add(new ChangeRequestItemStaging()
            {
                ChangeType      = ChangeType.Modify,
                EntityId        = entity.Id.ToString(),
                CreatedDateTime = DateTime.UtcNow,
                Entity          = typeof(BedLength).Name,
                Payload         = Serializer.Serialize(entity),
                ExistingPayload = Serializer.Serialize(existingEntity)
            });

            changeContent = string.Format("{0} / {1} > {2} / {3}"
                                          , bedLengthFromDb.Length, bedLengthFromDb.BedLengthMetric
                                          , entity.Length, entity.BedLengthMetric);

            var changeRequestId = await base.SubmitUpdateChangeRequestAsync(entity, id, requestedBy, ChangeType.Modify, changeRequestItemStagings, comment, attachments, changeContent);

            bedLengthFromDb.ChangeRequestId = changeRequestId;
            _bedLengthRepositoryService.Update(bedLengthFromDb);
            Repositories.SaveChanges();

            return(changeRequestId);
        }
예제 #33
0
파일: AddClient.cs 프로젝트: vadalex/ibank
        public override bool Execute()
        {
            if (!Verifier.CheckName(Country))
            {
                Information = StringSource.NameStructureError();
                return(false);
            }
            if (!Verifier.CheckAddress(Address))
            {
                Information = StringSource.AddressStructureError();
                return(false);
            }
            if (!Verifier.CheckPassportNumber(PassportNumber))
            {
                Information = StringSource.PassportNumberStructureError();
                return(false);
            }
            if (!Verifier.CheckName(FirstName))
            {
                Information = StringSource.NameStructureError();
                return(false);
            }
            if (!Verifier.CheckName(LastName))
            {
                Information = StringSource.NameStructureError();
                return(false);
            }
            if (!Verifier.CheckName(MiddleName))
            {
                Information = StringSource.NameStructureError();
                return(false);
            }
            if (!Verifier.CheckEMail(EMail))
            {
                Information = StringSource.EMailStructureError();
                return(false);
            }

            Client = new Customer {
                FirstName      = FirstName,
                LastName       = LastName,
                MiddleName     = MiddleName,
                PassportNumber = PassportNumber,
                Country        = Country,
                Address        = Address,
                Email          = EMail,
                Login          = LoginGeneration(),
                Passoword      = PasswordGeneration(),
                IsLocked       = false,
            };

            var gen = new Generator {
                NumberCount = DataSource.LengthCode
            };

            using (var localrepos = new Repositories()) {
                var all = localrepos.Customers.GetAll();
                if (all.Where(el => el.PassportNumber == PassportNumber).Count() > 0)
                {
                    Information = StringSource.ClientPassportNumberIsContains();
                    return(false);
                }

                localrepos.Customers.Add(Client);
                localrepos.SaveChanges();
                ////////////////////////////////////////////////////////////////////
                new Supporting().RemoveClientInformationById(Client.CustomerID);
                ////////////////////////////////////////////////////////////////////
                if (all.Count() > 0)
                {
                    var cl = all.Where(el => el.Login == Client.Login).ToList();
                    if (cl.Count() > 0)
                    {
                        var cc = (Customer)cl.ElementAt(0);
                        IdClient = cc.CustomerID;
                    }
                    else
                    {
                        Information = StringSource.ClientRegistredError(); return(false);
                    }
                }
                else
                {
                    Information = StringSource.ClientRegistredError(); return(false);
                }

                // зарегаем карту доступа
                AccessCard = new AccessCard {
                    //Customer=Client,
                    CustomerID      = Client.CustomerID,
                    EnteredCodeFail = 0,
                    IsBlocked       = false,
                    //AccessCodes=,
                };
                localrepos.AccessCards.Add(AccessCard);
                localrepos.SaveChanges();

                var acs = localrepos.AccessCards.GetAll();
                if (acs.Count() > 0)
                {
                    var acs2 = acs.Where(el => el.CustomerID == Client.CustomerID).ToArray();
                    if (acs2.Count() > 0)
                    {
                        AccessCard = acs2[0];
                    }
                    else
                    {
                        Information = StringSource.ClientRegistredError(); return(false);
                    }
                }
                else
                {
                    Information = StringSource.ClientRegistredError(); return(false);
                }

                for (int i = 0; i < 40; i++)
                {
                    localrepos.AccessCodes.Add(new AccessCode {
                        //AccessCard=ac,
                        AccessCardID = AccessCard.AccessCardID,
                        Code         = gen.NumberGenerate().ToString(),
                        Number       = i + 1,
                    });
                }
                ;
                localrepos.SaveChanges();
            }
            Login       = Client.Login;
            Information = StringSource.ClientRegistred(Client.Login);
            return(true);
        }
 public IDisposable StartOperation(string operation, string mainPackageId, string mainPackageVersion)
 {
     return(DisposableAction.All(
                Repositories.Select(r => r.StartOperation(operation, mainPackageId, mainPackageVersion))));
 }
예제 #35
0
 public static string GetGithubUrl(Repositories rep)
 {
     return("");
 }
예제 #36
0
        private void OkClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.Default;
                _branchListLoader.Cancel();

                // validate if destination path is supplied
                var destination = _NO_TRANSLATE_To.Text;
                if (string.IsNullOrWhiteSpace(destination))
                {
                    MessageBox.Show(this, _errorDestinationNotSupplied.Text, _errorCloneFailed.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _NO_TRANSLATE_To.Focus();
                    return;
                }

                if (!Path.IsPathRooted(destination))
                {
                    MessageBox.Show(this, _errorDestinationNotRooted.Text, _errorCloneFailed.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _NO_TRANSLATE_To.Focus();
                    return;
                }

                var dirTo = Path.Combine(destination, _NO_TRANSLATE_NewDirectory.Text);

                // this will fail if the path is anyhow invalid
                dirTo = new Uri(dirTo).LocalPath;

                if (!Directory.Exists(dirTo))
                {
                    Directory.CreateDirectory(dirTo);
                }

                // Shallow clone params
                int? depth          = null;
                bool?isSingleBranch = null;
                if (!cbDownloadFullHistory.Checked)
                {
                    depth = 1;

                    // Single branch considerations:
                    // If neither depth nor single-branch family params are specified, then it's like no-single-branch by default.
                    // If depth is specified, then single-branch is assumed.
                    // But with single-branch it's really nontrivial to switch to another branch in the GUI, and it's very hard in cmdline (obvious choices to fetch another branch lead to local repo corruption).
                    // So let's reset it to no-single-branch to (a) have the same branches behavior as with full clone, and (b) make it easier for users when switching branches.
                    isSingleBranch = false;
                }

                // Branch name param
                string branch = _NO_TRANSLATE_Branches.Text;
                if (branch == _branchDefaultRemoteHead.Text)
                {
                    branch = "";
                }
                else if (branch == _branchNone.Text)
                {
                    branch = null;
                }

                var cloneCmd = GitCommandHelpers.CloneCmd(_NO_TRANSLATE_From.Text, dirTo,
                                                          CentralRepository.Checked, cbIntializeAllSubmodules.Checked, branch, depth, isSingleBranch, cbLfs.Checked);
                using (var fromProcess = new FormRemoteProcess(Module, AppSettings.GitCommand, cloneCmd))
                {
                    fromProcess.SetUrlTryingToConnect(_NO_TRANSLATE_From.Text);
                    fromProcess.ShowDialog(this);

                    if (fromProcess.ErrorOccurred() || Module.InTheMiddleOfPatch())
                    {
                        return;
                    }
                }

                Repositories.AddMostRecentRepository(dirTo);

                if (!string.IsNullOrEmpty(_puttySshKey))
                {
                    var clonedGitModule = new GitModule(dirTo);
                    clonedGitModule.SetSetting(string.Format(SettingKeyString.RemotePuttySshKey, "origin"), _puttySshKey);
                    clonedGitModule.LocalConfigFile.Save();
                }

                if (_openedFromProtocolHandler && AskIfNewRepositoryShouldBeOpened(dirTo))
                {
                    Hide();
                    GitUICommands uiCommands = new GitUICommands(dirTo);
                    uiCommands.StartBrowseDialog();
                }
                else if (ShowInTaskbar == false && _gitModuleChanged != null &&
                         AskIfNewRepositoryShouldBeOpened(dirTo))
                {
                    _gitModuleChanged(this, new GitModuleEventArgs(new GitModule(dirTo)));
                }

                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Exception: " + ex.Message, _errorCloneFailed.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 public IPackageRepository Clone()
 {
     return(new AggregateRepository(Repositories.Select(PackageRepositoryExtensions.Clone)));
 }
예제 #38
0
 protected override void RegisterQuestions()
 {
     Repositories.RegisterQuestion <CustomQuestion>(language => language.GetExtension <ILanguageCustomModule>().Questions.Names.Custom);
 }
 public DelegationViewModel(Repositories.IDelegationRepository delegationRepository)
 {
     this.delegationRepository = delegationRepository;
 }
예제 #40
0
        public IEnumerable <SourcePackageDependencyInfo> ResolveDependencyGraph(PackageIdentity pkgId, IEnumerable <SourcePackageDependencyInfo> dependencies)
        {
            // We used PackageResolver to flatten the dependency graph. This is the process Nuget uses
            // when adding a package to a project. It takes:
            // - a list of targets, in this case the package we want to add
            // - a list of packages already installed, (i.e. the package that used to be defined in the packages.config)
            //      * in our case, the packages already added to this service
            // - a list of available packages (i.e. the list of packages in the nuget sources).
            //      * in our case, all the dependencies we already found via GetPackageDependencies
            // The resolver will then filter out the list such that only one version of each package
            //  gets installed.
            var resolverContext = new PackageResolverContext(
                dependencyBehavior: DependencyBehavior.Lowest,
                targetIds: new[] { pkgId.Id },
                requiredPackageIds: Enumerable.Empty <string>(),
                packagesConfig: Items.Select(p => new PackageReference(p, NETCOREAPP3_1, true)),
                preferredVersions: Enumerable.Empty <PackageIdentity>(),
                availablePackages: dependencies,
                packageSources: Repositories.Select(s => s.PackageSource),
                log: Logger);

            var resolver = new PackageResolver();

            try
            {
                return(resolver.Resolve(resolverContext, CancellationToken.None)
                       .Select(p => dependencies.Single(x => PackageIdentityComparer.Default.Equals(x, p))));
            }
            catch (NuGetResolverConstraintException exception)
            {
                Logger.LogWarning($"Exception caught when resolving package dependencies: {exception.Message}");
            }

            /*
             *  First we try using the NuGet PackageResolver to resolve all package dependencies.
             *  It's main purpose is to find which version of each package that needs to be loaded
             *  that satisfies all dependencies.
             *  But it may fail trying to find the perfect solution because some deeper package
             *  dependency might not be available, even though that dependency might never be
             *  needed in runtime.
             *  So we are opting to try to load our target package and all the available
             *  dependencies that could be found using the latest versions that are available in
             *  the local folders.
             */
            var uniquePackageIds        = dependencies.Select(pkg => pkg.Id).Distinct();
            var uniqueAvailablePackages = uniquePackageIds.SelectMany(
                pkgId =>
                LocalPackagesFinder.FindPackagesById(pkgId, Logger, CancellationToken.None)
                .OrderByDescending(pkg => pkg.Identity.Version)
                .Take(1)
                .Select(
                    pkg => new SourcePackageDependencyInfo(
                        id: pkg.Identity.Id,
                        version: pkg.Identity.Version,
                        dependencies: dependencies
                        .Where(d => d.Id == pkg.Identity.Id)
                        .OrderByDescending(d => d.Version.Version)
                        .FirstOrDefault()
                        ?.Dependencies ?? new List <PackageDependency>(),
                        listed: true,
                        source: GlobalPackagesSource))
                );

            return(uniqueAvailablePackages);
        }
예제 #41
0
 public void Reset()
 {
     Repositories.Clear();
 }
예제 #42
0
 public Library Main() => Repositories.Libraries.Query().FirstOrDefault(x => x.Name == MainLibraryName) ?? Repositories.Libraries.Add(new Library
 {
     Name = MainLibraryName
 }).With(x => Repositories.Save());
예제 #43
0
 protected override Task Load(bool forceCacheInvalidation)
 {
     return(Repositories.SimpleCollectionLoad(() => this.GetApplication().Client.Account.GetRepositoriesFollowing(forceCacheInvalidation)));
 }
        protected virtual void TransactionScopeFixture()
        {
            ClearSharedRepositories();

            using (var scope = new TransactionScope(TransactionScopeOption.Required,
                                                    new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                using (Repositories.Use())
                {
                    var model7 = new TestModel7()
                    {
                        Model7Id = 7, DataString = "data7", DataInt = 7, DataDateTime = DateTime.Now, NullableDateTime = DateTime.Now
                    };
                    TestModel7Repo.AddOne(model7).UpdateAll();
                    var model8 = new TestModel8()
                    {
                        Id = 8, Model7Id = 7, DataString = "data8", DataInt = 8, DataDateTime = DateTime.Now, NullableDateTime = DateTime.Now
                    };
                    TestModel8Repo.AddOne(model8).UpdateAll();
                    TestModel8Repo.UpdateAll();

                    scope.Complete();

                    var model70 = new TestModel7()
                    {
                        Model7Id = 70, DataString = "data7", DataInt = 7, DataDateTime = DateTime.Now, NullableDateTime = DateTime.Now
                    };
                    TestModel7Repo.AddOne(model70);
                    Assert.Throws <EntityException>(() => TestModel7Repo.UpdateAll());//The underlying provider failed on open
                }
            }

            using (var scope = new TransactionScope(TransactionScopeOption.Required,
                                                    new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                using (Repositories.Use())
                {
                    var model71 = new TestModel7()
                    {
                        Model7Id = 71, DataString = "data7", DataInt = 7, DataDateTime = DateTime.Now, NullableDateTime = DateTime.Now
                    };
                    TestModel7Repo.AddOne(model71).UpdateAll();
                    var model81 = new TestModel8()
                    {
                        Id = 81, Model7Id = 7, DataString = "data8", DataInt = 8, DataDateTime = DateTime.Now, NullableDateTime = DateTime.Now
                    };
                    TestModel8Repo.AddOne(model81).UpdateAll();
                }
            }

            using (Repositories.Use())
            {
                TestModel7Repo.GetOne(x => x.Model7Id == 7).Should().Not.Be.Null();
                TestModel8Repo.GetOne(x => x.Id == 8).Should().Not.Be.Null();
                TestModel7Repo.GetOne(x => x.Model7Id == 71).Should().Be.Null();
                TestModel8Repo.GetOne(x => x.Id == 81).Should().Be.Null();
            }


            ClearSharedRepositories();
        }
 protected override Task Load()
 {
     return(Repositories.SimpleCollectionLoad(this.GetApplication().Client.AuthenticatedUser.Repositories.GetStarred()));
 }
예제 #46
0
 public BaseService(Repositories repositories)
 {
     Repositories = repositories;
 }
예제 #47
0
 public IQueryable <IPackage> Search(string searchTerm, IEnumerable <string> targetFrameworks, bool allowPrereleaseVersions)
 {
     return(CreateAggregateQuery(Repositories.Select(r => r.Search(searchTerm, targetFrameworks, allowPrereleaseVersions))));
 }
예제 #48
0
 public InterestService(Repositories repos)
     : base(repos)
 {
 }
예제 #49
0
 public IEnumerable <Repository> GetLocalRepositories()
 {
     return(Repositories?.Where(r => r.IsDownloaded()) ?? Enumerable.Empty <Repository>());
 }
        public override async Task <long> SubmitUpdateChangeRequestAsync <TId>(FuelDeliveryType entity, TId id, string requestedBy,
                                                                               ChangeType changeType = ChangeType.None,
                                                                               List <ChangeRequestItemStaging> changeRequestItemStagings = null, CommentsStagingModel comment = null, List <AttachmentsModel> attachments = null, string changeContent = null)
        {
            if (string.IsNullOrWhiteSpace(entity?.FuelDeliveryTypeName))
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (id.Equals(default(TId)))
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (!entity.Id.Equals(id))
            {
                throw new ArgumentException("Invalid FuelDeliveryType Id");
            }

            var fuelDeliveryTypeFromDb = await FindAsync(id);

            if (fuelDeliveryTypeFromDb == null)
            {
                throw new NoRecordFound("Record Not Found");
            }

            // validations
            await ValidateFuelDeliveryTypeIsNotDuplicate(entity, ChangeType.Modify);
            await ValidateFuelDeliveryTypeHasNoChangeRequest(entity, ChangeType.Modify);
            await ValidateFuelDeliveryTypeLookUpHasNoChangeRequest(entity);

            // fill up audit information
            entity.InsertDate     = fuelDeliveryTypeFromDb.InsertDate;
            entity.LastUpdateDate = fuelDeliveryTypeFromDb.LastUpdateDate;
            entity.DeleteDate     = fuelDeliveryTypeFromDb.DeleteDate;

            changeRequestItemStagings = changeRequestItemStagings ?? new List <ChangeRequestItemStaging>();

            // to eliminate circular reference during serialize
            var existingEntity = new FuelDeliveryType()
            {
                Id = fuelDeliveryTypeFromDb.Id,
                FuelDeliveryTypeName    = fuelDeliveryTypeFromDb.FuelDeliveryTypeName,
                ChangeRequestId         = fuelDeliveryTypeFromDb.ChangeRequestId,
                FuelDeliveryConfigCount = fuelDeliveryTypeFromDb.FuelDeliveryConfigCount,
                FuelDeliveryConfigs     = fuelDeliveryTypeFromDb.FuelDeliveryConfigs,
                DeleteDate     = fuelDeliveryTypeFromDb.DeleteDate,
                InsertDate     = fuelDeliveryTypeFromDb.InsertDate,
                LastUpdateDate = fuelDeliveryTypeFromDb.LastUpdateDate
            };

            changeRequestItemStagings.Add(new ChangeRequestItemStaging
            {
                EntityId        = entity.Id.ToString(),
                Entity          = typeof(FuelDeliveryType).Name,
                ChangeType      = ChangeType.Modify,
                CreatedDateTime = DateTime.UtcNow,
                Payload         = Serializer.Serialize(entity),
                ExistingPayload = base.Serializer.Serialize(existingEntity) // add existing record as ExistingPayload
            });

            changeContent = string.Format("{0} > {1}"
                                          , fuelDeliveryTypeFromDb.FuelDeliveryTypeName
                                          , entity.FuelDeliveryTypeName);

            var changeRequestId = await
                                  base.SubmitUpdateChangeRequestAsync(entity, id, requestedBy, ChangeType.Modify,
                                                                      changeRequestItemStagings, comment, attachments, changeContent);

            fuelDeliveryTypeFromDb.ChangeRequestId = changeRequestId;
            _fuelDeliveryTypeRepositoryService.Update(fuelDeliveryTypeFromDb);
            Repositories.SaveChanges();

            return(changeRequestId);
        }
        public override async Task <long> SubmitUpdateChangeRequestAsync <TId>(WheelBase entity, TId id, string requestedBy,
                                                                               ChangeType changeType = ChangeType.None,
                                                                               List <ChangeRequestItemStaging> changeRequestItemStagings = null, CommentsStagingModel comment = null, List <AttachmentsModel> attachments = null, string changeContent = null)
        {
            if (String.IsNullOrWhiteSpace(entity?.Base))
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (String.IsNullOrWhiteSpace(entity?.WheelBaseMetric))
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (id.Equals(default(TId)))
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (!entity.Id.Equals(id))
            {
                throw new ArgumentException("Invalid Wheel Base Id");
            }

            var wheelBaseFromDb = await FindAsync(id);

            if (wheelBaseFromDb == null)
            {
                throw new NoRecordFound("No WheelBase exist");
            }

            changeRequestItemStagings = changeRequestItemStagings ?? new List <ChangeRequestItemStaging>();
            await ValidateWheelBaseHasNoChangeRequest(entity);

            entity.InsertDate = wheelBaseFromDb.InsertDate;
            var existingEntity = new WheelBase()
            {
                Id                      = wheelBaseFromDb.Id,
                Base                    = wheelBaseFromDb.Base,
                WheelBaseMetric         = wheelBaseFromDb.WheelBaseMetric,
                ChangeRequestId         = wheelBaseFromDb.ChangeRequestId,
                VehicleToWheelBaseCount = wheelBaseFromDb.VehicleToWheelBaseCount,
                DeleteDate              = wheelBaseFromDb.DeleteDate,
                InsertDate              = wheelBaseFromDb.InsertDate,
                LastUpdateDate          = wheelBaseFromDb.LastUpdateDate
            };

            changeRequestItemStagings.Add(new ChangeRequestItemStaging()
            {
                ChangeType      = ChangeType.Modify,
                EntityId        = entity.Id.ToString(),
                CreatedDateTime = DateTime.UtcNow,
                Entity          = typeof(WheelBase).Name,
                Payload         = Serializer.Serialize(entity),
                ExistingPayload = Serializer.Serialize(existingEntity)
            });

            changeContent = string.Format("{0} / {1} > {2} / {3}"
                                          , wheelBaseFromDb.Base, wheelBaseFromDb.WheelBaseMetric
                                          , entity.Base, entity.WheelBaseMetric);

            var changeRequestId = await base.SubmitUpdateChangeRequestAsync(entity, id, requestedBy, ChangeType.Modify, changeRequestItemStagings, comment, attachments, changeContent);

            wheelBaseFromDb.ChangeRequestId = changeRequestId;
            _wheelBaseRepositoryService.Update(wheelBaseFromDb);
            Repositories.SaveChanges();

            IList <VehicleToWheelBase> existingVehicleToWheelBases =
                await
                base.Repositories.GetRepositoryService <VehicleToWheelBase>()
                .GetAsync(item => item.WheelBaseId.Equals(wheelBaseFromDb.Id) && item.DeleteDate == null);

            if (existingVehicleToWheelBases == null || existingVehicleToWheelBases.Count == 0)
            {
                var vehicleToWheelBaseSearchResult = await _vehicleToWheelBaseSearchService.SearchAsync(null, $"wheelBaseId eq {wheelBaseFromDb.Id}");

                var existingVehicleToWheelBaseDocuments = vehicleToWheelBaseSearchResult.Documents;
                if (existingVehicleToWheelBaseDocuments != null && existingVehicleToWheelBaseDocuments.Any())
                {
                    foreach (var existingVehicleToWheelBaseDocument in existingVehicleToWheelBaseDocuments)
                    {
                        //existingVehicleDocument.VehicleId must be a GUID string
                        await _vehicleToWheelBaseIndexingService.UpdateWheelBaseChangeRequestIdAsync(existingVehicleToWheelBaseDocument.VehicleToWheelBaseId, changeRequestId);
                    }
                }
            }
            else
            {
                //NOTE: wheelBaseFromDb.VehicleToBrakeConfigs will be null because it is not lazy loaded
                foreach (var vehicleToWheelBase in existingVehicleToWheelBases)
                {
                    await _vehicleToWheelBaseIndexingService.UpdateWheelBaseChangeRequestIdAsync(vehicleToWheelBase.Id.ToString(), changeRequestId);
                }
            }
            return(changeRequestId);
        }
예제 #52
0
 public void Init()
 {
     this.service = new MealsService(Repositories.GetMealsRepository(), null);
 }
        private static void MarkInactiveUsers(Repositories.IMessangerRepository repo, IDependencyResolver resolver)
        {
            var connectionManager = resolver.Resolve<IConnectionManager>();
            var hubContext = connectionManager.GetHubContext<Hubs.MessangerHub>();
            var inactiveUsers = new List<Common.Models.MessangerUser>();

            IQueryable<Common.Models.MessangerUser> users = repo.Users.Online();

            foreach (var user in users)
            {
                var status = (Common.Models.UserStatus)user.Status;
                var elapsed = DateTime.UtcNow - user.LastActivity;

                if (elapsed.TotalMinutes > 15)
                {
                    user.Status = (int)Common.Models.UserStatus.Inactive;
                    inactiveUsers.Add(user);
                }
            }

            if (inactiveUsers.Count > 0)
            {
                var roomGroups = from usr in inactiveUsers
                                 from grp in usr.Groups
                                 select new { User = usr, Group = grp } into tuple
                                 group tuple by tuple.Group into g
                                 select new
                                 {
                                     Group = g.Key,
                                     Users = g.Select(t => new UserViewModel(t.User))
                                 };

                var parallelOpt = new System.Threading.Tasks.ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount };
                var result = System.Threading.Tasks.Parallel.ForEach(roomGroups, parallelOpt, roomGroup =>
                {
                    if (hubContext != null)
                        hubContext.Clients.Group(roomGroup.Group.Name).markInactive(roomGroup.Users).Wait();
                });

                //foreach (var roomGroup in roomGroups)
                //{
                //	hubContext.Clients.Group(roomGroup.Group.Name).markInactive(roomGroup.Users).Wait();
                //}
            }
        }
예제 #54
0
        /// <summary>
        /// This routine scans module.ifo for a campaign GUID.  If found, a
        /// campaign.cam file with the same GUID is searched for and its
        /// containing directory is added to the directory resource list.
        /// </summary>
        /// <param name="ModuleIfo">Supplies the module.ifo GFF reader.</param>
        /// <param name="HomeDirectory">Supplies the NWN2 home directory.</param>
        /// <param name="InstallDirectory">Supplies the NWN2 install directory.</param>
        private void AddModuleCampaign(GFFFile ModuleIfo, string HomeDirectory, string InstallDirectory)
        {
            byte[] GUIDData = ModuleIfo.TopLevelStruct.GetVoidDataSafe("Campaign_ID", null);

            if (GUIDData == null || GUIDData.Length != 16)
            {
                return;
            }

            Guid CampaignGUID = new Guid(GUIDData);

            string[] SearchDirs = new string[] { HomeDirectory, InstallDirectory };

            //
            // Attempt to locate a campaign.cam file with the same GUID as the
            // module.
            //

            foreach (string PathName in SearchDirs)
            {
                string CampaignFolder = String.Format("{0}\\Campaigns", PathName);

                if (!Directory.Exists(CampaignFolder))
                {
                    continue;
                }

                foreach (string CampaignDir in Directory.EnumerateDirectories(CampaignFolder))
                {
                    using (DirectoryResourceRepository Repository = new DirectoryResourceRepository(CampaignDir))
                    {
                        Repository.PopulateRepository();

                        IResourceEntry ResEntry = Repository.FindResource(new OEIResRef("campaign"), ResCAM);

                        if (ResEntry == null)
                        {
                            continue;
                        }

                        GFFFile CampaignCAM = new GFFFile(ResEntry.GetStream(false));

                        GUIDData = CampaignCAM.TopLevelStruct.GetVoidDataSafe("GUID", null);

                        if (GUIDData == null || GUIDData.Length != 16)
                        {
                            continue;
                        }

                        Guid ID = new Guid(GUIDData);

                        if (!CampaignGUID.Equals(ID))
                        {
                            continue;
                        }

                        Repositories.Add(new DirectoryResourceRepository(CampaignDir));
                        return;
                    }
                }
            }
        }
예제 #55
0
        private bool PushChanges(IWin32Window owner)
        {
            ErrorOccurred = false;
            if (PushToUrl.Checked && string.IsNullOrEmpty(PushDestination.Text))
            {
                MessageBox.Show(owner, _selectDestinationDirectory.Text);
                return(false);
            }

            var selectedRemoteName = _selectedRemote.Name;

            if (PushToRemote.Checked && string.IsNullOrEmpty(selectedRemoteName))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }
            if (TabControlTagBranch.SelectedTab == TagTab && string.IsNullOrEmpty(TagComboBox.Text))
            {
                MessageBox.Show(owner, _selectTag.Text);
                return(false);
            }

            //Extra check if the branch is already known to the remote, give a warning when not.
            //This is not possible when the remote is an URL, but this is ok since most users push to
            //known remotes anyway.
            if (TabControlTagBranch.SelectedTab == BranchTab && PushToRemote.Checked &&
                !Module.IsBareRepository())
            {
                //If the current branch is not the default push, and not known by the remote
                //(as far as we know since we are disconnected....)
                if (_NO_TRANSLATE_Branch.Text != AllRefs &&
                    RemoteBranch.Text != _gitRemoteController.GetDefaultPushRemote(_selectedRemote, _NO_TRANSLATE_Branch.Text) &&
                    !IsBranchKnownToRemote(selectedRemoteName, RemoteBranch.Text))
                {
                    //Ask if this is really what the user wants
                    if (!AppSettings.DontConfirmPushNewBranch &&
                        DialogResult.No == MessageBox.Show(owner, _branchNewForRemote.Text, _pushCaption.Text, MessageBoxButtons.YesNo))
                    {
                        return(false);
                    }
                }
            }

            if (PushToUrl.Checked)
            {
                Repositories.AddMostRecentRepository(PushDestination.Text);
            }
            AppSettings.RecursiveSubmodules = RecursiveSubmodules.SelectedIndex;

            var    remote = "";
            string destination;

            if (PushToUrl.Checked)
            {
                destination = PushDestination.Text;
            }
            else
            {
                EnsurePageant(selectedRemoteName);

                destination = selectedRemoteName;
                remote      = selectedRemoteName.Trim();
            }

            string pushCmd;

            if (TabControlTagBranch.SelectedTab == BranchTab)
            {
                bool track = ReplaceTrackingReference.Checked;
                if (!track && !string.IsNullOrWhiteSpace(RemoteBranch.Text))
                {
                    GitRef selectedLocalBranch = _NO_TRANSLATE_Branch.SelectedItem as GitRef;
                    track = selectedLocalBranch != null && string.IsNullOrEmpty(selectedLocalBranch.TrackingRemote) &&
                            !_gitRemoteController.Remotes.Any(x => _NO_TRANSLATE_Branch.Text.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase));
                    var autoSetupMerge = Module.EffectiveConfigFile.GetValue("branch.autoSetupMerge");
                    if (autoSetupMerge.IsNotNullOrWhitespace() && autoSetupMerge.ToLowerInvariant() == "false")
                    {
                        track = false;
                    }
                    if (track && !AppSettings.DontConfirmAddTrackingRef)
                    {
                        var result = MessageBox.Show(this,
                                                     string.Format(_updateTrackingReference.Text, selectedLocalBranch.Name, RemoteBranch.Text),
                                                     _pushCaption.Text,
                                                     MessageBoxButtons.YesNoCancel);
                        if (result == DialogResult.Cancel)
                        {
                            return(false);
                        }
                        track = result == DialogResult.Yes;
                    }
                }

                if (ForcePushBranches.Checked)
                {
                    if (GitCommandHelpers.VersionInUse.SupportPushForceWithLease)
                    {
                        var choice = MessageBox.Show(this,
                                                     _useForceWithLeaseInstead.Text,
                                                     "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                                                     MessageBoxDefaultButton.Button1);
                        switch (choice)
                        {
                        case DialogResult.Yes:
                            ForcePushBranches.Checked = false;
                            ckForceWithLease.Checked  = true;
                            break;

                        case DialogResult.Cancel:
                            return(false);
                        }
                    }
                }

                if (_NO_TRANSLATE_Branch.Text == AllRefs)
                {
                    pushCmd = Module.PushAllCmd(destination, GetForcePushOption(), track, RecursiveSubmodules.SelectedIndex);
                }
                else
                {
                    pushCmd = Module.PushCmd(destination, _NO_TRANSLATE_Branch.Text, RemoteBranch.Text,
                                             GetForcePushOption(), track, RecursiveSubmodules.SelectedIndex);
                }
            }
            else if (TabControlTagBranch.SelectedTab == TagTab)
            {
                string tag         = TagComboBox.Text;
                bool   pushAllTags = false;
                if (tag == AllRefs)
                {
                    tag         = "";
                    pushAllTags = true;
                }
                pushCmd = GitCommandHelpers.PushTagCmd(destination, tag, pushAllTags, GetForcePushOption());
            }
            else
            {
                // Push Multiple Branches Tab selected
                var pushActions = new List <GitPushAction>();
                foreach (DataRow row in _branchTable.Rows)
                {
                    var push   = Convert.ToBoolean(row["Push"]);
                    var force  = Convert.ToBoolean(row["Force"]);
                    var delete = Convert.ToBoolean(row["Delete"]);

                    if (push || force)
                    {
                        pushActions.Add(new GitPushAction(row["Local"].ToString(), row["Remote"].ToString(), force));
                    }
                    else if (delete)
                    {
                        pushActions.Add(GitPushAction.DeleteRemoteBranch(row["Remote"].ToString()));
                    }
                }
                pushCmd = GitCommandHelpers.PushMultipleCmd(destination, pushActions);
            }

            ScriptManager.RunEventScripts(this, ScriptEvent.BeforePush);

            //controls can be accessed only from UI thread
            _selectedBranch = _NO_TRANSLATE_Branch.Text;
            _candidateForRebasingMergeCommit = PushToRemote.Checked && (_selectedBranch != AllRefs) && TabControlTagBranch.SelectedTab == BranchTab;
            _selectedRemoteBranchName        = RemoteBranch.Text;

            using (var form = new FormRemoteProcess(Module, pushCmd)
            {
                Remote = remote,
                Text = string.Format(_pushToCaption.Text, destination),
                HandleOnExitCallback = HandlePushOnExit
            })
            {
                form.ShowDialog(owner);
                ErrorOccurred = form.ErrorOccurred();

                if (!Module.InTheMiddleOfAction() && !form.ErrorOccurred())
                {
                    ScriptManager.RunEventScripts(this, ScriptEvent.AfterPush);
                    if (_createPullRequestCB.Checked)
                    {
                        UICommands.StartCreatePullRequest(owner);
                    }
                    return(true);
                }
            }

            return(false);
        }
예제 #56
0
        public void InitializeJob(Pipelines.AgentJobRequestMessage message, CancellationToken token)
        {
            // Validation
            Trace.Entering();
            ArgUtil.NotNull(message, nameof(message));
            ArgUtil.NotNull(message.Resources, nameof(message.Resources));
            ArgUtil.NotNull(message.Variables, nameof(message.Variables));
            ArgUtil.NotNull(message.Plan, nameof(message.Plan));

            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);

            // Features
            Features = PlanUtil.GetFeatures(message.Plan);

            // Endpoints
            Endpoints = message.Resources.Endpoints;

            // SecureFiles
            SecureFiles = message.Resources.SecureFiles;

            // Repositories
            Repositories = message.Resources.Repositories;

            // JobSettings
            var checkouts = message.Steps?.Where(x => Pipelines.PipelineConstants.IsCheckoutTask(x)).ToList();

            JobSettings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            JobSettings[WellKnownJobSettings.HasMultipleCheckouts] = Boolean.FalseString;
            if (checkouts != null && checkouts.Count > 0)
            {
                JobSettings[WellKnownJobSettings.HasMultipleCheckouts] = checkouts.Count > 1 ? Boolean.TrueString : Boolean.FalseString;
                var firstCheckout = checkouts.First() as Pipelines.TaskStep;
                if (firstCheckout != null && Repositories != null && firstCheckout.Inputs.TryGetValue(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository, out string repoAlias))
                {
                    JobSettings[WellKnownJobSettings.FirstRepositoryCheckedOut] = repoAlias;
                    var repo = Repositories.Find(r => String.Equals(r.Alias, repoAlias, StringComparison.OrdinalIgnoreCase));
                    if (repo != null)
                    {
                        repo.Properties.Set <bool>(RepositoryUtil.IsPrimaryRepository, true);
                    }
                }
            }

            // Variables (constructor performs initial recursive expansion)
            List <string> warnings;

            Variables = new Variables(HostContext, message.Variables, out warnings);
            Variables.StringTranslator = TranslatePathForStepTarget;

            if (Variables.GetBoolean("agent.useWorkspaceId") == true)
            {
                try
                {
                    // We need an identifier that represents which repos make up the workspace.
                    // This allows similar jobs in the same definition to reuse that workspace and other jobs to have their own.
                    JobSettings[WellKnownJobSettings.WorkspaceIdentifier] = GetWorkspaceIdentifier(message);
                }
                catch (Exception ex)
                {
                    Trace.Warning($"Unable to generate workspace ID: {ex.Message}");
                }
            }

            // Prepend Path
            PrependPath = new List <string>();

            // Docker (JobContainer)
            string imageName = Variables.Get("_PREVIEW_VSTS_DOCKER_IMAGE");

            if (string.IsNullOrEmpty(imageName))
            {
                imageName = Environment.GetEnvironmentVariable("_PREVIEW_VSTS_DOCKER_IMAGE");
            }

            Containers         = new List <ContainerInfo>();
            _defaultStepTarget = null;
            _currentStepTarget = null;
            if (!string.IsNullOrEmpty(imageName) &&
                string.IsNullOrEmpty(message.JobContainer))
            {
                var dockerContainer = new Pipelines.ContainerResource()
                {
                    Alias = "vsts_container_preview"
                };
                dockerContainer.Properties.Set("image", imageName);
                var defaultJobContainer = HostContext.CreateContainerInfo(dockerContainer);
                _defaultStepTarget = defaultJobContainer;
                Containers.Add(defaultJobContainer);
            }
            else if (!string.IsNullOrEmpty(message.JobContainer))
            {
                var defaultJobContainer = HostContext.CreateContainerInfo(message.Resources.Containers.Single(x => string.Equals(x.Alias, message.JobContainer, StringComparison.OrdinalIgnoreCase)));
                _defaultStepTarget = defaultJobContainer;
                Containers.Add(defaultJobContainer);
            }
            else
            {
                _defaultStepTarget = new HostInfo();
            }
            // Include other step containers
            var sidecarContainers = new HashSet <string>(message.JobSidecarContainers.Values, StringComparer.OrdinalIgnoreCase);

            foreach (var container in message.Resources.Containers.Where(x =>
                                                                         !string.Equals(x.Alias, message.JobContainer, StringComparison.OrdinalIgnoreCase) && !sidecarContainers.Contains(x.Alias)))
            {
                Containers.Add(HostContext.CreateContainerInfo(container));
            }

            // Docker (Sidecar Containers)
            SidecarContainers = new List <ContainerInfo>();
            foreach (var sidecar in message.JobSidecarContainers)
            {
                var           networkAlias           = sidecar.Key;
                var           containerResourceAlias = sidecar.Value;
                var           containerResource      = message.Resources.Containers.Single(c => string.Equals(c.Alias, containerResourceAlias, StringComparison.OrdinalIgnoreCase));
                ContainerInfo containerInfo          = HostContext.CreateContainerInfo(containerResource, isJobContainer: false);
                containerInfo.ContainerNetworkAlias = networkAlias;
                SidecarContainers.Add(containerInfo);
            }

            // Proxy variables
            var agentWebProxy = HostContext.GetService <IVstsAgentWebProxy>();

            if (!string.IsNullOrEmpty(agentWebProxy.ProxyAddress))
            {
                Variables.Set(Constants.Variables.Agent.ProxyUrl, agentWebProxy.ProxyAddress);
                Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY", string.Empty);

                if (!string.IsNullOrEmpty(agentWebProxy.ProxyUsername))
                {
                    Variables.Set(Constants.Variables.Agent.ProxyUsername, agentWebProxy.ProxyUsername);
                    Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY_USERNAME", string.Empty);
                }

                if (!string.IsNullOrEmpty(agentWebProxy.ProxyPassword))
                {
                    Variables.Set(Constants.Variables.Agent.ProxyPassword, agentWebProxy.ProxyPassword, true);
                    Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY_PASSWORD", string.Empty);
                }

                if (agentWebProxy.ProxyBypassList.Count > 0)
                {
                    Variables.Set(Constants.Variables.Agent.ProxyBypassList, JsonUtility.ToString(agentWebProxy.ProxyBypassList));
                }
            }

            // Certificate variables
            var agentCert = HostContext.GetService <IAgentCertificateManager>();

            if (agentCert.SkipServerCertificateValidation)
            {
                Variables.Set(Constants.Variables.Agent.SslSkipCertValidation, bool.TrueString);
            }

            if (!string.IsNullOrEmpty(agentCert.CACertificateFile))
            {
                Variables.Set(Constants.Variables.Agent.SslCAInfo, agentCert.CACertificateFile);
            }

            if (!string.IsNullOrEmpty(agentCert.ClientCertificateFile) &&
                !string.IsNullOrEmpty(agentCert.ClientCertificatePrivateKeyFile) &&
                !string.IsNullOrEmpty(agentCert.ClientCertificateArchiveFile))
            {
                Variables.Set(Constants.Variables.Agent.SslClientCert, agentCert.ClientCertificateFile);
                Variables.Set(Constants.Variables.Agent.SslClientCertKey, agentCert.ClientCertificatePrivateKeyFile);
                Variables.Set(Constants.Variables.Agent.SslClientCertArchive, agentCert.ClientCertificateArchiveFile);

                if (!string.IsNullOrEmpty(agentCert.ClientCertificatePassword))
                {
                    Variables.Set(Constants.Variables.Agent.SslClientCertPassword, agentCert.ClientCertificatePassword, true);
                }
            }

            // Runtime option variables
            var runtimeOptions = HostContext.GetService <IConfigurationStore>().GetAgentRuntimeOptions();

            if (runtimeOptions != null)
            {
                if (PlatformUtil.RunningOnWindows && runtimeOptions.GitUseSecureChannel)
                {
                    Variables.Set(Constants.Variables.Agent.GitUseSChannel, runtimeOptions.GitUseSecureChannel.ToString());
                }
            }

            // Job timeline record.
            InitializeTimelineRecord(
                timelineId: message.Timeline.Id,
                timelineRecordId: message.JobId,
                parentTimelineRecordId: null,
                recordType: ExecutionContextType.Job,
                displayName: message.JobDisplayName,
                refName: message.JobName,
                order: null); // The job timeline record's order is set by server.

            // Logger (must be initialized before writing warnings).
            _logger = HostContext.CreateService <IPagingLogger>();
            _logger.Setup(_mainTimelineId, _record.Id);

            // Log warnings from recursive variable expansion.
            warnings?.ForEach(x => this.Warning(x));

            // Verbosity (from system.debug).
            WriteDebug = Variables.System_Debug ?? false;

            // Hook up JobServerQueueThrottling event, we will log warning on server tarpit.
            _jobServerQueue.JobServerQueueThrottling += JobServerQueueThrottling_EventReceived;
        }
예제 #57
0
        private bool PushChanges(IWin32Window owner)
        {
            ErrorOccurred = false;
            if (PushToUrl.Checked && string.IsNullOrEmpty(PushDestination.Text))
            {
                MessageBox.Show(owner, _selectDestinationDirectory.Text);
                return(false);
            }
            if (PushToRemote.Checked && string.IsNullOrEmpty(_NO_TRANSLATE_Remotes.Text))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }
            if (TabControlTagBranch.SelectedTab == TagTab && string.IsNullOrEmpty(TagComboBox.Text))
            {
                MessageBox.Show(owner, _selectTag.Text);
                return(false);
            }

            //Extra check if the branch is already known to the remote, give a warning when not.
            //This is not possible when the remote is an URL, but this is ok since most users push to
            //known remotes anyway.
            if (TabControlTagBranch.SelectedTab == BranchTab && PushToRemote.Checked &&
                !Module.IsBareRepository())
            {
                //If the current branch is not the default push, and not known by the remote
                //(as far as we know since we are disconnected....)
                if (_NO_TRANSLATE_Branch.Text != AllRefs &&
                    RemoteBranch.Text != GetDefaultPushRemote(_NO_TRANSLATE_Remotes.Text, _NO_TRANSLATE_Branch.Text) &&
                    !Module.GetRefs(false, true).Any(x => x.Remote == _NO_TRANSLATE_Remotes.Text && x.Name == RemoteBranch.Text))
                {
                    //Ask if this is really what the user wants
                    if (!AppSettings.DontConfirmPushNewBranch &&
                        MessageBox.Show(owner, _branchNewForRemote.Text, _pushCaption.Text, MessageBoxButtons.YesNo) ==
                        DialogResult.No)
                    {
                        return(false);
                    }
                }
            }

            if (PushToUrl.Checked)
            {
                Repositories.AddMostRecentRepository(PushDestination.Text);
            }
            AppSettings.RecursiveSubmodules = RecursiveSubmodules.SelectedIndex;

            var    remote = "";
            string destination;

            if (PushToUrl.Checked)
            {
                destination = PushDestination.Text;
            }
            else
            {
                if (GitCommandHelpers.Plink())
                {
                    if (!File.Exists(AppSettings.Pageant))
                    {
                        MessageBoxes.PAgentNotFound(owner);
                    }
                    else
                    {
                        Module.StartPageantForRemote(_NO_TRANSLATE_Remotes.Text);
                    }
                }

                destination = _NO_TRANSLATE_Remotes.Text;
                remote      = _NO_TRANSLATE_Remotes.Text.Trim();
            }

            string pushCmd;

            if (TabControlTagBranch.SelectedTab == BranchTab)
            {
                bool track = ReplaceTrackingReference.Checked;
                if (!track && !string.IsNullOrWhiteSpace(RemoteBranch.Text))
                {
                    GitRef selectedLocalBranch = _NO_TRANSLATE_Branch.SelectedItem as GitRef;
                    track = selectedLocalBranch != null && string.IsNullOrEmpty(selectedLocalBranch.TrackingRemote);

                    string[] remotes = _NO_TRANSLATE_Remotes.DataSource as string[];
                    if (remotes != null)
                    {
                        foreach (string remoteBranch in remotes)
                        {
                            if (!string.IsNullOrEmpty(remoteBranch) && _NO_TRANSLATE_Branch.Text.StartsWith(remoteBranch))
                            {
                                track = false;
                            }
                        }
                    }

                    if (track && !AppSettings.DontConfirmAddTrackingRef)
                    {
                        DialogResult result = MessageBox.Show(String.Format(_updateTrackingReference.Text, selectedLocalBranch.Name, RemoteBranch.Text), _pushCaption.Text, MessageBoxButtons.YesNoCancel);

                        if (result == DialogResult.Cancel)
                        {
                            return(false);
                        }

                        track = result == DialogResult.Yes;
                    }
                }

                // Try to make source rev into a fully qualified branch name. If that
                // doesn't exist, then it must be something other than a branch, so
                // fall back to using the name just as it was passed in.
                string srcRev          = "";
                bool   pushAllBranches = false;
                if (_NO_TRANSLATE_Branch.Text == AllRefs)
                {
                    pushAllBranches = true;
                }
                else
                {
                    srcRev = GitCommandHelpers.GetFullBranchName(_NO_TRANSLATE_Branch.Text);
                    if (String.IsNullOrEmpty(Module.RevParse(srcRev)))
                    {
                        srcRev = _NO_TRANSLATE_Branch.Text;
                    }
                }

                pushCmd = GitCommandHelpers.PushCmd(destination, srcRev, RemoteBranch.Text,
                                                    pushAllBranches, ForcePushBranches.Checked, track, RecursiveSubmodules.SelectedIndex);
            }
            else if (TabControlTagBranch.SelectedTab == TagTab)
            {
                string tag         = TagComboBox.Text;
                bool   pushAllTags = false;
                if (tag == AllRefs)
                {
                    tag         = "";
                    pushAllTags = true;
                }
                pushCmd = GitCommandHelpers.PushTagCmd(destination, tag, pushAllTags,
                                                       ForcePushBranches.Checked);
            }
            else
            {
                // Push Multiple Branches Tab selected
                var pushActions = new List <GitPushAction>();
                foreach (DataRow row in _branchTable.Rows)
                {
                    var push   = Convert.ToBoolean(row["Push"]);
                    var force  = Convert.ToBoolean(row["Force"]);
                    var delete = Convert.ToBoolean(row["Delete"]);

                    if (push || force)
                    {
                        pushActions.Add(new GitPushAction(row["Local"].ToString(), row["Remote"].ToString(), force));
                    }
                    else if (delete)
                    {
                        pushActions.Add(new GitPushAction(row["Remote"].ToString()));
                    }
                }
                pushCmd = GitCommandHelpers.PushMultipleCmd(destination, pushActions);
            }

            ScriptManager.RunEventScripts(this, ScriptEvent.BeforePush);

            //controls can be accessed only from UI thread
            _selectedBranch = _NO_TRANSLATE_Branch.Text;
            _candidateForRebasingMergeCommit = PushToRemote.Checked && (_selectedBranch != AllRefs) && TabControlTagBranch.SelectedTab == BranchTab;
            _selectedBranchRemote            = _NO_TRANSLATE_Remotes.Text;
            _selectedRemoteBranchName        = RemoteBranch.Text;

            using (var form = new FormRemoteProcess(Module, pushCmd)
            {
                Remote = remote,
                Text = string.Format(_pushToCaption.Text, destination),
                HandleOnExitCallback = HandlePushOnExit
            })
            {
                form.ShowDialog(owner);
                ErrorOccurred = form.ErrorOccurred();

                if (!Module.InTheMiddleOfConflictedMerge() &&
                    !Module.InTheMiddleOfRebase() && !form.ErrorOccurred())
                {
                    ScriptManager.RunEventScripts(this, ScriptEvent.AfterPush);
                    if (_createPullRequestCB.Checked)
                    {
                        UICommands.StartCreatePullRequest(owner);
                    }
                    return(true);
                }
            }

            return(false);
        }
예제 #58
0
 public void Update()
 {
     Repositories.Update();
 }
예제 #59
0
파일: Join.cs 프로젝트: kwmcrell/ArmedCards
 public Join(Repositories.GamePlayer.Base.IInsert insertGamePlayer)
 {
     this._insertGamePlayer = insertGamePlayer;
 }
예제 #60
0
        public bool IsMainRepositoryRegistered(UpdateLevel level)
        {
            string url = GetMainRepositoryUrl(level);

            return(Repositories.ContainsRepository(url));
        }