Example #1
0
        public void when_disposing_with_only_async_disposables(RegistrationType registration, ServiceLifetime lifetime)
        {
            var container = Container.For(services =>
            {
                switch (registration)
                {
                case RegistrationType.Lambda:
                    services.For <OnlyAsyncDisposable>().Use(s => new OnlyAsyncDisposable())
                    .Lifetime = lifetime;
                    break;

                case RegistrationType.Object:
                    services.For <OnlyAsyncDisposable>().Use(new OnlyAsyncDisposable())
                    .Lifetime = lifetime;
                    break;

                case RegistrationType.Type:
                    services.For <OnlyAsyncDisposable>().Use <OnlyAsyncDisposable>()
                    .Lifetime = lifetime;
                    break;
                }
            });

            var item = container.GetInstance <OnlyAsyncDisposable>();

            container.Dispose();

            item.WasAsyncDisposed.ShouldBeTrue();
        }
Example #2
0
        /// <summary>
        /// Uninstalls a SharpShell server located at 'path' vis RegAsm.
        /// </summary>
        /// <param name="path">The path to the SharpShell server.</param>
        /// <param name="registrationType">Type of the registration.</param>
        private void UninstallServerViaRegAsm(string path, RegistrationType registrationType)
        {
            //  Validate the path.
            if (string.IsNullOrWhiteSpace(path) || File.Exists(path) == false)
            {
                outputService.WriteError("File '" + path + "' does not exist.", true);
                return;
            }

            var regAsm = new RegAsm();

            var success =
                registrationType == RegistrationType.OS32Bit
                    ? regAsm.Unregister32(path)
                    : regAsm.Unregister64(path);

            if (success)
            {
                outputService.WriteSuccess($"    {path} uninstalled.", true);
                outputService.WriteMessage(regAsm.StandardOutput);
            }
            else
            {
                outputService.WriteError($"    {path} failed to uninstall.", true);
                outputService.WriteError(regAsm.StandardError);
            }
        }
        /// <summary>
        /// Opens the classes root.
        /// </summary>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="registrationLocation">Location of the registration.</param>
        /// <returns>The classes root key.</returns>
        private static RegistryKey OpenClassesRoot(RegistrationType registrationType, RegistrationLocation registrationLocation)
        {
            //  Get the classes base key.
            RegistryKey classesBaseKey;

            switch (registrationLocation.UserSid)
            {
            case RegistrationLocation.CurrentUserPseudoSid:
                classesBaseKey = registrationType == RegistrationType.OS64Bit
                        ? RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64) :
                                 RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32);
                classesBaseKey = classesBaseKey.OpenSubKey(@"SOFTWARE\Classes", true);
                break;

            case RegistrationLocation.LocalMachinePseudoSid:
                classesBaseKey = registrationType == RegistrationType.OS64Bit
                        ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                                 RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                classesBaseKey = classesBaseKey.OpenSubKey(@"SOFTWARE\Classes", true);
                break;

            default:
                classesBaseKey = registrationType == RegistrationType.OS64Bit
                        ? RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Registry64) :
                                 RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Registry32);
                classesBaseKey = classesBaseKey.OpenSubKey(registrationLocation.UserSid + @"_Classes", true);
                break;
            }

            //  Return the classes key.
            return(classesBaseKey);
        }
Example #4
0
 public RegistrationDto(int id, RegistrationType registrationType, DateTime dateTime, int distanceMeter)
 {
     Id = id;
     RegistrationType = registrationType;
     DateTime         = dateTime.ToString("yyyy-MM-dd HH:mm");
     DistanceMeter    = distanceMeter;
 }
Example #5
0
 /// <summary>
 /// Determines whether an extension is approved.
 /// </summary>
 /// <param name="serverClsid">The server CLSID.</param>
 /// <param name="registrationType">Type of the registration.</param>
 /// <returns>
 ///   <c>true</c> if the extension is approved; otherwise, <c>false</c>.
 /// </returns>
 /// <exception cref="System.InvalidOperationException">Failed to open the Approved Extensions key.</exception>
 private static bool IsExtensionApproved(Guid serverClsid, RegistrationType registrationType)
 {
     //  Open the approved extensions key.
     using (var approvedKey = GetApprovedShellExtKey(registrationType)) {
         return(approvedKey.GetValueNames().Any(vn => vn.Equals(serverClsid.ToRegistryString(), StringComparison.OrdinalIgnoreCase)));
     }
 }
 private void EmailID_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         RegistrationType.Focus();
     }
 }
        /// <summary>
        /// Unregisters the server associations.
        /// </summary>
        /// <param name="serverType">Type of the server.</param>
        /// <param name="serverName">Name of the server.</param>
        /// <param name="associationClassNames">The association class names.</param>
        /// <param name="registrationType">Type of the registration.</param>
        private static void UnregisterServerAssociations(
            ServerType serverType,
            string serverName,
            IEnumerable <string> associationClassNames,
            RegistrationType registrationType)
        {
            //  Open the classes key...
            using (var classesKey = OpenClassesRoot(registrationType))
            {
                //  ...then go through each association class.
                foreach (var associationClassName in associationClassNames)
                {
                    //  Get the key for the association.
                    var associationKeyPath = GetKeyForServerType(associationClassName, serverType, serverName);

                    //  Delete it if it exists.
                    classesKey.DeleteSubKeyTree(associationKeyPath, false);

                    //  If we're a shell icon handler, we must also unset the defaulticon.
                    if (serverType == ServerType.ShellIconHandler)
                    {
                        UnsetIconHandlerDefaultIcon(classesKey, associationClassName);
                    }
                }
            }
        }
