Пример #1
0
        public void ConvertObjectToEntitiesThenConvertBackTest()
        {
            var partition = new PartitionInfo <TestModel>("UR", obj => obj.Id);

            partition.Row("NM", obj => obj.Version, e => new { e.FirstName, e.LastName });
            partition.Row("DS", obj => obj.Version, e => e.Description);

            var model = new TestModel
            {
                Id          = Guid.NewGuid(),
                Version     = DateTime.UtcNow,
                FirstName   = "Yue",
                LastName    = "Liu",
                Description = "This is my model."
            };

            var entities = partition.ConvertObjectToEntities(model).ToArray();

            Assert.AreEqual(entities.Length, 2);

            var emptyModel = new TestModel();

            partition.FillObjectWithEntity(emptyModel, entities[0]);
            partition.FillObjectWithEntity(emptyModel, entities[1]);

            Assert.AreEqual(emptyModel.Id, model.Id);
            Assert.AreEqual(emptyModel.Version, model.Version);
            Assert.AreEqual(emptyModel.FirstName, model.FirstName);
            Assert.AreEqual(emptyModel.LastName, model.LastName);
            Assert.AreEqual(emptyModel.Description, model.Description);
        }
Пример #2
0
        public void AddPartitionInfo(PartitionInfo aPartitionInfo)
        {
            try
            {
                CopyPartitionInfo _copy = new CopyPartitionInfo()
                {
                    Index = this.CopyPartitionInfoList.Count, PartitionInfo = aPartitionInfo
                };
                this.CopyPartitionInfoList.Add(_copy);

                this.lv_Alg.ItemsSource = null;
                this.lv_Alg.ItemsSource = CopyPartitionInfoList;

                this.chb_selectAll.IsChecked = true;

                if (lv_Alg.SelectionMode != SelectionMode.Single)
                {
                    this.lv_Alg.SelectAll();
                }
            }
            catch (Exception _ex)
            {
                GeneralTools.Tools.WriteToLog(_ex);
            }
        }
Пример #3
0
 public static bool CanOpen(PartitionInfo volumeInfo)
 {
     using (var content = volumeInfo.Open())
     {
         return(SearchLabel(content, out _));
     }
 }
Пример #4
0
        private static WellKnownPartitionType GetPartitionType(PartitionInfo Partition)
        {
            switch (Partition.BiosType)
            {
            case BiosPartitionTypes.Fat16:
            case BiosPartitionTypes.Fat32:
            case BiosPartitionTypes.Fat32Lba:
                return(WellKnownPartitionType.WindowsFat);

            case BiosPartitionTypes.Ntfs:
                return(WellKnownPartitionType.WindowsNtfs);

            case BiosPartitionTypes.LinuxNative:
                return(WellKnownPartitionType.Linux);

            case BiosPartitionTypes.LinuxSwap:
                return(WellKnownPartitionType.LinuxSwap);

            case BiosPartitionTypes.LinuxLvm:
                return(WellKnownPartitionType.LinuxLvm);

            default:
                throw new ArgumentException(
                          String.Format("Unsupported partition type: '{0}'", BiosPartitionTypes.ToString(Partition.BiosType)), "Partition");
            }
        }
        private void btSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveFileDialog _dlg = new SaveFileDialog();
                _dlg.Filter      = "ARFF Documents (*.arff)|*.arff";
                _dlg.FilterIndex = 1;

                PartitionInfo _partinf   = partitionsInfo[currentIndex];
                string[]      names      = _partinf.AlgorithmName.Split(' ');
                string        final_name = "";
                foreach (string item in names)
                {
                    final_name += item;
                }

                _dlg.FileName = Enviroment.Set.RelationName + "_" + final_name;

                if (_dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string    dir   = _dlg.FileName;
                    ArffSaver saver = new ArffSaver(dir);
                    saver.Save(_partinf.Partition);
                }
            }
            catch (Exception _ex)
            {
                GeneralTools.Tools.WriteToLog(_ex);
            }
        }
        private async Task <TResult> CallAsync <TResult>(String serviceName, Int64?partitionKey, CancellationToken cancellationToken,
                                                         Func <IReadOnlyDictionary <String, String>, CancellationToken, Task <TResult> > func)
        {
            var serviceNameAndPartition = serviceName + ";" + partitionKey?.ToString();

            for (;;)
            {
                PartitionInfo servicePartitionInfo = m_clusterPartitionEndpointCache.Get(serviceNameAndPartition);
                try {
                    // We do not have endpoints, get them using https://msdn.microsoft.com/en-us/library/azure/dn707638.aspx
                    if (servicePartitionInfo == null)
                    {
                        servicePartitionInfo = await ResolvePartitionEndpointsAsync(serviceName, partitionKey, servicePartitionInfo?.PreviousRspVersion, cancellationToken);

                        m_clusterPartitionEndpointCache.Add(serviceNameAndPartition, servicePartitionInfo);
                    }
                    return(await func(servicePartitionInfo.Endpoints, cancellationToken));
                }
                catch (HttpRequestException ex) when((ex.InnerException as WebException)?.Status == WebExceptionStatus.ConnectFailure)
                {
                    // Force update of latest endpoints from naming service
                    servicePartitionInfo = await ResolvePartitionEndpointsAsync(serviceName, partitionKey, servicePartitionInfo?.PreviousRspVersion, cancellationToken);

                    m_clusterPartitionEndpointCache.Set(serviceNameAndPartition, servicePartitionInfo);
                }
            }
        }
