Esempio n. 1
0
        private Azure(RestClient restClient, string subscriptionId, string tenantId, IAuthenticated authenticated)
        {
            resourceManager          = ResourceManager.Fluent.ResourceManager.Authenticate(restClient).WithSubscription(subscriptionId);
            storageManager           = StorageManager.Authenticate(restClient, subscriptionId);
            computeManager           = ComputeManager.Authenticate(restClient, subscriptionId);
            networkManager           = NetworkManager.Authenticate(restClient, subscriptionId);
            batchManager             = BatchManager.Authenticate(restClient, subscriptionId);
            keyVaultManager          = KeyVaultManager.Authenticate(restClient, subscriptionId, tenantId);
            trafficManager           = TrafficManager.Fluent.TrafficManager.Authenticate(restClient, subscriptionId);
            dnsZoneManager           = DnsZoneManager.Authenticate(restClient, subscriptionId);
            sqlManager               = SqlManager.Authenticate(restClient, subscriptionId);
            redisManager             = RedisManager.Authenticate(restClient, subscriptionId);
            cdnManager               = CdnManager.Authenticate(restClient, subscriptionId);
            appServiceManager        = AppServiceManager.Authenticate(restClient, subscriptionId, tenantId);
            searchManager            = SearchManager.Authenticate(restClient, subscriptionId);
            serviceBusManager        = ServiceBusManager.Authenticate(restClient, subscriptionId);
            containerInstanceManager = ContainerInstanceManager.Authenticate(restClient, subscriptionId);
            registryManager          = RegistryManager.Authenticate(restClient, subscriptionId);
            containerServiceManager  = ContainerServiceManager.Authenticate(restClient, subscriptionId);
            cosmosDBManager          = CosmosDBManager.Authenticate(restClient, subscriptionId);
            authorizationManager     = AuthorizationManager.Authenticate(restClient, subscriptionId);
            msiManager               = MsiManager.Authenticate(restClient, subscriptionId);
            batchAIManager           = BatchAIManager.Authenticate(restClient, subscriptionId);
            monitorManager           = MonitorManager.Authenticate(restClient, subscriptionId);
            eventHubManager          = EventHubManager.Authenticate(restClient, subscriptionId);

            SubscriptionId     = subscriptionId;
            this.authenticated = authenticated;
        }
Esempio n. 2
0
        // Set IoTHub connection strings, using either the user provided value or the configuration
        public void SetCurrentIotHub()
        {
            try
            {
                // Retrieve connection string from file/storage
                this.connString = this.connectionStringManager.GetIotHubConnectionString();

                // Parse connection string, this triggers an exception if the string is invalid
                IotHubConnectionStringBuilder connStringBuilder = IotHubConnectionStringBuilder.Create(this.connString);

                // Prepare registry class used to create/retrieve devices
                this.registry = this.registry.CreateFromConnectionString(this.connString);
                this.log.Debug("Device registry object ready", () => new { this.ioTHubHostName });

                // Prepare hostname used to build device connection strings
                this.ioTHubHostName = connStringBuilder.HostName;
                this.log.Info("Selected active IoT Hub for devices", () => new { this.ioTHubHostName });

                // Prepare the auth key used for all the devices
                this.fixedDeviceKey = connStringBuilder.SharedAccessKey;
                this.log.Debug("Device authentication key defined", () => new { this.ioTHubHostName });

                this.setupDone = true;
            }
            catch (Exception e)
            {
                this.log.Error("IoT Hub connection setup failed", e);
                throw;
            }
        }
Esempio n. 3
0
 ///GENMHASH:FC4CCB4833EA2DD311741B384FD9316F:8E288AFF39988D3B6818D60EB161D26B
 internal RegistryTaskRunImpl(IRegistryManager registryManager, RunInner runInner)
 {
     this.registryManager = registryManager;
     this.registriesInner = registryManager.Inner.Registries;
     this.platform        = new PlatformProperties();
     this.inner           = runInner;
 }
Esempio n. 4
0
        ///GENMHASH:D18EDD2A0D462DC25F8E338158E130F1:92497F2001C42DEB1C90E3A01204233E
        internal RegistryImpl(string name, RegistryInner innerObject, IRegistryManager manager, IStorageManager storageManager) : base(name, innerObject, manager)
        {
            this.storageManager = storageManager;

            this.storageAccountId = null;
            this.webhooks         = new WebhooksImpl(this, "Webhook");
        }