Example #8
0
        public void GetApplicantByCriteriaTest()
        {
            ApplicantService    target      = new ApplicantService();                     // TODO: Initialize to an appropriate value
            RegistrationType    userRegType = DTO.RegistrationType.OIC;                   // TODO: Initialize to an appropriate value
            string              compCode    = "";                                         // TODO: Initialize to an appropriate value
            string              idCard      = "";;                                        // TODO: Initialize to an appropriate value
            string              testingNo   = string.Empty;                               // TODO: Initialize to an appropriate value
            string              firstName   = string.Empty;                               // TODO: Initialize to an appropriate value
            string              lastName    = string.Empty;                               // TODO: Initialize to an appropriate value
            Nullable <DateTime> startDate   = Convert.ToDateTime("2557/07/04");           // TODO: Initialize to an appropriate value
            Nullable <DateTime> toDate      = Convert.ToDateTime("2557/10/01");           // TODO: Initialize to an appropriate value
            string              paymentNo   = string.Empty;                               // TODO: Initialize to an appropriate value
            string              billNo      = string.Empty;                               // TODO: Initialize to an appropriate value
            int    pageNo             = 1;                                                // TODO: Initialize to an appropriate value
            int    recordPerPage      = 20;                                               // TODO: Initialize to an appropriate value
            bool   Count              = false;                                            // TODO: Initialize to an appropriate value
            string license            = string.Empty;                                     // TODO: Initialize to an appropriate value
            string time               = string.Empty;                                     // TODO: Initialize to an appropriate value
            string examPlaceGroupCode = string.Empty;                                     // TODO: Initialize to an appropriate value
            string examPlaceCode      = string.Empty;                                     // TODO: Initialize to an appropriate value
            string chequeNo           = string.Empty;                                     // TODO: Initialize to an appropriate value
            string examResult         = string.Empty;                                     // TODO: Initialize to an appropriate value
            Nullable <DateTime>       startCandidates = Convert.ToDateTime("2557/05/26"); // TODO: Initialize to an appropriate value
            Nullable <DateTime>       endCandidates   = Convert.ToDateTime("2557/07/04"); // TODO: Initialize to an appropriate value
            ResponseService <DataSet> expected        = null;                             // TODO: Initialize to an appropriate value
            ResponseService <DataSet> actual;

            actual = target.GetApplicantByCriteria(userRegType, compCode, idCard, testingNo, firstName, lastName, startDate, toDate, paymentNo, billNo, pageNo, recordPerPage, Count, license, time, examPlaceGroupCode, examPlaceCode, chequeNo, examResult, startCandidates, endCandidates);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Example #9
0
        public async Task <IActionResult> PostRegistrationType([FromBody] RegistrationType registrationType)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.RegistrationType.Add(registrationType);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (RegistrationTypeExists(registrationType.IdTypeRegistration))
                {
                    return(new StatusCodeResult(StatusCodes.Status409Conflict));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetRegistrationType", new { id = registrationType.IdTypeRegistration }, registrationType));
        }
Example #10
0
        protected void btnNextParticipantInfo_Click(object sender, ImageClickEventArgs e)
        {
            Page.Validate("Type");
            if (Page.IsValid)
            {
                string type = GetSelectedType();
                List <RegistrationType> regTypes = PopulateRegistrationTypes();

                if (!string.IsNullOrWhiteSpace(type))
                {
                    RegistrationType selectedRegType = regTypes.Where(x => x.Text == type).FirstOrDefault();
                    WriteToViewState(REG_TYPE_VIEW_STATE, selectedRegType);

                    businessName.Visible = false;
                    if (selectedRegType.IsMerchant)
                    {
                        businessName.Visible = true;
                    }

                    pParticipantInfo.Visible   = true;
                    pParticipantFooter.Visible = true;

                    pRegistrationInfo.Visible   = false;
                    pRegistrationFooter.Visible = false;
                }
            }
        }
Example #11
0
        internal static void CustomUnregisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                                             RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the ShellIconOverlayIdentifiers.
                using (var overlayIdentifiers = localMachineBaseKey
                                                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers",
                                                            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.Delete | RegistryRights.EnumerateSubKeys | RegistryRights.ReadKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (overlayIdentifiers == null)
                    {
                        throw new InvalidOperationException("Cannot open the ShellIconOverlayIdentifiers key.");
                    }

                    //  Delete the overlay key.
                    if (overlayIdentifiers.GetSubKeyNames().Any(skn => skn == serverType.Name))
                    {
                        overlayIdentifiers.DeleteSubKey(serverType.Name);
                    }
                }
            }
        }
 public InjectAttribute(
     RegistrationScope scope = RegistrationScope.Transient,
     RegistrationType type   = RegistrationType.AsImplementedInterfaces)
 {
     Scope = scope;
     Type  = type;
 }
        /// <summary> </summary>
        /// <param name="context"></param>
        protected override void DoWork(CodeActivityContext context)
        {
            string                  localStatus               = "FAILED";
            string                  _dcmInstanceId            = UnitId.Get(context);
            int                     nDcmInstanceId            = Convert.ToInt32(_dcmInstanceId);
            IList <string>          sourceFrameOfReferenceUid = new List <string>();
            string                  targetFrameOfReferenceUid = "";
            IList <IList <double> > transformationMatrix      = new List <IList <double> >();
            IList <string>          transformationComment     = new List <string>();
            byte                    nRegistrationType         = 0;

            context.GetExtension <CompositionContainer>().SatisfyImportsOnce(this);

            _processSpatialRegistrationObject.ParseTreatmentPlanningSpatialRegistration(nDcmInstanceId, ref sourceFrameOfReferenceUid, ref targetFrameOfReferenceUid, ref transformationMatrix, ref transformationComment, ref nRegistrationType);

            if (sourceFrameOfReferenceUid != null && sourceFrameOfReferenceUid.Count > 0)
            {
                localStatus = "SUCCESS";
            }

            SourceFrameOfReferenceUID.Set(context, sourceFrameOfReferenceUid);
            TargetFrameOfReferenceUID.Set(context, targetFrameOfReferenceUid);
            TransformationMatrix.Set(context, transformationMatrix);
            TransformationMatrixComment.Set(context, transformationComment);
            RegistrationType.Set(context, nRegistrationType);
            ActivityStatus.Set(context, localStatus);
        }
Example #14
0
        /// <summary> </summary>
        /// <param name="context"></param>
        protected override void DoWork(CodeActivityContext context)
        {
            string                  localStatus               = "FAILED";
            string                  _dcmInstanceId            = UnitId.Get(context);
            int                     nDcmInstanceId            = Convert.ToInt32(_dcmInstanceId);
            byte                    nRegistrationType         = RegistrationType.Get(context);
            string                  _manufacturer             = Manufacturer.Get(context);
            string                  _model                    = ModelName.Get(context);
            string                  _softwareVersion          = SoftwareVersions.Get(context);
            IList <string>          sourceFrameOfReferenceUid = SourceFrameOfReferenceUID.Get(context);
            string                  targetFrameOfReferenceUid = TargetFrameOfReferenceUID.Get(context);
            IList <IList <double> > transformationMatrix      = TransformationMatrix.Get(context);
            IList <string>          transformationComment     = TransformationMatrixComment.Get(context);
            string                  _offsetId                 = OffsetID.Get(context);
            int                     nOffsetId                 = 0;

            if (_offsetId.Length > 0)
            {
                nOffsetId = Convert.ToInt32(_offsetId);
            }

            context.GetExtension <CompositionContainer>().SatisfyImportsOnce(this);

            try
            {
                _processSpatialRegistrationObject.CreateRegistrationRecord(nDcmInstanceId, transformationMatrix, transformationComment, sourceFrameOfReferenceUid, targetFrameOfReferenceUid, nRegistrationType, _manufacturer, _model, _softwareVersion, nOffsetId);
                localStatus = "SUCCESS";
                ActivityStatus.Set(context, localStatus);
            }
            catch (Exception ex)
            {
                ActivityStatus.Set(context, localStatus);
            }
        }
Example #15
0
        public async Task <IActionResult> PutRegistrationType([FromRoute] int id, [FromBody] RegistrationType registrationType)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != registrationType.IdTypeRegistration)
            {
                return(BadRequest());
            }

            _context.Entry(registrationType).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RegistrationTypeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #16
