public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            QueryDescriptor descriptor = new QueryDescriptor {
                PageIndex = 1, Conditions = new List <QueryCondition>(), OrderByMuilt = new List <OrderByClause>()
            };
            var provider = controllerContext.Controller.ValueProvider;

            var orderby = provider.GetValue("_query.orderbyasc");

            if (orderby != null)
            {
                descriptor.OrderBy = new OrderByClause {
                    Key = orderby.AttemptedValue, Order = OrderSequence.ASC
                };
            }
            orderby = provider.GetValue("_query.orderbydesc");
            if (orderby != null)
            {
                descriptor.OrderBy = new OrderByClause {
                    Key = orderby.AttemptedValue, Order = OrderSequence.DESC
                };
            }

            var pageSize = provider.GetValue("_query.pagesize");

            if (pageSize != null)
            {
                descriptor.PageSize = int.Parse(pageSize.AttemptedValue);
            }

            var pageIndex = provider.GetValue("page");

            if (pageIndex != null)
            {
                descriptor.PageIndex = int.Parse(pageIndex.AttemptedValue);
            }

            var request = controllerContext.HttpContext.Request;

            var keys = FilterExcludeKeys(controllerContext.HttpContext.Request);

            foreach (var k in keys)
            {
                var segments = k.Split('.');
                if (!ContainKeyword(segments) && segments.Last() != "operator")
                {
                    string value = provider.GetValue(k).AttemptedValue;
                    if (!string.IsNullOrEmpty(value))
                    {
                        string key = k.Substring(k.IndexOf('.') + 1);
                        string opt = QueryOperator.EQUAL.ToString();
                        if (provider.GetValue(k + ".operator") != null &&
                            !string.IsNullOrEmpty(provider.GetValue(k + ".operator").AttemptedValue))
                        {
                            opt = provider.GetValue(k + ".operator").AttemptedValue;
                        }

                        string valueType = "string";
                        if (provider.GetValue(k + ".valuetype") != null &&
                            !string.IsNullOrEmpty(provider.GetValue(k + ".valuetype").AttemptedValue))
                        {
                            valueType = provider.GetValue(k + ".valuetype").AttemptedValue;
                        }
                        object realValue = value;
                        switch (valueType.ToLower())
                        {
                        case "int":
                            realValue = int.Parse(value);
                            break;

                        case "float":
                            realValue = float.Parse(value);
                            break;

                        case "double":
                            realValue = double.Parse(value);
                            break;

                        case "decimal":
                            realValue = decimal.Parse(value);
                            break;

                        case "time":
                            realValue = DateTime.Parse(value);
                            break;

                        case "datetime":
                            realValue = DateTime.Parse(value);
                            break;

                        case "string":
                            break;

                        case "enum":
                            realValue = Enum.Parse(typeof(Enum), value);
                            break;

                        case "boolean":
                            realValue = Boolean.Parse(value);
                            break;

                        default:
                            throw new NotSupportedException(string.Format(valueType, "Value Type of {0} is not supported"));
                        }

                        //deal with duplicate key names.
                        string postfix = key.LastIndexOf('.') > -1 ? key.Substring(key.LastIndexOf('.') + 1) : "nope";
                        int    post;
                        if (int.TryParse(postfix, out post))
                        {
                            key = key.Substring(0, key.LastIndexOf('.'));
                        }

                        QueryCondition cond = new QueryCondition
                        {
                            Key       = key,
                            Operator  = OptDictionary[opt],
                            Value     = realValue,
                            ValueType = valueType
                        };
                        descriptor.Conditions.Add(cond);
                    }
                }
            }
            return(descriptor);
        }
示例#2
0
        public bool ReadBoolean(string attribName)
        {
            XmlAttribute attrib = GetGuaranteedAttribute(attribName);

            return(Boolean.Parse(attrib.Value));
        }
示例#3
0
        public void allServersToServerView()
        {
            ResetColours(GetAllCheckBoxes(filterpanel));

            serverview.Items.Clear();
            lvs.Enabled = false;

            var continueHit = new Dictionary <Control, int>();

            int count = 0;
            int max   = serversInstance.masterServers.Values.Count;

            foreach (Server s in serversInstance.masterServers.Values)
            {
                Controller.ToolStripText(toolStripStatusLabel1, ref statusStrip1,
                                         "Adding server " + count + "/" + max.ToString());
                count++;
                if (inactivecheck.Checked == false && s.getVariable(Protocol.Protocol.pingSTR) == null)
                {
                    ContinueHit(continueHit, inactivecheck);
                    continue;
                }

                if (mapcheck.Checked &&
                    (s.getVariable(Protocol.Protocol.mapNameSTR) == null ||
                     s.getVariable(Protocol.Protocol.mapNameSTR) == mapdrop.Text == false))
                {
                    ContinueHit(continueHit, mapcheck);
                    continue;
                }

                if (latencycheck.Checked &&
                    (s.getVariable(Protocol.Protocol.pingSTR) == null ||
                     (Controller.GetLatencyDrop(latencydrop) < Int32.Parse(s.getVariable(Protocol.Protocol.pingSTR)))))
                {
                    ContinueHit(continueHit, latencycheck);
                    continue;
                }

                if (punkbustercheck.Checked == false &&
                    (s.getVariable(Protocol.Protocol.punkBusterSTR) == null ||
                     s.getVariable(Protocol.Protocol.punkBusterSTR) == "1"))
                {
                    ContinueHit(continueHit, punkbustercheck);
                    continue;
                }

                if (pingcheck.Checked == false &&
                    (s.getVariable(Protocol.Protocol.maxPingSTR) == null ||
                     s.getVariable(Protocol.Protocol.pingSTR) == null ||
                     (Int32.Parse(s.getVariable(Protocol.Protocol.pingSTR)) >
                      Int32.Parse(s.getVariable(Protocol.Protocol.maxPingSTR)))))
                {
                    ContinueHit(continueHit, pingcheck);
                    continue;
                }

                if (gametypecheck.Checked &&
                    (s.getVariable(Protocol.Protocol.gameTypeSTR) == null ||
                     gametypedrop.Text.Equals(s.getVariable(Protocol.Protocol.gameTypeSTR)) == false))
                {
                    ContinueHit(continueHit, gametypecheck);
                    continue;
                }

                if (s.getVariable(Protocol.Protocol.clientsSTR) != null &&
                    s.getVariable(Protocol.Protocol.maxClientsSTR) != null)
                {
                    if (allowfullcheck.Checked == false &&
                        Int32.Parse(s.getVariable(Protocol.Protocol.clientsSTR)) >=
                        Int32.Parse(s.getVariable(Protocol.Protocol.maxClientsSTR)))
                    {
                        ContinueHit(continueHit, allowfullcheck);
                        continue;
                    }

                    if (allowemptycheck.Checked == false &&
                        Int32.Parse(s.getVariable(Protocol.Protocol.clientsSTR)) <= 0)
                    {
                        ContinueHit(continueHit, allowemptycheck);
                        continue;
                    }
                }
                else if (allowemptycheck.Checked == false && s.getVariable(Protocol.Protocol.clientsSTR) == null)
                {
                    ContinueHit(continueHit, allowemptycheck);
                    continue;
                }

                if (favouritecheck.Checked == false &&
                    (s.getVariable(Protocol.Protocol.favouriteSTR) == null ||
                     Boolean.Parse(s.getVariable(Protocol.Protocol.favouriteSTR)) == false))
                {
                    ContinueHit(continueHit, favouritecheck);
                    continue;
                }


                Controller.AddServerToServerView(s, serverview);
            }
            ListViewExtras.AutoResize(serverview);
            Controller.ToolStripText(toolStripStatusLabel1, ref statusStrip1, "Ready");
            lvs.Enabled = true;
            SetColours(continueHit, serversInstance.masterServers.Values.Count);
            if (mapdrop.Items.Count > 0 && mapdrop.Text == "")
            {
                mapdrop.Text = mapdrop.Items[0].ToString();
            }

            if (gametypedrop.Items.Count > 0 && gametypedrop.Text == "")
            {
                gametypedrop.Text = gametypedrop.Items[0].ToString();
            }
        }