Пример #7
0
        public bool ReadNextPartition()
        {
            if (_currentPartition >= _header.partitionCount)
            {
                _partitionInfo = null;
                return(false);
            }

            _reader.BaseStream.Position = _headerSize + _currentPartition * 8;

            _partitionInfo = new PartitionInfo
            {
                absOffset = _reader.ReadInt16() * 2,
                codeCount = _reader.ReadInt16(),
                flags1    = _reader.ReadInt16(),
                flags2    = _reader.ReadInt16()
            };

            _readCodes = 0;
            _reader.BaseStream.Position = _partitionInfo.absOffset;

            _currentPartition++;

            return(true);
        }
Пример #8
0
    void OnEnable()
    {
        CharacterVariant variant = target as CharacterVariant;

        for (int i = 0; i < variant.Partitions.Count; i++)
        {
            string assetPath = PartitionAssetManager.Instance.GetAssetPath(variant.Partitions[i].AssetName);
            if (string.IsNullOrEmpty(assetPath))
            {
                continue;
            }
            PartitionInfo partition = variant.Partitions[i];
            partition.AssetObject = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;
            variant.Partitions[i] = partition;
            PartitionAssetManager.Instance.RegisterAssetObject(partition.AssetName, partition.AssetObject);

            CharacterPartitionLink link = partition.AssetObject.GetComponent <CharacterPartitionLink>();
            if (link != null)
            {
                for (int j = 0; j < link.LinkedPartitions.Count; j++)
                {
                    string linkedAssetPath = PartitionAssetManager.Instance.GetAssetPath(link.LinkedPartitions[j].AssetName);
                    if (string.IsNullOrEmpty(linkedAssetPath))
                    {
                        continue;
                    }
                    PartitionInfo linkedPartition = link.LinkedPartitions[j];
                    linkedPartition.AssetObject = AssetDatabase.LoadAssetAtPath(linkedAssetPath, typeof(GameObject)) as GameObject;
                    link.LinkedPartitions[j]    = linkedPartition;
                    PartitionAssetManager.Instance.RegisterAssetObject(linkedPartition.AssetName, linkedPartition.AssetObject);
                }
            }
        }
    }
Пример #9
0
        /// <summary>
        /// Adds partition info to the list of partitions.
        /// </summary>
        /// <param name="partInfo">The partition info to add.</param>
        protected void AddPartitionToList(PartitionInfo partInfo)
        {
#if MBR_TRACE
            BasicConsole.WriteLine("MBR: 9");
#endif

            //If we need to expand the capacity of the partitions array
            //Note: This stuff was programmed before the List class was programmed.
            if (numPartitions >= PartitionsCapacity)
            {
#if MBR_TRACE
                BasicConsole.WriteLine("MBR: 10");
#endif

                PartitionInfo[] newArray = new PartitionInfo[NumPartitions + 4];
                for (int i = 0; i < numPartitions; i++)
                {
                    newArray[i] = Partitions[i];
                }
                Partitions = newArray;

#if MBR_TRACE
                BasicConsole.WriteLine("MBR: 11");
#endif
            }

            //Add the partition entry.
            Partitions[numPartitions++] = partInfo;

#if MBR_TRACE
            BasicConsole.WriteLine("MBR: 12");
#endif
        }
Пример #10
0
 public PartitionInfoDecorator(PartitionInfo partitionInfo)
 {
     this.partitionInfo = partitionInfo;
     if (this.partitionInfo == null)
     {
         throw new ArgumentNullException("partitionInfo cannot be null.");
     }
 }
