/// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        internal static ApplicationCredentials GetApplicationCredentials(XmlDocument xml, bool sandbox)
        {

            string appId;
            string appKey;

            if (sandbox)
            {
                appId = GetDataConfiguration(xml, PagSeguroConfigSerializer.SandboxAppId);
                appKey = GetDataConfiguration(xml, PagSeguroConfigSerializer.SandboxAppKey);
            }
            else
            {
                appId = GetDataConfiguration(xml, PagSeguroConfigSerializer.AppId);
                appKey = GetDataConfiguration(xml, PagSeguroConfigSerializer.AppKey);
            }

            try
            {
                ApplicationCredentials credential = new ApplicationCredentials(appId, appKey);
                return credential;
            }
            catch (System.Exception)
            {
                throw new ArgumentException("To use credentials from config.properties file you must "
                + "configure the properties credential appId and credential appKey.");
            }
            
        }
Ejemplo n.º 2
0
        public static String DisplayStockHint(string sProductID, string sVariantID, string page, string className, string renderAsElement)
        {
            Customer ThisCustomer = AppLogic.GetCurrentCustomer();

            StringBuilder results = new StringBuilder();

            InputValidator IV        = new InputValidator("DisplayProductStockHint");
            int            productID = IV.ValidateInt("ProductID", sProductID);
            int            variantID = IV.ValidateInt("VariantID", sVariantID);

            bool trackInventoryBySizeAndColor = AppLogic.ProductTracksInventoryBySizeAndColor(productID);

            bool probablyOutOfStock = AppLogic.ProbablyOutOfStock(productID, variantID, trackInventoryBySizeAndColor, page);

            bool displayOutOfStockOnProductPages = AppLogic.AppConfigBool("DisplayOutOfStockOnProductPages");
            bool displayOutOfStockOnEntityPage   = AppLogic.AppConfigBool("DisplayOutOfStockOnEntityPages");

            if (renderAsElement == string.Empty)
            {
                if (probablyOutOfStock)
                {
                    // the css is always 3 set and you can customized
                    // and create new one just pass as parameter
                    //(Default - StockHint for instock - out-stock-hint and outstock - in-stock-hint)
                    results.AppendLine();

                    // display Out of Stock
                    if (page.Equals("Product", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnProductPages)
                    {
                        results.Append("Out of stock");
                    }
                    else if (page.Equals("Entity", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnEntityPage)
                    {
                        results.Append("Out of stock");
                    }
                }
                else
                {
                    results.AppendLine();
                    // display "In Stock"
                    if (page.Equals("Product", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnProductPages)
                    {
                        results.Append("In stock");
                    }
                    else if (page.Equals("Entity", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnEntityPage)
                    {
                        results.Append("In stock");
                    }
                }
            }
            else
            {
                if (probablyOutOfStock)
                {
                    // the css is always 3 set and you can customized
                    // and create new one just pass as parameter
                    //(Default - StockHint for instock - out-stock-hint and outstock - in-stock-hint)

                    className = string.Format("{0} {1}", className, "out-stock-hint");
                    results.AppendLine();

                    // display Out of Stock
                    if (page.Equals("Product", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnProductPages)
                    {
                        results.AppendFormat("<{0} class=\"{1}\" >\n", renderAsElement, className);
                        results.Append("Out of stock");
                        results.AppendFormat("</{0}>\n", renderAsElement);
                    }
                    else if (page.Equals("Entity", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnEntityPage)
                    {
                        results.AppendFormat("<{0} class=\"{1}\" >\n", renderAsElement, className);
                        results.Append("Out of stock");
                        results.AppendFormat("</{0}>\n", renderAsElement);
                    }
                }
                else
                {
                    className = string.Format("{0} {1}", className, "in-stock-hint");
                    results.AppendLine();
                    // display "In Stock"
                    if (page.Equals("Product", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnProductPages)
                    {
                        results.AppendFormat("<{0} class=\"{1}\" >\n", renderAsElement, className);
                        results.Append("In stock");
                        results.AppendFormat("</{0}>\n", renderAsElement);
                    }
                    else if (page.Equals("Entity", StringComparison.InvariantCultureIgnoreCase) && displayOutOfStockOnEntityPage)
                    {
                        results.AppendFormat("<{0} class=\"{1}\" >\n", renderAsElement, className);
                        results.Append("In stock");
                        results.AppendFormat("</{0}>\n", renderAsElement);
                    }
                }
            }
            results.AppendLine();

            return(results.ToString().Trim());
        }
Ejemplo n.º 3
0
 private void DisablePenControl()
 {
     btnPen.Enabled = false;
     isPen = false;
 }
        /**
         * \fn connectDeviceAsync
         */
        public async Task <uint> ConnectDeviceAsync(String macAddress)
        {
            uint uiErrorCode = ErrorServiceHandlerBase.ERR_ELA_BLE_COMMUNICATION_NOT_CONNECTED;

            try
            {
                ulong ulMacAddress = MacAddress.macAdressHexaToLong(macAddress);
                // try to get data
                m_ConnectedDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(ulMacAddress);

                if (null != m_ConnectedDevice)
                {
                    m_Gatt = await m_ConnectedDevice.GetGattServicesAsync(BluetoothCacheMode.Cached);

                    if (null != m_Gatt)
                    {
                        foreach (GattDeviceService service in m_Gatt.Services)
                        {
                            if (service.Uuid.ToString().Equals(NORDIC_UART_SERVICE))
                            {
                                bool bFoundRx = false;
                                bool bFoundTx = false;
                                m_Characteristics = await service.GetCharacteristicsAsync();

                                foreach (var charac in m_Characteristics.Characteristics)
                                {
                                    if (charac.Uuid.ToString().Equals(NORDIC_UART_TX_CHAR))
                                    {
                                        m_TxNordicCharacteristic = charac;
                                        bFoundTx = true;
                                    }
                                    if (charac.Uuid.ToString().Equals(NORDIC_UART_RX_CHAR))
                                    {
                                        m_RxNordicCharacteristic = charac;
                                        var result = await m_RxNordicCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                                        if (result == GattCommunicationStatus.Success)
                                        {
                                            m_RxNordicCharacteristic.ValueChanged += AssociatedCharacteristic_ValueChanged;
                                        }
                                        bFoundRx = true;
                                    }
                                    //
                                    if (true == bFoundRx && true == bFoundTx)
                                    {
                                        m_IsConnected = true;
                                        uiErrorCode   = ErrorServiceHandlerBase.ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                m_IsConnected = false;
                //return ErrorServiceHandlerBase.ERR_CONNECT_ERROR;
                throw new ElaBleException($"Exception while trying to connect to device {macAddress}.", ex);
            }
            //
            return(uiErrorCode);
        }
 public static extern NtStatus NtQueryDirectoryObject(SafeKernelObjectHandle DirectoryHandle,
     SafeBuffer Buffer, int Length, bool ReturnSingleEntry, bool RestartScan, ref int Context, out int ReturnLength);
        public override void CompPostTick(ref float severityAdjustment)
        {
            base.CompPostTick(ref severityAdjustment);
            bool flag = base.Pawn != null;

            if (flag)
            {
                if (!initialized)
                {
                    initialized = true;
                    this.Initialize();
                }
            }

            if (Find.TickManager.TicksGame % 60 == 0)
            {
                if (this.Pawn.RaceProps != null && this.Pawn.RaceProps.lifeExpectancy != 0)
                {
                    maxAge = this.Pawn.RaceProps.lifeExpectancy;
                }
                int roundedYearAging = Mathf.RoundToInt(this.Pawn.ageTracker.AgeBiologicalYears / 100);
                if (isBad)
                {
                    if (this.Pawn.ageTracker.AgeBiologicalYears >= 100)
                    {
                        this.Pawn.ageTracker.AgeBiologicalTicks += roundedYearAging * 3600000;
                    }
                    else
                    {
                        this.Pawn.ageTracker.AgeBiologicalTicks = Mathf.RoundToInt(this.Pawn.ageTracker.AgeBiologicalTicks * (1.02f + (.002f * this.parent.Severity)));
                    }
                }
                else
                {
                    if (this.Pawn.ageTracker.AgeBiologicalYears >= 200)
                    {
                        this.Pawn.ageTracker.AgeBiologicalTicks += roundedYearAging * 3600000;
                    }
                    else
                    {
                        this.Pawn.ageTracker.AgeBiologicalTicks = Mathf.RoundToInt(this.Pawn.ageTracker.AgeBiologicalTicks * 1.00001f) + 2500;
                    }
                }
                if (this.Pawn.ageTracker.AgeBiologicalYears > this.currentAge)
                {
                    this.currentAge = this.Pawn.ageTracker.AgeBiologicalYears;
                    if (Rand.Chance(this.currentAge / this.maxAge))
                    {
                        BirthdayBiological(this.Pawn, this.currentAge);
                    }
                    if (this.isBad)
                    {
                        RaceAgainstTime(this.Pawn, this.currentAge);
                    }
                }

                AccelerateHediff(this.Pawn, 60);
                this.durationTicks -= 60;

                if (Find.TickManager.TicksGame % this.tickEffect == 0)
                {
                    AccelerateEffects(this.Pawn, 1);
                }
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="PropertyEntryMetadata" /> class.
 /// </summary>
 /// <param name="declaringType"> The type that the property is declared on. </param>
 /// <param name="propertyType"> Type of the property. </param>
 /// <param name="propertyName"> The property name. </param>
 /// <param name="isMapped">
 ///     if set to <c>true</c> the property is mapped in the EDM.
 /// </param>
 /// <param name="isComplex">
 ///     if set to <c>true</c> the property is a complex property.
 /// </param>
 public PropertyEntryMetadata(
     Type declaringType, Type propertyType, string propertyName, bool isMapped, bool isComplex)
     : base(declaringType, propertyType, propertyName)
 {
     _isMapped  = isMapped;
     _isComplex = isComplex;
 }
Ejemplo n.º 8
0
        public byte this[int address]
        {
            get
            {
                address &= 0xFFFF;                         // Mostly just a sanity check

                if (address >= 0xFF80 && address < 0xFFFF) // HRAM
                {
                    return(HRAM[address & 0x7F]);
                }

                // During DMA, only HRAM is accessable
                else if (DMAInProcess)
                {
                    return(0);
                }

                if (address >= 0xF000)
                {
                    if (address >= 0xFF00) // IO Registers
                    {
                        switch (address & 0xF0)
                        {
                        default: return(0);

                        case 0:
                            switch (address & 0x0F)
                            {
                            case 0: return(Joypad.P1Register);

                            case 1: return(SerialTxReg);

                            case 2: return(SerialControlReg);

                            //   3: unused
                            case 4: return(Timer.DivisionRegister);

                            case 5: return(Timer.CountRegister);

                            case 6: return(Timer.ModuloRegister);

                            case 7: return(Timer.ControlRegister);

                            //   8 - 14 unused
                            case 15: return((byte)IFlagsReg);
                            }
                            return(0);

                        case 0x10:     // Sound Registers
                        case 0x20:
                        case 0x30:
                            return(0); //su.ReadByte(address);

                        case 0x40:     // LCD registers
                            switch (address & 0x0F)
                            {
                            case 0: return(GraphicsUnit.LCDCReg);

                            case 1: return(GraphicsUnit.STATReg);

                            case 2: return(GraphicsUnit.SCY);

                            case 3: return(GraphicsUnit.SCX);

                            case 4: return(GraphicsUnit.LCDYCoord);

                            case 5: return(GraphicsUnit.LYC);

                            case 6: return(DMAStart);

                            case 7: return(GraphicsUnit.BGPallet);

                            case 8: return(GraphicsUnit.ObjPallets[0]);

                            case 9: return(GraphicsUnit.ObjPallets[1]);

                            case 10: return(GraphicsUnit.WY);

                            case 11: return(GraphicsUnit.WX);
                            }
                            return(0);

                        case 0xF0: return((byte)IEnableReg);
                        }
                    }

                    // Addresses 0xFE00 - 0xFE9A is reserved for the graphics OAM.
                    // The rest is intentionally empty and should not be used.
                    else if (address >= 0xFEA0)
                    {
                        return(0);
                    }
                    else if (address >= 0xFE00)
                    {
                        return(GraphicsUnit.ReadOAM(address));
                    }

                    // F000-FDFF echos D000-DDFF
                    return(InternalRAM[(address & 0x1FFF)]);
                }

                else if (address >= 0xC000) // C000 - EFFF: Internal RAM and Internal RAM Echo
                {
                    // C000 ~ DFFF is the actual internal RAM
                    // E000 ~ FDFF is an echo of the RAM, so we just read from the same place
                    return(InternalRAM[(address & 0x1FFF)]);
                }

                else if (address >= 0xA000) // A000 - BFFF: Switchable RAM bank, i.e. External/Cartridge RAM
                {
                    return(Cartridge.ReadRAM(address));
                }

                else if (address >= 0x8000) //  Graphics VRAM
                {
                    return(GraphicsUnit.ReadVRAM(address));
                }

                // Cartidge ROM
                else if ((address < 0x100) && BIOSLoaded)
                {
                    return(BIOS[address]);
                }

                return(Cartridge.ReadROM(address));
            }

            set
            {
                address &= 0xFFFF;                         // Sanity check again

                if (address >= 0xFF80 && address < 0xFFFF) // HRAM
                {
                    HRAM[address & 0x7F] = value;
                }

                // During DMA, only HRAM is accessable
                else if (DMAInProcess)
                {
                    return;
                }

                if (address >= 0xF000)
                {
                    if (address >= 0xFF00) // IO Registers
                    {
                        switch (address & 0xF0)
                        {
                        case 0:
                            switch (address & 0x0F)
                            {
                            case 0: Joypad.P1Register = value; break;

                            case 1: SerialTxReg = value; break;

                            case 2: SerialControlReg = value; break;

                            //   3: unused
                            case 4: Timer.DivisionRegister = value; break;

                            case 5: Timer.CountRegister = value; break;

                            case 6: Timer.ModuloRegister = value; break;

                            case 7: Timer.ControlRegister = value; break;

                            //   8 - 14 unused
                            case 15: IFlagsReg = (InterruptFlags)value; break;
                            }
                            return;

                        case 0x10:     // Sound Registers
                        case 0x20:
                        case 0x30:
                            return;    //su.WriteByte(address, value);

                        case 0x40:     // LCD registers
                            switch (address & 0x0F)
                            {
                            case 0: GraphicsUnit.LCDCReg = value; break;

                            case 1: GraphicsUnit.STATReg = value; break;

                            case 2: GraphicsUnit.SCY = value; break;

                            case 3: GraphicsUnit.SCX = value; break;

                            //   4: LY (read-only)
                            case 5: GraphicsUnit.LYC = value; break;

                            case 6:
                                DMAStart = value;
                                StartDMATransfer();
                                break;

                            case 7: GraphicsUnit.BGPallet = value; break;

                            case 8: GraphicsUnit.ObjPallets[0] = value; break;

                            case 9: GraphicsUnit.ObjPallets[1] = value; break;

                            case 10: GraphicsUnit.WY = value; break;

                            case 11: GraphicsUnit.WX = value; break;
                            }
                            return;

                        case 0x50:
                            if (BIOSLoaded)
                            {
                                BIOSLoaded = value == 0;
                            }
                            break;

                        case 0xF0:
                            if (address == 0xFFFF)
                            {
                                IEnableReg = (InterruptFlags)value;
                            }
                            break;
                        }
                    }

                    // Addresses 0xFE00 - 0xFE9A is reserved for the graphics OAM.
                    // The rest is intentionally empty and should not be used.
                    else if (address >= 0xFE00 && address < 0xFEA0)
                    {
                        GraphicsUnit.WriteOAM(address, value);
                    }

                    // F000-FDFF echos D000-DDFF and is read-only
                }

                else if (address >= 0xC000 && address < 0xE000) // C000-DFFF - Internal RAM
                {
                    switch (address)
                    {
                    case 0xc004:
                        break;
                    }

                    InternalRAM[address & 0x1FFF] = value;
                }

                else if (address >= 0xA000 && address < 0xC000) // A000-BFFF : External/Cartridge RAM
                {
                    Cartridge.WriteRAM(address, value);
                }

                else if (address >= 0x8000 && address < 0xA000) // Graphics VRAM
                {
                    GraphicsUnit.WriteVRAM(address, value);
                }

                else if (address < 0x8000)
                {
                    Cartridge.WriteToRegister(address, value);
                }
            }
        }
Ejemplo n.º 9
0
 public EventBean GetPublicEventBean(EventBean @event, EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext context)
 {
     return(_eventToPublic.Convert(@event, eventsPerStream, isNewData, context));
 }
		public static MvcHtmlString DynamicDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object viewData = null, bool readOnly = false, bool disabled = false, bool visible = true)
		{
			DynamicComponentBaseFor<TModel, TProperty> dynamicComponentBase = new DynamicComponentBaseFor<TModel, TProperty>(helper, expression, viewData, readOnly, disabled, visible);

			TagBuilder_Select<TModel, TProperty> tagBuilder = new TagBuilder_Select<TModel, TProperty>(dynamicComponentBase);
			tagBuilder.AddOptionLabel(optionLabel);
			tagBuilder.AddOptions(selectList);

			return tagBuilder.GenerateElementMvcString(TagRenderMode.Normal);
		}
Ejemplo n.º 11
0
 private void StartDMATransfer()
 {
     DMAClock         = 0;
     DMACurrentOffset = 0;
     DMAInProcess     = true;
 }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// This method will do the heavy work of actually of performing our enumeration through
        /// the target REST API.  Since it is possible that we might retrieve only a subset of
        /// the sought records for each call, we might need to make repeated calls to the API.
        /// If the current batch has not been exhausted, then the MoveNext() method will return the
        /// next record from that batch.  However, if we're at the start of the enumeration or if
        /// the current batch has been exhausted, this method will then make a subsequent call
        /// to the API in order to retrieve the next batch.
        ///
        /// <returns>The indicator of whether another batch was pulled through the REST API</returns>
        /// </summary>
        private bool PullNextSet()
        {
            bool   bMoreData   = false;
            string sRequestURL = "";

            CurrIndex = -1;

            if (!String.IsNullOrEmpty(EnumAPIConfiguration.CurrentAnchor))
            {
                sRequestURL = EnumAPIConfiguration.CurrentAnchor;
            }
            else
            {
                sRequestURL = AceXmlReader.FormatRequestURL(EnumAPIConfiguration);
            }

            System.Console.WriteLine("DEBUG: The next request via the Change API is URL (" + sRequestURL + ")..." + DateTime.Now.ToString());
            System.Console.Out.Flush();

            CurrXmlResponse = AceXmlReader.PullXmlDoc(EnumAPIConfiguration, sRequestURL);

            if (!String.IsNullOrEmpty(EnumAPIConfiguration.AnchorIndicator))
            {
                string sAnchorIndicator = CurrXmlResponse.Root.Element(EnumAPIConfiguration.AnchorIndicator).Value;
                if (!String.IsNullOrEmpty(sAnchorIndicator) && sAnchorIndicator.Equals("true", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (!String.IsNullOrEmpty(EnumAPIConfiguration.AnchorElement))
                    {
                        string sAnchorValue = CurrXmlResponse.Root.Element(EnumAPIConfiguration.AnchorElement).Value;

                        if (!String.IsNullOrEmpty(sAnchorValue))
                        {
                            if (sAnchorValue.ToLower().StartsWith("http"))
                            {
                                EnumAPIConfiguration.CurrentAnchor = sAnchorValue;
                            }
                            else
                            {
                                EnumAPIConfiguration.CurrentAnchor = AceXmlReader.FormatAnchorURL(EnumAPIConfiguration) + sAnchorValue;
                            }

                            if (XmlReader.FoundNewAnchorCallback != null)
                            {
                                XmlReader.FoundNewAnchorCallback(EnumAPIConfiguration.CurrentAnchor);
                            }
                        }
                    }
                }
                else
                {
                    IsFinalSet = true;
                    EnumAPIConfiguration.CurrentAnchor = "";
                }
            }
            else
            {
                IsFinalSet = true;
                EnumAPIConfiguration.CurrentAnchor = "";
            }

            if (!String.IsNullOrEmpty(EnumAPIConfiguration.TargetTag) && !String.IsNullOrEmpty(EnumAPIConfiguration.TargetKeyTag))
            {
                if (!String.IsNullOrEmpty(EnumAPIConfiguration.ResponseFilterPath))
                {
                    // NOTE: Currently, the sought parent tag of our enumerated records is "body",
                    //       but that can also be configured through metadata
                    CurrRecordList =
                        (
                            from x in CurrXmlResponse.Root.Elements(EnumAPIConfiguration.TargetTag)
                            where x.XPathSelectElement(EnumAPIConfiguration.ResponseFilterPath) != null &&
                            x.XPathSelectElement(EnumAPIConfiguration.ResponseFilterPath).Value != null
                            select new Hashtable()
                    {
                        { EnumAPIConfiguration.TargetKeyTag, x.Element(EnumAPIConfiguration.TargetKeyTag).Value },
                        { AceXmlReader.CONST_RESPONSE_XML_BODY_KEY, x.ToString() }
                    }
                        ).ToList();
                }
                else
                {
                    // NOTE: Currently, the sought parent tag of our enumerated records is "body",
                    //       but that can also be configured through metadata
                    CurrRecordList =
                        (
                            from x in CurrXmlResponse.Root.Elements(EnumAPIConfiguration.TargetTag)
                            // where x.
                            select new Hashtable()
                    {
                        { EnumAPIConfiguration.TargetKeyTag, x.Element(EnumAPIConfiguration.TargetKeyTag).Value },
                        { AceXmlReader.CONST_RESPONSE_XML_BODY_KEY, x.ToString() }
                    }
                        ).ToList();
                }

                if (CurrRecordList.Count > 0)
                {
                    bMoreData = true;
                }
            }

            return(bMoreData);
        }
Ejemplo n.º 13
0
        /// <summary>
        ///
        /// This method will make the next call to the REST API and then retrieve the
        /// XML payload as a XDocument.
        ///
        /// <param name="poEnumConfiguration">The Configuration metadata for our calls to the REST API</param>
        /// <param name="psRequestURL">The formatted Request URL for our call to the REST API</param>
        /// <returns>The XDocument representation of the XML payload from the REST API</returns>
        /// </summary>
        static public XDocument PullXmlDoc(AceAPIConfiguration poEnumConfiguration, string psRequestURL)
        {
            bool bContentTypeXml = (poEnumConfiguration.DataContentType == ContentType.XML);

            XDocument  oXDoc          = null;
            WebRequest oWebAPIRequest = null;

            for (int nRetryCount = 0; nRetryCount < CONST_MAX_RETRY_COUNT; ++nRetryCount)
            {
                try
                {
                    oWebAPIRequest = WebRequest.Create(psRequestURL);

                    oWebAPIRequest.Timeout = AceXmlReader.CONST_WEB_REQUEST_TIMEOUT_MS;

                    // If required by the server, set the credentials.
                    oWebAPIRequest.Credentials = CredentialCache.DefaultCredentials;

                    if ((poEnumConfiguration.RequestHeaderArgs != null) && (poEnumConfiguration.RequestHeaderArgs.Count > 0))
                    {
                        foreach (string sTmpName in poEnumConfiguration.RequestHeaderArgs.Keys)
                        {
                            oWebAPIRequest.Headers.Add(sTmpName, poEnumConfiguration.RequestHeaderArgs[sTmpName]);
                        }
                    }

                    using (WebResponse oWebAPIResponse = oWebAPIRequest.GetResponse())
                    {
                        // Get the stream containing content returned by the server.
                        Stream oDataStream = oWebAPIResponse.GetResponseStream();

                        // Open the stream using a StreamReader for easy access.
                        using (StreamReader oWebReader = new StreamReader(oDataStream))
                        {
                            if (bContentTypeXml)
                            {
                                oXDoc = XDocument.Load(oWebReader, LoadOptions.PreserveWhitespace);
                            }
                            else
                            {
                                string sJsonOutput = oWebReader.ReadToEnd();

                                if (sJsonOutput.StartsWith("["))
                                {
                                    sJsonOutput = "{\n \"root\": { \n  \"product\": " + sJsonOutput + "} }";
                                }

                                XmlDocument oXmlDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(sJsonOutput);

                                using (var nodeReader = new XmlNodeReader(oXmlDoc))
                                {
                                    nodeReader.MoveToContent();
                                    oXDoc = XDocument.Load(nodeReader);
                                }
                            }
                        }
                    }

                    break;
                }
                catch (WebException ex)
                {
                    if ((nRetryCount + 1) < CONST_MAX_RETRY_COUNT)
                    {
                        if (oWebAPIRequest != null)
                        {
                            System.Console.WriteLine("DEBUG: Timeout (value=" + oWebAPIRequest.Timeout + ") issue with pulling catalog data for URL(" +
                                                     oWebAPIRequest.RequestUri.ToString() + ")...attempting to pull the data again..." + DateTime.Now.ToString());
                        }

                        Thread.Sleep(5000);
                    }
                    else
                    {
                        throw ex;
                    }
                }
                catch (IOException ex)
                {
                    if ((nRetryCount + 1) < CONST_MAX_RETRY_COUNT)
                    {
                        System.Console.WriteLine("DEBUG: General network issue with pulling catalog data for URL(" + oWebAPIRequest.RequestUri.ToString() +
                                                 ")...attempting to pull the data again...");

                        Thread.Sleep(5000);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }

            return(oXDoc);
        }
Ejemplo n.º 14
0
        public void Run()
        {
            // ----- Find -----
            if (!string.IsNullOrEmpty(findtype))
                invoker = findtype;

            Type t = Type.GetType(invoker);
            if (t == null)
            {
                foreach (var asm in assemblies)
                {
                    t = asm.GetType(invoker);
                    if (t != null)
                        break;
                }

            }

            // ----- Found? -----
            if (!string.IsNullOrEmpty(findtype))
            {
                if ((findtype.Equals("System.Void")) // special type only for reflections - ignore!
                 || (t == null))
                {
                    Console.WriteLine(FALSE);
                    return;
                }

                else
                    Console.WriteLine(TRUE);

            }

            // ----- Print (all necessary info about this type to reconstruct it) -----

            if (t != null)
            {
                if (!string.IsNullOrEmpty(findtype))
                    PrintBaseTypes(t);

                bool showAny = any;
                if (any == false && !string.IsNullOrEmpty(findtype)) showAny = true;

                // ----- FIELDS -----
                var fields = new List<FieldInfo>();
                if (showAny)
                {
                    fields = t.GetFields().ToList();
                }
                else
                {
                    var f = t.GetField(member);
                    if (f != null) fields.Add(f);
                }

                foreach (var f in fields)
                    PrintField(f);

                // ----- PROPERTIES -----
                var properties = new List<PropertyInfo>();
                if (showAny)
                {
                    properties = t.GetProperties().ToList();
                }
                else
                {
                    var p = t.GetProperty(member);
                    if (p != null) properties.Add(p);
                }

                foreach (var p in properties)
                    PrintProperty(p);

                // ----- METHODS & CONSTRUCTORS -----
                var methods = new List<MethodBase>();
                if (showAny)
                {
                    foreach (var mi in t.GetMethods())
                        methods.Add(mi);
                    foreach (var ci in t.GetConstructors())
                        methods.Add(ci);
                }
                else
                {
                    var mi = t.GetMethod(member);
                    if (mi != null) methods.Add(mi);

                    // TODO get constructors
                }

                foreach (var m in methods)
                    PrintMethod(m);

                // TODO add nested types 
                //else if ((member.MemberType & MemberTypes.TypeInfo) > 0
                //    || (member.MemberType & MemberTypes.NestedType) > 0)
                //PrintType(member as TypeInfo);

            
            
                // warning !!! no support for extension methods
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            certStore  = new X509Store(StoreLocation.CurrentUser);
            collection = new X509CertificateCollection();
            string server        = "gemini.circumlunar.space";
            string page          = "/";
            bool   validProtocol = true;

            int windowLineCount = Console.WindowHeight;

            if (args.Length > 0)
            {
                string hostArgument = args[0];

                if (hostArgument.Contains("gemini://"))
                {
                    hostArgument = hostArgument.Trim();
                    hostArgument = hostArgument.Substring(9);
                }
                else if (hostArgument.Contains("https://") || hostArgument.Contains("http://") || hostArgument.Contains("gopher://"))
                {
                    Console.WriteLine("Protocol not supported.");
                    validProtocol = false;
                }

                if (hostArgument.Contains("/"))
                {
                    int firstSlashIndex = hostArgument.IndexOf('/');
                    server = hostArgument.Remove(firstSlashIndex);
                    page   = hostArgument.Substring(firstSlashIndex, hostArgument.Length - firstSlashIndex);
                }
                else
                {
                    server = hostArgument;
                }
                if (validProtocol)
                {
                    TcpClient client = new TcpClient(server, 1965);


                    using (SslStream sslStream = new SslStream(client.GetStream(), false,
                                                               new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                    {
                        sslStream.AuthenticateAsClient(server);
                        byte[] messageToSend = Encoding.UTF8.GetBytes("gemini://" + server + page + '\r' + '\n');
                        sslStream.Write(messageToSend);

                        string responseData = ReadMessage(sslStream);

                        handleResponse(responseData);
                    }
                    client.Close();
                }
            }
            else
            {
                inInteractive = true;
                LineBuffer    = new string[windowLineCount];

                buildRequest(server + page);
                LineBuffer  = fetchPage();
                linksInPage = buildLinkSet(LineBuffer);

                while (inInteractive)
                {
                    interactiveLoop();
                }
            }
        }
Ejemplo n.º 16
0
        public void AddTableUpdateStrategyReceiver(string statementName, TableUpdateStrategyReceiver receiver, EventBeanUpdateHelper updateHelper, bool onMerge)
        {
            var receivers = _stmtNameToUpdateStrategyReceivers.Get(statementName);

            if (receivers == null)
            {
                receivers = new List <TableUpdateStrategyReceiverDesc>(2);
                _stmtNameToUpdateStrategyReceivers.Put(statementName, receivers);
            }
            receivers.Add(new TableUpdateStrategyReceiverDesc(receiver, updateHelper, onMerge));
        }
        private void AccelerateHediff(Pawn pawn, int ticks)
        {
            float totalBleedRate = 0;

            using (IEnumerator <Hediff> enumerator = pawn.health.hediffSet.GetHediffs <Hediff>().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Hediff rec = enumerator.Current;
                    HediffComp_Immunizable immuneComp = rec.TryGetComp <HediffComp_Immunizable>();
                    if (immuneComp != null)
                    {
                        if (immuneComp.Def.CompProps <HediffCompProperties_Immunizable>() != null)
                        {
                            float immuneSevDay = immuneComp.Def.CompProps <HediffCompProperties_Immunizable>().severityPerDayNotImmune;
                            if (immuneSevDay != 0 && !rec.FullyImmune())
                            {
                                rec.Severity += ((immuneSevDay * ticks * this.parent.Severity) / (24 * 2500));
                            }
                        }
                    }
                    HediffComp_SeverityPerDay sevDayComp = rec.TryGetComp <HediffComp_SeverityPerDay>();
                    if (sevDayComp != null)
                    {
                        if (sevDayComp.Def.CompProps <HediffCompProperties_SeverityPerDay>() != null)
                        {
                            float sevDay = sevDayComp.Def.CompProps <HediffCompProperties_SeverityPerDay>().severityPerDay;
                            if (sevDay != 0)
                            {
                                rec.Severity += ((sevDay * ticks * this.parent.Severity) / (24 * 2500));
                            }
                        }
                    }
                    HediffComp_Disappears tickComp = rec.TryGetComp <HediffComp_Disappears>();
                    if (tickComp != null)
                    {
                        int ticksToDisappear = Traverse.Create(root: tickComp).Field(name: "ticksToDisappear").GetValue <int>();
                        if (ticksToDisappear != 0)
                        {
                            Traverse.Create(root: tickComp).Field(name: "ticksToDisappear").SetValue(ticksToDisappear - (Mathf.RoundToInt(60 * this.parent.Severity)));
                        }
                    }
                    Hediff_Pregnant hdp = this.Pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("Pregnant")) as Hediff_Pregnant;
                    if (hdp != null)
                    {
                        hdp.Severity += (1f / (this.Pawn.RaceProps.gestationPeriodDays * (2500f / this.parent.Severity)));
                    }
                    CompEggLayer eggComp = this.Pawn.TryGetComp <CompEggLayer>();
                    if (eggComp != null)
                    {
                        float eggProgress = Traverse.Create(root: eggComp).Field(name: "eggProgress").GetValue <float>();
                        bool  isActive    = Active(eggComp);
                        if (isActive)
                        {
                            eggProgress += (1f / (eggComp.Props.eggLayIntervalDays * (2500f / this.parent.Severity)));
                            Traverse.Create(root: eggComp).Field(name: "eggProgress").SetValue(eggProgress);
                        }
                    }
                    //CompHasGatherableBodyResource gatherComp = this.Pawn.TryGetComp<CompHasGatherableBodyResource>();
                    //if (gatherComp != null)
                    //{
                    //    float gatherProgress = gatherComp.Fullness;

                    //    int rate = Traverse.Create(root: gatherComp).Field(name: "GatherResourcesIntervalDays").GetValue<int>();
                    //    bool isActive = Active();
                    //    if (isActive)
                    //    {
                    //        gatherProgress += (1f / ((float)(rate * (2500f / this.parent.Severity))));
                    //        Traverse.Create(root: gatherComp).Field(name: "fullness").SetValue(gatherProgress);
                    //    }
                    //}
                    CompMilkable milkComp = this.Pawn.TryGetComp <CompMilkable>();
                    if (milkComp != null)
                    {
                        float milkProgress = milkComp.Fullness;
                        int   rate         = milkComp.Props.milkIntervalDays;
                        bool  isActive     = Active(milkComp);
                        if (isActive)
                        {
                            milkProgress += (1f / ((float)(rate * (2500f / this.parent.Severity))));
                            Traverse.Create(root: milkComp).Field(name: "fullness").SetValue(milkProgress);
                        }
                    }
                    if (rec.Bleeding)
                    {
                        totalBleedRate += rec.BleedRate;
                    }
                }
                if (totalBleedRate != 0)
                {
                    HealthUtility.AdjustSeverity(pawn, HediffDefOf.BloodLoss, (totalBleedRate * 60 * this.parent.Severity) / (24 * 2500));
                }
            }
        }
Ejemplo n.º 18
0
        public TableMetadata(string tableName, string eplExpression, string statementName, Type[] keyTypes, IDictionary <String, TableMetadataColumn> tableColumns, TableStateRowFactory rowFactory, int numberMethodAggregations, StatementResourceService createTableResources, string contextName, ObjectArrayEventType internalEventType, ObjectArrayEventType publicEventType, TableMetadataInternalEventToPublic eventToPublic, bool queryPlanLogging, string createTableStatementName)
        {
            _tableName               = tableName;
            _eplExpression           = eplExpression;
            _statementName           = statementName;
            KeyTypes                 = keyTypes;
            TableColumns             = tableColumns;
            RowFactory               = rowFactory;
            NumberMethodAggregations = numberMethodAggregations;
            _createTableResources    = createTableResources;
            ContextName              = contextName;
            InternalEventType        = internalEventType;
            _publicEventType         = publicEventType;
            _eventToPublic           = eventToPublic;
            _queryPlanLogging        = queryPlanLogging;

            if (keyTypes.Length > 0)
            {
                var pair = TableServiceUtil.GetIndexMultikeyForKeys(tableColumns, internalEventType);
                _eventTableIndexMetadataRepo.AddIndex(true, pair.Second, tableName, createTableStatementName, true);
                _tableRowKeyFactory = new TableRowKeyFactory(pair.First);
            }
        }
 /// <summary>
 /// Publishes a specific version of the application
 /// </summary>
 /// <param name="appId">app id</param>
 /// <param name="appVersionId">app version</param>
 /// <param name="isStaging">The flag "isStaging" should be set to true in case you want to publish to the STAGING slot, otherwise the application version will be published to the PRODUCTION slot</param>
 /// <param name="directVersionPublish">In case you do not want to publish to either the PRODUCTION or STAGING slots, you can set the flag "directVersionPublish" to true and query the endpoint [directly using the versionId] (https://westus.dev.cognitive.microsoft.com/docs/services/luis-endpoint-api-v3-0-preview/operations/5cb0a9459a1fe8fa44c28dd8).</param>
 /// <returns>A object of publish details</returns>
 public async Task<Publish> PublishAsync(string appId, string appVersionId, bool isStaging = false, bool directVersionPublish = false)
 {
     var model = new
     {
         versionId = appVersionId,
         isStaging = isStaging.ToString(),
         directVersionPublish = directVersionPublish
     };
     var response = await Post($"apps/{appId}/publish", model);
     return JsonConvert.DeserializeObject<Publish>(response);
 }
Ejemplo n.º 20
0
        //-----------------------------------------------------------------------------------
        // Marks the end of a query's execution, waiting for all tasks to finish and
        // propagating any relevant exceptions.  Note that the full set of tasks must have
        // been initialized (with SetTask) before calling this.
        //

        internal void QueryEnd(bool userInitiatedDispose)
        {
            Debug.Assert(_rootTask != null);
            //Debug.Assert(Task.Current == null || (Task.Current != _rootTask && Task.Current.Parent != _rootTask));

            if (Interlocked.Exchange(ref _alreadyEnded, 1) == 0)
            {
                // There are four cases:
                // Case #1: Wait produced an exception that is not OCE(ct), or an AggregateException which is not full of OCE(ct) ==>  We rethrow.
                // Case #2: External cancellation has been requested ==> we'll manually throw OCE(externalToken).
                // Case #3a: We are servicing a call to Dispose() (and possibly also external cancellation has been requested).. simply return.
                // Case #3b: The enumerator has already been disposed (and possibly also external cancellation was requested).  Throw an ODE.
                // Case #4: No exceptions or explicit call to Dispose() by this caller ==> we just return.

                // See also "InlinedAggregationOperator" which duplicates some of this logic for the aggregators.
                // See also "QueryOpeningEnumerator" which duplicates some of this logic.
                // See also "ExceptionAggregator" which duplicates some of this logic.

                try
                {
                    // Wait for all the tasks to complete
                    // If any of the tasks ended in the Faulted stated, an AggregateException will be thrown.
                    _rootTask.Wait();
                }
                catch (AggregateException ae)
                {
                    AggregateException flattenedAE = ae.Flatten();
                    bool allOCEsOnTrackedExternalCancellationToken = true;
                    for (int i = 0; i < flattenedAE.InnerExceptions.Count; i++)
                    {
                        OperationCanceledException oce = flattenedAE.InnerExceptions[i] as OperationCanceledException;

                        // we only let it pass through iff:
                        // it is not null, not default, and matches the exact token we were given as being the external token
                        // and the external Token is actually canceled (i.e. not a spoof OCE(extCT) for a non-canceled extCT)
                        if (oce == null ||
                            !oce.CancellationToken.IsCancellationRequested ||
                            oce.CancellationToken != _cancellationState.ExternalCancellationToken)
                        {
                            allOCEsOnTrackedExternalCancellationToken = false;
                            break;
                        }
                    }

                    // if all the exceptions were OCE(externalToken), then we will propagate only a single OCE(externalToken) below
                    // otherwise, we flatten the aggregate (because the WaitAll above already aggregated) and rethrow.
                    if (!allOCEsOnTrackedExternalCancellationToken)
                        throw flattenedAE;  // Case #1
                }
                finally
                {
                    //_rootTask don't support Dispose on some platforms
                    IDisposable disposable = _rootTask as IDisposable;
                    if (disposable != null)
                        disposable.Dispose();
                }

                if (_cancellationState.MergedCancellationToken.IsCancellationRequested)
                {
                    // cancellation has occurred but no user-delegate exceptions were detected 

                    // NOTE: it is important that we see other state variables correctly here, and that
                    // read-reordering hasn't played havoc. 
                    // This is OK because 
                    //   1. all the state writes (e,g. in the Initiate* methods) are volatile writes (standard .NET MM)
                    //   2. tokenCancellationRequested is backed by a volatile field, hence the reads below
                    //   won't get reordered about the read of token.IsCancellationRequested.

                    // If the query has already been disposed, we don't want to throw an OCE
                    if (!_cancellationState.TopLevelDisposedFlag.Value)
                    {
                        CancellationState.ThrowWithStandardMessageIfCanceled(_cancellationState.ExternalCancellationToken); // Case #2
                    }

                    //otherwise, given that there were no user-delegate exceptions (they would have been rethrown above),
                    //the only remaining situation is user-initiated dispose.
                    Debug.Assert(_cancellationState.TopLevelDisposedFlag.Value);

                    // If we aren't actively disposing, that means somebody else previously disposed
                    // of the enumerator. We must throw an ObjectDisposedException.
                    if (!userInitiatedDispose)
                    {
                        throw new ObjectDisposedException("enumerator", SR.PLINQ_DisposeRequested); // Case #3
                    }
                }
                // Case #4. nothing to do.
            }
        }
Ejemplo n.º 21
0
 public Player(string name, int number, bool starter)
 {
     Name    = name;
     Number  = number;
     Starter = starter;
 }
    // 트리거 클릭시 선택된 오브젝트가 있는지 점검//
    void OnSelect()
    {

        if (GameObject.Find("TextBubble01") || GameObject.Find("TextBubble02") || GameObject.Find("QuestionPanel"))
        {
            //Debug.Log("UI 인터페이스가 활성화 되어있습니다.");
            return;
        }

        if (uAction == null)
        {
            Debug.Log("어떤 함수도 준비되지 않았습니다.");
            //Debug.Log("시나리오 넘버:"+ConstDataScript.scenarioNum +" ::멀티상태: "+ ConstDataScript.isMulti + " ::롤넘버: "+ ConstDataScript.roleNum + " ::액션넘버: "+ GameObject.Find("Characters/010_CrewA").GetComponent<ICT_Engine.MoveOnPathScript>().actionNum );


            //수동문열기를 하면 리턴을 하는 것이 아니라 아래 주석처리한 부분을 살려주어야 한다.
            //return;

            // 문을 여는 조건은 여기서 정해주어야 한다.//
            // 다른 시나리오 다른 캐릭터가 되면 또 그에 맞는 조건을 만들어주면 된다.//

            // 시나리오 1번(화재) 조건

            #region 수동 문열기 기능
            
            if (
                (ConstDataScript.scenarioNum == 1 && 
                ConstDataScript.isMulti == true && 
                ConstDataScript.roleNum == 10 && 
                GameObject.Find("Characters/010_CrewA").GetComponent<ICT_Engine.MoveOnPathScript>().actionNum == 10)
                ||
                // 시나리오 4번(거주구역화재)조건
                (ConstDataScript.scenarioNum == 4 && 
                ConstDataScript.isMulti == true && 
                (ConstDataScript.roleNum == 10 || ConstDataScript.roleNum == 13) && 
                GameObject.Find("Characters/010_CrewA").GetComponent<ICT_Engine.MoveOnPathScript>().actionNum == 10)
                )
            {
                Debug.Log("문을 열 수 있습니다.");
                //GameObject prop = pc.GetComponent<ICT_Engine.MoveOnPathScript>().TriggerEnterObj;
                //Debug.Log("선택된 프랍이 있습니다. ::: " + prop.name);

                //prop.GetComponent<Animation>().Play("DoorOpen");
                //return;
            }
            else
            {
                return;
            }
            
            #endregion
        }
        if (isOnSelect == true) return;
        isOnSelect = true;
        Transform characters = GameObject.Find("Characters").transform;
        for (int i = 0; i < characters.childCount; i++)
        {

            // 플레이어 캐릭터를 찾는다.
            if (characters.GetChild(i).name.Contains(ConstDataScript.roleNum.ToString()))
            {
                Debug.Log("Player Character!!");
                pc = characters.GetChild(i);
                // 플레이어 캐릭터는 찾았고...
                // PC에 붙어있는 MoveOnPathScript의 TriggerEnterObj에 오브젝트가 들어가 있는지 확인한다.
                // (오브젝트가 들어갔다는 것은 현재 컨트롤러가 오브젝트(프랍)를 가리키고 있다는 것이다).
                GameObject prop = pc.GetComponent<ICT_Engine.MoveOnPathScript>().TriggerEnterObj;
                Debug.Log("선택된 프랍이 있습니다. ::: " + prop.name);
                if(prop != null)
                {

                    // Null이 아니라면 현재 캐릭터와 프랍과 관련있는 것인지 알아본다.
                    // 프랍이 어떤 캐릭터와 관련이 있는지는 아래 배열변수의 내용을 보면 알 수 있다.
                    string[] rollNum = prop.GetComponent<ClickProp>().ConnectedRoll;

                    for(int j = 0; j<rollNum.Length; i++)
                    {
                        if (pc.name.Contains(rollNum[j]))
                        {
                            AnimationClip cp;
                            // 연결된 플레이어 넘버를 보여준다.
                            Debug.Log("J number: "+ j+ " :: 연결된 캐릭터: " + rollNum[j]);


                            #region 수동문열기(문인지 확인하는 부분).
                            
                            // 문을 여는 경우.
                            if (prop.tag.ToLower().Contains("door"))
                            {
                                //prop.GetComponent<Animation>().Play("DoorOpen");
                                //Debug.Log("애니메이션 이름: " + prop.GetComponent<Animation>().clip.name);

                                cp = prop.GetComponent<Animation>().GetClip("DoorOpen");
                                prop.GetComponent<Animation>().Play(cp.name);
                            }
                            // 다른 경우.(경우의 수가 많아지면 나중에 스위치를 이용하자.)
                            else
                            
                            #endregion
                            {
                                prop.GetComponent<Animation>().Play();
                                cp = prop.GetComponent<Animation>().clip;
                            }
                            Debug.Log("델리게이트 부를 준비1");
                            
                            float clpLength = 2f;
                            Debug.Log("ClpLength:: " + cp.length);
                            clpLength = cp.length;

                            // 여기서 이벤트를 삽입하여야 한다.
                            // 여기서 이벤트는 플레이어 캐릭터에 전달하거나 또는 그곳에서
                            // 바로 실행이 되어야 될 코드(함수)를 지칭한다.
                            Debug.Log("델리게이트 부를 준비2");
                            StartCoroutine(AfterMethod(clpLength, prop));
                            // 4 touchpadPosition::: (0.1, -1.0) - 터치패드 눌렀을 때.
                            // 4 grasped::: True - 옆구립 그립 눌렀을 때.
                            // 4 selectPressedAmount(Trigger)::: 0.1764706 - 앞쪽의 트리거 눌렀을 때.

                            break;

                        }
                    }
                }
            }
        }
    }
        /// <summary>
        /// Get a directory entry based on a name.
        /// </summary>
        /// <param name="name">The name of the entry.</param>
        /// <param name="typename">The typename to verify against, can be null.</param>
        /// <param name="case_sensitive">True if look up is case sensitive.</param>
        /// <returns>The directory entry, or null if it can't be found.</returns>
        public ObjectDirectoryInformation GetDirectoryEntry(string name, string typename, bool case_sensitive)
        {
            StringComparison comparison_type = case_sensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
            foreach (ObjectDirectoryInformation dir_info in Query())
            {
                if (!dir_info.Name.Equals(name, comparison_type))
                {
                    continue;
                }

                if (typename != null && !typename.Equals(typename, comparison_type))
                {
                    continue;
                }

                return dir_info;
            }
            return null;
        }
        private void populateSmartAttributesForDisk_againstSmartctl(string smartCtlExeFullPath, DetectedDisk disk, string forceDeviceType = null)
        {
            // Build up the command that will gather all SMART information for a given physical disk.
            string command = null;
            if (String.IsNullOrEmpty(forceDeviceType))
            {
                // Call the normal routine to gather all SMART data, letting it determine the device type by itself.
                command = @"""" + smartCtlExeFullPath + @"""" + " -a /dev/pd" + disk.DiskNumber.ToString();
            }
            else
            {
                // Rather than rely on SMARTCTL to determine the device type, force it to treat it as a certain device type, because we have found
                // that it doesn't always choose the correct device type, by itself.  And when it has the wrong device type, it will incorrectly
                // report that SMART support is unavailable.
                command = @"""" + smartCtlExeFullPath + @"""" + " -a -d " + forceDeviceType + " /dev/pd" + disk.DiskNumber.ToString();
            }

            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.RedirectStandardError = false;

            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();
            string standardOutput = proc.StandardOutput.ReadToEnd();  // Seems odd to read to end before waiting for exit, but that's what ol' MSDN tells us to do.
            proc.WaitForExit();

            if (false == String.IsNullOrEmpty(standardOutput))
            {
                // Grab a copy of the big old output.
                disk.SmartctlOutput = standardOutput;

                string[] outputLines = standardOutput.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                // Read SMART support and rotation rate, which is in the information section.
                // Seek past the header line that denotes the information section, and parse out the lines that speak to SMART support and rotation rate.
                bool isPastInfoSectionHeader = false;
                string supportLabel = "SMART support is: ";
                string rotationRateLabel = "Rotation Rate: ";
                bool foundSupportLabels = false;
                bool supportIsAvailable = false;
                bool supportIsEnabled = false;
                for (int lineIdx = 0; lineIdx < outputLines.Length; lineIdx++)
                {
                    string line = outputLines[lineIdx];
                    if ((false == isPastInfoSectionHeader) && (line.StartsWith("=== START OF INFORMATION SECTION ===")))
                    {
                        isPastInfoSectionHeader = true;
                    }
                    else if (isPastInfoSectionHeader)
                    {
                        if (line.StartsWith("=== START"))
                        {
                            // Start of the next section, so we are past the area that reveals SMART support and rotation rate.
                            break;
                        }
                        else
                        {
                            // This is in the first chunk of lines after the information section header, where we find the SMART support indicators and rotation rate.
                            if (line.StartsWith(supportLabel))
                            {
                                foundSupportLabels = true;
                                string supportValue = line.Substring(supportLabel.Length).Trim();
                                if (supportValue.StartsWith("Available"))
                                {
                                    supportIsAvailable = true;
                                }
                                else if (supportValue.StartsWith("Enabled"))
                                {
                                    supportIsEnabled = true;
                                }
                            }
                            else if (line.StartsWith(rotationRateLabel))
                            {
                                // Found the rotation rate.
                                disk.SmartRotationRate = line.Substring(rotationRateLabel.Length).Trim();
                            }
                        }
                    }
                }
                if (foundSupportLabels)
                {
                    if (supportIsAvailable)
                    {
                        if (supportIsEnabled)
                        {
                            disk.SmartSupport = DiskSmartSupport.AvailableAndEnabled;
                        }
                        else
                        {
                            disk.SmartSupport = DiskSmartSupport.AvailableButDisabled;
                        }
                    }
                    else
                    {
                        disk.SmartSupport = DiskSmartSupport.Unavailable;
                    }
                }

                // Look for additional SMART information only if SMART support is available and enabled.
                if (disk.SmartSupport == DiskSmartSupport.AvailableAndEnabled)
                {
                    // Read SMART overall health test result (or health status, as not every drive supports self test logging).
                    // Seek past the header line that denotes the data section, and parse out the line that speaks to the SMART overall health test result (or health status).
                    bool isPastDataSectionHeader = false;
                    string overallTestResultLabel = "SMART overall-health self-assessment test result: ";
                    string healthStatusLabel = "SMART Health Status: ";
                    for (int lineIdx = 0; lineIdx < outputLines.Length; lineIdx++)
                    {
                        string line = outputLines[lineIdx];
                        if ((false == isPastDataSectionHeader) && (line.StartsWith("=== START OF READ SMART DATA SECTION ===")))
                        {
                            isPastDataSectionHeader = true;
                        }
                        else if (isPastDataSectionHeader)
                        {
                            if (line.StartsWith("=== START"))
                            {
                                // Start of the next section, so we are past the area that reveals SMART overall health test result (or health status).
                                break;
                            }
                            else
                            {
                                // This is in the first chunk of lines after the data section header, where we find the SMART overall health test result (or health status).
                                if (line.StartsWith(overallTestResultLabel))
                                {
                                    string overallTestResultValue = line.Substring(overallTestResultLabel.Length).Trim();
                                    if (overallTestResultValue.StartsWith("PASSED"))
                                    {
                                        disk.OverallFailurePredicted = false;
                                    }
                                    else
                                    {
                                        disk.OverallFailurePredicted = true;
                                    }
                                }
                                else if (line.StartsWith(healthStatusLabel))
                                {
                                    // Remember, no every drive supports self test logging, so on these disks we read the health status instead.
                                    string healthStatusResultValue = line.Substring(healthStatusLabel.Length).Trim();
                                    if (healthStatusResultValue == "OK")
                                    {
                                        disk.OverallFailurePredicted = false;
                                    }
                                    else
                                    {
                                        disk.OverallFailurePredicted = true;
                                    }
                                }
                            }
                        }
                    }

                    // Read SMART attributes.
                    // Seek past the header line that appears above the attribute lines, then parse the attribute lines. 
                    bool isPastAttrHeader = false;
                    bool hadErrorParsingAttributes = false;
                    for (int lineIdx = 0; lineIdx < outputLines.Length; lineIdx++)
                    {
                        string line = outputLines[lineIdx];
                        if ((false == isPastAttrHeader) && (line.StartsWith("ID#")))
                        {
                            isPastAttrHeader = true;
                        }
                        else if (isPastAttrHeader)
                        {
                            if (line.Trim().Length == 0)
                            {
                                // First blank line after listing the attributes, which means there are no more attributes listed.
                                break;
                            }
                            else
                            {
                                // This must be an attribute line.

                                bool hadParseError = false;
                                int smartAttributeId = -1;
                                string attributeName = null;
                                int value = 0;
                                int worst = 0;
                                int thresh = 0;
                                string attrType = null;
                                string rawValue = null;
                                parseSmartctlAttributeOutputLine(line, out hadParseError, out smartAttributeId, out attributeName, out value, out worst, out thresh, out attrType, out rawValue);

                                if (hadParseError)
                                {
                                    // Keep track of the error.
                                    hadErrorParsingAttributes = true;
                                }
                                else if (false == disk.SmartAttributes.ContainsKey(smartAttributeId))
                                {
                                    DetectedDisk.SmartAttribute attr = new DetectedDisk.SmartAttribute(attributeName);

                                    attr.AttributeType = attrType;
                                    attr.Current = value;
                                    attr.Worst = worst;
                                    attr.RawValue = rawValue;
                                    attr.Threshold = thresh;

                                    if (attrType.ToUpper() == "PRE-FAIL")
                                    {
                                        // This type of attribute has a meaningful threshold.
                                        if (value <= thresh)
                                        {
                                            // Failure is imminent.
                                            attr.IsOK = false;
                                        }
                                        else
                                        {
                                            attr.IsOK = true;
                                        }
                                    }
                                    else
                                    {
                                        attr.IsOK = true;  // Must be an OLD-AGE attribute, so no real threshold ... let's just say its okay.
                                    }

                                    disk.SmartAttributes.Add(smartAttributeId, attr);
                                }
                            }
                        }
                    }

                    if (hadErrorParsingAttributes)
                    {
                        // There was at least one attribute line that we had trouble parsing.

                        // So, if the disk hasn't had any sort of SMART failure indicated up to this point, we are going to flip the SMART support indicator to "Unknown", since
                        // we don't really want to give it a passing grade if we had problems parsing attributes.
                        if ((disk.OverallFailurePredicted.HasValue) && (disk.OverallFailurePredicted.Value))
                        {
                            // Already going to be reporting a failure, so the parse error doesn't really affect anything.
                        }
                        else
                        {
                            var smartAttributeFailures = disk.SmartAttributes.Values.Where(sav => false == sav.IsOK);
                            if (true == smartAttributeFailures.Any())
                            {
                                // Already going to be reporting a failure, so the parse error doesn't really affect anything.
                            }
                            else
                            {
                                // No SMART failure of any kind to report -- so we need to flip the SMART support indicator to "Unknown", so that this disk doesn't slip through with a passing grade.
                                disk.SmartSupport = DiskSmartSupport.Unknown;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public void LoadFromRS(IDataReader rs)
        {
            m_productid          = DB.RSFieldInt(rs, "ProductID");
            m_productguid        = DB.RSFieldGUID(rs, "ProductGUID");
            m_name               = DB.RSField(rs, "Name");
            m_summary            = DB.RSField(rs, "Summary");
            m_description        = DB.RSField(rs, "Description");
            m_sekeywords         = DB.RSField(rs, "SEKeywords");
            m_sedescription      = DB.RSField(rs, "SEDescription");
            m_misctext           = DB.RSField(rs, "MiscText");
            m_froogledescription = DB.RSField(rs, "FroogleDescription");
            m_setitle            = DB.RSField(rs, "SETitle");
            m_sealttext          = DB.RSField(rs, "SEAltText");
            m_sizeoptionprompt   = DB.RSField(rs, "SizeOptionPrompt");
            m_coloroptionprompt  = DB.RSField(rs, "ColorOptionPrompt");
            m_textoptionprompt   = DB.RSField(rs, "TextOptionPrompt");
            m_producttypeid      = DB.RSFieldInt(rs, "ProductTypeID");
            m_taxclassid         = DB.RSFieldInt(rs, "TaxClassID");
            m_sku = DB.RSField(rs, "SKU");
            m_manufacturerpartnumber = DB.RSField(rs, "ManufacturerPartNumber");
            m_salespromptid          = DB.RSFieldInt(rs, "SalesPromptID");
            m_xmlpackage             = DB.RSField(rs, "XmlPackage");
            m_colwidth             = DB.RSFieldInt(rs, "ColWidth");
            m_published            = DB.RSFieldBool(rs, "Published");
            m_wholesale            = DB.RSFieldBool(rs, "Wholesale");
            m_requiresregistration = DB.RSFieldBool(rs, "RequiresRegistration");
            m_looks = DB.RSFieldInt(rs, "Looks");
            m_notes = DB.RSField(rs, "Notes");
            m_quantitydiscountid = DB.RSFieldInt(rs, "QuantityDiscountID");
            m_relatedproducts    = DB.RSField(rs, "RelatedProducts");
            m_upsellproducts     = DB.RSField(rs, "UpsellProducts");
            m_upsellproductdiscountpercentage = DB.RSFieldDecimal(rs, "UpsellProductDiscountPercentage");
            m_relateddocuments             = DB.RSField(rs, "RelatedDocuments");
            m_trackinventorybysizeandcolor = DB.RSFieldBool(rs, "TrackInventoryBySizeAndColor");
            m_trackinventorybysize         = DB.RSFieldBool(rs, "TrackInventoryBySize");
            m_trackinventorybycolor        = DB.RSFieldBool(rs, "TrackInventoryByColor");
            m_isakit = DB.RSFieldBool(rs, "IsAKit");
            m_showinproductbrowser  = DB.RSFieldBool(rs, "ShowInProductBrowser");
            m_showbuybutton         = DB.RSFieldBool(rs, "ShowBuyButton");
            m_requiresproducts      = DB.RSField(rs, "RequiresProducts");
            m_hidepriceuntilcart    = DB.RSFieldBool(rs, "HidePriceUntilCart");
            m_iscalltoorder         = DB.RSFieldBool(rs, "IsCalltoOrder");
            m_excludefrompricefeeds = DB.RSFieldBool(rs, "ExcludeFromPriceFeeds");
            m_requirestextoption    = DB.RSFieldBool(rs, "RequiresTextOption");
            m_textoptionmaxlength   = DB.RSFieldInt(rs, "TextOptionMaxLength");
            m_sename                = DB.RSField(rs, "SEName");
            m_extensiondata         = DB.RSField(rs, "ExtensionData");
            m_extensiondata2        = DB.RSField(rs, "ExtensionData2");
            m_extensiondata3        = DB.RSField(rs, "ExtensionData3");
            m_extensiondata4        = DB.RSField(rs, "ExtensionData4");
            m_extensiondata5        = DB.RSField(rs, "ExtensionData5");
            m_imagefilenameoverride = DB.RSField(rs, "ImageFilenameOverride");
            m_isimport              = DB.RSFieldBool(rs, "IsImport");
            m_issystem              = DB.RSFieldBool(rs, "IsSystem");
            m_deleted               = DB.RSFieldBool(rs, "Deleted");
            m_createdon             = DB.RSFieldDateTime(rs, "CreatedOn");
            m_warehouselocation     = DB.RSField(rs, "WarehouseLocation");
            m_skinid                = DB.RSFieldInt(rs, "SkinID");
            m_templatename          = DB.RSField(rs, "TemplateName");

            //m_productvariants = GetVariants(true);
            m_productvariants = new List <ProductVariant>();
        }
        /// <summary>
        /// Detects all normal (not primary, not boot) disks, and gathers attributes about each.
        /// </summary>
        /// <param name="hadError"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public List<DetectedDisk> Detect(bool doGatherSmartData, out Boolean hadError, out String errorMessage)
        {
            // Inititialize out parameters.
            hadError = false;
            errorMessage = null;

            // Initialize return object.
            List<DetectedDisk> detectedDisks = new List<DetectedDisk>();

            // Assume primary and boot partitions are both Physical Disk 0.
            UInt32 primaryPartitionDiskNumber = 0;
            UInt32 bootPartitionDiskNumber = 0;

            // Keep track of errors encountered while iterating disks.
            List<string> diskIterationErrors = new List<string>();
            // Get the list of Win32_DiskDrive items.
            List<Win32_DiskDrive> w32diskDrives;
            try
            {
                w32diskDrives = GetDiskDrives();
            }
            catch (Exception ex)
            {
                hadError = true;
                errorMessage = "Error while retrieving disk drives: " + ex.Message;

                w32diskDrives = new List<Win32_DiskDrive>();
            }
            foreach (Win32_DiskDrive w32diskDrive in w32diskDrives)
            {
                try
                {
                    if (w32diskDrive.Index.HasValue)
                    {
                        // Skip this if it is the hosting the boot partition or primary partition.
                        if ((w32diskDrive.Index.Value != primaryPartitionDiskNumber) && (w32diskDrive.Index.Value != bootPartitionDiskNumber))
                        {
                            // Make sure it has the other attributes we need.
                            if ((w32diskDrive.Size.HasValue) &&
                                (w32diskDrive.BytesPerSector.HasValue) &&
                                (w32diskDrive.SectorsPerTrack.HasValue) &&
                                (w32diskDrive.TotalTracks.HasValue))
                            {
                                // This is one we want, as a detected disk.
                                DetectedDisk disk = new DetectedDisk();

                                // Parse the Vendor and ProductId out of the PNPDeviceId.
                                string vendor = "UNK";
                                string productId = "UNK";
                                string pnpDeviceId = w32diskDrive.PNPDeviceID;
                                if (false == String.IsNullOrEmpty(pnpDeviceId))
                                {
                                    // EXAMPLE: SCSI\DISK&VEN_WDC&PROD_WD3200BEKX-75B7W\4&2C8732C3&0&000000
                                    string[] pnpThreePartsArray = pnpDeviceId.Split('\\');
                                    if (pnpThreePartsArray.Length >= 2)
                                    {
                                        string[] typeVenProdRevArray = pnpThreePartsArray[1].Split('&');
                                        foreach (string part in typeVenProdRevArray)
                                        {
                                            if (part.StartsWith("VEN_"))
                                            {
                                                vendor = part.Substring(("VEN_").Length);
                                            }
                                            if (part.StartsWith("PROD_"))
                                            {
                                                productId = part.Substring(("PROD_").Length);
                                            }
                                        }
                                    }
                                }

                                disk.DiskNumber = w32diskDrive.Index.Value;
                                disk.Vendor = vendor;
                                disk.ProductId = productId;
                                //Data From Win32_DiskDrive Below
                                disk.Availability = w32diskDrive.Availability;
                                disk.BytesPerSector = w32diskDrive.BytesPerSector;
                                disk.Capabilities = w32diskDrive.Capabilities;
                                disk.CapabilityDescriptions = w32diskDrive.CapabilityDescriptions;
                                disk.Caption = w32diskDrive.Caption;
                                disk.CompressionMethod = w32diskDrive.CompressionMethod;
                                disk.ConfigManagerErrorCode = w32diskDrive.ConfigManagerErrorCode;
                                disk.ConfigManagerUserConfig = w32diskDrive.ConfigManagerUserConfig;
                                disk.CreationClassName = w32diskDrive.CreationClassName;
                                disk.DefaultBlockSize = w32diskDrive.DefaultBlockSize;
                                disk.Description = w32diskDrive.Description;
                                disk.DeviceID = w32diskDrive.DeviceID;
                                disk.ErrorCleared = w32diskDrive.ErrorCleared;
                                disk.ErrorDescription = w32diskDrive.ErrorDescription;
                                disk.ErrorMethodology = w32diskDrive.ErrorMethodology;
                                disk.FirmwareRevision = w32diskDrive.FirmwareRevision;
                                disk.Index = w32diskDrive.Index;
                                disk.InstallDate = w32diskDrive.InstallDate;
                                disk.InterfaceType = w32diskDrive.InterfaceType;
                                disk.Manufacturer = w32diskDrive.Manufacturer;
                                disk.MaxBlockSize = w32diskDrive.MaxBlockSize;
                                disk.MaxMediaSize = w32diskDrive.MaxMediaSize;
                                disk.MediaLoaded = w32diskDrive.MediaLoaded;
                                disk.MediaType = w32diskDrive.MediaType;
                                disk.MinBlockSize = w32diskDrive.MinBlockSize;
                                disk.Model = w32diskDrive.Model;
                                disk.Name = w32diskDrive.Name;
                                disk.NeedsCleaning = w32diskDrive.NeedsCleaning;
                                disk.NumberOfMediaSupported = w32diskDrive.NumberOfMediaSupported;
                                disk.Partitions = w32diskDrive.Partitions;
                                disk.PNPDeviceID = w32diskDrive.PNPDeviceID;
                                disk.PowerManagementCapabilities = w32diskDrive.PowerManagementCapabilities;
                                disk.PowerManagementSupported = w32diskDrive.PowerManagementSupported;
                                disk.SCSIBus = w32diskDrive.SCSIBus;
                                disk.SCSILogicalUnit = w32diskDrive.SCSILogicalUnit;
                                disk.SCSIPort = w32diskDrive.SCSIPort;
                                disk.SCSITargetId = w32diskDrive.SCSITargetId;
                                disk.SectorsPerTrack = w32diskDrive.SectorsPerTrack;
                                disk.SerialNumber = String.IsNullOrEmpty(w32diskDrive.SerialNumber) ? "" : w32diskDrive.SerialNumber.Trim();
                                disk.Signature = w32diskDrive.Signature;
                                disk.Size = w32diskDrive.Size;
                                disk.Status = w32diskDrive.Status;
                                disk.StatusInfo = w32diskDrive.StatusInfo;
                                disk.SystemCreationClassName = w32diskDrive.SystemCreationClassName;
                                disk.SystemName = w32diskDrive.SystemName;
                                disk.TotalCylinders = w32diskDrive.TotalCylinders;
                                disk.TotalHeads = w32diskDrive.TotalHeads;
                                disk.TotalSectors = w32diskDrive.TotalSectors;
                                disk.TotalTracks = w32diskDrive.TotalTracks;
                                disk.TracksPerCylinder = w32diskDrive.TracksPerCylinder;
                                detectedDisks.Add(disk);
                            }
                            else
                            {
                                diskIterationErrors.Add("Physical Disk " + w32diskDrive.Index.Value.ToString() + " is missing fundamental attributes.");
                                continue;  // Jump out without adding it to the collection to return.
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if ((null != w32diskDrive) && (w32diskDrive.Index.HasValue))
                    {
                        diskIterationErrors.Add("Unexpected error while processing Physical Disk " + w32diskDrive.Index.Value.ToString() + ": " + ex.Message);
                        continue;  // Jump out without adding it to the collection to return.
                    }
                    else
                    {
                        diskIterationErrors.Add("Unexpected error while processing Physical Disk: " + ex.Message);
                        continue;  // Jump out without adding it to the collection to return.
                    }
                }
            }

            // See if we had any errors while iterating the disks.
            if (false == hadError)
            {
                if (diskIterationErrors.Count > 0)
                {
                    hadError = true;
                    errorMessage = "Encountered errors while iterating disks: " + String.Join("; ", diskIterationErrors);
                }
            }

            if (false == hadError)
            {
                // Since gathering SMART data can take a while, we don't do it unless caller wants us to.
                if (doGatherSmartData)
                {
                    if (false == File.Exists(SMARTCTL_FULL_FILE_PATH))
                    {
                        hadError = true;
                        errorMessage = "Unable to find third-party SMARTCTL software at: " + SMARTCTL_FULL_FILE_PATH;
                    }
                    else
                    {
                        try
                        {
                            // Grab the SMART-related data for the detected disks.
                            populateSmartAttributes_againstSmartctl(SMARTCTL_FULL_FILE_PATH, detectedDisks);

                            // Consider the SMART-related data, and apply the SMART grades.
                            foreach (DetectedDisk disk in detectedDisks)
                            {
                                // Interpret the SMART output only if it is available and enabled.
                                if (disk.SmartSupport == DiskSmartSupport.AvailableAndEnabled)
                                {
                                    var smartAttributeFailures = disk.SmartAttributes.Values.Where(sav => false == sav.IsOK);
                                    if (true == smartAttributeFailures.Any())
                                    {
                                        // Okay, we know there is at least one failure reported by the SMART attributes.
                                        // We will want to list out the problems.
                                        // So see if there was also an overall failure.
                                        string smartGrade = "FAILED";
                                        if (disk.OverallFailurePredicted.HasValue && disk.OverallFailurePredicted.Value)
                                        {
                                            // Also an overall failure.
                                            smartGrade += " [overall failure predicted; also failures with SMART attributes: ";
                                        }
                                        else
                                        {
                                            // No overall failure predicted, but at least one SMART attribute failure reported.
                                            smartGrade += " [failures with SMART attributes: ";
                                        }
                                        bool isFirstFailure = true;
                                        foreach (var failure in smartAttributeFailures)
                                        {
                                            if (false == isFirstFailure)
                                            {
                                                smartGrade += ", ";
                                            }
                                            smartGrade += failure.AttributeDescription;
                                        }
                                        smartGrade += "]";

                                        disk.SmartGrade = smartGrade;
                                        disk.SmartPassed = false;
                                    }
                                    else
                                    {
                                        if (disk.OverallFailurePredicted.HasValue)
                                        {
                                            if (disk.OverallFailurePredicted.Value)
                                            {
                                                disk.SmartGrade = "FAILED [overall failure predicted]";
                                                disk.SmartPassed = false;
                                            }
                                            else
                                            {
                                                // We want to let the user know if we are passing it based on only the crude check (without detailed SMART data).
                                                if (disk.SmartAttributes.Values.Any())
                                                {
                                                    // We had some detailed SMART data, yet nothing to cause failure.
                                                    disk.SmartGrade = "PASSED [found SMART attributes]";
                                                    disk.SmartPassed = true;
                                                }
                                                else
                                                {
                                                    // We are passing it on the crude check, without any detailed SMART data.
                                                    disk.SmartGrade = "PASSED [no SMART attributes found]";
                                                    disk.SmartPassed = true;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            // We really don't know.
                                            disk.SmartGrade = "UNK [unable to find overall failure indicator]";
                                            disk.SmartPassed = null; // To indicate unknown.
                                        }
                                    }
                                }
                                else
                                {
                                    // SMART is not available and enabled on the disk.
                                    if (disk.SmartSupport == DiskSmartSupport.Unavailable)
                                    {
                                        disk.SmartGrade = "UNK [SMART unavailable]";
                                        disk.SmartPassed = null; // To indicate unknown.
                                    }
                                    else if (disk.SmartSupport == DiskSmartSupport.AvailableButDisabled)
                                    {
                                        disk.SmartGrade = "UNK [SMART disabled]";
                                        disk.SmartPassed = null; // To indicate unknown.
                                    }
                                    else
                                    {
                                        disk.SmartGrade = "UNK [unable to determine SMART support]";
                                        disk.SmartPassed = null; // To indicate unknown.
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            hadError = true;
                            errorMessage = "Encountered unexpected error while gathering SMART data: " + ex.Message;
                        }
                    }
                }
            }

            return detectedDisks;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>.
        /// <para>
        /// Prettifing the message includes:
        /// * Removing empty lines from the beginning and end.
        /// * Removing trailing spaces from every line.
        /// * Turning multiple consecutive empty lines between paragraphs into just one empty line.
        /// * Ensuring the commit message ends with a newline.
        /// * Removing every line starting with "#".
        /// </para>
        /// </summary>
        /// <param name="author">The <see cref="Signature"/> of who made the change.</param>
        /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param>
        /// <param name="message">The description of why a change was made to the repository.</param>
        /// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param>
        /// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param>
        /// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param>
        /// <param name="commentChar">Character that lines start with to be stripped if prettifyMessage is true.</param>
        /// <returns>The created <see cref="Commit"/>.</returns>
        public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable <Commit> parents, bool prettifyMessage, char?commentChar = null)
        {
            Ensure.ArgumentNotNull(message, "message");
            Ensure.ArgumentDoesNotContainZeroByte(message, "message");
            Ensure.ArgumentNotNull(author, "author");
            Ensure.ArgumentNotNull(committer, "committer");
            Ensure.ArgumentNotNull(tree, "tree");
            Ensure.ArgumentNotNull(parents, "parents");

            if (prettifyMessage)
            {
                message = Proxy.git_message_prettify(message, commentChar);
            }
            GitOid[] parentIds = parents.Select(p => p.Id.Oid).ToArray();

            ObjectId commitId = Proxy.git_commit_create(repo.Handle, null, author, committer, message, tree, parentIds);

            return(repo.Lookup <Commit>(commitId));
        }
Ejemplo n.º 28
0
        public static void interactiveLoop()
        {
            Console.Clear();

            for (int i = 0; i < Console.WindowWidth - LineBuffer[0].Length; i++)
            {
                Console.Write(" ");
            }
            Console.WriteLine(LineBuffer[0]);

            for (int i = 0; i < Console.WindowWidth; i++)
            {
                Console.Write("-");
            }
            Console.Write('\n');

            for (int i = 1; i < LineBuffer.Length; i++)
            {
                if (LineBuffer[i] != null)
                {
                    if (LineBuffer[i].Length < Console.WindowWidth)
                    {
                        Console.WriteLine(LineBuffer[i]);
                    }
                    else if (LineBuffer[i].Substring(0, 2) == "=>")
                    {
                        Console.WriteLine(LineBuffer[i]);
                    }
                    else
                    {
                        lineWrapString(LineBuffer[i]);
                    }
                }
            }

            if (selectedLinkIndex != -1)
            {
                Console.WriteLine(linksInPage[selectedLinkIndex]);
            }

            ConsoleKeyInfo keyRead = Console.ReadKey();

            if (keyRead.Key == ConsoleKey.Escape)
            {
                inInteractive = false;
            }
            else if (keyRead.Key == ConsoleKey.Enter)
            {
                string newInput;

                if (selectedLinkIndex == -1)
                {
                    Console.Write("url: ");
                    page     = "";
                    newInput = Console.ReadLine();
                }
                else
                {
                    newInput = linksInPage[selectedLinkIndex];
                }

                if (newInput.Length != 0)
                {
                    buildRequest(newInput);

                    string[] fetchedPage = fetchPage();

                    LineBuffer = fetchedPage;

                    if (LineBuffer[0] == "No such host is known.")
                    {
                        linksInPage = new string[0];
                    }
                    else
                    {
                        linksInPage = buildLinkSet(LineBuffer);
                    }


                    selectedLinkIndex = -1;
                }
            }
            else if (keyRead.Key == ConsoleKey.RightArrow)
            {
                if (selectedLinkIndex < linksInPage.Length - 1)
                {
                    selectedLinkIndex++;
                }
            }
            else if (keyRead.Key == ConsoleKey.LeftArrow)
            {
                if (selectedLinkIndex > -1)
                {
                    selectedLinkIndex--;
                }
            }

            if (selectedLinkIndex < 0)
            {
                selectedLinkIndex = -1;
            }
        }
Ejemplo n.º 29
0
 private void DisableEraserControl()
 {
     btnEraser.Enabled = false;
     isEraser = false;
 }
Ejemplo n.º 30
0
		public List<string> searchForValidity(List<string> str){
			connstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IskrabolDictionary.accdb";

			List<string> arrTemp = new List<string>();
			List<string> arrTemp2 = new List<string>();


						

			try
			{
				con = new OleDbConnection(connstr);
				cmd = new OleDbCommand();
				con.Open();

	 			for(int ctr = 0; ctr < str.Count; ctr++){			
	 					cmd.Connection = con;

						if(str[ctr].StartsWith("A")){
						 	cmd.CommandText = query0 + AWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'B'){
						 	cmd.CommandText = query0 + BWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'C'){
						 	cmd.CommandText = query0 + CWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'D'){
						 	cmd.CommandText = query0 + DWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'E'){
						 	cmd.CommandText = query0 + EWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'F'){
						 	cmd.CommandText = query0 + FWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'G'){
						 	cmd.CommandText = query0 + GWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'H'){
						 	cmd.CommandText = query0 + HWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'I'){
						 	cmd.CommandText = query0 + IWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'J'){
						 	cmd.CommandText = query0 + JWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'K'){
						 	cmd.CommandText = query0 + KWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'L'){
						 	cmd.CommandText = query0 + LWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'M'){
						 	cmd.CommandText = query0 + MWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'N'){
						 	cmd.CommandText = query0 + NWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'O'){
						 	cmd.CommandText = query0 + OWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'P'){
						 	cmd.CommandText = query0 + PWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'Q'){
						 	cmd.CommandText = query0 + QWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'R'){
						 	cmd.CommandText = query0 + RWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'S'){
						 	cmd.CommandText = query0 + SWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'T'){
						 	cmd.CommandText = query0 + TWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'U'){
						 	cmd.CommandText = query0 + UWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'V'){
						 	cmd.CommandText = query0 + VWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'W'){
						 	cmd.CommandText = query0 + WWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'X'){
						 	cmd.CommandText = query0 + XWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'Y'){
						 	cmd.CommandText = query0 + YWords + query1 + str[ctr] + "'";
						}else if(str[ctr][0] == 'Z'){
						 	cmd.CommandText = query0 + ZWords + query1 + str[ctr] + "'";
						}


						string temp = Convert.ToString(cmd.ExecuteScalar());
						if(temp.Equals(str[ctr])) {
							Console.WriteLine("Valid word: " + temp);
							arrTemp.Add(str[ctr]);
						}else{
							Console.WriteLine("Invalid word: " + str[ctr] );
							arrTemp2.Add(str[ctr]);
					}
				}
				

			}catch(Exception err){
				 MessageBox.Show(err.ToString());
			}finally{
				con.Close();
			}


			if(getValid == false){
				return arrTemp2;

			}else{
				getValid= false;
				return arrTemp;
			}

		}