示例#4
0
        private List <Configuration> buildConfigs(VariabilityModel vm, List <SamplingStrategies> binaryStrats, List <ExperimentalDesign> numericStrats, List <HybridStrategy> hybridStrats)
        {
            List <Configuration> result = new List <Configuration>();

            List <List <BinaryOption> > binaryConfigs = new List <List <BinaryOption> >();
            List <Dictionary <NumericOption, Double> > numericConfigs = new List <Dictionary <NumericOption, double> >();

            foreach (SamplingStrategies strat in binaryStrats)
            {
                switch (strat)
                {
                //Binary sampling heuristics
                case SamplingStrategies.ALLBINARY:
                    if (optionsToConsider.ContainsKey(SamplingStrategies.ALLBINARY))
                    {
                        List <List <BinaryOption> > variants =
                            vg.GenerateAllVariantsFast(vm.reduce(optionsToConsider[SamplingStrategies.ALLBINARY]));
                        binaryConfigs.AddRange(changeModel(vm, variants));
                    }
                    else
                    {
                        binaryConfigs.AddRange(vg.GenerateAllVariantsFast(vm));
                    }
                    break;

                case SamplingStrategies.SAT:
                    int numberSamples = 2;
                    foreach (Dictionary <string, string> parameters in binaryParams.satParameters)
                    {
                        if (parameters.ContainsKey("henard"))
                        {
                            try
                            {
                                bool b = Boolean.Parse(parameters["henard"]);
                                ((Z3VariantGenerator)vg).henard = b;
                            }
                            catch (FormatException e)
                            {
                                Console.Error.WriteLine(e);
                            }
                        }
                        if (parameters.ContainsKey("numConfigs"))
                        {
                            try
                            {
                                numberSamples = Int32.Parse(parameters["numConfigs"]);
                            }
                            catch (FormatException)
                            {
                                TWise tw = new TWise();
                                numberSamples = tw.generateT_WiseVariants_new(GlobalState.varModel, Int32.Parse(parameters["numConfigs"].Remove(0, 4))).Count;
                            }
                        }

                        if (parameters.ContainsKey("seed") && vg is Z3VariantGenerator)
                        {
                            uint seed = 0;
                            seed = UInt32.Parse(parameters["seed"]);
                            ((Z3VariantGenerator)vg).setSeed(seed);
                        }
                        if (optionsToConsider.ContainsKey(SamplingStrategies.SAT))
                        {
                            List <List <BinaryOption> > variants =
                                vg.GenerateUpToNFast(vm.reduce(optionsToConsider[SamplingStrategies.SAT]), numberSamples);
                            binaryConfigs.AddRange(changeModel(vm, variants));
                        }
                        else
                        {
                            binaryConfigs.AddRange(vg.GenerateUpToNFast(vm, numberSamples));
                        }
                        numberSamples = 2;
                    }
                    break;

                case SamplingStrategies.BINARY_RANDOM:
                    RandomBinary rb;
                    if (optionsToConsider.ContainsKey(SamplingStrategies.BINARY_RANDOM))
                    {
                        rb = new RandomBinary(vm.reduce(optionsToConsider[SamplingStrategies.BINARY_RANDOM]));
                    }
                    else
                    {
                        rb = new RandomBinary(vm);
                    }
                    foreach (Dictionary <string, string> expDesignParamSet in binaryParams.randomBinaryParameters)
                    {
                        binaryConfigs.AddRange(changeModel(vm, rb.getRandomConfigs(expDesignParamSet)));
                    }

                    break;

                case SamplingStrategies.OPTIONWISE:
                {
                    FeatureWise fw = new FeatureWise();
                    if (optionsToConsider.ContainsKey(SamplingStrategies.OPTIONWISE))
                    {
                        List <List <BinaryOption> > variants = fw.generateFeatureWiseConfigurations(GlobalState.varModel
                                                                                                    .reduce(optionsToConsider[SamplingStrategies.OPTIONWISE]));
                        binaryConfigs.AddRange(changeModel(vm, variants));
                    }
                    else
                    {
                        binaryConfigs.AddRange(fw.generateFeatureWiseConfigurations(GlobalState.varModel));
                    }
                }
                break;

                case SamplingStrategies.DISTANCE_BASED:
                    foreach (Dictionary <string, string> parameters in binaryParams.distanceMaxParameters)
                    {
                        DistanceBased distSampling = new DistanceBased(vm);
                        binaryConfigs.AddRange(distSampling.getSample(parameters));
                    }
                    break;

                //case SamplingStrategies.MINMAX:
                //    {
                //        MinMax mm = new MinMax();
                //        binaryConfigs.AddRange(mm.generateMinMaxConfigurations(GlobalState.varModel));

                //    }
                //    break;

                case SamplingStrategies.PAIRWISE:
                {
                    PairWise pw = new PairWise();
                    if (optionsToConsider.ContainsKey(SamplingStrategies.PAIRWISE))
                    {
                        List <List <BinaryOption> > variants = pw.generatePairWiseVariants(GlobalState.varModel
                                                                                           .reduce(optionsToConsider[SamplingStrategies.PAIRWISE]));
                        binaryConfigs.AddRange(changeModel(vm, variants));
                    }
                    else
                    {
                        binaryConfigs.AddRange(pw.generatePairWiseVariants(GlobalState.varModel));
                    }
                }
                break;

                case SamplingStrategies.NEGATIVE_OPTIONWISE:
                {
                    NegFeatureWise neg = new NegFeatureWise();        //2nd option: neg.generateNegativeFWAllCombinations(GlobalState.varModel));
                    if (optionsToConsider.ContainsKey(SamplingStrategies.NEGATIVE_OPTIONWISE))
                    {
                        List <List <BinaryOption> > variants = neg.generateNegativeFW(GlobalState.varModel
                                                                                      .reduce(optionsToConsider[SamplingStrategies.NEGATIVE_OPTIONWISE]));
                        binaryConfigs.AddRange(changeModel(vm, variants));
                    }
                    else
                    {
                        binaryConfigs.AddRange(neg.generateNegativeFW(GlobalState.varModel));
                    }
                }
                break;

                case SamplingStrategies.T_WISE:
                    foreach (Dictionary <string, string> ParamSet in binaryParams.tWiseParameters)
                    {
                        TWise tw = new TWise();
                        int   t  = 3;

                        foreach (KeyValuePair <String, String> param in ParamSet)
                        {
                            if (param.Key.Equals(TWise.PARAMETER_T_NAME))
                            {
                                t = Convert.ToInt16(param.Value);
                            }

                            if (optionsToConsider.ContainsKey(SamplingStrategies.T_WISE))
                            {
                                List <List <BinaryOption> > variants = tw.generateT_WiseVariants_new(
                                    vm.reduce(optionsToConsider[SamplingStrategies.T_WISE]), t);
                                binaryConfigs.AddRange(changeModel(vm, variants));
                            }
                            else
                            {
                                binaryConfigs.AddRange(tw.generateT_WiseVariants_new(vm, t));
                            }
                        }
                    }
                    break;
                }
            }

            //Experimental designs for numeric options
            if (numericStrats.Count != 0)
            {
                handleDesigns(numericStrats, numericConfigs, vm);
            }


            foreach (List <BinaryOption> binConfig in binaryConfigs)
            {
                if (numericConfigs.Count == 0)
                {
                    Configuration c = new Configuration(binConfig);
                    result.Add(c);
                }
                foreach (Dictionary <NumericOption, double> numConf in numericConfigs)
                {
                    Configuration c = new Configuration(binConfig, numConf);
                    result.Add(c);
                }
            }

            // Filter configurations based on the NonBooleanConstraints
            List <Configuration> filtered = new List <Configuration>();

            foreach (Configuration conf in result)
            {
                bool isValid = true;
                foreach (NonBooleanConstraint nbc in vm.NonBooleanConstraints)
                {
                    if (!nbc.configIsValid(conf))
                    {
                        isValid = false;
                    }
                }

                if (isValid)
                {
                    filtered.Add(conf);
                }
            }
            result = filtered;


            // Hybrid designs
            if (hybridStrats.Count != 0)
            {
                existingConfigurations = new List <Configuration>(result);
                List <Configuration> configurations = ExecuteHybridStrategy(hybridStrats, vm);

                if (numericStrats.Count == 0 && binaryStrats.Count == 0)
                {
                    result = configurations;
                }
                else
                {
                    // Prepare the previous sample sets
                    if (result.Count == 0 && binaryConfigs.Count == 0)
                    {
                        foreach (Dictionary <NumericOption, double> numConf in numericConfigs)
                        {
                            Configuration c = new Configuration(new Dictionary <BinaryOption, BinaryOption.BinaryValue>(), numConf);
                            result.Add(c);
                        }
                    }


                    if (hybridStrats.Count > 1)
                    {
                        // TODO handling of more than one hybrid strategy
                        throw new NotImplementedException("Handling more than one hybrid strategy has not been fully implemented yet!");
                    }
                    HybridStrategy hybridStrategy = hybridStrategies.First();
                    if (hybridStrategy.GetSamplingParameters(DistributionSensitive.ONLY_BINARY).Equals("true") && binaryStrats.Count > 0 ||
                        hybridStrategy.GetSamplingParameters(DistributionSensitive.ONLY_NUMERIC).Equals("true") && numericStrats.Count > 0)
                    {
                        result.AddRange(configurations);
                    }
                    else
                    {
                        // Build the cartesian product
                        List <Configuration> newResult = new List <Configuration>();
                        foreach (Configuration config in result)
                        {
                            foreach (Configuration hybridConfiguration in configurations)
                            {
                                Dictionary <BinaryOption, BinaryOption.BinaryValue> binOpts = new Dictionary <BinaryOption, BinaryOption.BinaryValue>(config.BinaryOptions);
                                Dictionary <NumericOption, double> numOpts = new Dictionary <NumericOption, double>(config.NumericOptions);

                                Dictionary <BinaryOption, BinaryOption.BinaryValue> hybridBinOpts = hybridConfiguration.BinaryOptions;
                                foreach (BinaryOption binOpt in hybridConfiguration.BinaryOptions.Keys)
                                {
                                    binOpts.Add(binOpt, hybridBinOpts[binOpt]);
                                }

                                Dictionary <NumericOption, double> hybridNumOpts = hybridConfiguration.NumericOptions;
                                foreach (NumericOption numOpt in hybridConfiguration.NumericOptions.Keys)
                                {
                                    numOpts.Add(numOpt, hybridNumOpts[numOpt]);
                                }

                                newResult.Add(new Configuration(binOpts, numOpts));
                            }
                        }
                        result = newResult;
                    }
                }
            }

            if (vm.MixedConstraints.Count == 0)
            {
                if (binaryStrats.Count == 1 && binaryStrats.Last().Equals(SamplingStrategies.ALLBINARY) && numericStrats.Count == 1 && numericStrats.Last() is FullFactorialDesign)
                {
                    return(replaceReference(result.ToList()));
                }
                return(replaceReference(result.Distinct().ToList()));
            }
            List <Configuration> unfilteredList        = result.Distinct().ToList();
            List <Configuration> filteredConfiguration = new List <Configuration>();

            foreach (Configuration toTest in unfilteredList)
            {
                bool isValid = true;
                foreach (MixedConstraint constr in vm.MixedConstraints)
                {
                    if (!constr.configIsValid(toTest))
                    {
                        isValid = false;
                    }
                }

                if (isValid)
                {
                    filteredConfiguration.Add(toTest);
                }
            }
            return(replaceReference(filteredConfiguration));
        }