0
 public static void postDoRegister(Type type, RegistrationType registrationType)
 {
     try
     {
         using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"\CLSID\" +
                                                                  type.GUID.ToRegistryString() + @"\InprocServer32"))
         {
             if (key != null && key.GetSubKeyNames().Count() != 0)
             {
                 Console.WriteLine("Found old version in registry, cleaning up ...");
                 foreach (var k in key.GetSubKeyNames())
                 {
                     if (k != type.Assembly.GetName().Version.ToString())
                     {
                         Registry.ClassesRoot.DeleteSubKeyTree(@"\CLSID\" +
                                                               type.GUID.ToRegistryString() + @"\InprocServer32\" + k);
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         Logger.Error("Reg Error"
                      , e.Message);
     }
 }
Example #17
0
        /// <summary>
        /// Actually performs registration. The ComRegisterFunction decorated method will call this function
        /// internally with the flag appropriate for the operating system processor architecture.
        /// However, this function can also be called manually if needed.
        /// </summary>
        /// <param name="type">The type of object to register, this must be a SharpShellServer derived class.</param>
        /// <param name="registrationType">Type of the registration.</param>
        internal static void DoRegister(Type type, RegistrationType registrationType)
        {
            Logging.Log($"Preparing to register SharpShell Server {type.Name} as {registrationType}");

            //  Get the association data.
            var associationAttributes = type.GetCustomAttributes(typeof(COMServerAssociationAttribute), true)
                                        .OfType <COMServerAssociationAttribute>().ToList();

            //  Get the server type and the registration name.
            var serverType       = ServerTypeAttribute.GetServerType(type);
            var registrationName = RegistrationNameAttribute.GetRegistrationNameOrTypeName(type);

            //  Register the server associations, if there are any.
            if (associationAttributes.Any())
            {
                ServerRegistrationManager.RegisterServerAssociations(
                    type.GUID, serverType, registrationName, associationAttributes, registrationType);
            }

            //  If a DisplayName attribute has been set, then set the display name of the COM server.
            var displayName = DisplayNameAttribute.GetDisplayName(type);

            if (!string.IsNullOrEmpty(displayName))
            {
                ServerRegistrationManager.SetServerDisplayName(type.GUID, displayName, registrationType);
            }

            //  Execute the custom register function, if there is one.
            CustomRegisterFunctionAttribute.ExecuteIfExists(type, registrationType);

            //  Notify the shell we've updated associations.
            Shell32.SHChangeNotify(Shell32.SHCNE_ASSOCCHANGED, 0, IntPtr.Zero, IntPtr.Zero);
            Logging.Log($"Registration of {type.Name} completed");
        }
Example #18
0
        internal ServiceRegistration(Type implementationType, RegistrationType registrationType, ContainerConfiguration containerConfiguration,
                                     RegistrationContext registrationContext, bool isDecorator)
        {
            this.Configuration          = containerConfiguration;
            this.ImplementationType     = implementationType;
            this.ImplementationTypeInfo = implementationType.GetTypeInfo();
            this.RegistrationContext    = registrationContext;
            this.IsDecorator            = isDecorator;
            this.RegistrationType       = registrationType;

            this.IsResolvableByUnnamedRequest = this.RegistrationContext.Name == null || containerConfiguration.NamedDependencyResolutionForUnNamedRequestsEnabled;

            if (this.RegistrationContext.Lifetime is NamedScopeLifetime lifetime)
            {
                this.HasScopeName = true;
                this.NamedScopeRestrictionIdentifier = lifetime.ScopeName;
            }

            this.HasCondition = this.RegistrationContext.TargetTypeConditions.Length > 0 ||
                                this.RegistrationContext.ResolutionConditions.Length > 0 ||
                                this.RegistrationContext.AttributeConditions.Length > 0;

            this.RegistrationId            = ReserveRegistrationId();
            this.RegistrationOrder         = ReserveRegistrationOrder();
            this.RegistrationDiscriminator = containerConfiguration.RegistrationBehavior == Rules.RegistrationBehavior.PreserveDuplications
                    ? this.RegistrationId
                    : this.RegistrationContext.Name ?? implementationType;
        }
Example #19
0
        /// <summary>
        /// Actually performs unregistration. The ComUnregisterFunction decorated method will call this function
        /// internally with the flag appropriate for the operating system processor architecture.
        /// However, this function can also be called manually if needed.
        /// </summary>
        /// <param name="type">The type of object to unregister, this must be a SharpShellServer derived class.</param>
        /// <param name="registrationType">Type of the registration to unregister.</param>
        internal static void DoUnregister(Type type, RegistrationType registrationType)
        {
            Logging.Log($"Preparing to unregister SharpShell Server {type.Name} as {registrationType}");

            //  Get the association data.
            var associationAttributes = type.GetCustomAttributes(typeof(COMServerAssociationAttribute), true)
                                        .OfType <COMServerAssociationAttribute>().ToList();

            //  Get the server type and the registration name.
            var serverType       = ServerTypeAttribute.GetServerType(type);
            var registrationName = RegistrationNameAttribute.GetRegistrationNameOrTypeName(type);

            //  Unregister the server associations, if there are any.
            if (associationAttributes.Any())
            {
                ServerRegistrationManager.UnregisterServerAssociations(
                    type.GUID, serverType, registrationName, associationAttributes, registrationType);
            }

            //  Execute the custom unregister function, if there is one.
            CustomUnregisterFunctionAttribute.ExecuteIfExists(type, registrationType);

            //  Notify the shell we've updated associations.
            Shell32.SHChangeNotify(Shell32.SHCNE_ASSOCCHANGED, 0, IntPtr.Zero, IntPtr.Zero);
            Logging.Log($"Unregistration of {type.Name} completed");
        }
Example #20
0
        public void GetApplicantByCriteriaTest()
        {
            IApplicantService   target      = CreateIApplicantService(); // TODO: Initialize to an appropriate value
            RegistrationType    userRegType = new RegistrationType();    // TODO: Initialize to an appropriate value
            string              compCode    = string.Empty;              // TODO: Initialize to an appropriate value
            string              idCard      = string.Empty;              // TODO: Initialize to an appropriate value
            string              testingNo   = string.Empty;              // TODO: Initialize to an appropriate value
            string              firstName   = string.Empty;              // TODO: Initialize to an appropriate value
            string              lastName    = string.Empty;              // TODO: Initialize to an appropriate value
            Nullable <DateTime> startDate   = new Nullable <DateTime>(); // TODO: Initialize to an appropriate value
            Nullable <DateTime> toDate      = new Nullable <DateTime>(); // TODO: Initialize to an appropriate value
            string              paymentNo   = string.Empty;              // TODO: Initialize to an appropriate value
            string              billNo      = string.Empty;              // TODO: Initialize to an appropriate value
            int    RowPerPage         = 0;                               // TODO: Initialize to an appropriate value
            int    pageNum            = 0;                               // TODO: Initialize to an appropriate value
            bool   Count              = false;                           // TODO: Initialize to an appropriate value
            string license            = string.Empty;                    // TODO: Initialize to an appropriate value
            string time               = string.Empty;                    // TODO: Initialize to an appropriate value
            string examPlaceGroupCode = string.Empty;
            string examPlaceCode      = string.Empty;
            string chequeNo           = string.Empty;
            string examResult         = string.Empty;
            Nullable <DateTime>       startCandidates = new Nullable <DateTime>();
            Nullable <DateTime>       endCandidates   = new Nullable <DateTime>();
            ResponseService <DataSet> expected        = null; // TODO: Initialize to an appropriate value
            ResponseService <DataSet> actual;

            actual = target.GetApplicantByCriteria(userRegType, compCode, idCard, testingNo, firstName, lastName, startDate, toDate, paymentNo, billNo, RowPerPage, pageNum, Count, license, time, examPlaceGroupCode, examPlaceCode, chequeNo, examResult, startCandidates, endCandidates);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
        /// <summary>
        /// Unregisters the SharpShell Preview Handler with the given type.
        /// </summary>
        /// <param name="serverType">Type of the server.</param>
        /// <param name="registrationType">Type of the registration.</param>
        public static void Unregister(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                                             RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the Preview Handlers.
                using (var previewHandlersKey = localMachineBaseKey
                                                .OpenSubKey(PreviewHandlersKey,
                                                            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey | RegistryRights.ReadKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (previewHandlersKey == null)
                    {
                        throw new InvalidOperationException("Cannot open the PreviewHandlers key.");
                    }

                    //  If there's a value for the server, delete it.
                    var serverGuid = serverType.GUID.ToRegistryString();
                    if (previewHandlersKey.GetValueNames().Any(vm => vm == serverGuid))
                    {
                        previewHandlersKey.DeleteValue(serverGuid);
                    }

                    //  If the server has an AppID registered for it's surrogate host, clean it up.
                    var appId = GetAppIdForServerClsid(serverType.GUID).ToRegistryString();
                    DeletePrevhostApp(appId);
                }
            }
        }
Example #22
0
 public override byte[] ToByteArray()
 {
     return(ToByteArray(new List <string>()
     {
         ClientType.ToString(), RegistrationType.ToString(), Channel
     }.ToArray()));
 }
Example #23
0
        public async Task when_async_disposing_with_both_disposables(RegistrationType registration, ServiceLifetime lifetime)
        {
            var container = Container.For(services =>
            {
                switch (registration)
                {
                case RegistrationType.Lambda:
                    services.For <BothDisposable>().Use(s => new BothDisposable())
                    .Lifetime = lifetime;
                    break;

                case RegistrationType.Object:
                    services.For <BothDisposable>().Use(new BothDisposable())
                    .Lifetime = lifetime;
                    break;

                case RegistrationType.Type:
                    services.For <BothDisposable>().Use <BothDisposable>()
                    .Lifetime = lifetime;
                    break;
                }
            });

            var item = container.GetInstance <BothDisposable>();

            await container.DisposeAsync();

            item.WasAsyncDisposed.ShouldBeTrue();
            item.WasDisposed.ShouldBeFalse();
        }
Example #24
0
 public ActionResult RegisterPartial(RegistrationType registrationType)
 {
     return(PartialView(new RegisterViewModel()
     {
         RegistrationType = registrationType
     }));
 }
        private async Task <bool> IsUserEnabled(RegistrationType type)
        {
            switch (type)
            {
            case RegistrationType.None:
                throw new CallerException("Registration is set to none");

            case RegistrationType.Private:
                return(IsAdmin);

            case RegistrationType.Public:
                return(true);

            case RegistrationType.Verified:
                if (!IsAdmin)
                {
                    return(false);
                }

                // The text for this setting is 'Auto-verify admin 'Verified' registrations'. This means, if true, if an admin registers they will not have to verify
                return(await GetSetting("SystemSettings_VerifyAdminRegistrations"));

            default:
                throw new NotSupportedException("RegistrationType not supported");
            }
        }
 public static void Register(string assemblyPath, RegistrationType type)
 {
     foreach (ISharpShellServer server in GetServers(assemblyPath))
     {
         ServerRegistrationManager.RegisterServer(server, type);
     }
 }
Example #27
0
        internal static void CustomUnregisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                                             RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the Preview Handlers.
                using (var previewHandlersKey = localMachineBaseKey
                                                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\PreviewHandlers",
                                                            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey | RegistryRights.ReadKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (previewHandlersKey == null)
                    {
                        throw new InvalidOperationException("Cannot open the PreviewHandlers key.");
                    }

                    //  If there's a value for the server, delete it.
                    var serverGuid = serverType.GUID.ToRegistryString();
                    if (previewHandlersKey.GetValueNames().Any(vm => vm == serverGuid))
                    {
                        previewHandlersKey.DeleteValue(serverGuid);
                    }
                }
            }
        }
        internal static void CustomRegisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                                             RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the ShellIconOverlayIdentifiers.
                using (var overlayIdentifiers = localMachineBaseKey
                                                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers",
                                                            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.CreateSubKey | RegistryRights.CreateSubKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (overlayIdentifiers == null)
                    {
                        throw new InvalidOperationException("Cannot open the ShellIconOverlayIdentifiers key.");
                    }

                    //  Create the overlay key.
                    using (var overlayKey = overlayIdentifiers.CreateSubKey(serverType.Name))
                    {
                        //  If we don't have the overlay key, we've got a problem.
                        if (overlayKey == null)
                        {
                            throw new InvalidOperationException("Cannot create the key for the overlay server.");
                        }

                        //  Set the server CLSID.
                        overlayKey.SetValue(null, serverType.GUID.ToRegistryString());
                    }
                }
            }
        }