Esempio n. 5
0
 ///GENMHASH:90436C433DC4B4C48CC8286CCD933506:75801DEBDE7DF693898C5439817D4492
 internal RegistryTaskImpl(IRegistryManager registryManager, string taskName)
 {
     this.tasksInner           = registryManager.Inner.Tasks;
     this.taskName             = taskName;
     this.inner                = new TaskInner();
     this.taskUpdateParameters = new TaskUpdateParametersInner();
 }
        // Temporary workaround, see https://github.com/Azure/device-simulation-dotnet/issues/136
        private IRegistryManager GetRegistry()
        {
            if (this.registryCount > REGISTRY_LIMIT_REQUESTS)
            {
                this.registry.CloseAsync();

                try
                {
                    this.registry.Dispose();
                }
                catch (Exception e)
                {
                    // Errors might occur here due to pending requests, they can be ignored
                    this.log.Debug("Ignoring registry manager Dispose() error", () => new { e });
                }

                this.registryCount = -1;
            }

            if (this.registryCount == -1)
            {
                string connString = this.connectionStringManager.GetIotHubConnectionString();
                this.registry = this.registry.CreateFromConnectionString(connString);
                this.registry.OpenAsync();
            }

            this.registryCount++;

            return(this.registry);
        }
 public SettingsViewModel(
     IRegistryManager registryManager,
     IProcessManager processManager)
 {
     this.registryManager = registryManager;
     this.processManager = processManager;
 }
Esempio n. 8
0
        public StartupScanEnabledViewModel(IResolver resolver, IRegistryManager registryManager, ILoginsReader loginsReader, Action onCloseOut, bool isAutoShowPopup)
            : base(resolver, null)
        {
            this.onCloseOut = onCloseOut;
            this.onClose    = OnClose;
            // By default
            ScanStatus  = DefaultProperties.ReturnString("Onboardv4StatusUnknown");
            ScanSummary = registryManager.GetScanSummary();

            popupViewModel = new ScanPopupNotificationViewModel(resolver, this, OnClose);

            _currentVM = mainViewModel;

            bool isScanSummaryEmpty = ScanSummary.Duplicate + ScanSummary.Weak + ScanSummary.Insecure == 0;

            IsScanSummaryPopupVisible = isAutoShowPopup && !isScanSummaryEmpty;

            if (IsScanSummaryPopupVisible)
            {
                mainViewModel = new ScanNowViewModel(_resolver, OnClose, () => StartScanCommand.Execute(this));
            }
            else
            {
                mainViewModel = new ProgressScanViewModel(_resolver, loginsReader, OnClose, OnScanCompleted);
            }

            ClosePopup = new RelayCommand((o) =>
            {
                popupViewModel.LogStep(MarketingActionType.Continue);
                IsScanSummaryPopupVisible = false;
                CurrentVM = new ScanNowViewModel(_resolver, OnClose, () =>
                {
                    StartScanCommand.Execute(o);
                });
            });

            StartScanCommand = new RelayCommand((o) =>
            {
                mainViewModel = new ProgressScanViewModel(_resolver, loginsReader, OnClose, OnScanCompleted);
                var vm        = mainViewModel as ProgressScanViewModel;
                if (vm != null)
                {
                    CurrentVM = vm;
                    vm.StartScan();         // TODO: better move to View.Loaded event, where animation starts now
                }
            }
                                                );

            if (IsScanSummaryPopupVisible)
            {
            }
            else
            {
                Task.Factory.StartNew(() =>
                {
                    StartScanCommand.Execute(this);
                });
            }
        }
        /// <summary>
        /// Creates an instance of external child resource in-memory.
        /// </summary>
        /// <param name="resourceGroupName">The resource group name.</param>
        /// <param name="registryName">The registry name.</param>
        /// <param name="name">The name of this external child resource.</param>
        /// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
        /// <param name="containerRegistryManager">Reference to the container registry manager that accesses web hook operations.</param>
        ///GENMHASH:A21B1A64BBD5DE45FE96382827594FDE:C13877D7A53C23149EEDA94679AF13A2
        internal WebhookImpl(string resourceGroupName, string registryName, string name, WebhookInner innerObject, IRegistryManager containerRegistryManager) : base(name, null, innerObject)
        {
            this.containerRegistryManager = containerRegistryManager;
            this.resourceGroupName        = resourceGroupName;
            this.registryName             = registryName;

            this.InitCreateUpdateParams();
        }
        /// <summary>
        /// Get IoTHub connection string from either the user provided value or the configuration
        /// </summary>
        public void SetCurrentIotHub()
        {
            string connString = this.connectionStringManager.GetIotHubConnectionString();

            this.registry       = this.registry.CreateFromConnectionString(connString);
            this.ioTHubHostName = IotHubConnectionStringBuilder.Create(connString).HostName;
            this.log.Info("Selected active IoT Hub for devices", () => new { this.ioTHubHostName });
        }