示例#5
0
        private void StoreClasses(List <SearchResultEntry> classSchema)
        {
            if (ForestBase.CurrentClassesNode.Elements("All").FirstOrDefault() == null)
            {
                ForestBase.CurrentClassesNode.Add(new XElement("All", new XAttribute("value", "*")));
            }

            ForestBase.ClassCache.Add("All", "*");

            foreach (SearchResultEntry entry in classSchema)
            {
                bool isdefunct = false;

                if (entry.Attributes["isDefunct"] != null)
                {
                    string sdef = entry.Attributes["isDefunct"].GetValues(typeof(string))[0].ToString();

                    isdefunct = Boolean.Parse(sdef);
                }

                if (!isdefunct)
                {
                    string name = entry.Attributes["lDAPDisplayName"][0].ToString();

                    string oid = null;

                    foreach (byte[] value in entry.Attributes["schemaIDGUID"].GetValues(typeof(byte[])))
                    {
                        oid = new Guid(value).ToString();

                        break;
                    }

                    List <string> mustmay = new List <string>();

                    if (entry.Attributes["systemMustContain"] != null)
                    {
                        mustmay.AddRange(((string[])entry.Attributes["systemMustContain"].GetValues(typeof(string))).ToList());
                    }

                    if (entry.Attributes["systemMayContain"] != null)
                    {
                        mustmay.AddRange(((string[])entry.Attributes["systemMayContain"].GetValues(typeof(string))).ToList());
                    }

                    if (entry.Attributes["mayContain"] != null)
                    {
                        mustmay.AddRange(((string[])entry.Attributes["mayContain"].GetValues(typeof(string))).ToList());
                    }

                    if (entry.Attributes["mustContain"] != null)
                    {
                        mustmay.AddRange(((string[])entry.Attributes["mustContain"].GetValues(typeof(string))).ToList());
                    }

                    List <string> aux = new List <string>();

                    if (entry.Attributes["systemAuxiliaryClass"] != null)
                    {
                        aux.AddRange(((string[])entry.Attributes["systemAuxiliaryClass"].GetValues(typeof(string))).ToList());
                    }

                    if (entry.Attributes["auxiliaryClass"] != null)
                    {
                        aux.AddRange(((string[])entry.Attributes["auxiliaryClass"].GetValues(typeof(string))).ToList());
                    }

                    if (entry.Attributes["subClassOf"] != null)
                    {
                        string superior = entry.Attributes["subClassOf"][0].ToString();

                        AddSubClass(name, superior, true);
                    }

                    foreach (string relative in aux)
                    {
                        AddSubClass(name, relative);
                    }

                    if (ForestBase.RightsGuids.AddSafe <string, string>(oid, name))
                    {
                        ForestBase.CurrentExtendedRightsNode.Add(new XElement("GUID" + oid.ToUpperInvariant(), name));
                    }

                    foreach (string attributename in mustmay)
                    {
                        AssociateAttributesToClass(attributename, name);
                    }
                }
            }

            WalkClasses();
        }
        private void DIGITAL_SHOP_FLOOR_OS_Load(object sender, EventArgs e)
        {
            try
            {
                DataTable dtXML = ReadXML(Application.StartupPath + "\\Config.XML");
                lblDateTime.Text = string.Format(DateTime.Now.ToString("yyyy-MM-dd\nHH:mm:ss"));
                if (tblMain.Controls.Count > 0)
                {
                    tblMain.Controls.Clear();
                }
                //splashScreenManager1.ShowWaitForm();
                //splashScreenManager1.SetWaitFormCaption("Đợi chút...");
                //Load All Datatable
                DataTable dtOSD    = Db.SEL_OSD_DATA("Q");
                DataTable dtPROD   = Db.SEL_OS_PRODUCTION_DATA("Q");
                DataTable dtINV    = Db.SEL_OS_INV_DATA("Q");
                DataTable dtAbsent = Db.SEL_OS_ABSENT_DATA("Q");
                DataTable dtPOD    = Db.SEL_OS_POD_DATA("Q");
                tblMain.Controls.Add(UC_MENU, 0, 0);
                UC_MENU.OnMenuClick += MenuOnClick;
                UC_MENU.MoveLeave   += MoveLeaveClick;
                tblMain.Controls.Add(UC_OSD, 1, 0);

                tblMain.Controls.Add(UC_PRODUCTION, 2, 0);

                tblMain.Controls.Add(UC_POD, 0, 1);

                tblMain.Controls.Add(UC_INV, 1, 1);

                tblMain.Controls.Add(UC_ABSENT, 2, 1);
                UC_OSD.BindingData(dtOSD);
                UC_PRODUCTION.BindingData(dtPROD);
                UC_POD.BindingData(dtPOD);
                UC_INV.BindingData(dtINV);
                UC_ABSENT.BindingData(dtAbsent);
                pic_under.Visible = false;
                if (dtXML.Rows[0]["Office_YN"].ToString() == "Y")
                {
                    cmdBack.Visible = true;
                    btn_WS1.Visible = btn_WS2.Visible = btn_WS3.Visible = btn_WS4.Visible = false;
                    if (Screen.AllScreens.Length > 1)
                    {
                        MoveToScreen2();
                    }
                    this.WindowState = FormWindowState.Minimized;
                }
                if (dtXML.Rows[0]["Office_YN"].ToString() == "2Y")
                {
                    cmdBack.Visible = true;
                    start4Process();
                    btn_WS1.Visible = btn_WS2.Visible = btn_WS3.Visible = btn_WS4.Visible = true;
                }
                else
                {
                    start4Process();
                    btn_WS1.Visible = btn_WS2.Visible = btn_WS3.Visible = btn_WS4.Visible = true;
                }

                Dictionary <string, string>[] dtn = Init_File_XML(AppDomain.CurrentDomain.BaseDirectory + "App.xml", "form");
                cmdBack.Visible = Boolean.Parse(dtn[0]["cmdBack"]);
                //splashScreenManager1.CloseWaitForm();
            }
            catch
            {
                //splashScreenManager1.CloseWaitForm();
            }
        }
示例#7
0
        }//Scan

        /// <summary>
        /// Return the Value inside of an object that boxes the
        /// built in type or references the string
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="sValue"></param>
        /// <returns></returns>
        private object ReturnValue(string typeName, string sValue)
        {
            object o = null;

            switch (typeName)
            {
            case "String":
                o = sValue;
                break;

            case "Int16":
                o = Int16.Parse(sValue);
                break;

            case "UInt16":
                o = UInt16.Parse(sValue);
                break;

            case "Int32":
                o = Int32.Parse(sValue);
                break;

            case "UInt32":
                o = UInt32.Parse(sValue);
                break;

            case "Int64":
                o = Int64.Parse(sValue);
                break;

            case "UInt64":
                o = UInt64.Parse(sValue);
                break;

            case "Single":
                o = Single.Parse(sValue);
                break;

            case "Double":
                o = Double.Parse(sValue);
                break;

            case "Boolean":
                o = Boolean.Parse(sValue);
                break;

            case "Byte":
                o = Byte.Parse(sValue);
                break;

            case "SByte":
                o = SByte.Parse(sValue);
                break;

            case "Char":
                o = Char.Parse(sValue);
                break;

            case "Decimal":
                o = Decimal.Parse(sValue);
                break;
            }
            return(o);
        }//ReturnValue
示例#8
0
        public override void Initialize()
        {
            base.Initialize();
            form.Setup(this);

            PlayerControl.PlayerStateChanged  += OnPlayerStateChanged;
            PlayerControl.PlaybackCompleted   += OnPlaybackCompleted;
            PlayerControl.FormClosed          += OnFormClosed;
            PlayerControl.DragEnter           += OnDragEnter;
            PlayerControl.DragDrop            += OnDragDrop;
            PlayerControl.CommandLineFileOpen += OnCommandLineFileOpen;
            mpdnForm          = PlayerControl.Form;
            mpdnForm.Move    += OnMpdnFormMove;
            mpdnForm.KeyDown += OnMpdnFormKeyDown;
            mpdnForm.MainMenuStrip.MenuActivate += OnMpdnFormMainMenuActivated;
            form.Move            += OnFormMove;
            form.LocationChanged += OnFormLocationChanged;

            if (Settings.RememberWindowBounds)
            {
                form.RememberWindowBounds = Settings.RememberWindowBounds;
                form.WindowBounds         = Settings.WindowBounds;

                if (Settings.Columns != null && Settings.Columns.Count > 0)
                {
                    form.Columns = Settings.Columns;
                }
            }

            if (Settings.ShowPlaylistOnStartup)
            {
                form.Show(PlayerControl.VideoPanel);
            }

            if (Settings.AutomaticallyPlayFileOnStartup)
            {
                form.AutomaticallyPlayFileOnStartup = Settings.AutomaticallyPlayFileOnStartup;
            }

            if (Settings.RememberPlaylist)
            {
                if (Settings.RememberedFiles.Count > 0)
                {
                    List <PlaylistItem> playList = new List <PlaylistItem>();

                    foreach (var f in Settings.RememberedFiles)
                    {
                        string[]   s            = f.Split('|');
                        string     filePath     = s[0];
                        List <int> skipChapters = new List <int>();
                        if (s[1].Length > 0)
                        {
                            if (s[1].Contains(","))
                            {
                                skipChapters = s[1].Split(',').Select(int.Parse).ToList();
                            }
                            else
                            {
                                skipChapters.Add(int.Parse(s[1]));
                            }
                        }
                        int  endChapter = int.Parse(s[2]);
                        bool active     = Boolean.Parse(s[3]);

                        playList.Add(new PlaylistItem(filePath, skipChapters, endChapter, active));
                    }

                    int activeItem = (playList.FindIndex(i => i.Active) > -1) ? playList.FindIndex(i => i.Active) : 0;

                    form.Playlist = playList;
                    form.PopulatePlaylist();
                    form.RefreshPlaylist();
                    form.FocusPlaylistItem(activeItem);

                    if (Settings.AutomaticallyPlayFileOnStartup)
                    {
                        form.PlayActive();
                    }
                }
            }
        }
示例#9
0
        public object Create(object parent, object configContext, XmlNode section)
        {
            XPathNavigator navigator = section.CreateNavigator();

            string path = (string)navigator.Evaluate("string(@path)");

            if (path != null && path.Length > 0)
            {
                bool envFriendly = false;
                try
                {
                    envFriendly = Boolean.Parse((string)navigator.Evaluate("string(@envFriendly)"));
                }
                catch { }

                if (envFriendly)
                {
                    path = ChoEnvironmentSettings.ToEnvSpecificConfigFile(path);
                }

                path = ChoPath.GetFullPath(path);
                if (!File.Exists(path))
                {
                    throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, Resources.ES1002, path));
                }

                XmlDocument document = new XmlDocument();
                document.Load(path);

                section   = document.DocumentElement;
                navigator = section.CreateNavigator();
            }

            string typename = (string)navigator.Evaluate("string(@type)");

            if (typename == null || typename.Trim().Length == 0)
            {
                throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, Resources.ES1003, section.Name));
            }

            Type type = Type.GetType(typename);

            if (type == null)
            {
                type = ChoType.GetType(typename);
            }

            if (type == null)
            {
                throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, Resources.ES1004, typename));
            }

            ChoConfigFilesMapper.Add(section.Name, path);

            XmlSerializer serializer = new XmlSerializer(type);

            try
            {
                return(serializer.Deserialize(new XmlNodeReader(section)));
            }
            catch
            {
                if (section.Name != type.Name && section.Name.ToUpper() == type.Name.ToUpper())
                {
                    XmlNode newSection = new XmlDocument().CreateElement(type.Name);
                    newSection.InnerXml = section.InnerXml;
                    section             = newSection;
                }
                return(serializer.Deserialize(new XmlNodeReader(section)));
            }
        }
示例#10
0
 public override void CheckRules(DataAction dataAction)
 {
     foreach (DataRow drField in _dsStruct.Tables[0].Rows)
     {
         if (!Boolean.Parse(drField["Visible"].ToString()))
         {
             continue;
         }
         string fieldName = drField["FieldName"].ToString();
         int    pType     = Int32.Parse(drField["Type"].ToString());
         if (pType == 3 || pType == 6)
         {
             continue;
         }
         if (Boolean.Parse(drField["IsBetween"].ToString()))
         {
             IsBetweenCheckRules(drField);
             continue;
         }
         if (!Boolean.Parse(drField["AllowNull"].ToString()))
         {
             if (_drCurrentMaster[fieldName].ToString() == string.Empty)
             {
                 _drCurrentMaster.SetColumnError(fieldName, "Phải nhập");
             }
             else
             {
                 _drCurrentMaster.SetColumnError(fieldName, string.Empty);
             }
         }
         if (_drCurrentMaster[fieldName].ToString() == string.Empty)
         {
             continue;
         }
         int value = 0;
         if (!Int32.TryParse(_drCurrentMaster[fieldName].ToString(), out value))
         {
             continue;
         }
         if (drField["MinValue"].ToString() != string.Empty)
         {
             int minValue = Int32.Parse(drField["MinValue"].ToString());
             if (minValue > value)
             {
                 _drCurrentMaster.SetColumnError(fieldName, "Phải lớn hơn hoặc bằng " + minValue.ToString());
                 continue;
             }
             else
             {
                 _drCurrentMaster.SetColumnError(fieldName, string.Empty);
             }
         }
         if (drField["MaxValue"].ToString() != string.Empty)
         {
             int maxValue = Int32.Parse(drField["MaxValue"].ToString());
             if (maxValue < value)
             {
                 _drCurrentMaster.SetColumnError(fieldName, "Phải nhỏ hơn hoặc bằng " + maxValue.ToString());
             }
             else
             {
                 _drCurrentMaster.SetColumnError(fieldName, string.Empty);
             }
         }
     }
 }