Example #29
0
        internal static void CustomRegisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  We will use the display name a few times.
            var displayName = DisplayNameAttribute.GetDisplayNameOrTypeName(serverType);

            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                                             RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the Preview Handlers.
                using (var previewHandlersKey = localMachineBaseKey
                                                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\PreviewHandlers",
                                                            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (previewHandlersKey == null)
                    {
                        throw new InvalidOperationException("Cannot open the PreviewHandlers key.");
                    }

                    //  Write the server guid as a name, and the display name as the value.
                    //  The display name isn't needed, it's just helpful for debugging and checking the registry.
                    previewHandlersKey.SetValue(serverType.GUID.ToRegistryString(), displayName);
                }
            }

            //  Open the classes root.
            using (var classesBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry64) :
                                        RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32))
            {
                //  Our server guid.
                var serverGuid = serverType.GUID.ToRegistryString();

                //  Open the Class Key.
                using (var classKey = classesBaseKey
                                      .OpenSubKey(string.Format(@"CLSID\{0}", serverGuid),
                                                  RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (classKey == null)
                    {
                        throw new InvalidOperationException("Cannot open the class key.");
                    }

                    //  Set the AppID as the preview host surrogate.
                    classKey.SetValue(null, serverType.Name);
                    classKey.SetValue("AppID", "{6d2b5079-2f0b-48dd-ab7f-97cec514d30b}");

                    //  Set the display name and TODO icon.
                    classKey.SetValue("DisplayName", displayName, RegistryValueKind.String);
                    classKey.SetValue("Icon", "%SystemRoot%\\system32\\fontext.dll,10", RegistryValueKind.ExpandString);

                    //  Disable low integrity process isolation - TODO maybe this should be optional.
                    classKey.SetValue("DisableLowILProcessIsolation", 1, RegistryValueKind.DWord);
                }
            }
        }