Пример #11
0
 public PartitionListing(int num, DiskListing disk, PartitionInfo part)
 {
     this.Disk      = disk;
     this.PartNum   = num;
     this.Partition = part;
     this.Size      = part.TotalSize;
     this.ID        = part.SystemID;
 }
Пример #12
0
 public RaftInfo(PartitionInfo pInfo, bool isMaster)
 {
     term      = 0;
     votedTerm = 0;
     state     = isMaster ? RaftState.MASTER : RaftState.FOLLOWER;
     Logs      = new List <KeyValuePair <string, string> >();
     PInfo     = pInfo;
 }
Пример #13
0
 public void SetPartitionInfo(PartitionInfo info)
 {
     if (info == null)
     {
         return;
     }
     partitionInfo   = info;
     m_NameText.text = partitionInfo.Name;
     gameObject.name = partitionInfo.Name;
 }
Пример #14
0
        /// <summary>
        /// Determines if a physical volume contains LDM data.
        /// </summary>
        /// <param name="volumeInfo">The volume to inspect</param>
        /// <returns><c>true</c> if the physical volume contains LDM data, else <c>false</c>.</returns>
        public static bool HandlesPhysicalVolume(PhysicalVolumeInfo volumeInfo)
        {
            PartitionInfo pi = volumeInfo.Partition;

            if (pi != null)
            {
                return(IsLdmPartition(pi));
            }
            return(false);
        }
Пример #15
0
        private void GenerateWords(IDictionaryRequest request, PartitionInfo partitionInfo)
        {
            var partitionedWords = new ConcurrentQueue <IDictionary <int, IGeneratedWord> >();
            var useNoise         = dictionaryConfiguration.UseNoise;
            var startTime        = DateTime.Now;

            maxValue = dictionary.WordList.Count;

            FireGenerateChanged(new ProgressChangedEventArgs(10, String.Empty));

            // Multi-Threaded block
            var tasks = new Task[partitionInfo.NumberOfPartitions];
            var index = 0;

            for (; index < partitionInfo.NumberOfPartitions; index++)
            {
                tasks[index] = Task.Run(() =>
                {
                    var iterations = index == partitionInfo.NumberOfPartitions - 1 ?
                                     partitionInfo.LastPartitionSize :
                                     partitionInfo.FullPartitionSize;

                    var wordsPartition = useNoise ?
                                         GeneratePartitionedWordsWithNoise(iterations) :
                                         GeneratePartitionedWords(iterations);

                    partitionedWords.Enqueue(wordsPartition);
                });
            }

            try
            {
                Task.WaitAll(tasks);

                var words = new WordContainer(dictionaryConfiguration.UseNoise)
                {
                    PartitionedWords = partitionedWords
                };

                var endTime  = DateTime.Now;
                var duration = endTime - startTime;

                var result = new DictionaryResult(request, duration, words)
                {
                    Words = words
                };

                FireGenerateChanged(new ProgressChangedEventArgs(100, null));
                FireGenerateCompleted(new DictionaryEventArgs(null, false, null, result));
            }
            catch (AggregateException ae)
            {
                FireGenerateCompleted(new DictionaryEventArgs(ae.Flatten(), false, ae, null));
            }
        }
Пример #16
0
        public PartitionInfo ReadDatabaseParitionInfo()
        {
            if (LogCallback != null)
            {
                LogCallback.LogEvent("Reading Database Partition Info...");
            }
            WriteCommand(DexcomCommands.READ_DATABASE_PARTITION_INFO);
            PacketReader result = ReadPacket();

            return(PartitionInfo.Parse(result.Payload));
        }
Пример #17
0
        /// <summary>
        /// Returns the offset within the FAT of the next block
        /// </summary>
        /// <param name="baseBlock">The root block for the entry</param>
        public long BlockToFATOffset(uint baseBlock, PartitionInfo PartInfo)
        {
            if (baseBlock > PartInfo.Clusters)
            {
                // throw new Exception("Cluster ref of range");
            }
            long rVal = baseBlock * (int)PartInfo.EntrySize;

            rVal += PartInfo.FATOffset;
            return(rVal);
        }