Esempio n. 11
0
 ///GENMHASH:F712FF2645AF2A9EDD0A69A05FB730DB:9CE14828E093066A7923277DDBEF714A
 internal RegistryTaskImpl(IRegistryManager registryManager, TaskInner inner)
 {
     this.tasksInner           = registryManager.Inner.Tasks;
     this.taskName             = inner.Name;
     this.inner                = inner;
     this.resourceGroupName    = ResourceUtils.GroupFromResourceId(this.inner.Id);
     this.registryName         = ResourceUtils.NameFromResourceId(ResourceUtils.ParentResourcePathFromResourceId(this.inner.Id));
     this.taskUpdateParameters = new TaskUpdateParametersInner();
     SetTaskUpdateParameterTriggers();
 }
 /// <summary>
 /// Creates an instance of external child resource in-memory.
 /// </summary>
 /// <param name="name">The name of this external child resource.</param>
 /// <param name="parent">Reference to the parent of this external child resource.</param>
 /// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
 /// <param name="containerRegistryManager">Reference to the container registry manager that accesses web hook operations.</param>
 ///GENMHASH:A02845D0393045D983B12D9853197178:8FC0F03D2574AA46828F939572035BF5
 internal WebhookImpl(string name, RegistryImpl parent, WebhookInner innerObject, IRegistryManager containerRegistryManager) : base(name, parent, innerObject)
 {
     this.containerRegistryManager = containerRegistryManager;
     if (parent != null)
     {
         this.resourceGroupName = parent.ResourceGroupName;
         this.registryName      = parent.Name;
     }
     this.InitCreateUpdateParams();
 }
Esempio n. 13
0
        internal static int LoadBlockstates(IRegistryManager registryManager, ResourceManager resources, bool replace,
                                            bool reportMissing = false, IProgressReceiver progressReceiver = null)
        {
            //RuntimeIdTable = TableEntry.FromJson(raw);

            progressReceiver?.UpdateProgress(0, "Loading block models...");

            RegisterBuiltinBlocks();

            return(LoadModels(registryManager, resources, replace, reportMissing, progressReceiver));
        }
Esempio n. 14
0
        public StartupScanEnabled(IResolver resolver, IRegistryManager registryManager, ILoginsReader loginsReader, bool isAutoShowPopup)
        {
            _resizer     = new WindowResizer(this);
            this.Loaded += OnLoaded;
            viewModel    = new StartupScanEnabledViewModel(resolver,
                                                           registryManager,
                                                           loginsReader,
                                                           () => this.Close(), isAutoShowPopup);
            this.DataContext = viewModel;

            InitializeComponent();
        }
 public Devices(
     IServicesConfig config,
     IIotHubConnectionStringManager connStringManager,
     IRegistryManager registryManager,
     ILogger logger)
 {
     this.connectionStringManager = connStringManager;
     this.registry = registryManager;
     this.log      = logger;
     this.twinReadsWritesEnabled = config.TwinReadWriteEnabled;
     this.registryCount          = -1;
     this.setupDone = false;
 }
        public SettingsViewModel(
            IRegistryManager registryManager,
            IProcessManager processManager,
            ISettingsManager settingsManager,
            IKeyboardManager keyboardManager)
        {
            this.registryManager = registryManager;
            this.processManager  = processManager;
            this.settingsManager = settingsManager;
            this.keyboardManager = keyboardManager;

            pasteDurationBeforeUserInterfaceShowsInMilliseconds = settingsManager.LoadSetting(
                nameof(PasteDurationBeforeUserInterfaceShowsInMilliseconds),
                300);
        }
 public AppUpdateService(
     IActionLog log,
     IUpdateManager updateManager,
     IRegistryManager registryManager,
     IAppConfigurationManager configurationManager,
     IAppWindowManager appWindowManager,
     DispatcherTimer timer)
 {
     this.log                  = log;
     this.updateManager        = updateManager;
     this.registryManager      = registryManager;
     this.configurationManager = configurationManager;
     this.appWindowManager     = appWindowManager;
     this.timer                = timer;
 }
Esempio n. 18
0
 public Devices(
     IServicesConfig config,
     IIotHubConnectionStringManager connStringManager,
     IRegistryManager registryManager,
     IDeviceClientWrapper deviceClient,
     ILogger logger)
 {
     this.config = config;
     this.connectionStringManager = connStringManager;
     this.connString             = null;
     this.registry               = registryManager;
     this.deviceClient           = deviceClient;
     this.log                    = logger;
     this.twinReadsWritesEnabled = config.TwinReadWriteEnabled;
     this.setupDone              = false;
 }