Example #30
0
 public static FilterOptionViewModel FromRegistrationType(RegistrationType registrationType)
 {
     return(Equals(registrationType, RegistrationType.SelfRegisteredExternal)
         ? SelfRegisteredExternal
         : Equals(registrationType, RegistrationType.SelfRegistered)
             ? SelfRegistered
             : RegisteredByCentre);
 }
        private static LifetimeManager GetLifetimeManager(RegistrationType registrationType)
        {
            if (RegistrationType.Singleton == registrationType) {
                return new ContainerControlledLifetimeManager();
            }

            return new TransientLifetimeManager();
        }
        public ServiceLocatorRegistrationAttribute(Type interfaceType, RegistrationType registrationType, object tag = null)
        {
            Argument.IsNotNull("InterfaceType", interfaceType);

            InterfaceType = interfaceType;
            RegistrationType = registrationType;
            Tag = tag;
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="DependencyInjectionBehaviorAttribute" /> class.
        /// </summary>
        /// <param name="contractType">Type of the contract.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="tag">The tag.</param>
        public DependencyInjectionBehaviorAttribute(Type contractType,
            RegistrationType registrationType = RegistrationType.Singleton, object tag = null)
        {
            ContractType = contractType;
            RegistrationType = registrationType;
            Tag = tag;

            _serviceLocator = this.GetDependencyResolver().Resolve<IServiceLocator>();
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ServiceLocatorRegistrationBehaviorAttribute" /> class.
        /// </summary>
        /// <param name="contractType">Type of the contract.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="tag">The tag.</param>
        public ServiceLocatorRegistrationBehaviorAttribute(Type contractType,
            RegistrationType registrationType = RegistrationType.Singleton, object tag = null)
        {
            Argument.IsNotNull("registrationType", registrationType);

            ContractType = contractType;
            RegistrationType = registrationType;
            Tag = tag;
        }
        public RegisterInContainerAttribute(Type interfaceType, string name, RegistrationType registrationType)
        {
            if (interfaceType == null) {
                throw new ArgumentNullException("interfaceType");
            }

            this.InterfaceType = interfaceType;
            this.Name = name;
            this.RegistrationType = registrationType;
        }
Example #36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RegistrationInfo" /> class.
        /// </summary>
        /// <param name="declaringType">Type of the declaring.</param>
        /// <param name="implementingType">Type of the implementing.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="isTypeInstantiatedForSingleton">If set to <c>true</c> there already is an instance of this singleton registration.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="declaringType" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="implementingType" /> is <c>null</c>.</exception>
        internal RegistrationInfo(Type declaringType, Type implementingType, RegistrationType registrationType, bool isTypeInstantiatedForSingleton = false)
        {
            Argument.IsNotNull("declaringType", declaringType);
            Argument.IsNotNull("implementingType", implementingType);

            DeclaringType = declaringType;
            ImplementingType = implementingType;
            RegistrationType = registrationType;
            IsTypeInstantiatedForSingleton = isTypeInstantiatedForSingleton;
        }
        /// <summary>
        /// Executes the CustomUnregisterFunction if it exists for a type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="registrationType">Type of the registration.</param>
        public static void ExecuteIfExists(Type type, RegistrationType registrationType)
        {
            //  Does the type have the attribute?
            var methodWithAttribute = type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy)
                .FirstOrDefault(m => m.GetCustomAttributes(typeof (CustomUnregisterFunctionAttribute), false).Any());

            //  Do we have a method? If so, invoke it.
            if (methodWithAttribute != null)
                methodWithAttribute.Invoke(null, new object[] { type, registrationType });
        }
Example #38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeRegisteredEventArgs" /> class.
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="serviceImplementationType">Type of the service implementation.</param>
        /// <param name="tag">The tag.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="serviceType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="serviceImplementationType"/> is <c>null</c>.</exception>
        public TypeRegisteredEventArgs(Type serviceType, Type serviceImplementationType, object tag, RegistrationType registrationType)
        {
            Argument.IsNotNull("serviceType", serviceType);
            Argument.IsNotNull("serviceImplementationType", serviceImplementationType);

            ServiceType = serviceType;
            ServiceImplementationType = serviceImplementationType;
            Tag = tag;
            RegistrationType = registrationType;
        }
Example #39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InstanceProvider" /> class.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        /// <param name="contractType">Type of the contract.</param>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="tag">The tag.</param>
        /// <param name="registrationType">Type of the registration.</param>
        public InstanceProvider(IServiceLocator serviceLocator, Type contractType, Type serviceType, object tag = null, RegistrationType registrationType = RegistrationType.Singleton)
        {
            Argument.IsNotNull("serviceLocator", serviceLocator);
            Argument.IsNotNull("contractType", contractType);
            Argument.IsNotNull("serviceType", serviceType);

            _serviceLocator = serviceLocator;
            _contractType = contractType;

            _log.Debug("Register the contract type '{0}' for service type '{1}'", _contractType.Name, serviceType.Name);
            _serviceLocator.RegisterTypeIfNotYetRegistered(_contractType, serviceType, tag, registrationType);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceLocatorRegistration" /> class.
        /// </summary>
        /// <param name="declaringType">Type of the declaring.</param>
        /// <param name="implementingType">Type of the implementing.</param>
        /// <param name="tag">The tag.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="createServiceFunc">The create service function.</param>
        public ServiceLocatorRegistration(Type declaringType, Type implementingType, object tag, RegistrationType registrationType, Func<ServiceLocatorRegistration, object> createServiceFunc)
        {
            Argument.IsNotNull("createServiceFunc", createServiceFunc);

            CreateServiceFunc = createServiceFunc;
            DeclaringType = declaringType;
            DeclaringTypeName = declaringType.AssemblyQualifiedName;

            ImplementingType = implementingType;
            ImplementingTypeName = implementingType.AssemblyQualifiedName;

            Tag = tag;
            RegistrationType = registrationType;
        }
Example #41
0
            public RegisteredTypeInfo(Type declaringType, Type implementingType, object tag, RegistrationType registrationType, object originalContainer)
            {
                Argument.IsNotNull("declaringType", declaringType);
                Argument.IsNotNull("implementingType", implementingType);
                Argument.IsNotNull("originalContainer", originalContainer);

                DeclaringType = declaringType;
                DeclaringTypeName = declaringType.AssemblyQualifiedName;

                ImplementingType = implementingType;
                ImplementingTypeName = implementingType.AssemblyQualifiedName;

                Tag = tag;
                RegistrationType = registrationType;
                OriginalContainer = originalContainer;
            }
Example #42
0
        /// <summary>
        /// Installs a SharpShell server at the specified path.
        /// </summary>
        /// <param name="path">The path to the SharpShell server.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="codeBase">if set to <c>true</c> install from codebase rather than GAC.</param>
        private void InstallServer(string path, RegistrationType registrationType, bool codeBase)
        {
            //  Validate the path.
            if (File.Exists(path) == false)
            {
                outputService.WriteError("File '" + path + "' does not exist.", true);
                return;
            }
            
            //  Try and load the server types.
            IEnumerable<ISharpShellServer> serverTypes = null;
            try
            {
                serverTypes = LoadServerTypes(path);
            }
            catch (Exception e)
            {
                outputService.WriteError("An unhandled exception occured when loading the SharpShell");
                outputService.WriteError("Server Types from the specified assembly. Is it a SharpShell");
                outputService.WriteError("Server Assembly?");
                System.Diagnostics.Trace.Write(e);
                Logging.Error("An unhandled exception occured when loading a SharpShell server.", e);
            }

            //  Install each server type.
            foreach (var serverType in serverTypes)
            {
                //  Inform the user we're going to install the server.
                outputService.WriteMessage("Preparing to install (" + registrationType + "): " + serverType.DisplayName, true);

                //  Install the server.
                try
                {
                    SharpShell.ServerRegistration.ServerRegistrationManager.InstallServer(serverType, registrationType, codeBase);
                    SharpShell.ServerRegistration.ServerRegistrationManager.RegisterServer(serverType, registrationType);
                }
                catch (Exception e)
                {
                    outputService.WriteError("Failed to install and register the server.");
                    Logging.Error("An unhandled exception occured installing and registering the server " + serverType.DisplayName, e);
                    continue;
                }

                outputService.WriteSuccess("    " + serverType.DisplayName + " installed and registered.", true);
            }
        }
Example #43
0
        /// <summary>
        /// Actually performs registration. The ComRegisterFunction decorated method will call this function
        /// internally with the flag appropriate for the operating system processor architecture.
        /// However, this function can also be called manually if needed.
        /// </summary>
        /// <param name="type">The type of object to register, this must be a SharpShellServer derived class.</param>
        /// <param name="registrationType">Type of the registration.</param>
        internal static void DoRegister(Type type, RegistrationType registrationType)
        {
            //  Get the assoication data.
            var assocationAttributes = type.GetCustomAttributes(typeof(COMServerAssociationAttribute), true)
                .OfType<COMServerAssociationAttribute>().ToList();

            //  Get the server type.
            var serverType = ServerTypeAttribute.GetServerType(type);

            //  Register the server associations, if there are any.
            if (assocationAttributes.Any())
            {
                ServerRegistrationManager.RegisterServerAssociations(
                    type.GUID, serverType, type.Name, assocationAttributes, registrationType);
            }

            //  Execute the custom register function, if there is one.
            CustomRegisterFunctionAttribute.ExecuteIfExists(type, registrationType);
        }
 public RegisterInContainerAttribute(Type interfaceType, RegistrationType registrationType)
     : this(interfaceType, null, registrationType)
 {
 }
Example #45
0
 internal static void CustomRegisterFunction(Type serverType, RegistrationType registrationType)
 {
     //  Register preview handlers via the registrar.
     PreviewHandlerRegistrar.Register(serverType, registrationType);
 }
Example #46
0
        /// <summary>
        /// Registers an implementation of a service using a create type callback, but only if the type is not yet registered.
        /// </summary>
        /// <param name="serviceType">The type of the service.</param>
        /// <param name="createServiceFunc">The create service function.</param>
        /// <param name="tag">The tag to register the service with. The default value is <c>null</c>.</param>
        /// <param name="registrationType">The registration type. The default value is <see cref="RegistrationType.Singleton" />.</param>
        /// <param name="registerIfAlreadyRegistered">If set to <c>true</c>, an older type registration is overwritten by this new one.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="serviceType" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="createServiceFunc" /> is <c>null</c>.</exception>
        /// <remarks>Note that the actual implementation lays in the hands of the IoC technique being used.</remarks>
        public void RegisterType(Type serviceType, Func<ServiceLocatorRegistration, object> createServiceFunc, object tag = null, RegistrationType registrationType = RegistrationType.Singleton, bool registerIfAlreadyRegistered = true)
        {
            Argument.IsNotNull("createServiceFunc", createServiceFunc);

            RegisterType(serviceType, null, tag, registrationType, registerIfAlreadyRegistered, this, createServiceFunc);
        }
        /// <summary>
        /// Determines whether an extension is approved.
        /// </summary>
        /// <param name="serverClsid">The server CLSID.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <returns>
        ///   <c>true</c> if the extension is approved; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="System.InvalidOperationException">Failed to open the Approved Extensions key.</exception>
        private static bool IsExtensionApproved(Guid serverClsid, RegistrationType registrationType)
        {
            //  Open the approved extensions key.
            using (var approvedKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                registrationType == RegistrationType.OS64Bit ? RegistryView.Registry64 : RegistryView.Registry32)
                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", RegistryKeyPermissionCheck.ReadSubTree))
            {
                //  If we can't open the key, we're going to have problems.
                if (approvedKey == null)
                    throw new InvalidOperationException("Failed to open the Approved Extensions key.");

                return approvedKey.GetValueNames().Any(vn => vn.Equals(serverClsid.ToRegistryString(), StringComparison.OrdinalIgnoreCase));
            }
        }
        internal static void CustomRegisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using(var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                  RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the ShellIconOverlayIdentifiers.
                using(var overlayIdentifiers = localMachineBaseKey
                    .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers",
                    RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.EnumerateSubKeys | RegistryRights.QueryValues | RegistryRights.CreateSubKey | RegistryRights.CreateSubKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if(overlayIdentifiers == null)
                        throw new InvalidOperationException("Cannot open the ShellIconOverlayIdentifiers key.");

                    //  How many shell icon overlay identifiers do we have?
                    var overlayHandlersCount = overlayIdentifiers.GetSubKeyNames().Count();
                    if(overlayHandlersCount >= MaximumOverlayIdentifiers)
                        Diagnostics.Logging.Error("There are already the maximum number of overlay " +
                            "handlers registered for the system. Although " + serverType.Name + " is " +
                                                  "being registered, it will not be used by Windows Explorer.");

                    //  Create the overlay key.
                    using(var overlayKey = overlayIdentifiers.CreateSubKey(" " + serverType.Name))
                    {
                        //  If we don't have the overlay key, we've got a problem.
                        if(overlayKey == null)
                            throw new InvalidOperationException("Cannot create the key for the overlay server.");

                        //  Set the server CLSID.
                        overlayKey.SetValue(null, serverType.GUID.ToRegistryString());
                    }
                }
            }
        }
        /// <summary>
        /// Unapproves an extension.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="registrationType">Type of the registration.</param>
        /// <exception cref="System.InvalidOperationException">Failed to open the Approved Extensions key.</exception>
        private static void UnapproveExtension(ISharpShellServer server, RegistrationType registrationType)
        {
            //  Open the approved extensions key.
            using (var approvedKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                registrationType == RegistrationType.OS64Bit ? RegistryView.Registry64 : RegistryView.Registry32)
                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                //  If we can't open the key, we're going to have problems.
                if (approvedKey == null)
                    throw new InvalidOperationException("Failed to open the Approved Extensions key.");

                //  Delete the value if it's there.
                approvedKey.DeleteValue(server.ServerClsid.ToRegistryString(), false);
            }
        }