示例#11
0
        public void GenFilterString()
        {
            string ps = "1 = 1";

            if (DsData == null || DsData.Tables.Count == 0 || DsData.Tables[0].Rows.Count == 0)
            {
                _psString = ps;
                return;
            }
            DataRow drData = DsData.Tables[0].Rows[0];

            foreach (DataRow drField in _dsStruct.Tables[0].Rows)
            {
                string fieldName = drField["FieldName"].ToString();
                string value     = string.Empty;
                if (!Boolean.Parse(drField["IsBetween"].ToString()))
                {
                    value = drData[fieldName].ToString();
                    if (value == string.Empty)
                    {
                        continue;
                    }
                }
                else
                if (drData[fieldName + "1"].ToString() == string.Empty && drData[fieldName + "2"].ToString() == string.Empty)
                {
                    continue;
                }
                if (Boolean.Parse(drField["SpecialCond"].ToString()))
                {
                    continue;
                }
                int    pType = Int32.Parse(drField["Type"].ToString());
                string tmp = string.Empty, and = " and ", field = fieldName, operato = string.Empty;
                if (Boolean.Parse(drField["IsMaster"].ToString()))
                {
                    if (_drTable["mtTableID"].ToString() != string.Empty && _drTable["mtAlias"].ToString() != string.Empty)
                    {
                        field = _drTable["mtAlias"].ToString() + "." + fieldName;
                    }
                }
                else
                if (_drTable["dtTableID"].ToString() != string.Empty && _drTable["dtAlias"].ToString() != string.Empty)
                {
                    field = _drTable["dtAlias"].ToString() + "." + fieldName;
                }
                if (Boolean.Parse(drField["IsBetween"].ToString()))
                {
                    if (drData[fieldName + "1"].ToString() != string.Empty)
                    {
                        operato = " >= ";
                        value   = "'" + drData[fieldName + "1"].ToString() + "'";
                        tmp     = and + field + operato + value;
                    }
                    if (drData[fieldName + "2"].ToString() != string.Empty)
                    {
                        operato = " <= ";
                        value   = "'" + drData[fieldName + "2"].ToString() + "'";
                        tmp    += and + field + operato + value;
                    }
                }
                else
                {
                    if (pType == 1 || pType == 2 || pType == 13)
                    {
                        operato = " like ";
                    }
                    else
                    {
                        operato = " = ";
                    }
                    if (pType == 10)
                    {
                        if (Boolean.Parse(value) == true)
                        {
                            value = "1";
                        }
                        else
                        {
                            value = "0";
                        }
                    }
                    else if (pType == 1 || pType == 2)
                    {
                        value = "'" + value + "%'";
                    }
                    else if (pType == 13)
                    {
                        value = "N'%" + value + "%'";
                    }
                    else
                    {
                        value = "'" + value + "'";
                    }
                    tmp = and + field + operato + value;
                }
                ps += tmp;
            }
            _psString = ps;
        }
示例#12
0
        public override Tree VisitLiteral(LiteralContext context)
        {
            IToken  symbol;
            String  text;
            Object  value;
            TypeTag type;

            switch (context.literalType)
            {
            case INT:
                symbol = context.IntegerLiteral().Symbol;
                text   = symbol.Text;
                if (Int32.TryParse(text, out var intLit))
                {
                    type  = TypeTag.INT;
                    value = intLit;
                }
                else if (Int64.TryParse(text, out var longLit))
                {
                    type  = TypeTag.LONG;
                    value = longLit;
                }
                else
                {
                    log.error(
                        new DiagnosticPosition(context.Start.Line, context.Start.Column),
                        messages.intLiteratTooBig, context.GetText()
                        );
                    type  = TypeTag.ERROR;
                    value = 0;
                }
                break;

            case FLOAT:
                symbol = context.FloatingPointLiteral().Symbol;
                text   = symbol.Text;
                if (text.EndsWith("f") || text.EndsWith("F"))
                {
                    text = text.Substring(0, text.Length - 1);
                    type = TypeTag.FLOAT;
                    if (Single.TryParse(text, out var floatLit))
                    {
                        value = floatLit;
                    }
                    else
                    {
                        value = 0;
                        logFloatTooBig(context);
                    }
                }
                else if (text.EndsWith("d") || text.EndsWith("D"))
                {
                    type = TypeTag.DOUBLE;
                    if (Double.TryParse(text, out var doubleLit))
                    {
                        value = doubleLit;
                    }
                    else
                    {
                        value = 0;
                        logFloatTooBig(context);
                    }
                }
                else if (Single.TryParse(text, out var floatLit))
                {
                    type  = TypeTag.FLOAT;
                    value = floatLit;
                }
                else if (Double.TryParse(text, out var doubleLit))
                {
                    type  = TypeTag.DOUBLE;
                    value = doubleLit;
                }
                else
                {
                    type  = TypeTag.ERROR;
                    value = 0;
                    logFloatTooBig(context);
                }
                break;

            case BOOLEAN:
                symbol = context.BooleanLiteral().Symbol;
                text   = symbol.Text;
                type   = TypeTag.BOOLEAN;
                value  = Boolean.Parse(text);
                break;

            case CHAR:
                symbol = context.CharLiteral().Symbol;
                text   = symbol.Text;
                type   = TypeTag.CHAR;
                value  = parseCharLiteral(text);
                break;

            case CSTRING:
                symbol = context.CStringLiteral().Symbol;
                text   = symbol.Text;
                type   = TypeTag.C_STRING;
                value  = parseStringLiteral(text);
                break;

            case NULL:
                value  = null;
                symbol = context.NULL().Symbol;
                type   = TypeTag.NULL;
                text   = "null";
                break;

            default:
                throw new InvalidOperationException();
            }

            int line        = symbol.Line;
            int startColumn = symbol.Column;
            int endColumn   = startColumn + text.Length;

            return(new LiteralExpression(line, startColumn, line, endColumn, type, value));
        }