Esempio n. 19
0
        /// <summary>
        /// A Factory method to return concrete implementations of <see cref="ILifecycle"/>
        /// </summary>
        /// <typeparam name="TInterface">Object's contract for which the <see cref="ILifecycle"/> instance is returned</typeparam>
        /// <param name="registrar"><see cref="IRegistryManager"/> instance required as a pass through to <see cref="ILifecycle"/> implementations</param>
        /// <returns>Instance of <see cref="ILifecycle"/> implementations depending on the object interface's <see cref="LifecycleType"/></returns>
        /// <exception cref="InvalidOperationException">If not a valid type of <see cref="LifecycleType"/></exception>
        internal static ILifecycle GetLifecycleInstance <TInterface>(IRegistryManager registrar)
        {
            var existingRegistration = registrar.Find <TInterface>();

            switch (existingRegistration.Lifecycle)
            {
            case LifecycleType.Singleton:
                return(new SingletonLifecycle(registrar));

            case LifecycleType.Transient:
                return(new TransientLifecycle(registrar));

            default:
                throw new InvalidOperationException($"LifecycleType {existingRegistration.Lifecycle} invalid!");
            }
        }
Esempio n. 20
0
        public Devices(
            IServicesConfig config,
            IConnectionStrings connStrings,
            IRegistryManager registryManager,
            IDeviceClientWrapper deviceClientFactory,
            ILogger logger,
            IDiagnosticsLogger diagnosticsLogger,
            IInstance instance)
        {
            this.config              = config;
            this.connectionStrings   = connStrings;
            this.registry            = registryManager;
            this.deviceClientFactory = deviceClientFactory;
            this.log = logger;
            this.diagnosticsLogger = diagnosticsLogger;
            this.instance          = instance;

            this.connString = null;
        }
Esempio n. 21
0
        internal static int LoadResources(IRegistryManager registryManager, ResourceManager resources, McResourcePack resourcePack, bool replace,
                                          bool reportMissing = false, IProgressReceiver progressReceiver = null)
        {
            var raw = ResourceManager.ReadStringResource("Alex.Resources.runtimeidtable.json");

            RuntimeIdTable = TableEntry.FromJson(raw);

            var blockEntries = resources.Registries.Blocks.Entries;

            progressReceiver?.UpdateProgress(0, "Loading block registry...");
            for (int i = 0; i < blockEntries.Count; i++)
            {
                var kv = blockEntries.ElementAt(i);

                progressReceiver?.UpdateProgress(i * (100 / blockEntries.Count), "Loading block registry...",
                                                 kv.Key);

                ProtocolIdToBlockName.TryAdd(kv.Value.ProtocolId, kv.Key);
            }

            progressReceiver?.UpdateProgress(0, "Loading block models...");

            if (resourcePack.TryGetBlockModel("cube_all", out ResourcePackLib.Json.Models.Blocks.BlockModel cube))
            {
                cube.Textures["all"] = "no_texture";
                CubeModel            = cube;

                UnknownBlockModel = new ResourcePackBlockModel(resources, new BlockStateModel[]
                {
                    new BlockStateModel()
                    {
                        Model     = CubeModel,
                        ModelName = "Unknown model",
                    }
                });

                AirState.Model = UnknownBlockModel;
            }

            RegisterBuiltinBlocks();

            return(LoadModels(registryManager, resources, resourcePack, replace, reportMissing, progressReceiver));
        }
Esempio n. 22
0
        public Devices(
            IServicesConfig config,
            IIotHubConnectionStringManager connStringManager,
            IRegistryManager registryManager,
            IDeviceClientWrapper deviceClient,
            ILogger logger,
            IDiagnosticsLogger diagnosticsLogger,
            IInstance instance)
        {
            this.config = config;
            this.connectionStringManager = connStringManager;
            this.registry          = registryManager;
            this.deviceClient      = deviceClient;
            this.log               = logger;
            this.diagnosticsLogger = diagnosticsLogger;
            this.instance          = instance;

            this.connString             = null;
            this.twinReadsWritesEnabled = config.TwinReadWriteEnabled;
        }
        private void InitializeApplication(UIControlledApplication application)
        {
            ApplicationGlobals.UiControlledApplication = application;
            WindowsApplication.Application.EnableVisualStyles();
            var applicationContext = new ApplicationContext("UOL Revit Sample Addin", "1.0.0.0", "UOLSample");

            ApplicationGlobals.ApplicationContext = applicationContext;

            // Add all services to the ApplicationContext that this Revit Add-in requires.
            applicationContext.AddUOLRevitAddIn();

            var monitoredExecutionContext = ApplicationGlobals.ApplicationContext.GetService <IMonitoredExecutionContext>();
            var windowTools = new WindowTools(monitoredExecutionContext);

            ApplicationGlobals.HostWindow = windowTools.GetWindowHandle("Revit");

            registryManager = ApplicationGlobals.ApplicationContext.GetService <IRegistryManager>();
            var registryHelper = new RegistryHelper();

            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(registryHelper.GetLanguage());
        }