Example #50
0
    private static List<string> Get_Registrations_OverlapList(RegistrationType Registration, bool IsMetadata, bool IsAdminUploadedDSD)
    {
        List<string> RetVal;
        string FileURL, WSURL, Content, ElementName, AttributeName, PAIdPrefixRemoved, MFDId;
        WebRequest Request;
        WebResponse Response;
        StreamReader DataReader;
        Stream DataStream;
        XmlElement QueryElement;
        Registry.RegistryService Service;
        XmlDocument FileXML;

        RetVal = new List<string>();
        FileURL = string.Empty;
        WSURL = string.Empty;
        Content = string.Empty;
        ElementName = string.Empty;
        AttributeName = string.Empty;
        PAIdPrefixRemoved = string.Empty;
        MFDId = string.Empty;
        Request = null;
        Response = null;
        DataReader = null;
        DataStream = null;
        QueryElement = null;
        Service = new Registry.RegistryService();
        FileXML = new XmlDocument();

        if (IsMetadata == false)
        {
            if (Registration.Datasource[0] is SDMXObjectModel.Registry.QueryableDataSourceType)
            {
                WSURL = ((SDMXObjectModel.Registry.QueryableDataSourceType)Registration.Datasource[0]).DataURL;

                if (Registration.Datasource.Count == 2)
                {
                    FileURL = Registration.Datasource[1].ToString();
                }
            }
            else
            {
                FileURL = Registration.Datasource[0].ToString();

                if (Registration.Datasource.Count == 2)
                {
                    WSURL = ((SDMXObjectModel.Registry.QueryableDataSourceType)Registration.Datasource[1]).DataURL;
                }
            }

            if (IsAdminUploadedDSD == false)
            {
                if (!string.IsNullOrEmpty(FileURL))
                {
                    Request = WebRequest.Create(FileURL);
                    Response = Request.GetResponse();

                    DataStream = Response.GetResponseStream();
                    DataReader = new StreamReader(DataStream);
                    Content = DataReader.ReadToEnd();
                }
                else if (!string.IsNullOrEmpty(WSURL))
                {
                    QueryElement = SDMXUtility.Get_Query(SDMXSchemaType.Two_One, null, QueryFormats.StructureSpecificTS, DataReturnDetailTypes.SeriesKeyOnly, DevInfo.Lib.DI_LibSDMX.Constants.AgencyId, null, null).DocumentElement;
                    Service.Url = WSURL.ToString();
                    Service.GetStructureSpecificTimeSeriesData(ref QueryElement);
                    Content = QueryElement.OuterXml;
                }

                ElementName = "Series";
                AttributeName = DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id;
            }
            else
            {
                if (!string.IsNullOrEmpty(FileURL))
                {
                    Request = WebRequest.Create(FileURL);
                    Response = Request.GetResponse();

                    DataStream = Response.GetResponseStream();
                    DataReader = new StreamReader(DataStream);
                    Content = DataReader.ReadToEnd();
                }

                ElementName = SDMXApi_2_0.Constants.Namespaces.Prefixes.DevInfo + ":" + "Series";
                AttributeName = Constants.UNSD.Concept.Indicator.Id;
            }

            FileXML.LoadXml(Content);

            foreach (XmlNode Series in FileXML.GetElementsByTagName(ElementName))
            {
                if (!RetVal.Contains(Series.Attributes[AttributeName].Value))
                {
                    RetVal.Add(Series.Attributes[AttributeName].Value);
                }
            }
        }
        else
        {
            if (Registration.ProvisionAgreement != null && Registration.ProvisionAgreement.Items != null && Registration.ProvisionAgreement.Items.Count > 0)
            {
                PAIdPrefixRemoved = ((ProvisionAgreementRefType)Registration.ProvisionAgreement.Items[0]).id.Replace(DevInfo.Lib.DI_LibSDMX.Constants.PA.Prefix, string.Empty);
                MFDId = PAIdPrefixRemoved.Substring(PAIdPrefixRemoved.IndexOf('_') + 1);
                RetVal.Add(MFDId);
            }
        }

        return RetVal;
    }