Пример #18
0
 /// <summary>
 /// Initializes a new instance of the PhysicalVolumeInfo class.
 /// </summary>
 /// <param name="diskId">The containing disk's identity.</param>
 /// <param name="disk">The disk containing the partition.</param>
 /// <param name="partitionInfo">Information about the partition.</param>
 /// <remarks>Use this constructor to represent a (BIOS or GPT) partition.</remarks>
 internal PhysicalVolumeInfo(
     string diskId,
     VirtualDisk disk,
     PartitionInfo partitionInfo)
 {
     _diskId        = diskId;
     _disk          = disk;
     _streamOpener  = partitionInfo.Open;
     _type          = partitionInfo.VolumeType;
     _partitionInfo = partitionInfo;
 }
Пример #19
0
 /// <summary>
 /// Creates an instance representing a (BIOS or GPT) partition.
 /// </summary>
 /// <param name="diskId">The containing disk's identity</param>
 /// <param name="disk">The disk containing the partition</param>
 /// <param name="partitionInfo">Information about the partition</param>
 internal PhysicalVolumeInfo(
     string diskId,
     VirtualDisk disk,
     PartitionInfo partitionInfo
     )
 {
     _diskId        = diskId;
     _disk          = disk;
     _streamOpener  = partitionInfo.Open;
     _type          = (partitionInfo is GuidPartitionInfo) ? PhysicalVolumeType.GptPartition : PhysicalVolumeType.BiosPartition;
     _partitionInfo = partitionInfo;
 }
Пример #20
0
        /// <summary>
        /// Converts cluster (block) number to offset
        /// </summary>
        public long GetBlockOffset(uint block, PartitionInfo pinfo)
        {
            if (block > pinfo.Clusters)
            {
                // throw new Exception("Cluster ref of range");
            }
            //The way that FATX works is that the root block is considered block 0,
            //so let's think about this like an array...  if the block is reading block
            //2, then it's really block 1 in an array
            block--;
            long rVal = (pinfo.DataOffset + ((long)block * pinfo.ClusterSize));

            return(rVal);
        }