Esempio n. 24
0
 ///GENMHASH:CDAB2C7CC715005191421E1723AFA34B:07766DB5652046D840E62ECBE0F0FDCD
 internal WebhooksClientImpl(IRegistryManager containerRegistryManager, RegistryImpl containerRegistry)
 {
     this.containerRegistryManager = containerRegistryManager;
     this.containerRegistry        = containerRegistry;
 }
Esempio n. 25
0
 ///GENMHASH:C20A4C6092C094D9F582AF41A61BBEEE:6BB7F98668B697E6F973980EB0493963
 internal RegistryTaskRunsImpl(IRegistryManager registryManager)
 {
     this.registryManager = registryManager;
 }
Esempio n. 26
0
        public static void Init(IRegistryManager registryManager, ResourceManager resources, McResourcePack resourcePack, IProgressReceiver progressReceiver = null)
        {
            var blockRegistry = registryManager.GetRegistry <Block>();

            ResourceManager = resources;
            ResourcePack    = resourcePack;

            var otherRaw = ResourceManager.ReadStringResource("Alex.Resources.items3.json");

            SecItemEntries = JsonConvert.DeserializeObject <SecondItemEntry[]>(otherRaw);

            var raw = ResourceManager.ReadStringResource("Alex.Resources.items2.json");

            ItemEntries = JsonConvert.DeserializeObject <ItemEntry[]>(raw);


            var ii     = resources.Registries.Items.Entries;
            var blocks = resources.Registries.Blocks.Entries;

            LoadModels();

            Dictionary <ResourceLocation, Func <Item> > items = new Dictionary <ResourceLocation, Func <Item> >();

            for (int i = 0; i < blocks.Count; i++)
            {
                var entry = blocks.ElementAt(i);
                progressReceiver?.UpdateProgress((int)(100D * ((double)i / (double)blocks.Count)), $"Processing block items...", entry.Key);

                Item item;

                /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                 * {
                 *      item = new ItemBlock(blockState.Value);
                 * }*/
                var bs = BlockFactory.GetBlockState(entry.Key);
                if (!(bs.Block is Air))
                {
                    item = new ItemBlock(bs);
                    //  Log.Info($"Registered block item: {entry.Key}");
                }
                else
                {
                    continue;
                }

                var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", ""));
                if (minetItem != null)
                {
                    if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                    {
                        item.ItemType = t;
                    }

                    SetItemMaterial(item, minetItem.ItemMaterial);
                    // item.Material = minetItem.ItemMaterial;

                    item.Meta = minetItem.Metadata;
                    item.Id   = minetItem.Id;
                }

                item.Name        = entry.Key;
                item.DisplayName = entry.Key;

                var data = ItemEntries.FirstOrDefault(x =>
                                                      x.name.Equals(entry.Key.Substring(10), StringComparison.InvariantCultureIgnoreCase));
                if (data != null)
                {
                    item.MaxStackSize = data.stackSize;
                    item.DisplayName  = data.displayName;
                }

                string ns   = ResourceLocation.DefaultNamespace;
                string path = entry.Key;
                if (entry.Key.Contains(':'))
                {
                    var index = entry.Key.IndexOf(':');
                    ns   = entry.Key.Substring(0, index);
                    path = entry.Key.Substring(index + 1);
                }

                var key = new ResourceLocation(ns, $"block/{path}");

                ResourcePackModelBase model;
                if (!(ResourcePack.ItemModels.TryGetValue(key, out model)))
                {
                    foreach (var it in ResourcePack.ItemModels)
                    {
                        if (it.Key.Path.Equals(key.Path, StringComparison.InvariantCultureIgnoreCase))
                        {
                            model = it.Value;
                            break;
                        }
                    }
                }

                if (model != null)
                {
                    item.Renderer = new ItemBlockModelRenderer(bs, model, resourcePack, resources);
                    item.Renderer.Cache(resourcePack);
                }
                else
                {
                    Log.Warn($"Could not find block model renderer for: {key.ToString()}");
                }

                items.TryAdd(entry.Key, () =>
                {
                    return(item.Clone());
                });
            }

            for (int i = 0; i < ii.Count; i++)
            {
                var entry = ii.ElementAt(i);
                progressReceiver?.UpdateProgress(i * (100 / ii.Count), $"Processing items...", entry.Key);

                Item item;

                /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                 * {
                 *      item = new ItemBlock(blockState.Value);
                 * }*/
                /*   if (blocks.ContainsKey(entry.Key) && blockRegistry.TryGet(entry.Key, out var registryEntry))
                 * {
                 *         item = new ItemBlock(registryEntry.Value);
                 * }
                 * else
                 * {*/
                item = new Item();
                // }

                var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", ""));
                if (minetItem != null)
                {
                    if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                    {
                        item.ItemType = t;
                    }

                    SetItemMaterial(item, minetItem.ItemMaterial);

                    // item.Material = minetItem.ItemMaterial;
                    item.Meta = minetItem.Metadata;
                    item.Id   = minetItem.Id;
                }

                item.Name        = entry.Key;
                item.DisplayName = entry.Key;

                var data = ItemEntries.FirstOrDefault(x =>
                                                      x.name.Equals(entry.Key.Substring(10), StringComparison.InvariantCultureIgnoreCase));
                if (data != null)
                {
                    item.MaxStackSize = data.stackSize;
                    item.DisplayName  = data.displayName;
                }

                string ns   = ResourceLocation.DefaultNamespace;
                string path = entry.Key;
                if (entry.Key.Contains(':'))
                {
                    var index = entry.Key.IndexOf(':');
                    ns   = entry.Key.Substring(0, index);
                    path = entry.Key.Substring(index + 1);
                }

                var key = new ResourceLocation(ns, $"item/{path}");

                foreach (var it in ResourcePack.ItemModels)
                {
                    if (it.Key.Path.Equals(key.Path, StringComparison.InvariantCultureIgnoreCase))
                    {
                        //Log.Info($"Model found: {entry.Key} = {it.Key}");
                        ItemModelRenderer renderer;
                        if (ItemRenderers.TryGetValue(it.Key, out renderer))
                        {
                        }
                        else if (ItemRenderers.TryGetValue(key, out renderer))

                        {
                        }

                        if (renderer != null)
                        {
                            //Log.Debug($"Found renderer for {entry.Key}, textures: {it.Value.Textures.Count}");
                            item.Renderer = renderer;
                            break;
                        }
                    }
                }

                if (item.Renderer == null)
                {
                    Log.Warn($"Could not find item model renderer for: {key.ToString()}");
                }

                items.TryAdd(key, () => { return(item.Clone()); });
            }

            Items = new ReadOnlyDictionary <ResourceLocation, Func <Item> >(items);
        }
 public RegistryController(IRegistryManager registryManager)
 {
     _registryManager = registryManager;
 }