Example #51
0
    public static void Retrieve_SimpleAndQueryableDataSource_FromRegistration(RegistrationType Registration, out string SimpleDataSource, out SDMXObjectModel.Registry.QueryableDataSourceType QueryableDataSource)
    {
        SimpleDataSource = string.Empty;
        QueryableDataSource = null;

        if (Registration.Datasource != null && Registration.Datasource.Count > 0 && Registration.Datasource.Count < 3)
        {
            if (Registration.Datasource.Count == 1)
            {
                if (Registration.Datasource[0] is SDMXObjectModel.Registry.QueryableDataSourceType)
                {
                    QueryableDataSource = (SDMXObjectModel.Registry.QueryableDataSourceType)Registration.Datasource[0];
                }
                else if (Registration.Datasource[0] is string)
                {
                    SimpleDataSource = (string)Registration.Datasource[0];
                }
            }
            else if (Registration.Datasource.Count == 2)
            {
                if (Registration.Datasource[0] is SDMXObjectModel.Registry.QueryableDataSourceType)
                {
                    QueryableDataSource = (SDMXObjectModel.Registry.QueryableDataSourceType)Registration.Datasource[0];

                    if (Registration.Datasource[1] is string)
                    {
                        SimpleDataSource = (string)Registration.Datasource[1];
                    }
                }
                else if (Registration.Datasource[0] is string)
                {
                    SimpleDataSource = (string)Registration.Datasource[0];

                    if (Registration.Datasource[1] is SDMXObjectModel.Registry.QueryableDataSourceType)
                    {
                        QueryableDataSource = (SDMXObjectModel.Registry.QueryableDataSourceType)Registration.Datasource[1];
                    }
                }
            }
        }
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="FirstInterfaceRegistrationConvention"/> class.
 /// </summary>
 /// <param name="serviceLocator">The service locator.</param>
 /// <param name="registrationType">Type of the registration.</param>
 public FirstInterfaceRegistrationConvention(IServiceLocator serviceLocator, RegistrationType registrationType = RegistrationType.Singleton) 
     : base(serviceLocator, registrationType)
 {
 }
Example #53
0
        /// <summary>
        /// Registers the specific implementing type for the service type.
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="serviceImplementationType">Type of the implementing.</param>
        /// <param name="tag">The tag to register the service with. The default value is <c>null</c>.</param>
        /// <param name="registrationType">The registration type.</param>
        /// <param name="registerIfAlreadyRegistered">if set to <c>true</c>, an older type registration is overwritten by this new one.</param>
        /// <param name="originalContainer">The original container where the type was found in.</param>
        /// <param name="createServiceFunc">The create service function.</param>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="ArgumentNullException">The <paramref name="serviceType" /> is <c>null</c>.</exception>
        private void RegisterType(Type serviceType, Type serviceImplementationType, object tag, RegistrationType registrationType, bool registerIfAlreadyRegistered, object originalContainer, Func<ServiceLocatorRegistration, object> createServiceFunc)
        {
            Argument.IsNotNull("serviceType", serviceType);

            if (serviceImplementationType == null)
            {
                // Dynamic late-bound type
                serviceImplementationType = typeof(LateBoundImplementation);
            }

            if (serviceImplementationType.IsInterfaceEx())
            {
                throw Log.ErrorAndCreateException<InvalidOperationException>("Cannot register interface type '{0}' as implementation, make sure to specify an actual class", serviceImplementationType.GetSafeFullName());
            }

            /* TODO: This code have to be here to ensure the right usage of non-generic overloads of register methods.
             * TODO: If it is finally accepted then remove it from ServiceLocatorAutoRegistrationManager
            if (serviceImplementationType.IsAbstractEx() || !serviceType.IsAssignableFromEx(serviceImplementationType))
            {
                string message = string.Format("The type '{0}' is abstract or can't be registered as '{1}'", serviceImplementationType, serviceType);
                Log.Error(message);
                throw new InvalidOperationException(message);
            }
            */

            // Outside lock scope for event
            ServiceLocatorRegistration registeredTypeInfo = null;

            lock (this)
            {
                if (!registerIfAlreadyRegistered && IsTypeRegistered(serviceType, tag))
                {
                    //Log.Debug("Type '{0}' already registered, will not overwrite registration", serviceType.FullName);
                    return;
                }

                var serviceInfo = new ServiceInfo(serviceType, tag);
                if (_registeredInstances.ContainsKey(serviceInfo))
                {
                    _registeredInstances.Remove(serviceInfo);
                }

                Log.Debug("Registering type '{0}' to type '{1}'", serviceType.FullName, serviceImplementationType.FullName);

                registeredTypeInfo = new ServiceLocatorRegistration(serviceType, serviceImplementationType, tag, registrationType,
                    x => (createServiceFunc != null) ? createServiceFunc(x) : CreateServiceInstance(x));
                _registeredTypes[serviceInfo] = registeredTypeInfo;
            }

            TypeRegistered.SafeInvoke(this, new TypeRegisteredEventArgs(registeredTypeInfo.DeclaringType, registeredTypeInfo.ImplementingType, tag, registeredTypeInfo.RegistrationType));

            Log.Debug("Registered type '{0}' to type '{1}'", serviceType.FullName, serviceImplementationType.FullName);
        }
        internal static void CustomRegisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  We will use the display name a few times.
            var displayName = DisplayNameAttribute.GetDisplayNameOrTypeName(serverType);

            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                  RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the Preview Handlers.
                using (var previewHandlersKey = localMachineBaseKey
                    .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\PreviewHandlers",
                    RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (previewHandlersKey == null)
                        throw new InvalidOperationException("Cannot open the PreviewHandlers key.");

                    //  Write the server guid as a name, and the display name as the value.
                    //  The display name isn't needed, it's just helpful for debugging and checking the registry.
                    previewHandlersKey.SetValue(serverType.GUID.ToRegistryString(), displayName);
                }
            }

            //  Open the classes root.
            using (var classesBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry64) :
                  RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32))
            {
                //  Our server guid.
                var serverGuid = serverType.GUID.ToRegistryString();

                //  Open the Class Key.
                using (var classKey = classesBaseKey
                    .OpenSubKey(string.Format(@"CLSID\{0}", serverGuid),
                    RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (classKey == null)
                        throw new InvalidOperationException("Cannot open the class key.");

                    //  Set the AppID as the preview host surrogate.
                    classKey.SetValue(null, serverType.Name);
                    classKey.SetValue("AppID", "{6d2b5079-2f0b-48dd-ab7f-97cec514d30b}");
                    
                    //  Set the display name and TODO icon.
                    classKey.SetValue("DisplayName", displayName, RegistryValueKind.String);
                    classKey.SetValue("Icon", "%SystemRoot%\\system32\\fontext.dll,10", RegistryValueKind.ExpandString);

                    //  Disable low integrity process isolation - TODO maybe this should be optional.
                    classKey.SetValue("DisableLowILProcessIsolation", 1, RegistryValueKind.DWord);
                }
            }
        }
        internal static void CustomUnregisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                  RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the Preview Handlers.
                using (var previewHandlersKey = localMachineBaseKey
                    .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\PreviewHandlers",
                    RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey | RegistryRights.ReadKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (previewHandlersKey == null)
                        throw new InvalidOperationException("Cannot open the PreviewHandlers key.");

                    //  If there's a value for the server, delete it.
                    var serverGuid = serverType.GUID.ToRegistryString();
                    if(previewHandlersKey.GetValueNames().Any(vm => vm == serverGuid))
                        previewHandlersKey.DeleteValue(serverGuid);
                }
            }
        }
        internal static void CustomUnregisterFunction(Type serverType, RegistrationType registrationType)
        {
            //  Open the local machine.
            using (var localMachineBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) :
                  RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                //  Open the ShellIconOverlayIdentifiers.
                using (var overlayIdentifiers = localMachineBaseKey
                    .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers",
                    RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.Delete | RegistryRights.EnumerateSubKeys | RegistryRights.ReadKey))
                {
                    //  If we don't have the key, we've got a problem.
                    if (overlayIdentifiers == null)
                        throw new InvalidOperationException("Cannot open the ShellIconOverlayIdentifiers key.");

                    //  Delete the overlay key.
                    if (overlayIdentifiers.GetSubKeyNames().Any(skn => skn == (" " + serverType.Name)))
                        overlayIdentifiers.DeleteSubKey(" " + serverType.Name);
                }
            }
        }