Пример #21
0
        private void sendPartitionToServer(string server_id)
        {
            Console.WriteLine("Sending the partition to the server...");
#pragma warning disable CS0436 // Type conflicts with imported type
            CompletePartition complete_partition = new CompletePartition();
#pragma warning restore CS0436 // Type conflicts with imported type
            foreach (Partition p in this.partList)
            {
                Console.WriteLine($"Found partition: {p.getName()}");
#pragma warning disable CS0436 // Type conflicts with imported type
                PartitionInfo part = new PartitionInfo();
#pragma warning restore CS0436 // Type conflicts with imported type
                part.Partitionid = p.getName();
                foreach ((string s, bool b) in p.getServIDs())
                {
                    foreach (Server serv in this.servList)
                    {
                        if (serv.getID() == s)
                        {
                            Console.WriteLine($"Valur of server id: {serv.getID()}");
                            //add server info to message
#pragma warning disable CS0436 // Type conflicts with imported type
                            part.Servers.Add(new ServerInfo
#pragma warning restore CS0436 // Type conflicts with imported type
                            {
                                Serverid = s,
                                Url      = serv.getURL(),
                                Mindelay = serv.getMin(),
                                Maxdelay = serv.getMax(),
                                Ismaster = b
                            });
                        }
                    }
                }
                complete_partition.Partitions.Add(part);
            }

            //send partition to every server
            foreach (Server serv in this.servList)
            {
                if (serv.getID() == server_id)
                {
                    AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
                    GrpcChannel channel = GrpcChannel.ForAddress(serv.getURL());
                    GStoreServices.GStoreServicesClient client = new GStoreServices.GStoreServicesClient(channel);
                    client.ReceivePartitionInfo(complete_partition);
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Creates a temporary vhd of the given size in GB.
        /// The created VHD is dynamically allocated and is of type VHD (legacy)
        /// </summary>
        /// <param name="sizeInGB">The size of the VHD in GB</param>
        /// <returns>The path to the created vhd</returns>
        internal static string CreateVirtualDisk(long sizeInGB = 10)
        {
            long   diskSize = sizeInGB * 1024 * 1024 * 1024;
            string tempVhd  = Path.GetTempFileName();

            using Stream vhdStream = File.Create(tempVhd);
            using Disk disk        = Disk.InitializeDynamic(vhdStream, DiscUtils.Streams.Ownership.Dispose, diskSize);

            BiosPartitionTable table         = BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
            PartitionInfo      ntfsPartition = table.Partitions[0];

            NtfsFileSystem.Format(ntfsPartition.Open(), "Windows UUP Medium", Geometry.FromCapacity(diskSize), ntfsPartition.FirstSector, ntfsPartition.SectorCount);

            return(tempVhd);
        }
Пример #23
0
        public IActionResult GetPartition(int partitionId)
        {
            PartitionInfo p = (new AlarmSystemInfo(myAlarmSystem)).Partitions.FirstOrDefault(x => x.Id == partitionId);

            if (p == null)
            {
                return(NotFound());
            }

            return(new ObjectResult(new MyResponse <PartitionInfo>()
            {
                FromHost = Request.Host.Value,
                Route = Request.Path.Value,
                Response = p
            }));
        }
Пример #24
0
    void OnEnable()
    {
        CharacterPartitionLink link = target as CharacterPartitionLink;

        for (int i = 0; i < link.LinkedPartitions.Count; i++)
        {
            string assetPath = PartitionAssetManager.Instance.GetAssetPath(link.LinkedPartitions[i].AssetName);
            if (string.IsNullOrEmpty(assetPath))
            {
                continue;
            }
            PartitionInfo partition = link.LinkedPartitions[i];
            partition.AssetObject    = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;
            link.LinkedPartitions[i] = partition;
        }
    }
Пример #25
0
        private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Opening new project");
            fileLoaded = true;
            string fname = Interaction.InputBox("Enter project name.", "Dreamcaster", "project.bin");

            disk = new Disk(fname);
            PartitionTable partitions = disk.Partitions;
            PartitionInfo  fs_pi      = partitions[0];

            fs = new FatFileSystem(fs_pi.Open());
            PartitionInfo mfs_pi = partitions[1];

            mfs = new FatFileSystem(mfs_pi.Open());
            UpdateListbox();
            Text = "Dreamcaster -- " + fname;
            Console.WriteLine("Done");
        }
Пример #26
0
        private async Task GenerateAsyncInternal(IDictionaryRequest request, CancellationToken cancellationToken)
        {
            progressPercentage = 0;
            try
            {
                await LazyInitialization();

                var partitionInfo = PartitionInfo.Get(request.Iterations, threadService.GetThreadCountByIterations(request.Iterations));

                FireGenerateChanged(new ProgressChangedEventArgs(progressPercentage += 5, $"Created {partitionInfo.NumberOfPartitions} partitions."));

                GenerateWords(request, partitionInfo);
            }
            catch (Exception e)
            {
                FireGenerateCompleted(new DictionaryEventArgs(e, false, this, null));
            }
        }
Пример #27
0
        public static void Generate()
        {
            string rootPath = Path.Combine(Bootstrap.Root, @"Root");
            string vhdxPath = Path.Combine(Bootstrap.Root, @"Hyper-V\Virtual Hard Disks\Disk.vhdx");

            using (VirtualDisk virtualDisk = VirtualDisk.OpenDisk(vhdxPath, FileAccess.ReadWrite))
            {
                // Get system partition
                PartitionInfo partition = virtualDisk.Partitions.Partitions.FirstOrDefault();

                // Open FAT partition
                using (SparseStream partitionStream = partition.Open())
                    using (FatFileSystem fatFileSystem = new FatFileSystem(partitionStream))
                    {
                        // Clean partition
                        string[] fileSystemEntries = fatFileSystem.GetFileSystemEntries("");
                    }
            }
        }
Пример #28
0
        /// <summary>
        /// 仅用于不存在App对应的BlobMetaRaftGroup时创建之
        /// </summary>
        private static async ValueTask TryCreateMetaRaftGroupAsync(byte appStoreID)
        {
            var txn = await Transaction.BeginAsync(); //TODO: 移除事务依赖

            byte   appId    = appStoreID;
            var    partInfo = new PartitionInfo();
            IntPtr pkPtr;

            unsafe
            {
                partInfo.Flags   = IdUtil.RAFT_TYPE_BLOB_META << IdUtil.RAFTGROUPID_FLAGS_TYPE_OFFSET;
                partInfo.KeyPtr  = new IntPtr(&appId);
                partInfo.KeySize = new IntPtr(1);
                pkPtr            = new IntPtr(&partInfo);
            }

            await StoreApi.Api.MetaGenPartitionAsync(txn.Handle, pkPtr);

            await txn.CommitAsync();
        }
Пример #29
0
    void DrawPartition(int index, ref bool delete)
    {
        CharacterPartitionLink link = target as CharacterPartitionLink;
        string prefsKey             = string.Format("CharacterPartitionLink_Partition_{0}", index);
        bool   view = EditorPrefs.GetBool(prefsKey, true);

        PartitionInfo partition = link.LinkedPartitions[index];

        GUILayout.BeginHorizontal();
        {
            GUILayout.Space(12);
            view = EditorGUILayout.Foldout(view, partition.Name);

            if (GUILayout.Button("X", GUILayout.Width(20)))
            {
                delete = true;
            }
        }
        GUILayout.EndHorizontal();
        EditorPrefs.SetBool(prefsKey, view);

        if (view)
        {
            partition.Name = EditorGUILayout.TextField("Name", partition.Name);
            GUILayout.BeginHorizontal();
            {
                GUI.enabled         = false;
                partition.AssetName = EditorGUILayout.TextField("Asset Name", partition.AssetName);
                GUI.enabled         = true;

                partition.AssetObject = EditorGUILayout.ObjectField(partition.AssetObject, typeof(GameObject), false, GUILayout.Width(160)) as GameObject;
                if (partition.AssetObject != null)
                {
                    partition.AssetName = partition.AssetObject.name;
                }
            }
            GUILayout.EndHorizontal();
            link.LinkedPartitions[index] = partition;
        }
    }
Пример #30
0
        /// <summary>
        /// status information to the smart things zone
        /// </summary>
        /// <param name="zoneInfo"></param>
        public static void UpdatePartition(PartitionInfo partitionInfo)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null || authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError($"OAuth endpoints have not been created.  Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/UpdatePartition";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();
                parms.Add(new KeyValuePair <string, string>("Id", partitionInfo.Id.ToString()));
                parms.Add(new KeyValuePair <string, string>("Name", partitionInfo.Name));
                parms.Add(new KeyValuePair <string, string>("ReadyToArm", partitionInfo.ReadyToArm.ToString()));
                parms.Add(new KeyValuePair <string, string>("IsArmed", partitionInfo.IsArmed.ToString()));
                parms.Add(new KeyValuePair <string, string>("ArmingMode", partitionInfo.ArmingMode));
                parms.Add(new KeyValuePair <string, string>("AlarmOn", partitionInfo.AlarmOn.ToString()));
                parms.Add(new KeyValuePair <string, string>("SHMIntegrationEnabled", partitionInfo.SHMIntegrationEnabled.ToString()));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Пример #31
0
        /// <summary>
        /// status information to the smart things zone
        /// </summary>
        /// <param name="zoneInfo"></param>
        public static void UpdatePartition(PartitionInfo partitionInfo)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null || authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError($"OAuth endpoints have not been created.  Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/UpdatePartition";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
                parms.Add(new KeyValuePair<string, string>("Id", partitionInfo.Id.ToString()));
                parms.Add(new KeyValuePair<string, string>("Name", partitionInfo.Name));
                parms.Add(new KeyValuePair<string, string>("ReadyToArm", partitionInfo.ReadyToArm.ToString()));
                parms.Add(new KeyValuePair<string, string>("IsArmed", partitionInfo.IsArmed.ToString()));
                parms.Add(new KeyValuePair<string, string>("ArmingMode", partitionInfo.ArmingMode));
                parms.Add(new KeyValuePair<string, string>("AlarmOn", partitionInfo.AlarmOn.ToString()));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Пример #32
0
        /// <summary>
        /// Initialises a new GPT and attempts to read its information from the specified disk.
        /// </summary>
        /// <param name="disk">The disk to read the GPT from.</param>
        public GPT(Hardware.Devices.DiskDevice disk)
        {
#if GPT_TRACE
            BasicConsole.WriteLine("Checking for GPT...");
            BasicConsole.DelayOutput(1);
#endif
            //Assumed block size of 512.
            uint blockSize = 512;

            //Note: The GPT format specifies a protective MBR entry (1 partition 
            //          covering the entire disk) immediately followed (byte-wise)
            //          by the GPT. Thus the GPT must come at 512th byte.
            //      However, some disks can have 4096 bytes per sector (/block) 
            //          so the code below might break as reading LBA 1 (2nd LBA) would
            //          return the wrong data. We probably ought to find some way to 
            //          check the block size and just load the required amount of data.

            //Check for single MBR partition with 0xEE system ID
            byte[] blockData = new byte[blockSize];
            //Read the first sector of data.
            disk.ReadBlock(0UL, 1U, blockData);

            //Attempt to read the MBR
            MBR TheMBR = new MBR(blockData);
            //If the MBR isn't valid, the protective MBR partition specified as part of GPT
            //  isn't present / valid so this isn't a valid GPT.
            if (!TheMBR.IsValid)
            {
#if GPT_TRACE
                BasicConsole.WriteLine("MBR invalid.");
                BasicConsole.DelayOutput(1);
#endif

                return;
            }
            //Or, if there is not one and only one partition in the MBR then the 
            //  protective MBR isn't valid so this isn't a valid GPT
            else if (TheMBR.NumPartitions != 1)
            {
#if GPT_TRACE
                BasicConsole.WriteLine("No partitions in MBR.");
                BasicConsole.DelayOutput(1);
#endif
                return;
            }
            //Or, the first (/only) partition entry has the wrong ID. 0xEE is the partition
            //  ID for a GOT formatted MBR partition.
            else if (TheMBR.Partitions[0].SystemID != 0xEE)
            {
#if GPT_TRACE
                BasicConsole.WriteLine(((FOS_System.String)"MBR partition 0 system ID not GPT. ") + TheMBR.Partitions[0].SystemID);
                BasicConsole.DelayOutput(1);
#endif

                return;
            }

#if GPT_TRACE
            BasicConsole.WriteLine("GPT MBR partition detected.");
            BasicConsole.DelayOutput(1);
#endif

            //Now we know this is very-likely to be GPT formatted. 
            //  But we must check the GPT header for signature etc.

            //Read the GPT block
            disk.ReadBlock(1UL, 1U, blockData);

            //Check for GPT signature: 0x45 0x46 0x49 0x20 0x50 0x41 0x52 0x54
            bool OK = blockData[0] == 0x45;
            OK = OK && blockData[1] == 0x46;
            OK = OK && blockData[2] == 0x49;
            OK = OK && blockData[3] == 0x20;
            OK = OK && blockData[4] == 0x50;
            OK = OK && blockData[5] == 0x41;
            OK = OK && blockData[6] == 0x52;
            OK = OK && blockData[7] == 0x54;

            //If any part of the ID was wrong, this is not a valid GPT.
            if (!OK)
            {
#if GPT_TRACE
                BasicConsole.WriteLine("GPT signature invalid.");
                BasicConsole.DelayOutput(1);
#endif
                return;
            }

            //Now we know, this is a valid GPT. Whether or not the actual entries are valid
            //  is yet to be determined. There is of course the small chance that some other
            //  data has conflicted with GPT data and that this isn't a GPT, it just looks 
            //  like it. If that is the case, what idiot formatted the disk we are reading
            //  because a conflict like that is impossible to detect without user input!
            IsValid = true;
            
#if GPT_TRACE
            BasicConsole.WriteLine("Valid GPT detected.");
            BasicConsole.DelayOutput(5);
#endif

            //Load-in GPT global data
            Revision = ByteConverter.ToUInt32(blockData, 8);
            HeaderSize = ByteConverter.ToUInt32(blockData, 12);
            HeaderCRC32 = ByteConverter.ToUInt32(blockData, 16);
            HeaderLBA = ByteConverter.ToUInt64(blockData, 24);
            HeaderBackupLBA = ByteConverter.ToUInt64(blockData, 32);
            FirstUsableLBAForPartitions = ByteConverter.ToUInt64(blockData, 40);
            LastUsableLBAForPartitions = ByteConverter.ToUInt64(blockData, 48);

#if GPT_TRACE
            BasicConsole.WriteLine(((FOS_System.String)"Revision : ") + Revision);
            BasicConsole.WriteLine(((FOS_System.String)"Header size : ") + HeaderSize);
            BasicConsole.WriteLine(((FOS_System.String)"Header CRC32 : ") + HeaderCRC32);
            BasicConsole.WriteLine(((FOS_System.String)"Header LBA : ") + HeaderLBA);
            BasicConsole.WriteLine(((FOS_System.String)"Header Backup LBA : ") + HeaderBackupLBA);
            BasicConsole.WriteLine(((FOS_System.String)"First usable LBA for partitions : ") + FirstUsableLBAForPartitions);
            BasicConsole.WriteLine(((FOS_System.String)"Last usable LBA for partitions : ") + LastUsableLBAForPartitions);
            BasicConsole.DelayOutput(5);
#endif

            //Load the disk ID
            DiskGUID = new byte[16];
            DiskGUID[0] = blockData[56];
            DiskGUID[1] = blockData[57];
            DiskGUID[2] = blockData[58];
            DiskGUID[3] = blockData[59];
            DiskGUID[4] = blockData[60];
            DiskGUID[5] = blockData[61];
            DiskGUID[6] = blockData[62];
            DiskGUID[7] = blockData[63];
            DiskGUID[8] = blockData[64];
            DiskGUID[9] = blockData[65];
            DiskGUID[10] = blockData[66];
            DiskGUID[11] = blockData[67];
            DiskGUID[12] = blockData[68];
            DiskGUID[13] = blockData[69];
            DiskGUID[14] = blockData[70];
            DiskGUID[15] = blockData[71];

            //Load more global GPT data
            StartingLBAOfPartitionArray = ByteConverter.ToUInt64(blockData, 72);
            NumPartitionEntries = ByteConverter.ToUInt32(blockData, 80);
            SizeOfPartitionEntry = ByteConverter.ToUInt32(blockData, 84);
            PartitionArrayCRC32 = ByteConverter.ToUInt32(blockData, 88);

#if GPT_TRACE
            BasicConsole.WriteLine(((FOS_System.String)"Start LBA of part arrray : ") + StartingLBAOfPartitionArray);
            BasicConsole.WriteLine(((FOS_System.String)"Num part entries : ") + NumPartitionEntries);
            BasicConsole.WriteLine(((FOS_System.String)"Size of part entry : ") + SizeOfPartitionEntry);
            BasicConsole.WriteLine(((FOS_System.String)"Part array CRC32 : ") + PartitionArrayCRC32);
            BasicConsole.DelayOutput(5);
#endif

            ulong blockNum = StartingLBAOfPartitionArray;
            uint entriesPerBlock = blockSize / SizeOfPartitionEntry;

#if GPT_TRACE
            BasicConsole.WriteLine("Reading partition entries...");
            BasicConsole.WriteLine(((FOS_System.String)"blockNum=") + blockNum);
            BasicConsole.WriteLine(((FOS_System.String)"entriesPerBlock=") + entriesPerBlock);
            BasicConsole.DelayOutput(1);
#endif

            //TODO: Check the CRC32 values of the header and partition table
            //      are correct. 
            //Note: By not checking the CRCs, we have the option to manually edit
            //      the GPT without rejecting it if CRCs end up incorrect.
            //TODO: Add an override option to ignore the CRCs
            //TODO: Add a method to update / correct the CRCs

            //Read partition infos
            for(uint i = 0; i < NumPartitionEntries; i++)
            {
                //If we're on a block boundary, we need to load the next block
                //  of data to parse.
                if (i % entriesPerBlock == 0)
                {
#if GPT_TRACE
                    BasicConsole.WriteLine("Reading block data...");
                    BasicConsole.WriteLine(((FOS_System.String)"blockNum=") + blockNum);
                    BasicConsole.DelayOutput(1);
#endif
                    //Load the next block of data
                    disk.ReadBlock(blockNum++, 1u, blockData);
                }

                //Calculate the offset into the current data block
                uint offset = (i % entriesPerBlock) * SizeOfPartitionEntry;
#if GPT_TRACE
                BasicConsole.WriteLine("Reading entry...");
                BasicConsole.WriteLine(((FOS_System.String)"offset=") + offset);
#endif
                //Attempt to load the partition info
                PartitionInfo inf = new PartitionInfo(blockData, offset, SizeOfPartitionEntry);
                //Partitions are marked as empty by an all-zero type ID. If the partition is empty,
                //  there is no point adding it.
                if (!inf.Empty)
                {
#if GPT_TRACE
                    BasicConsole.WriteLine("Entry not empty.");
#endif
                    //Add the non-empty partition
                    Partitions.Add(inf);
                }
#if GPT_TRACE
                else
                {
                    BasicConsole.WriteLine("Entry empty.");
                }
#endif   
            }
        }
Пример #33
0
        /// <summary>
        /// Adds partition info to the list of partitions.
        /// </summary>
        /// <param name="partInfo">The partition info to add.</param>
        protected void AddPartitionToList(PartitionInfo partInfo)
        {
#if MBR_TRACE
            BasicConsole.WriteLine("MBR: 9");
#endif

            //If we need to expand the capacity of the partitions array
            //Note: This stuff was programmed before the List class was programmed.
            if (numPartitions >= PartitionsCapacity)
            {
#if MBR_TRACE
                BasicConsole.WriteLine("MBR: 10");
#endif

                PartitionInfo[] newArray = new PartitionInfo[NumPartitions + 4];
                for (int i = 0; i < numPartitions; i++)
                {
                    newArray[i] = Partitions[i];
                }
                Partitions = newArray;

#if MBR_TRACE
                BasicConsole.WriteLine("MBR: 11");
#endif
            }

            //Add the partition entry.
            Partitions[numPartitions++] = partInfo;

#if MBR_TRACE
            BasicConsole.WriteLine("MBR: 12");
#endif
        }