Esempio n. 28
0
        private static int LoadModels(IRegistryManager registryManager, ResourceManager resources,
                                      McResourcePack resourcePack, bool replace,
                                      bool reportMissing, IProgressReceiver progressReceiver)
        {
            long idCounter          = 0;
            var  blockRegistry      = registryManager.GetRegistry <Block>();
            var  blockModelRegistry = registryManager.GetRegistry <BlockModel>();

            var data           = BlockData.FromJson(ResourceManager.ReadStringResource("Alex.Resources.NewBlocks.json"));
            int total          = data.Count;
            int done           = 0;
            int importCounter  = 0;
            int multipartBased = 0;

            uint c = 0;

            foreach (var entry in data)
            {
                double percentage = 100D * ((double)done / (double)total);
                progressReceiver.UpdateProgress((int)percentage, $"Importing block models...", entry.Key);

                var variantMap   = new BlockStateVariantMapper();
                var defaultState = new BlockState
                {
                    Name          = entry.Key,
                    VariantMapper = variantMap
                };

                if (entry.Value.Properties != null)
                {
                    foreach (var property in entry.Value.Properties)
                    {
                        //	if (property.Key.Equals("waterlogged"))
                        //		continue;

                        defaultState = (BlockState)defaultState.WithPropertyNoResolve(property.Key,
                                                                                      property.Value.FirstOrDefault(), false);
                    }
                }

                foreach (var s in entry.Value.States)
                {
                    var id = s.ID;

                    BlockState variantState = (BlockState)(defaultState).CloneSilent();
                    variantState.ID   = id;
                    variantState.Name = entry.Key;

                    if (s.Properties != null)
                    {
                        foreach (var property in s.Properties)
                        {
                            //if (property.Key.Equals("waterlogged"))
                            //		continue;

                            variantState =
                                (Blocks.State.BlockState)variantState.WithPropertyNoResolve(property.Key,
                                                                                            property.Value, false);
                        }
                    }

                    if (!replace && RegisteredBlockStates.TryGetValue(id, out BlockState st))
                    {
                        Log.Warn(
                            $"Duplicate blockstate id (Existing: {st.Name}[{st.ToString()}] | New: {entry.Key}[{variantState.ToString()}]) ");
                        continue;
                    }


                    var cachedBlockModel = GetOrCacheModel(resources, resourcePack, variantState, id, replace);
                    if (cachedBlockModel == null)
                    {
                        if (reportMissing)
                        {
                            Log.Warn($"Missing blockmodel for blockstate {entry.Key}[{variantState.ToString()}]");
                        }

                        cachedBlockModel = UnknownBlockModel;
                    }

                    if (variantState.IsMultiPart)
                    {
                        multipartBased++;
                    }

                    string displayName = entry.Key;
                    IRegistryEntry <Block> registryEntry;

                    if (!blockRegistry.TryGet(entry.Key, out registryEntry))
                    {
                        registryEntry = new UnknownBlock(id);
                        displayName   = $"(MISSING) {displayName}";

                        registryEntry = registryEntry.WithLocation(entry.Key);                         // = entry.Key;
                    }
                    else
                    {
                        registryEntry = registryEntry.WithLocation(entry.Key);
                    }

                    var block = registryEntry.Value;

                    variantState.Model   = cachedBlockModel;
                    variantState.Default = s.Default;

                    if (string.IsNullOrWhiteSpace(block.DisplayName) ||
                        !block.DisplayName.Contains("minet", StringComparison.InvariantCultureIgnoreCase))
                    {
                        block.DisplayName = displayName;
                    }

                    variantState.Block = block;
                    block.BlockState   = variantState;

                    if (variantMap.TryAdd(variantState))
                    {
                        if (!RegisteredBlockStates.TryAdd(variantState.ID, variantState))
                        {
                            if (replace)
                            {
                                RegisteredBlockStates[variantState.ID] = variantState;
                                importCounter++;
                            }
                            else
                            {
                                Log.Warn(
                                    $"Failed to add blockstate (variant), key already exists! ({variantState.ID} - {variantState.Name})");
                            }
                        }
                        else
                        {
                            importCounter++;
                        }
                    }
                    else
                    {
                        Log.Warn(
                            $"Could not add variant to variant map: {variantState.Name}[{variantState.ToString()}]");
                    }
                }

                if (!BlockStateByName.TryAdd(defaultState.Name, variantMap))
                {
                    if (replace)
                    {
                        BlockStateByName[defaultState.Name] = variantMap;
                    }
                    else
                    {
                        Log.Warn($"Failed to add blockstate, key already exists! ({defaultState.Name})");
                    }
                }

                done++;
            }

            Log.Info($"Got {multipartBased} multi-part blockstate variants!");
            return(importCounter);
        }