Example #57
0
    private RegistryInterfaceType Get_SubmitRegistrations_Reponse(RegistrationType Registration, StatusType StatusType, string StatusMessage, string StatusLanguage)
    {
        RegistryInterfaceType RetVal;

        RetVal = null;

        try
        {
            RetVal = new RegistryInterfaceType();
            RetVal.Header = Global.Get_Appropriate_Header();
            RetVal.Footer = null;
            RetVal.Item = new SDMXObjectModel.Registry.SubmitRegistrationsResponseType();
            ((SDMXObjectModel.Registry.SubmitRegistrationsResponseType)RetVal.Item).RegistrationStatus = new List<RegistrationStatusType>();
            ((SDMXObjectModel.Registry.SubmitRegistrationsResponseType)RetVal.Item).RegistrationStatus.Add(new RegistrationStatusType());
            ((SDMXObjectModel.Registry.SubmitRegistrationsResponseType)RetVal.Item).RegistrationStatus[0].Registration = Registration;
            ((SDMXObjectModel.Registry.SubmitRegistrationsResponseType)RetVal.Item).RegistrationStatus[0].StatusMessage = new SDMXObjectModel.Registry.StatusMessageType(StatusType, StatusMessage, StatusLanguage);
        }
        catch (Exception ex)
        {
            Global.CreateExceptionString(ex, null);
            throw ex;
        }
        finally
        {
        }

        return RetVal;
    }
Example #58
0
        /// <summary>
        /// Registers an implementation of a service, but only if the type is not yet registered.
        /// </summary>
        /// <param name="serviceType">The type of the service.</param>
        /// <param name="serviceImplementationType">The type of the implementation.</param>
        /// <param name="tag">The tag to register the service with. The default value is <c>null</c>.</param>
        /// <param name="registrationType">The registration type. The default value is <see cref="RegistrationType.Singleton" />.</param>
        /// <param name="registerIfAlreadyRegistered">If set to <c>true</c>, an older type registration is overwritten by this new one.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="serviceType" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="serviceImplementationType" /> is <c>null</c>.</exception>
        /// <remarks>Note that the actual implementation lays in the hands of the IoC technique being used.</remarks>
        public void RegisterType(Type serviceType, Type serviceImplementationType, object tag = null, RegistrationType registrationType = RegistrationType.Singleton, bool registerIfAlreadyRegistered = true)
        {
            Argument.IsNotNull("serviceImplementationType", serviceImplementationType);

            RegisterType(serviceType, serviceImplementationType, tag, registrationType, registerIfAlreadyRegistered,
                this, null);
        }
        /// <summary>
        /// Opens the classes root.
        /// </summary>
        /// <param name="registrationType">Type of the registration.</param>
        /// <returns>The classes root key.</returns>
        private static RegistryKey OpenClassesRoot(RegistrationType registrationType)
        {
            //  Get the classes base key.
            var classesBaseKey = registrationType == RegistrationType.OS64Bit
                ? RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry64) :
                  RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32);

            //  Return the classes key.
            return classesBaseKey;
        }
        /// <summary>
        /// Opens the classes key.
        /// </summary>
        /// <param name="registrationType">Type of the registration.</param>
        /// <param name="permissions">The permissions.</param>
        /// <returns></returns>
        private static RegistryKey OpenClassesKey(RegistrationType registrationType, RegistryKeyPermissionCheck permissions)
        {
            //  Get the classes base key.
            var classesBaseKey = OpenClassesRoot(registrationType);

            //  Open classes.
            var classesKey = classesBaseKey.OpenSubKey(KeyName_Classes, permissions, RegistryRights.QueryValues | RegistryRights.ReadPermissions | RegistryRights.EnumerateSubKeys);
            if (classesKey == null)
                throw new InvalidOperationException("Cannot open classes.");

            return classesKey;
        }