示例#13
0
        // Read file to initalize the list of Anime
        private bool ReadXat()
        {
            StreamReader sr   = new StreamReader(_ai.Path);
            string       line = sr.ReadLine();

            if (String.IsNullOrEmpty(line))
            {
                return(false);
            }

            string[] info = line.Split('\t');
            if (info.Length != 3)
            {
                return(false);
            }

            //int lasttotal = _ai.Total;

            int it;

            if (!Int32.TryParse(info[0], out it))
            {
                MessageBox.Show(this, "The line 1 is wrong.", "Read error",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                sr.Close();

                return(false);
            }
            else
            {
                _ai.Total = it;
            }

            long lt;

            if (!Int64.TryParse(info[1], out lt))
            {
                MessageBox.Show(this, "The line 1 is wrong.", "Read error",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                sr.Close();

                return(false);
            }
            else
            {
                _ai.Space = lt;
            }

            uint ut;

            if (!UInt32.TryParse(info[2], out ut))
            {
                MessageBox.Show(this, "The line 1 is wrong.", "Read error",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                sr.Close();

                return(false);
            }
            else
            {
                _ai.Uid = ut;
            }

            List <Anime> lstAnime = new List <Anime>();
            int          iErr     = 0;

            try
            {
                while (!String.IsNullOrEmpty(line = sr.ReadLine()))
                {
                    iErr++;
                    info = line.Split('\t');

                    Anime ani = new Anime();
                    ani.ID         = UInt32.Parse(info[0]);
                    ani.Title      = info[1];
                    ani.Name       = info[2];
                    ani.Year       = UInt32.Parse(info[3]);
                    ani.Season     = (PlaySeason)Enum.Parse(typeof(PlaySeason), info[4]);
                    ani.Type       = (MediaType)Enum.Parse(typeof(MediaType), info[5]);
                    ani.Format     = (MergeFormat)Enum.Parse(typeof(MergeFormat), info[6]);
                    ani.SubTeam    = info[7];
                    ani.SubStyle   = (SubStyles)Enum.Parse(typeof(SubStyles), info[8]);
                    ani.Path       = info[9];
                    ani.Size       = Int64.Parse(info[10]);
                    ani.Store      = Boolean.Parse(info[11]);
                    ani.Enjoy      = Boolean.Parse(info[12]);
                    ani.Grade      = Int32.Parse(info[13]);
                    ani.CreateTime = DateTime.Parse(info[14]);
                    ani.UpdateTime = DateTime.Parse(info[15]);
                    ani.Kana       = info[16];
                    ani.Episode    = info[17];
                    ani.Inc        = info[18];
                    ani.Note       = info[19];

                    //_lani.Add(ani);
                    lstAnime.Add(ani);
                }

                //_lani.RemoveRange(0, lasttotal);
            }
            catch (Exception)
            {
                MessageBox.Show(this, String.Format("The line {0} is wrong.", iErr + 1), "Read error",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);

                //_lani.RemoveRange(lasttotal, iErr - 1);
                lstAnime.Clear();

                return(false);
            }
            finally
            {
                sr.Close();
            }

            if (!_ai.IsNew)
            {
                ResetAll();
            }

            _ai.IsNew   = false;
            _ai.IsSaved = true;
            _ai.Backup();

            this.folvAnime.SetObjects(lstAnime);

            this.tctlAnime.SelectedTab.Text        = _ai.Name;
            this.tctlAnime.SelectedTab.ToolTipText = _ai.Path;
            this.tsslTotal.Text = String.Format("Total: {0}", _ai.Total);
            this.tsslSpace.Text = String.Format("Total Size: {0:#,##0.#0} GB", _ai.Space / 1073741824D);

            return(true);
        }
示例#14
0
        public static async IAsyncEnumerable <Schema> GetRefreshSchemas(IConnectionFactory connFactory,
                                                                        RepeatedField <Schema> refreshSchemas, int sampleSize = 5)
        {
            var conn = connFactory.GetConnection();
            await conn.OpenAsync();

            foreach (var schema in refreshSchemas)
            {
                if (string.IsNullOrWhiteSpace(schema.Query))
                {
                    yield return(await GetRefreshSchemaForTable(connFactory, schema, sampleSize));

                    continue;
                }

                var cmd = connFactory.GetCommand(schema.Query, conn);

                var reader = await cmd.ExecuteReaderAsync();

                var schemaTable = reader.GetSchemaTable();

                var properties = new List <Property>();
                if (schemaTable != null)
                {
                    var unnamedColIndex = 0;

                    // get each column and create a property for the column
                    foreach (DataRow row in schemaTable.Rows)
                    {
                        // get the column name
                        var colName = row["ColumnName"].ToString();
                        if (string.IsNullOrWhiteSpace(colName))
                        {
                            colName = $"UNKNOWN_{unnamedColIndex}";
                            unnamedColIndex++;
                        }

                        // create property
                        var property = new Property
                        {
                            Id                = Utility.Utility.GetSafeName(colName, '"'),
                            Name              = colName,
                            Description       = "",
                            Type              = GetPropertyType(row),
                            TypeAtSource      = row["DataType"].ToString(),
                            IsKey             = Boolean.Parse(row["IsKey"].ToString()),
                            IsNullable        = Boolean.Parse(row["AllowDBNull"].ToString()),
                            IsCreateCounter   = false,
                            IsUpdateCounter   = false,
                            PublisherMetaJson = ""
                        };

                        // add property to properties
                        properties.Add(property);
                    }
                }

                // add only discovered properties to schema
                schema.Properties.Clear();
                schema.Properties.AddRange(properties);

                // get sample and count
                yield return(await AddSampleAndCount(connFactory, schema, sampleSize));
            }

            await conn.CloseAsync();
        }
示例#15
0
 public static bool isEnabled(string section)
 {
     return(Boolean.Parse(Config[section]["enabled"]));
 }
        public static bool ExtractBool(XmlDocument document, string path)
        {
            string s = Extract(document, path, String.Empty);

            return(Boolean.Parse(s));
        }
示例#17
0
 /// <summary> Reads "value" as bool from "key" in "section" from INI configuration. </summary>
 public bool ReadBool(string section, string key)
 {
     return(Boolean.Parse(_INI.GetValue(section, key).ToLower()));
 }
        public ActionResult ImportCsv(FormCollection form)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            try
            {
                var file = Request.Files["importcsvfile"];
                if (file != null && file.ContentLength > 0)
                {
                    int count = 0;

                    using (var reader = new StreamReader(file.InputStream))
                    {
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            if (String.IsNullOrWhiteSpace(line))
                            {
                                continue;
                            }
                            string[] tmp = line.Split(',');

                            var  email    = "";
                            bool isActive = true;
                            //parse
                            if (tmp.Length == 1)
                            {
                                //"email" only
                                email = tmp[0].Trim();
                            }
                            else if (tmp.Length == 2)
                            {
                                //"email" and "active" fields specified
                                email    = tmp[0].Trim();
                                isActive = Boolean.Parse(tmp[1].Trim());
                            }
                            else
                            {
                                throw new NopException("Wrong file format");
                            }

                            //import
                            var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmail(email);
                            if (subscription != null)
                            {
                                subscription.Email  = email;
                                subscription.Active = isActive;
                                _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
                            }
                            else
                            {
                                subscription = new NewsLetterSubscription()
                                {
                                    Active       = isActive,
                                    CreatedOnUtc = DateTime.UtcNow,
                                    Email        = email,
                                    NewsLetterSubscriptionGuid = Guid.NewGuid()
                                };
                                _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
                            }
                            count++;
                        }
                        SuccessNotification(String.Format(_localizationService.GetResource("Admin.Promotions.NewsLetterSubscriptions.ImportEmailsSuccess"), count));
                        return(RedirectToAction("List"));
                    }
                }
                ErrorNotification(_localizationService.GetResource("Admin.Common.UploadFile"));
                return(RedirectToAction("List"));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
                return(RedirectToAction("List"));
            }
        }
示例#19
0
        internal static object ConvertTo(this object value, Type toType, Func <object> getConverter,
                                         IServiceProvider serviceProvider, out Exception exception)
        {
            exception = null;
            if (value == null)
            {
                return(null);
            }

            if (value is string str)
            {
                //If there's a [TypeConverter], use it
                object converter;
                try
                {                 //minforetriver can fail
                    converter = getConverter?.Invoke();
                }
                catch (Exception e)
                {
                    exception = e;
                    return(null);
                }
                try
                {
                    if (converter is IExtendedTypeConverter xfExtendedTypeConverter)
                    {
                        return(xfExtendedTypeConverter.ConvertFromInvariantString(str, serviceProvider));
                    }
                    if (converter is TypeConverter xfTypeConverter)
                    {
                        return(xfTypeConverter.ConvertFromInvariantString(str));
                    }
                }
                catch (Exception e)
                {
                    exception = e as XamlParseException ?? new XamlParseException($"Type converter failed: {e.Message}", serviceProvider, e);
                    return(null);
                }
                var converterType = converter?.GetType();
                if (converterType != null)
                {
                    var convertFromStringInvariant = converterType.GetRuntimeMethod("ConvertFromInvariantString",
                                                                                    new[] { typeof(string) });
                    if (convertFromStringInvariant != null)
                    {
                        try
                        {
                            return(convertFromStringInvariant.Invoke(converter, new object[] { str }));
                        }
                        catch (Exception e)
                        {
                            exception = new XamlParseException("Type conversion failed", serviceProvider, e);
                            return(null);
                        }
                    }
                }
                var ignoreCase = (serviceProvider?.GetService(typeof(IConverterOptions)) as IConverterOptions)?.IgnoreCase ?? false;

                //If the type is nullable, as the value is not null, it's safe to assume we want the built-in conversion
                if (toType.GetTypeInfo().IsGenericType&& toType.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    toType = Nullable.GetUnderlyingType(toType);
                }

                //Obvious Built-in conversions
                try
                {
                    if (toType.GetTypeInfo().IsEnum)
                    {
                        return(Enum.Parse(toType, str, ignoreCase));
                    }
                    if (toType == typeof(SByte))
                    {
                        return(SByte.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Int16))
                    {
                        return(Int16.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Int32))
                    {
                        return(Int32.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Int64))
                    {
                        return(Int64.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Byte))
                    {
                        return(Byte.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(UInt16))
                    {
                        return(UInt16.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(UInt32))
                    {
                        return(UInt32.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(UInt64))
                    {
                        return(UInt64.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Single))
                    {
                        return(Single.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Double))
                    {
                        return(Double.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Boolean))
                    {
                        return(Boolean.Parse(str));
                    }
                    if (toType == typeof(TimeSpan))
                    {
                        return(TimeSpan.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(DateTime))
                    {
                        return(DateTime.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Char))
                    {
                        Char.TryParse(str, out var c);
                        return(c);
                    }
                    if (toType == typeof(String) && str.StartsWith("{}", StringComparison.Ordinal))
                    {
                        return(str.Substring(2));
                    }
                    if (toType == typeof(String))
                    {
                        return(value);
                    }
                    if (toType == typeof(Decimal))
                    {
                        return(Decimal.Parse(str, CultureInfo.InvariantCulture));
                    }
                }
                catch (FormatException fe)
                {
                    exception = fe;
                    return(null);
                }
            }

            //if the value is not assignable and there's an implicit conversion, convert
            if (value != null && !toType.IsAssignableFrom(value.GetType()))
            {
                var opImplicit = value.GetType().GetImplicitConversionOperator(fromType: value.GetType(), toType: toType)
                                 ?? toType.GetImplicitConversionOperator(fromType: value.GetType(), toType: toType);

                if (opImplicit != null)
                {
                    value = opImplicit.Invoke(null, new[] { value });
                    return(value);
                }
            }

            var nativeValueConverterService = DependencyService.Get <INativeValueConverterService>();

            object nativeValue = null;

            if (nativeValueConverterService != null && nativeValueConverterService.ConvertTo(value, toType, out nativeValue))
            {
                return(nativeValue);
            }

            return(value);
        }
示例#20
0
        /// <summary>
        /// Verifies if user has password
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task <bool> HasPasswordAsync(TUser user)
        {
            var hasPassword = !string.IsNullOrEmpty(userTable.GetPasswordHash(user.Id));

            return(Task.FromResult <bool>(Boolean.Parse(hasPassword.ToString())));
        }
示例#21
0
        public void ExecuteBefore()
        {
            var drCur = _data.DsData.Tables[0].Rows[_data.CurMasterIndex];

            if (drCur.RowState == DataRowState.Deleted)
            {
                return;
            }

            // trường hợp duyệt
            if (drCur.RowState == DataRowState.Modified &&
                Boolean.Parse(drCur["Duyet", DataRowVersion.Current].ToString()) == true &&
                Boolean.Parse(drCur["Duyet", DataRowVersion.Original].ToString()) == false)
            {
                return;
            }

            // trường hợp bỏ duyệt
            if (drCur.RowState == DataRowState.Modified &&
                Boolean.Parse(drCur["Duyet", DataRowVersion.Current].ToString()) == false &&
                Boolean.Parse(drCur["Duyet", DataRowVersion.Original].ToString()) == true)
            {
                return;
            }

            string mtid      = drCur["MTID"].ToString();
            var    listTable = _data.DsData.Tables;
            var    sprows    = listTable["mDTKhuyenMaiSP"].Select("MTID = '" + mtid + "'");

            foreach (var row in sprows)
            {
                if ((row["MaSPTang"] != DBNull.Value || row["SLTang"] != DBNull.Value) && row["NhieuSP"] != DBNull.Value)
                {
                    XtraMessageBox.Show("Không được chọn nhiều sản phẩm khi đã nhập sản phẩm tặng hoặc số lượng tặng", Config.GetValue("PackageName").ToString());
                    _info.Result = false;
                    return;
                }
                else if ((row["MaSPTang"] == DBNull.Value || row["SLTang"] == DBNull.Value) && row["NhieuSP"] == DBNull.Value)
                {
                    XtraMessageBox.Show("Phải nhập đủ sản phẩm tặng và số lượng tặng", Config.GetValue("PackageName").ToString());
                    _info.Result = false;
                    return;
                }
                else if (row["MaSPTang"] == DBNull.Value && row["SLTang"] == DBNull.Value && row["NhieuSP"] == DBNull.Value)
                {
                    XtraMessageBox.Show("Phải nhập sản phẩm tặng hoặc nhiều sản phẩm tặng.", Config.GetValue("PackageName").ToString());
                    _info.Result = false;
                    return;
                }
                else if (row["MaSPTang"] == DBNull.Value && row["SLTang"] == DBNull.Value && row["NhieuSP"] != DBNull.Value)
                {
                    string spid = row["DTSPID"].ToString();
                    string mess = "Phải nhập ít nhất một sản phẩm và số lượng khi chọn nhiều sản phẩm tặng.";
                    if (!listTable.Contains("mDTKMNhieuSP"))
                    {
                        XtraMessageBox.Show(mess, Config.GetValue("PackageName").ToString());
                        _info.Result = false;
                        return;
                    }

                    var dataRows = listTable["mDTKMNhieuSP"].Select("DTSPID = " + spid);
                    if (dataRows.Length == 0)
                    {
                        XtraMessageBox.Show(mess, Config.GetValue("PackageName").ToString());
                        _info.Result = false;
                        return;
                    }
                }
            }
        }
示例#22
0
 /**
  * The boolean value of this atom.
  *
  * @return the value of this atom expressed as a boolean value. If the atom
  *         consists of the characters "true" (independent of case) the value
  *         will be true. For any other values, the value will be false.
  *
  */
 public bool boolValue()
 {
     return(Boolean.Parse(atomValue()));
 }
示例#23
0
        private void StoreAttributes(List <SearchResultEntry> attributeSchema)
        {
            foreach (SearchResultEntry entry in attributeSchema)
            {
                bool isdefunct = false;

                ActiveDirectorySyntax syntax = ActiveDirectorySyntax.CaseIgnoreString;

                if (entry.Attributes["isDefunct"] != null)
                {
                    string sdef = entry.Attributes["isDefunct"].GetValues(typeof(string))[0].ToString();

                    isdefunct = Boolean.Parse(sdef);
                }

                if (!isdefunct)
                {
                    #region name + syntax

                    string name = entry.Attributes["lDAPDisplayName"][0].ToString();

                    string asyntax = entry.Attributes["attributeSyntax"][0].ToString();

                    int omsyntax = 0;

                    if (Int32.TryParse(entry.Attributes["oMSyntax"][0].ToString(), out omsyntax))
                    {
                        syntax = DecodeLDAPAttributeSyntax(asyntax, omsyntax);
                    }

                    long systemflags = 0;

                    if (entry.Attributes.Contains("systemFlags"))
                    {
                        long.TryParse(entry.Attributes["systemFlags"][0].ToString(), out systemflags);
                    }

                    long linkid = 0;

                    if (entry.Attributes.Contains("linkID"))
                    {
                        long.TryParse(entry.Attributes["linkID"][0].ToString(), out linkid);
                    }



                    bool flags = false;
                    if ((systemflags & 4) == 4)
                    {
                        flags = true;
                    }

                    ForestBase.AttributeCache.Add(name, new AttributeSchema(name, syntax, flags, linkid));

                    ForestBase.CurrentAttributesNode.Add(new XElement(name, syntax.ToString(), new XAttribute("checked", "0"), new XAttribute("constructed", Convert.ToInt32(flags)), new XAttribute("linked", Convert.ToInt32(linkid))));

                    ForestBase.CurrentClassesNode.Elements("All").FirstOrDefault().Add(new XElement("Attribute", name));

                    #endregion

                    #region guids

                    string oid = String.Empty;

                    foreach (byte[] value in entry.Attributes["schemaIDGUID"].GetValues(typeof(byte[])))
                    {
                        oid = new Guid(value).ToString();

                        if (ForestBase.RightsGuids.AddSafe <string, string>(oid, name))
                        {
                            ForestBase.CurrentExtendedRightsNode.Add(new XElement("GUID" + oid.ToUpperInvariant(), name));
                        }
                    }

                    if (entry.Attributes.Contains("attributeSecurityGUID"))
                    {
                        foreach (byte[] value in entry.Attributes["attributeSecurityGUID"].GetValues(typeof(byte[])))
                        {
                            oid = new Guid(value).ToString();

                            if (ForestBase.RightsGuids.AddSafe <string, string>(oid, name))
                            {
                                ForestBase.CurrentExtendedRightsNode.Add(new XElement("GUID" + oid.ToUpperInvariant(), name));
                            }
                        }
                    }

                    #endregion
                }
            }
        }
示例#24
0
        private void ParseSchema()
        {
            m_TextFields = new TextFieldCollection();

            XmlDocument doc = new XmlDocument();

            doc.Load(m_FilePath);

            XmlNodeList lst = doc.GetElementsByTagName("TABLE");

            if (lst.Count == 0)
            {
                throw new XmlException("Could not locate the 'TABLE' node." + Environment.NewLine +
                                       "The Schema is case sensitive.");
            }

            if (lst.Count > 1)
            {
                throw new XmlException("There are multiple 'TABLE' nodes." + Environment.NewLine +
                                       "There can be only one 'TABLE' node.");
            }

            XmlNode tableNode = lst[0];

            foreach (XmlAttribute attribute in tableNode.Attributes)
            {
                switch (attribute.Name.ToLower())
                {
                case "name":
                    m_TableName = attribute.Value;
                    break;

                case "fileformat":
                    m_FileFormat = (FileFormat)Enum.Parse(typeof(FileFormat), attribute.Value);
                    break;

                case "delimiter":
                    m_FieldDelimiter = attribute.Value[0];
                    break;

                case "quotecharacter":
                    m_QuoteDelimiter = attribute.Value[0];
                    break;

                default:
                    throw new NotSupportedException("The attribute '" + attribute.Name + "' is not supported.");
                }
            }

            lst = doc.GetElementsByTagName("FIELD");
            TextField field;
            string    name = "";
            TypeCode  datatype;
            bool      quoted = false;
            int       length = 0;

            foreach (XmlNode node in lst)
            {
                name     = "";
                datatype = TypeCode.String;
                quoted   = false;
                length   = 0;

                foreach (XmlAttribute fattribute in node.Attributes)
                {
                    switch (fattribute.Name.ToLower())
                    {
                    case "name":
                        name = fattribute.Value;
                        break;

                    case "datatype":
                        datatype = (TypeCode)Enum.Parse(typeof(TypeCode), fattribute.Value);
                        break;

                    case "quoted":
                        quoted = Boolean.Parse(fattribute.Value);
                        break;

                    case "length":
                        length = Int32.Parse(fattribute.Value);
                        break;

                    default:
                        throw new NotSupportedException("The attribute '" + fattribute.Name + "' is not supported.");
                    }
                }

                if (name.Trim().Length == 0)
                {
                    throw new ArgumentException("The attribute 'Name' cannot be blank");
                }

                if (m_FileFormat == FileFormat.FixedWidth && length <= 0)
                {
                    throw new ArgumentOutOfRangeException("A 'Length' attribute > 0 must be specified for all fields in a fixed width file.");
                }

                if (m_FileFormat == FileFormat.FixedWidth)
                {
                    field = new TextField(name, datatype, length);
                }
                else
                {
                    field = new TextField(name, datatype, quoted);
                }

                m_TextFields.Add(field);
            }
        }
示例#25
0
        public ISettings Create()
        {
            var document = new XmlDocument();

            document.Load(Stream);
            var settings = new StandardSettingsFactory().Create();

            var parent  = document["Settings"];
            var version = parent.HasAttribute("version")
                ? Version.Parse(parent.Attributes["version"].Value)
                : new Version(1, 0, 0, 0);

            var keyStart = parent["SplitKey"];

            if (!string.IsNullOrEmpty(keyStart.InnerText))
            {
                settings.SplitKey = new KeyOrButton(keyStart.InnerText);
            }
            else
            {
                settings.SplitKey = null;
            }

            var keyReset = parent["ResetKey"];

            if (!string.IsNullOrEmpty(keyReset.InnerText))
            {
                settings.ResetKey = new KeyOrButton(keyReset.InnerText);
            }
            else
            {
                settings.ResetKey = null;
            }

            var keySkip = parent["SkipKey"];

            if (!string.IsNullOrEmpty(keySkip.InnerText))
            {
                settings.SkipKey = new KeyOrButton(keySkip.InnerText);
            }
            else
            {
                settings.SkipKey = null;
            }

            var keyUndo = parent["UndoKey"];

            if (!string.IsNullOrEmpty(keyUndo.InnerText))
            {
                settings.UndoKey = new KeyOrButton(keyUndo.InnerText);
            }
            else
            {
                settings.UndoKey = null;
            }

            settings.GlobalHotkeysEnabled = SettingsHelper.ParseBool(parent["GlobalHotkeysEnabled"]);
            settings.WarnOnReset          = SettingsHelper.ParseBool(parent["WarnOnReset"], settings.WarnOnReset);
            settings.DoubleTapPrevention  = SettingsHelper.ParseBool(parent["DoubleTapPrevention"], settings.DoubleTapPrevention);
            settings.LastTimingMethod     = SettingsHelper.ParseEnum <TimingMethod>(parent["LastTimingMethod"], settings.LastTimingMethod);
            settings.SimpleSumOfBest      = SettingsHelper.ParseBool(parent["SimpleSumOfBest"], settings.SimpleSumOfBest);
            settings.LastComparison       = SettingsHelper.ParseString(parent["LastComparison"], settings.LastComparison);
            settings.DeactivateHotkeysForOtherPrograms = SettingsHelper.ParseBool(parent["DeactivateHotkeysForOtherPrograms"], settings.DeactivateHotkeysForOtherPrograms);
            settings.HotkeyDelay      = SettingsHelper.ParseFloat(parent["HotkeyDelay"], settings.HotkeyDelay);
            settings.AgreedToSRLRules = SettingsHelper.ParseBool(parent["AgreedToSRLRules"], settings.AgreedToSRLRules);

            var recentLayouts = parent["RecentLayouts"];

            foreach (var layoutNode in recentLayouts.GetElementsByTagName("LayoutPath"))
            {
                var layoutElement = layoutNode as XmlElement;
                settings.RecentLayouts.Add(layoutElement.InnerText);
            }

            if (version > new Version(1, 0, 0, 0))
            {
                var keyPause = parent["PauseKey"];
                if (!string.IsNullOrEmpty(keyPause.InnerText))
                {
                    settings.PauseKey = new KeyOrButton(keyPause.InnerText);
                }
                else
                {
                    settings.PauseKey = null;
                }

                var keyToggle = parent["ToggleGlobalHotkeys"];
                if (!string.IsNullOrEmpty(keyToggle.InnerText))
                {
                    settings.ToggleGlobalHotkeys = new KeyOrButton(keyToggle.InnerText);
                }
                else
                {
                    settings.ToggleGlobalHotkeys = null;
                }
            }

            if (version >= new Version(1, 3))
            {
                var switchComparisonPrevious = parent["SwitchComparisonPrevious"];
                if (!string.IsNullOrEmpty(switchComparisonPrevious.InnerText))
                {
                    settings.SwitchComparisonPrevious = new KeyOrButton(switchComparisonPrevious.InnerText);
                }
                else
                {
                    settings.SwitchComparisonPrevious = null;
                }
                var switchComparisonNext = parent["SwitchComparisonNext"];
                if (!string.IsNullOrEmpty(switchComparisonNext.InnerText))
                {
                    settings.SwitchComparisonNext = new KeyOrButton(switchComparisonNext.InnerText);
                }
                else
                {
                    settings.SwitchComparisonNext = null;
                }

                settings.RaceViewer = RaceViewer.FromName(parent["RaceViewer"].InnerText);
            }

            if (version >= new Version(1, 4))
            {
                var activeAutoSplitters = parent["ActiveAutoSplitters"];
                foreach (var splitter in activeAutoSplitters.GetElementsByTagName("AutoSplitter").OfType <XmlElement>())
                {
                    settings.ActiveAutoSplitters.Add(splitter.InnerText);
                }
            }

            var recentSplits = parent["RecentSplits"];

            if (version >= new Version(1, 6))
            {
                foreach (var generatorNode in parent["ComparisonGeneratorStates"].ChildNodes)
                {
                    settings.ComparisonGeneratorStates[((XmlNode)generatorNode).Attributes["name"].Value] = Boolean.Parse(((XmlNode)generatorNode).InnerText);
                }

                foreach (var splitNode in recentSplits.GetElementsByTagName("SplitsFile"))
                {
                    var    splitElement = splitNode as XmlElement;
                    string gameName     = splitElement.GetAttribute("gameName");
                    string categoryName = splitElement.GetAttribute("categoryName");
                    var    path         = splitElement.InnerText;

                    var recentSplitsFile = new RecentSplitsFile(path, gameName, categoryName);
                    settings.RecentSplits.Add(recentSplitsFile);
                }
            }
            else
            {
                var comparisonsFactory = new StandardComparisonGeneratorsFactory();
                var runFactory         = new StandardFormatsRunFactory();

                foreach (var splitNode in recentSplits.GetElementsByTagName("SplitsPath"))
                {
                    var splitElement = splitNode as XmlElement;
                    var path         = splitElement.InnerText;

                    try
                    {
                        using (var stream = File.OpenRead(path))
                        {
                            runFactory.FilePath = path;
                            runFactory.Stream   = stream;
                            var run = runFactory.Create(comparisonsFactory);

                            var recentSplitsFile = new RecentSplitsFile(path, run.GameName, run.CategoryName);
                            settings.RecentSplits.Add(recentSplitsFile);
                        }
                    }
                    catch { }
                }
            }

            return(settings);
        }
示例#26
0
        private void BuildPlinkCommands(XmlElement overrideParms)
        {
            OnStepProgress("OverrideFile", overrideParms.OuterXml);

            HashSet <string> validUsersOld = new HashSet <string>();

            Dictionary <string, UserType> validUsers = new Dictionary <string, UserType>();

            foreach (UserType user in _wfp.Plink.Users)
            {
                validUsers.Add(user.Name.Trim(), user);
            }

            String startWith = "-";
            String joinWith  = " ";
            bool   useQuotes = true;

            if (_wfp.Plink.ArgType != null)
            {
                if (_wfp.Plink.ArgType.value == ArgumentType.Ordered)
                {
                    startWith = "";
                }

                if (_wfp.Plink.ArgType.PrefixWith != null)
                {
                    startWith = _wfp.Plink.ArgType.PrefixWith;
                }
                if (_wfp.Plink.ArgType.JoinWith != null)
                {
                    joinWith = _wfp.Plink.ArgType.JoinWith;
                }
                if (_wfp.Plink.ArgType.UseQuotes != null)
                {
                    useQuotes = Boolean.Parse(_wfp.Plink.ArgType.UseQuotes);
                }
            }

            foreach (XmlNode userNode in overrideParms.ChildNodes)
            {
                string   user      = userNode.Attributes["value"].FirstChild.Value;
                UserType validUser = null;

                // if (!(validUsers.Contains(user.Trim())))
                if (!(validUsers.ContainsKey(user.Trim())))
                {
                    OnStepProgress("OverrideFile", "User [" + user.Trim() + "] Is Not A Valid User For This Package.");
                    continue;
                }
                else
                {
                    validUsers.TryGetValue(user.Trim(), out validUser);
                }

                // Build Argument String
                String scriptArgs = null;

                StringBuilder args = new StringBuilder();
                if (_wfp.Parameters != null)
                {
                    if (_wfp.Plink.ArgType.value == ArgumentType.Ordered)
                    {
                        scriptArgs = Utils.FormatOrderedParameters(_wfp.Parameters, startWith, useQuotes, userNode);
                    }
                    else if (_wfp.Plink.ArgType.value == ArgumentType.Named)
                    {
                        scriptArgs = Utils.FormatNamedParameters(_wfp.Parameters, startWith, joinWith, useQuotes);
                    }
                }

                if ((!string.IsNullOrWhiteSpace(scriptArgs)) && (!string.IsNullOrWhiteSpace(_wfp.Plink.CommandFile.Name)))
                {
                    scriptArgs = scriptArgs.Replace(@"""", @"\""");
                }

                args.Append(@"-ssh ");

                if (!(String.IsNullOrWhiteSpace(validUser.Password)))
                {
                    String ptPassword = Utils.Decrypt(validUser.Password);
                    if (!(ptPassword.StartsWith("UNABLE TO DECRYPT")))
                    {
                        args.Append(@"-pw """ + ptPassword + @""" ");
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_wfp.Plink.PrivateKey))
                {
                    args.Append(@"-i """ + _wfp.Plink.PrivateKey + @""" ");
                }


                args.Append(@"-batch ");

                if (!string.IsNullOrWhiteSpace(user))
                {
                    args.Append(user + " ");
                }

                if (!string.IsNullOrWhiteSpace(_wfp.Plink.Command))
                {
                    args.Append(_wfp.Plink.Command + " ");
                    if (scriptArgs != null)
                    {
                        args.Append(scriptArgs + " ");
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_wfp.Plink.CommandFile.Name))
                {
                    string codePage = "437";
                    if (!string.IsNullOrWhiteSpace(_wfp.Plink.CommandFile.CodePage))
                    {
                        codePage = _wfp.Plink.CommandFile.CodePage;
                    }

                    args.Append(@"""dos2unix -" + codePage + " | sh /dev/stdin ");
                    if (scriptArgs != null)
                    {
                        args.Append(scriptArgs + " ");
                    }
                    args.Append(@""" < """ + _wfp.Plink.CommandFile.Name + @"""");
                }

                RemoteCommand cmd = new RemoteCommand();
                if (_wfp.RunUsing == RunUsingProtocolType.ProcessStart)
                {
                    cmd.server = "localhost";
                }
                else
                {
                    cmd.server = _wfp.Servers[0];
                }
                cmd.command = "plink " + args.ToString().Trim();
                if (user.IndexOf("@") >= 0)
                {
                    cmd.callbackLabel = user.Substring(user.IndexOf("@") + 1);
                }
                else
                {
                    cmd.callbackLabel = user;
                }
                remoteCommands.Add(cmd);
            }
        }
示例#27
0
		public HighlightRuleSet(XmlElement el)
		{
			XmlNodeList nodes = el.GetElementsByTagName("KeyWords");
			
			if (el.Attributes["name"] != null) {
				Name = el.Attributes["name"].InnerText;
			}
			
			if (el.Attributes["noescapesequences"] != null) {
				noEscapeSequences = Boolean.Parse(el.Attributes["noescapesequences"].InnerText);
			}
			
			if (el.Attributes["reference"] != null) {
				reference = el.Attributes["reference"].InnerText;
			}
			
			if (el.Attributes["ignorecase"] != null) {
				ignoreCase  = Boolean.Parse(el.Attributes["ignorecase"].InnerText);
			}
			
			for (int i  = 0; i < Delimiters.Length; ++i) {
				Delimiters[i] = false;
			}
			
			if (el["Delimiters"] != null) {
				string delimiterString = el["Delimiters"].InnerText;
				foreach (char ch in delimiterString) {
					Delimiters[(int)ch] = true;
				}
			}
			
//			Spans       = new LookupTable(!IgnoreCase);

			keyWords    = new LookupTable(!IgnoreCase);
			prevMarkers = new LookupTable(!IgnoreCase);
			nextMarkers = new LookupTable(!IgnoreCase);
			
			foreach (XmlElement el2 in nodes) {
				HighlightColor color = new HighlightColor(el2);
				
				XmlNodeList keys = el2.GetElementsByTagName("Key");
				foreach (XmlElement node in keys) {
					keyWords[node.Attributes["word"].InnerText] = color;
				}
			}
			
			nodes = el.GetElementsByTagName("Span");
			foreach (XmlElement el2 in nodes) {
				Spans.Add(new Span(el2));
				/*
				Span span = new Span(el2);
				Spans[span.Begin] = span;*/
			}
			
			nodes = el.GetElementsByTagName("MarkPrevious");
			foreach (XmlElement el2 in nodes) {
				PrevMarker prev = new PrevMarker(el2);
				prevMarkers[prev.What] = prev;
			}
			
			nodes = el.GetElementsByTagName("MarkFollowing");
			foreach (XmlElement el2 in nodes) {
				NextMarker next = new NextMarker(el2);
				nextMarkers[next.What] = next;
			}
		}
示例#28
0
        private void BuildPlinkCommands()
        {
            String startWith       = "-";
            String joinWith        = " ";
            bool   useQuotes       = true;
            bool   skipBlankValues = false;

            if (_wfp.Plink.ArgType != null)
            {
                if (_wfp.Plink.ArgType.PrefixWith != null)
                {
                    startWith = _wfp.Plink.ArgType.PrefixWith;
                }
                if (_wfp.Plink.ArgType.JoinWith != null)
                {
                    joinWith = _wfp.Plink.ArgType.JoinWith;
                }
                if (_wfp.Plink.ArgType.UseQuotes != null)
                {
                    useQuotes = Boolean.Parse(_wfp.Plink.ArgType.UseQuotes);
                }
                if (_wfp.Plink.ArgType.SkipBlankValues != null)
                {
                    skipBlankValues = Boolean.Parse(_wfp.Plink.ArgType.SkipBlankValues);
                }

                if (_wfp.Plink.ArgType.value == ArgumentType.Ordered)
                {
                    startWith = "";
                }
            }

            foreach (UserType user in _wfp.Plink.Users)
            {
                // Build Argument String
                String scriptArgs = null;

                StringBuilder args = new StringBuilder();
                if (_wfp.Parameters != null)
                {
                    if (_wfp.Plink.ArgType.value == ArgumentType.Ordered)
                    {
                        scriptArgs = Utils.FormatOrderedParameters(_wfp.Parameters, startWith, useQuotes);
                    }
                    else if (_wfp.Plink.ArgType.value == ArgumentType.Named)
                    {
                        scriptArgs = Utils.FormatNamedParameters(_wfp.Parameters, startWith, joinWith, useQuotes, skipBlankValues);
                    }
                }

                if (_wfp.Plink.CommandFile != null)
                {
                    if ((!string.IsNullOrWhiteSpace(scriptArgs)) && (!string.IsNullOrWhiteSpace(_wfp.Plink.CommandFile.Name)))
                    {
                        scriptArgs = scriptArgs.Replace(@"""", @"\""");
                    }
                }

                if (config.Default.DebugMode)
                {
                    args.Append(@"-v ");
                }
                args.Append(@"-ssh ");


                if (!(String.IsNullOrWhiteSpace(user.Password)))
                {
                    String ptPassword = Utils.Decrypt(user.Password);
                    if (!(ptPassword.StartsWith("UNABLE TO DECRYPT")))
                    {
                        args.Append(@"-pw """ + ptPassword + @""" ");
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_wfp.Plink.PrivateKey))
                {
                    args.Append(@"-i """ + _wfp.Plink.PrivateKey + @""" ");
                }

                if (!_wfp.Plink.RunInteractive)
                {
                    args.Append(@"-batch ");
                }

                if (!string.IsNullOrWhiteSpace(user.Name))
                {
                    args.Append(user.Name + " ");
                }

                if (!string.IsNullOrWhiteSpace(_wfp.Plink.Command))
                {
                    args.Append(_wfp.Plink.Command + " ");
                    if (scriptArgs != null)
                    {
                        args.Append(scriptArgs + " ");
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_wfp.Plink.CommandFile.Name))
                {
                    string codePage = "437";
                    if (!string.IsNullOrWhiteSpace(_wfp.Plink.CommandFile.CodePage))
                    {
                        codePage = _wfp.Plink.CommandFile.CodePage;
                    }

                    args.Append(@"""dos2unix -" + codePage + " | sh /dev/stdin ");
                    if (scriptArgs != null)
                    {
                        args.Append(scriptArgs + " ");
                    }
                    args.Append(@""" < """ + _wfp.Plink.CommandFile.Name + @"""");
                }

                RemoteCommand cmd = new RemoteCommand();
                if (_wfp.RunUsing == RunUsingProtocolType.ProcessStart)
                {
                    cmd.server = "localhost";
                }
                else
                {
                    cmd.server = _wfp.Servers[0];
                }
                if (String.IsNullOrWhiteSpace(_wfp.WorkingDir))
                {
                    cmd.command = "plink.exe";
                }
                else
                {
                    cmd.command = Path.Combine(_wfp.WorkingDir, "plink.exe");
                }
                cmd.args = args.ToString().Trim();
                if (user.Name.IndexOf("@") >= 0)
                {
                    cmd.callbackLabel = user.Name.Substring(user.Name.IndexOf("@") + 1);
                }
                else
                {
                    cmd.callbackLabel = user.Name;
                }
                remoteCommands.Add(cmd);
            }
        }
示例#29
0
        public static Workspace LoadWorkspaceFile(string filename)
        {
            try
            {
                if (!File.Exists(filename))
                {
                    return(null);
                }

                XmlDocument xml = new XmlDocument();
                xml.Load(filename);

                XmlNode root = xml.ChildNodes[1];
                if (root.Name == "workspace")
                {
                    string name                = GetAttribute(root, "name");
                    string xmlfolder           = GetAttribute(root, "xmlmetafolder");
                    string folder              = GetAttribute(root, "folder");
                    string defaultExportFolder = GetAttribute(root, "export");
                    if (string.IsNullOrEmpty(name) ||
                        string.IsNullOrEmpty(xmlfolder) ||
                        string.IsNullOrEmpty(folder) ||
                        string.IsNullOrEmpty(defaultExportFolder))
                    {
                        throw new Exception(Resources.LoadWorkspaceError);
                    }

                    Workspace ws = new Workspace(filename, name, xmlfolder, folder, defaultExportFolder);

                    foreach (XmlNode subnode in root)
                    {
                        if (subnode.NodeType == XmlNodeType.Element)
                        {
                            switch (subnode.Name)
                            {
                            // Load all XML plugins.
                            case "xmlmeta":
                                string nodeName = subnode.InnerText.Trim();
                                if (!string.IsNullOrEmpty(nodeName))
                                {
                                    ws.AddXMLPlugin(nodeName);
                                }
                                break;

                            // Load export nodes.
                            case "export":
                                foreach (XmlNode exportNode in subnode)
                                {
                                    if (exportNode.NodeType == XmlNodeType.Element)
                                    {
                                        if (!ws._exportDatas.ContainsKey(exportNode.Name))
                                        {
                                            ws._exportDatas[exportNode.Name] = new ExportData();
                                        }
                                        ExportData data = ws._exportDatas[exportNode.Name];

                                        foreach (XmlNode exportInfoNode in exportNode)
                                        {
                                            switch (exportInfoNode.Name)
                                            {
                                            case "isexported":
                                                data.IsExported = Boolean.Parse(exportInfoNode.InnerText.Trim());
                                                break;

                                            case "filename":
                                                data.ExportFilename = exportInfoNode.InnerText.Trim();
                                                break;

                                            case "folder":
                                                data.ExportFolder = exportInfoNode.InnerText.Trim();
                                                break;

                                            case "includedfilenames":
                                                foreach (XmlNode sn in exportInfoNode)
                                                {
                                                    if (sn.NodeType == XmlNodeType.Element && sn.Name == "includedfilename")
                                                    {
                                                        string includeFilename = sn.InnerText.Trim();
                                                        if (!data.ExportIncludedFilenames.Contains(includeFilename))
                                                        {
                                                            data.ExportIncludedFilenames.Add(includeFilename);
                                                        }
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }

                    return(ws);
                }
            }
            catch (Exception)
            {
                string msgError = string.Format(Resources.LoadWorkspaceError, filename);
                MessageBox.Show(msgError, Resources.LoadError, MessageBoxButtons.OK);
            }

            return(null);
        }
示例#30
0
        private void CargarDatosDinamicos(Location Cliente)
        {
            //Variables Auxiliares
            IList <ShowData> DetailDataList = null;
            ShowData         DetailData     = null;

            //Limpio los datos dinamicos
            View.GetStackPanelDinamicos.Children.Clear();

            //Deserializo el Xml para obtener el Showdata
            DetailDataList = Util.DeserializeMetaDataWF(View.Model.DataInformationSearch.XmlData);

            //Evaluo si el tipo de dato a editar es documento
            if (View.Model.DataInformationSearch.Entity.ClassEntityID == EntityID.Document)
            {
                View.Model.CamposDinamicosEditList = service.GetDataDefinitionByBin(new DataDefinitionByBin
                {
                    DataDefinition = new DataDefinition
                    {
                        //Location = service.GetDocument(new Document { DocID = View.Model.DataInformationSearch.EntityRowID }).First().Location
                        Location = Cliente
                    }
                }).OrderBy(f => f.DataDefinition.NumOrder).ToList();
            }

            //Evaluo si el tipo de dato a editar es un label
            if (View.Model.DataInformationSearch.Entity.ClassEntityID == EntityID.Label)
            {
                View.Model.CamposDinamicosEditList = service.GetDataDefinitionByBin(new DataDefinitionByBin
                {
                    DataDefinition = new DataDefinition
                    {
                        Location = Cliente,
                        IsHeader = false,
                        IsSerial = false
                    }
                });

                //Recorro la lista para filtrar los campos que estan repetidos
                IList <DataDefinitionByBin> controList = new List <DataDefinitionByBin>();
                foreach (DataDefinitionByBin dfx in View.Model.CamposDinamicosEditList)
                {
                    if (controList.Any(f => f.DataDefinition.Code == dfx.DataDefinition.Code))
                    {
                        continue;
                    }
                    else
                    {
                        controList.Add(dfx);
                    }
                }

                View.Model.CamposDinamicosEditList = controList.OrderBy(f => f.DataDefinition.NumOrder).ToList();
            }

            string          ucType; //Tipo del User Control
            Assembly        assembly;
            UserControl     someObject = null;
            IList <MMaster> listCombo  = null;

            foreach (DataDefinitionByBin DataDefinitionByBin in View.Model.CamposDinamicosEditList)
            {
                try
                {
                    DetailData = DetailDataList.Where(f => f.DataKey == DataDefinitionByBin.DataDefinition.Code).First();
                }
                catch { continue; }

                if (DataDefinitionByBin.DataDefinition.DataType.UIControl != null)
                {
                    assembly = Assembly.GetAssembly(Type.GetType(DataDefinitionByBin.DataDefinition.DataType.UIControl));
                    //El primer elemento del assembly antes de la coma
                    ucType     = DataDefinitionByBin.DataDefinition.DataType.UIControl.Split(",".ToCharArray())[0];
                    someObject = (UserControl)Activator.CreateInstance(assembly.GetType(ucType));
                }
                else
                {
                    assembly   = Assembly.GetAssembly(Type.GetType("WpfFront.Common.WFUserControls.WFStringText, WpfFront, Version=1.0.3598.33141, Culture=neutral, PublicKeyToken=null"));
                    someObject = (UserControl)Activator.CreateInstance(assembly.GetType("WpfFront.Common.WFUserControls.WFStringText"));
                    ucType     = "WpfFront.Common.WFUserControls.WFStringText";
                }
                someObject.GetType().GetProperty("UcLabel").SetValue(someObject, DataDefinitionByBin.DataDefinition.DisplayName, null);
                if (ucType.Contains("WFDateTime"))
                {
                    if (DetailData.DataValue != "")
                    {
                        try
                        {
                            someObject.GetType().GetProperty("UcValue").SetValue(someObject, DateTime.Parse(DetailData.DataValue), null);
                        }
                        catch { }
                    }
                }
                else
                {
                    if (ucType.Contains("WFCheckBox"))
                    {
                        if (DetailData.DataValue != "")
                        {
                            someObject.GetType().GetProperty("UcValue").SetValue(someObject, Boolean.Parse(DetailData.DataValue), null);
                        }
                        else
                        {
                            someObject.GetType().GetProperty("UcValue").SetValue(someObject, false, null);
                        }
                    }
                    else
                    {
                        someObject.GetType().GetProperty("UcValue").SetValue(someObject, DetailData.DataValue, null);
                    }
                }
                someObject.GetType().GetProperty("Name").SetValue(someObject, "f_" + DataDefinitionByBin.DataDefinition.Code.Replace(" ", "").ToString(), null);
                try
                {
                    listCombo = null;
                    if (DataDefinitionByBin.DataDefinition.MetaType != null)
                    {
                        listCombo = service.GetMMaster(new MMaster {
                            MetaType = DataDefinitionByBin.DataDefinition.MetaType
                        }).OrderBy(f => f.NumOrder).ToList();
                        listCombo.Add(new MMaster {
                            Code = "", Name = "..."
                        });

                        someObject.GetType().GetProperty("UcList").SetValue(someObject, listCombo, null);

                        try { someObject.GetType().GetProperty("DefaultList").SetValue(someObject, listCombo, null); }
                        catch { }
                    }
                }
                catch { }
                View.GetStackPanelDinamicos.Children.Add(someObject);
            }
        }