Esempio n. 29
0
 public ManageController(IRegistryManager registryManager, IConfiguration configuration)
 {
     _registryManager = registryManager;
     _configuration   = configuration;
 }
Esempio n. 30
0
 public Registry(IRegistryManager rm)
 {
     _registryManager = rm;
 }
Esempio n. 31
0
 public ManageController(IRegistryManager registryManager, IConfiguration configuration)
 {
     _registryManager = registryManager;
     _configuration = configuration;
 }
Esempio n. 32
0
        public static void Init(IRegistryManager registryManager, ResourceManager resources, IProgressReceiver progressReceiver = null)
        {
            ResourceManager = resources;
            // ResourcePack = resourcePack;

            var otherRaw = ResourceManager.ReadStringResource("Alex.Resources.items3.json");

            SecItemEntries = JsonConvert.DeserializeObject <SecondItemEntry[]>(otherRaw);

            var raw = ResourceManager.ReadStringResource("Alex.Resources.items2.json");

            ItemEntries = JsonConvert.DeserializeObject <ItemEntry[]>(raw);


            var ii     = resources.Registries.Items.Entries;
            var blocks = resources.Registries.Blocks.Entries;

            // LoadModels();

            ConcurrentDictionary <ResourceLocation, Func <Item> > items = new ConcurrentDictionary <ResourceLocation, Func <Item> >();

            // for(int i = 0; i < blocks.Count; i++)
            // List<ResourceLocation> addedCurrently = n
            int done = 0;

            Parallel.ForEach(
                blocks, e =>
            {
                try
                {
                    var entry = e;
                    progressReceiver?.UpdateProgress(done, blocks.Count, $"Processing block items...", entry.Key);

                    Item item;

                    /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                     * {
                     *      item = new ItemBlock(blockState.Value);
                     * }*/
                    var bs = BlockFactory.GetBlockState(entry.Key);

                    if (!(bs.Block is Air) && bs != null)
                    {
                        item = new ItemBlock(bs);
                        //  Log.Info($"Registered block item: {entry.Key}");
                    }
                    else
                    {
                        return;
                    }

                    /*var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", ""));
                     *
                     * if (minetItem != null)
                     * {
                     *      if (Enum.TryParse<ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                     *      {
                     *              item.ItemType = t;
                     *      }
                     *
                     *      SetItemMaterial(item, minetItem.ItemMaterial);
                     *      // item.Material = minetItem.ItemMaterial;
                     *
                     *      item.Meta = minetItem.Metadata;
                     *      item.Id = minetItem.Id;
                     * }*/

                    item.Name        = entry.Key;
                    item.DisplayName = entry.Key;

                    var data = ItemEntries.FirstOrDefault(
                        x => x.name.Equals(entry.Key.Substring(10), StringComparison.OrdinalIgnoreCase));

                    if (data != null)
                    {
                        item.MaxStackSize = data.stackSize;
                        item.DisplayName  = data.displayName;
                    }


                    string ns   = ResourceLocation.DefaultNamespace;
                    string path = entry.Key;

                    if (entry.Key.Contains(':'))
                    {
                        var index = entry.Key.IndexOf(':');
                        ns        = entry.Key.Substring(0, index);
                        path      = entry.Key.Substring(index + 1);
                    }


                    var resourceLocation = new ResourceLocation(ns, $"block/{path}");

                    ResourcePackModelBase model = null;

                    if (!ResourceManager.TryGetBlockModel(resourceLocation, out model))
                    {
                        /*foreach (var it in ResourcePack.ItemModels)
                         * {
                         *      if (it.Key.Path.Equals(key.Path, StringComparison.OrdinalIgnoreCase))
                         *      {
                         *              model = it.Value;
                         *
                         *              break;
                         *      }
                         * }*/
                    }

                    if (model == null)
                    {
                        Log.Debug($"Missing item render definition for block {entry.Key}, using default.");
                        //  model = new ResourcePackItem() {Display = _defaultDisplayElements};
                    }
                    else
                    {
                        item.Renderer = new ItemBlockModelRenderer(bs, model, bs.Block.Animated ? resources.Atlas.GetAtlas(0) : resources.Atlas.GetStillAtlas());
                        item.Renderer.Cache(resources);


                        if (!items.TryAdd(entry.Key, () => { return(item.Clone()); }))
                        {
                            // items[entry.Key] = () => { return item.Clone(); };
                        }
                    }
                }
                finally
                {
                    done++;
                }
            });

            int i = 0;

            Parallel.ForEach(
                ii, (entry) =>
            {
                // var entry = ii.ElementAt(i);
                progressReceiver?.UpdateProgress(i++, ii.Count, $"Processing items...", entry.Key);
                var resourceLocation = new ResourceLocation(entry.Key);
                resourceLocation     = new ResourceLocation(resourceLocation.Namespace, $"item/{resourceLocation.Path}");

                if (items.ContainsKey(resourceLocation))
                {
                    return;
                }

                Item item;

                /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                 * {
                 *      item = new ItemBlock(blockState.Value);
                 * }*/
                /*   if (blocks.ContainsKey(entry.Key) && blockRegistry.TryGet(entry.Key, out var registryEntry))
                 * {
                 *         item = new ItemBlock(registryEntry.Value);
                 * }
                 * else
                 * {*/
                item = new Item();
                // }

                var minetItem = MiNET.Items.ItemFactory.GetItem(resourceLocation.Path);

                if (minetItem != null)
                {
                    if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                    {
                        item.ItemType = t;
                    }

                    SetItemMaterial(item, minetItem.ItemMaterial);

                    // item.Material = minetItem.ItemMaterial;
                    item.Meta = minetItem.Metadata;
                    item.Id   = minetItem.Id;
                }

                item.Name        = entry.Key;
                item.DisplayName = entry.Key;

                var data = ItemEntries.FirstOrDefault(
                    x => x.name.Equals(resourceLocation.Path, StringComparison.OrdinalIgnoreCase));

                if (data != null)
                {
                    item.MaxStackSize = data.stackSize;
                    item.DisplayName  = data.displayName;
                }

                ItemModelRenderer renderer;
                if (!ItemRenderers.TryGetValue(resourceLocation, out renderer))
                {
                    if (ResourceManager.TryGetItemModel(resourceLocation, out var model))
                    {
                        renderer = new ItemModelRenderer(model);
                        renderer.Cache(ResourceManager);

                        ItemRenderers.TryAdd(resourceLocation, renderer);
                    }

                    if (renderer == null)
                    {
                        var r = ItemRenderers.FirstOrDefault(
                            x => x.Key.Path.Equals(resourceLocation.Path, StringComparison.OrdinalIgnoreCase));

                        if (r.Value != null)
                        {
                            renderer = r.Value;
                        }
                    }

                    //  if (ResourcePack.ItemModels.TryGetValue(resourceLocation, out var itemModel)) { }
                }

                if (renderer != null)
                {
                    item.Renderer = renderer;
                }

                if (item.Renderer == null)
                {
                    Log.Warn($"Could not find item model renderer for: {resourceLocation}");
                }

                if (!items.TryAdd(resourceLocation, () => { return(item.Clone()); }))
                {
                    //var oldItem = items[resourceLocation];
                    //  items[resourceLocation] = () => { return item.Clone(); };
                }
            });

            Items = new ReadOnlyDictionary <ResourceLocation, Func <Item> >(items);
        }
Esempio n. 33
0
 public RegistryController(IRegistryManager registryManager, IConfiguration configuration,ILoggingService loggingService )
 {
     _registryManager = registryManager;
     _config = configuration;
     _loggingService = loggingService;
 }