Example #1
0
        public DradisForm(MainForm parent)
        {
            InitializeComponent();
            this.parent = parent;

            _sectors = new Dictionary<ListBox, DeckManager.Boards.Dradis.DradisNodeName>();
            _sectors.Add(alphaListBox, DeckManager.Boards.Dradis.DradisNodeName.Alpha);
            _sectors.Add(bravoListBox, DeckManager.Boards.Dradis.DradisNodeName.Bravo);
            _sectors.Add(charlieListBox, DeckManager.Boards.Dradis.DradisNodeName.Charlie);
            _sectors.Add(deltaListBox, DeckManager.Boards.Dradis.DradisNodeName.Delta);
            _sectors.Add(echoListBox, DeckManager.Boards.Dradis.DradisNodeName.Echo);
            _sectors.Add(foxtrotListBox, DeckManager.Boards.Dradis.DradisNodeName.Foxtrot);

            foreach (DeckManager.Boards.Dradis.DradisNode node in Program.GManager.CurrentGameState.Dradis.Nodes)
            {
                ListBox sector = _sectors.FirstOrDefault(x => x.Value == node.Name).Key;
                sector.Items.AddRange(node.Components.ToArray());
            }


            var values = Enum.GetValues(typeof(DeckManager.Components.Enums.ComponentType));
            foreach (DeckManager.Components.Enums.ComponentType type in values)
            { 
                if (type == DeckManager.Components.Enums.ComponentType.Unknown) 
                    continue;
                this.LaunchComponentComboBox.Items.Add(type);
            }
            values = Enum.GetValues(typeof(DeckManager.Boards.Dradis.DradisNodeName));
            foreach (DeckManager.Boards.Dradis.DradisNodeName sector in values)
            {
                if (sector == DeckManager.Boards.Dradis.DradisNodeName.Unknown) 
                    continue;
                this.LaunchLocationComboBox.Items.Add(sector);
            }
        }
Example #2
0
 //Given a sequence of non-negative integers find a subsequence of length 3 having maximum product with the numbers of the subsequence being in ascending order.
 //Example:
 //Input: 6 7 8 1 2 3 9 10
 //Ouput: 8 9 10
 //Wrong!!!
 public List<int> Max(int[] a)
 {
     Dictionary<List<int>, int> result = new Dictionary<List<int>, int>();
     List<int> list = new List<int>();
     list.Add(a[0]);
     result.Add(list, a[0]);
     int max = 0, min = 0;
     for (int i = 1; i < a.Length; i++)
     {
         min = result.Values.Min();
         max = result.Values.Max();
         if (a[i] >= max)
         {
             list = result.FirstOrDefault(x => x.Value == max).Key;
             list.Add(a[i]);
             result[list] = a[i];
             if (list.Count > 3)
                 list.RemoveAt(0);
         }
         else if (a[i] <= min)
         {
             list = new List<int>();
             list.Add(a[i]);
             result.Add(list, a[i]);
         }
         else
         {
             for(int x=0;x<result.Count;x++)
             {
                 var t = result.ElementAt(x);
                 if (t.Value < a[i])
                 {
                     t.Key.Add(a[i]);
                     result[t.Key] = a[i];
                     if (t.Key.Count > 3)
                         t.Key.RemoveAt(0);
                 }
             }
         }
     }
     max = result.Values.Max();
     list = result.FirstOrDefault(x => x.Value == max).Key;
     return list;
 }
Example #3
0
        internal static string Both_have_same(string[] master, string[] slave)
        {
            string[] tmpMaster = new string[5];
            string[] tmpSlave = new string[5];
            int[] tmpMasterInt = new int[5];
            int[] tmpSlaveInt = new int[5];

            for (int i = 0; i < 5; i++)
            { 
                tmpMaster[i] = master[i].Remove(master[i].Length - 1);
                tmpSlave[i] = slave[i].Remove(slave[i].Length - 1);
            }

            for (int i = 0; i < 5; i++)
            {
                if (tmpMaster[i] == "A") tmpMasterInt[i] = 14;
                else if (tmpMaster[i] == "K") tmpMasterInt[i] = 13;
                else if (tmpMaster[i] == "Q") tmpMasterInt[i] = 12;
                else if (tmpMaster[i] == "J") tmpMasterInt[i] = 11;
                else
                {
                    Int32.TryParse(tmpMaster[i], out tmpMasterInt[i]);
                }
            }

            for (int i = 0; i < 5; i++)
            {
                if (tmpSlave[i] == "A") tmpSlaveInt[i] = 14;
                else if (tmpSlave[i] == "K") tmpSlaveInt[i] = 13;
                else if (tmpSlave[i] == "Q") tmpSlaveInt[i] = 12;
                else if (tmpSlave[i] == "J") tmpSlaveInt[i] = 11;
                else
                {
                    Int32.TryParse(tmpSlave[i], out tmpSlaveInt[i]);
                }
            }

            Dictionary<int, int> dic_m = new Dictionary<int, int>();
            foreach (int num in tmpMasterInt)
            {
                if (dic_m.ContainsKey(num))
                {
                    dic_m[num] += 1; 
                }
                else
                {
                    dic_m.Add(num,1);
                }
            }

            Dictionary<int, int> dic_s = new Dictionary<int, int>();
            foreach (int num in tmpSlaveInt)
            {
                if (dic_s.ContainsKey(num))
                {
                    dic_s[num] += 1;
                }
                else
                {
                    dic_s.Add(num, 1);
                }
            }

            if (dic_m.Count == 4)
            {
                int m = dic_m.FirstOrDefault(x => x.Value == 2).Key;
                int s = dic_s.FirstOrDefault(x => x.Value == 2).Key;
                if (m > s) return "m";
                else if (m < s) return "s";
                else return "n"; 
            }
            else if (dic_m.Count == 3)
            {
                int m = dic_m.FirstOrDefault(x => x.Value == 3).Key;
                int s = dic_s.FirstOrDefault(x => x.Value == 3).Key;
                if (m > s) return "m";
                else if (m < s) return "s";
                else return "n";
            }
            else if (dic_m.Count == 2)
            {
                int m = dic_m.FirstOrDefault(x => x.Value == 4).Key;
                int s = dic_s.FirstOrDefault(x => x.Value == 4).Key;
                if (m > s) return "m";
                else if (m < s) return "s";
                else return "n";
            }
            else return "n";
        }
    private static ValuesType GetEqualValues(ValuesType originalValues, Dictionary<ValuesType, ValuesType> variableValuesMapping) {
      if (variableValuesMapping.ContainsKey(originalValues)) return variableValuesMapping[originalValues];

      var matchingValues = variableValuesMapping.FirstOrDefault(kv => kv.Key == kv.Value && EqualVariableValues(originalValues, kv.Key)).Key ?? originalValues;
      variableValuesMapping[originalValues] = matchingValues;
      return matchingValues;
    }
        public override void OutAAProgram(AAProgram node)
        {
            if (strings.Count == 0)
                return;

            //Obfuscate all strings
            List<string> obfuscated = new List<string>();
            foreach (AStringConstExp stringConstExp in strings)
            {
                TStringLiteral token = stringConstExp.GetStringLiteral();
                string s = token.Text.Substring(1, token.Text.Length - 2);
                obfuscated.Add(Obfuscate(s));
            }

            //Set invokes instead of string constants, and move varaiabes down
            List<AFieldDecl> ignoredFields = new List<AFieldDecl>();
            List<AFieldDecl> moveFieldsIn = new List<AFieldDecl>();
            Dictionary<AFieldDecl, AMethodDecl> fieldMethods = new Dictionary<AFieldDecl, AMethodDecl>();
            for (int i = 0; i < strings.Count; i++)
            {
                AStringConstExp stringExp = strings[i];
                Token token = stringExp.GetStringLiteral();
                bool inDeobfuscator = Util.GetAncestor<AMethodDecl>(stringExp) == finalTrans.data.DeobfuscateMethod;

                if (inDeobfuscator)
                {
                    AFieldDecl field = finalTrans.data.UnobfuscatedStrings[stringExp];

                    AStringConstExp newStringConst = new AStringConstExp(stringExp.GetStringLiteral());

                    field.SetInit(newStringConst);

                    AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
                    finalTrans.data.FieldLinks[fieldRef] = field;

                    stringExp.ReplaceBy(new ALvalueExp(fieldRef));
                }
                else
                {
                    AFieldDecl field;
                    if (!finalTrans.data.ObfuscatedStrings.ContainsKey(stringExp))
                    {
                        int line = -finalTrans.data.ObfuscatedStrings.Count - 1;
                        field = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const", line, 0),
                                                new ANamedType(new TIdentifier("string", line, 1), null),
                                                new TIdentifier("Galaxy_pp_stringO" +
                                                                finalTrans.data.ObfuscatedStrings.Count), null);
                        //If the strings are the same - point them to same field
                        bool newField = true;
                        foreach (AStringConstExp oldStringConstExp in finalTrans.data.ObfuscatedStrings.Keys)
                        {
                            if (stringExp.GetStringLiteral().Text == oldStringConstExp.GetStringLiteral().Text)
                            {
                                field = finalTrans.data.ObfuscatedStrings[oldStringConstExp];
                                newField = false;
                                break;
                            }
                        }
                        if (newField)
                        {
                            AASourceFile file = (AASourceFile)finalTrans.data.DeobfuscateMethod.Parent();
                            file.GetDecl().Insert(file.GetDecl().IndexOf(finalTrans.data.DeobfuscateMethod) + 1, field);

                            finalTrans.data.Fields.Add(new SharedData.DeclItem<AFieldDecl>(file, field));
                        }
                        finalTrans.data.ObfuscatedStrings.Add(stringExp, field);

                    }
                    field = finalTrans.data.ObfuscatedStrings[stringExp];
                    string obfuscatedString = obfuscated[i];

                    ASimpleInvokeExp invoke = new ASimpleInvokeExp();
                    invoke.SetName(new TIdentifier(finalTrans.data.DeobfuscateMethod.GetName().Text,
                                                   stringExp.GetStringLiteral().Line,
                                                   stringExp.GetStringLiteral().Pos));

                    AStringConstExp newStringConst =
                        new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                    invoke.GetArgs().Add(newStringConst);
                    finalTrans.data.SimpleMethodLinks[invoke] = finalTrans.data.DeobfuscateMethod;

                    if (Util.GetAncestor<PStm>(stringExp) == null && false)
                    {
                        ignoredFields.Add(field);
                        /*if (Util.GetAncestor<ASimpleInvokeExp>(stringExp) == null)
                            stringExp.ReplaceBy(invoke);*/
                        //Add obfuscate call to this location);
                        continue;
                        /*ASimpleInvokeExp invoke = new ASimpleInvokeExp();
                        invoke.SetName(new TIdentifier(finalTrans.data.DeobfuscateMethod.GetName().Text,
                                                       stringExp.GetStringLiteral().Line,
                                                       stringExp.GetStringLiteral().Pos));

                        AStringConstExp newStringConst =
                            new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                        invoke.GetArgs().Add(newStringConst);
                        stringExp.ReplaceBy(invoke);

                        finalTrans.data.SimpleMethodLinks[invoke] = finalTrans.data.DeobfuscateMethod;
                        continue;*/
                    }

                    if (field.GetInit() == null)
                    {
                        /*field.SetInit(invoke);
                        field.SetConst(null);*/

                        if (
                            stringExp.GetStringLiteral().Text.Remove(0, 1).Substring(0,
                                                                                     stringExp.GetStringLiteral().Text.
                                                                                         Length - 2) == "")
                        {
                            //Make method
                            /*
                                string <field>Method()
                                {
                                    return "";
                                }
                             *
                             */
                            ANullExp nullExp = new ANullExp();

                            field.SetInit(nullExp);
                            field.SetConst(null);

                            AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\"\""));
                            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                                 new ANamedType(new TIdentifier("string"), null),
                                                                 new TIdentifier("Get" + field.GetName()),
                                                                 new ArrayList(),
                                                                 new AABlock(
                                                                     new ArrayList()
                                                                         {
                                                                             new AValueReturnStm(new TReturn("return"),
                                                                                                 stringConst)
                                                                         },
                                                                     new TRBrace("}")));

                            AASourceFile pFile = (AASourceFile)field.Parent();
                            pFile.GetDecl().Insert(pFile.GetDecl().IndexOf(field) + 1, method);
                            finalTrans.data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null);
                            finalTrans.data.ExpTypes[nullExp] = new ANamedType(new TIdentifier("null"), null);

                            fieldMethods[field] = method;
                        }
                        else
                        {
                            //Make method
                            /*
                                string <field>Method()
                                {
                                    if (field == null)
                                    {
                                        field = Invoke;
                                    }
                                    if (field == null)
                                    {
                                        return Invoke;
                                    }
                                    return field;
                                }
                             */

                            ANullExp nullExp1 = new ANullExp();

                            field.SetInit(nullExp1);
                            field.SetConst(null);

                            ANullExp nullExp2 = new ANullExp();
                            AFieldLvalue fieldRef1 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            AFieldLvalue fieldRef2 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            AFieldLvalue fieldRef3 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            ALvalueExp fieldRef1Exp = new ALvalueExp(fieldRef1);
                            ALvalueExp fieldRef3Exp = new ALvalueExp(fieldRef3);
                            ABinopExp binop1 = new ABinopExp(fieldRef1Exp, new AEqBinop(new TEq("==")), nullExp2);
                            AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef2, invoke);

                            AIfThenStm ifStm1 = new AIfThenStm(new TLParen("("), binop1,
                                                              new ABlockStm(new TLBrace("{"),
                                                                            new AABlock(
                                                                                new ArrayList()
                                                                                    {
                                                                                        new AExpStm(new TSemicolon(";"),
                                                                                                    assignment)
                                                                                    },
                                                                                new TRBrace("}"))));

                            /*ANullExp nullExp3 = new ANullExp();
                            AFieldLvalue fieldRef4 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            ALvalueExp fieldRef4Exp = new ALvalueExp(fieldRef4);
                            AStringConstExp invokeArgClone =
                                new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                            ASimpleInvokeExp invokeClone = new ASimpleInvokeExp(new TIdentifier(invoke.GetName().Text),
                                                                                new ArrayList() { invokeArgClone });
                            finalTrans.data.SimpleMethodLinks[invokeClone] = finalTrans.data.DeobfuscateMethod;
                            ABinopExp binop2 = new ABinopExp(fieldRef4Exp, new AEqBinop(new TEq("==")), nullExp3);

                            AIfThenStm ifStm2 = new AIfThenStm(new TLParen("("), binop2,
                                                              new ABlockStm(new TLBrace("{"),
                                                                            new AABlock(
                                                                                new ArrayList()
                                                                                    {
                                                                                        new AValueReturnStm(new TReturn("return"), invokeClone)
                                                                                    },
                                                                                new TRBrace("}"))));*/

                            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                                 new ANamedType(new TIdentifier("string"), null),
                                                                 new TIdentifier("Get" + field.GetName()),
                                                                 new ArrayList(),
                                                                 new AABlock(
                                                                     new ArrayList()
                                                                         {
                                                                             ifStm1,
                                                                             //ifStm2,
                                                                             new AValueReturnStm(new TReturn("return"),
                                                                                                 fieldRef3Exp)
                                                                         },
                                                                     new TRBrace("}")));
                            AASourceFile pFile = (AASourceFile) field.Parent();
                            pFile.GetDecl().Insert(pFile.GetDecl().IndexOf(field) + 1, method);

                            finalTrans.data.FieldLinks[fieldRef1] =
                                finalTrans.data.FieldLinks[fieldRef2] =
                                finalTrans.data.FieldLinks[fieldRef3] =
                                /*finalTrans.data.FieldLinks[fieldRef4] = */field;
                            finalTrans.data.LvalueTypes[fieldRef1] =
                                finalTrans.data.LvalueTypes[fieldRef2] =
                                finalTrans.data.LvalueTypes[fieldRef3] =
                                //finalTrans.data.LvalueTypes[fieldRef4] =
                                finalTrans.data.ExpTypes[fieldRef1Exp] =
                                finalTrans.data.ExpTypes[fieldRef3Exp] =
                                //finalTrans.data.ExpTypes[fieldRef4Exp] =
                                finalTrans.data.ExpTypes[assignment] = field.GetType();

                            finalTrans.data.ExpTypes[nullExp1] =
                                finalTrans.data.ExpTypes[nullExp2] =
                                /*finalTrans.data.ExpTypes[nullExp3] =*/ new ANamedType(new TIdentifier("null"), null);
                            finalTrans.data.ExpTypes[binop1] =
                                /*finalTrans.data.ExpTypes[binop2] = */new ANamedType(new TIdentifier("bool"), null);

                            fieldMethods[field] = method;
                        }

                        /* AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
                         finalTrans.data.FieldLinks[fieldRef] = field;*/

                        //stringExp.ReplaceBy(new ALvalueExp(fieldRef));
                    }
                    ASimpleInvokeExp invoke2 =
                            new ASimpleInvokeExp(new TIdentifier(fieldMethods[field].GetName().Text), new ArrayList());
                    finalTrans.data.SimpleMethodLinks[invoke2] = fieldMethods[field];
                    stringExp.ReplaceBy(invoke2);

                    //If we are in a field, move it in
                    if (Util.GetAncestor<AFieldDecl>(invoke2) != null)
                        moveFieldsIn.Add(Util.GetAncestor<AFieldDecl>(invoke2));
                }
            }

            foreach (AFieldDecl field in finalTrans.data.ObfuscationFields)
            {
                if (field.GetInit() == null && field.Parent() != null)
                {
                    field.Parent().RemoveChild(field);
                }
            }

            //A constant field, or a field used by a constant field cannot be moved in
            List<AFieldDecl> constantFields = new List<AFieldDecl>();
            foreach (SharedData.DeclItem<AFieldDecl> field in finalTrans.data.Fields)
            {
                if (field.Decl.GetConst() != null)
                    constantFields.Add(field.Decl);
            }
            for (int i = 0; i < constantFields.Count; i++)
            {
                GetFieldLvalues lvalues = new GetFieldLvalues();
                constantFields[i].Apply(lvalues);
                foreach (AFieldLvalue lvalue in lvalues.Lvalues)
                {
                    AFieldDecl field = finalTrans.data.FieldLinks[lvalue];
                    if (!constantFields.Contains(field))
                        constantFields.Add(field);
                }
            }
            moveFieldsIn.RemoveAll(constantFields.Contains);
            Dictionary<AFieldDecl, List<AFieldDecl>> dependancies = new Dictionary<AFieldDecl, List<AFieldDecl>>();
            //Order the fields so any dependancies are instansiated first
            foreach (AFieldDecl field in moveFieldsIn)
            {
                dependancies.Add(field, new List<AFieldDecl>());
                GetFieldLvalues lvalues = new GetFieldLvalues();
                field.Apply(lvalues);
                foreach (AFieldLvalue lvalue in lvalues.Lvalues)
                {
                    AFieldDecl dependancy = finalTrans.data.FieldLinks[lvalue];
                    if (!dependancies[field].Contains(dependancy))
                        dependancies[field].Add(dependancy);
                }
            }
            List<PStm> newStatements = new List<PStm>();
            while (dependancies.Keys.Count > 0)
            {
                AFieldDecl field = dependancies.FirstOrDefault(f1 => f1.Value.Count == 0).Key ??
                                   dependancies.Keys.First(f => true);

                AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef, field.GetInit());
                field.SetInit(null);

                newStatements.Add(new AExpStm(new TSemicolon(";"), assignment));

                finalTrans.data.FieldLinks[fieldRef] = field;
                finalTrans.data.LvalueTypes[fieldRef] =
                    finalTrans.data.ExpTypes[assignment] = field.GetType();

                foreach (KeyValuePair<AFieldDecl, List<AFieldDecl>> dependancy in dependancies)
                {
                    if (dependancy.Value.Contains(field))
                        dependancy.Value.Remove(field);
                }

                dependancies.Remove(field);
            }
            AABlock initBody = (AABlock) finalTrans.mainEntry.GetBlock();
            for (int i = newStatements.Count - 1; i >= 0; i--)
            {
                initBody.GetStatements().Insert(0, newStatements[i]);
            }
        }
        /// <summary>
        /// Get the private config value for a specific attribute.
        /// The private config looks like this:
        /// XML:
        ///    <PrivateConfig xmlns="namespace">
        ///      <StorageAccount name = "name" key="key" endpoint="endpoint" />
        ///      <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/>
        ///    </PrivateConfig>
        ///
        /// JSON:
        ///    "PrivateConfig":{
        ///      "storageAccountName":"name",
        ///      "storageAccountKey":"key",
        ///      "storageAccountEndPoint":"endpoint",
        ///      "EventHub":{
        ///        "Url":"url",
        ///        "SharedAccessKeyName":"sasKeyName",
        ///        "SharedAccessKey":"sasKey"
        ///      }
        ///    }
        /// </summary>
        /// <param name="configurationPath">The path to the configuration file</param>
        /// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param>
        /// <param name="attributeName">The attribute name of the element</param>
        /// <returns></returns>
        public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName)
        {
            string value = string.Empty;
            var configFileType = GetConfigFileType(configurationPath);

            if (configFileType == ConfigFileType.Xml)
            {
                var xmlConfig = XElement.Load(configurationPath);

                if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
                {
                    var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr);
                    var configElem = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName);
                    var attribute = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName));
                    value = attribute == null ? null : attribute.Value;
                }
            }
            else if (configFileType == ConfigFileType.Json)
            {
                // Find the PrivateConfig
                var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
                var properties = jsonConfig.Properties().Select(p => p.Name);
                var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr));

                if (privateConfigProperty == null)
                {
                    return value;
                }
                var privateConfig = jsonConfig[privateConfigProperty] as JObject;

                // Find the target config object corresponding to elementName
                JObject targetConfig = null;
                if (elementName == StorageAccountElemStr)
                {
                    // Special handling as private storage config is flattened
                    targetConfig = privateConfig;
                    var attributeNameMapping = new Dictionary<string, string>()
                    {
                        { PrivConfNameAttr, "storageAccountName" },
                        { PrivConfKeyAttr, "storageAccountKey" },
                        { PrivConfEndpointAttr, "storageAccountEndPoint" }
                    };
                    attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value;
                }
                else
                {
                    properties = privateConfig.Properties().Select(p => p.Name);
                    var configProperty = properties.FirstOrDefault(p => p.Equals(elementName));
                    targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject;
                }

                if (targetConfig == null || attributeName == null)
                {
                    return value;
                }

                // Find the config value corresponding to attributeName
                properties = targetConfig.Properties().Select(p => p.Name);
                var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName));
                value = attributeProperty == null ? null : targetConfig[attributeProperty].Value<string>();
            }

            return value;
        }
Example #7
0
        public bool Convert(ProgressBar progressBar = null)
        {
            if (progressBar != null) {
                progressBar.Value = 0;
            }
            int AppealIndex = 1;
            // Запоминаем текущую дату и время, чтобы установить их всем создаваемым обращениям.
            this.ConvertDate = DateTime.Now;

            // Находим заявителей с фиктивным ID и создаём их.
            Dictionary<string, string> FakeToReal = new Dictionary<string, string>();
            foreach (Declarant d in Declarants) {
                if (d.GetID().Contains("fake-")) {
                    string FakeID = d.GetID();
                    string RealID = "";
                    try {
                        RealID = d.SaveToDB(this.ConvertDate);
                        FakeToReal.Add(FakeID, RealID);
                    } catch (Exception e) {
                        e.Data.Add("UserMessage", "Заявитель: " + d.GetFIO());
                        DB.Rollback();
                        throw;
                    }
                    this.Log("cat_declarants", RealID);
                }
            }

            // Записываем обращения в БД
            foreach (Appeal NewAppeal in this.SimpleAppeals) {
                // Заменяем фиктивные id заявителей на реальные.
                for(int i = 0; i < NewAppeal.multi.Count; i++) {
                    string[] str = (string[]) NewAppeal.multi[i];
                    if (str[0] == "declarant") {
                        KeyValuePair<string, string> ids = FakeToReal.FirstOrDefault(x => x.Key == str[1]);
                        if (ids.Value != null && ids.Value != "") {
                            ((string[])NewAppeal.multi[i])[1] = ids.Value;
                            //NewAppeal.multi[i] = new string[] { "declarant", ids.Value, str[2] };
                        }
                    }
                }
                try {
                    CreateAppeal(NewAppeal);
                } catch (Exception e) {
                    e.Data.Add("UserMessage", "Заявка: " + NewAppeal.numb);
                    DB.Rollback();
                    throw;
                }
                if (progressBar != null) {
                    double percent = (double)AppealIndex / this.SimpleAppeals.Count * 100;
                    progressBar.Value = System.Convert.ToInt32(percent);
                }
                AppealIndex++;
            }
            LinkAppeals();
            DB.Commit();
            return true;
        }
Example #8
0
		/// <summary>
		/// Get the LangCode from the Database.ssf file and insert it in css file
		/// </summary>
		public static string ParaTextDcLanguage(string dataBaseName, bool hyphenlang)
		{
			string dcLanguage = string.Empty;
			if (AppDomain.CurrentDomain.FriendlyName.ToLower() == "paratext.exe") // is paratext00
			{
				// read Language Code from ssf
				SettingsHelper settingsHelper = new SettingsHelper(dataBaseName);
				string fileName = settingsHelper.GetSettingsFilename();
				string xPath = "//ScriptureText/EthnologueCode";
				XmlNode xmlLangCode = GetXmlNode(fileName, xPath);
				if (xmlLangCode != null && xmlLangCode.InnerText != string.Empty)
				{
					dcLanguage = xmlLangCode.InnerText;
				}
				xPath = "//ScriptureText/Language";
				XmlNode xmlLangNameNode = GetXmlNode(fileName, xPath);
				if (xmlLangNameNode != null && xmlLangNameNode.InnerText != string.Empty)
				{
					if (dcLanguage == string.Empty)
					{
						Dictionary<string, string> _languageCodes = new Dictionary<string, string>();
						_languageCodes = LanguageCodesfromXMLFile();
						if (_languageCodes.Count > 0)
						{
							foreach (
								var languageCode in
									_languageCodes.Where(
										languageCode => languageCode.Value.ToLower() == xmlLangNameNode.InnerText.ToLower()))
							{
								if (hyphenlang)
								{
									dcLanguage = _languageCodes.ContainsValue(languageCode.Key.ToLower())
										? _languageCodes.FirstOrDefault(x => x.Value == languageCode.Key.ToLower()).Key
										: languageCode.Key;
								}
								else
								{
									dcLanguage = languageCode.Key;
								}
								break;
							}
						}
					}
					dcLanguage += ":" + xmlLangNameNode.InnerText;
				}
			}
			return dcLanguage;
		}
Example #9
0
    private static IEnumerable<IList<Expression>> GenerateList(Dictionary<Expression, IEnumerable<object>> elements, IList<Expression> list) {
      Contract.Requires(elements != null);

      var tmp = list ?? new List<Expression>();
      var kvp = elements.FirstOrDefault();
      if (kvp.Equals(default(KeyValuePair<Expression, IEnumerable<Object>>))) {
        if (list != null)
          yield return list;
        else {
          yield return new List<Expression>();
        }
      } else {

        elements.Remove(kvp.Key);
        foreach (var result in kvp.Value) {
          var resultExpr = result is IVariable ? Util.VariableToExpression(result as IVariable) : result as Expression;
          tmp.Add(resultExpr);
          foreach (var value in GenerateList(elements, tmp)) {
            yield return value;
          }
        }
      }
    }
        // ------------------------------------------------------------
        // Name: UpdateConvertedProspects
        // Abstract: Retrieve subscribers from a list
        // ------------------------------------------------------------
        public static Dictionary<string, string> GetDuplicateSubscribers()
        {
            Dictionary<string, string> dctDuplicateSubscribers = new Dictionary<string, string>();
            Dictionary<string, string> dctSubscribers = new Dictionary<string, string>();
            Dictionary<string, string> dctAllSubscribers = new Dictionary<string, string>();
            try
            {
                string strCustomerNumber = "";
                string strSubscriberKey = "";
                string strEmail = "";

                // Get subscriber dates
                ET_Subscriber getSub = new ET_Subscriber();
                getSub.AuthStub = m_etcTDClient;
                getSub.Props = new string[] { "SubscriberKey", "EmailAddress" };
                GetReturn getResponse = getSub.Get();
                Console.WriteLine("Get Status: " + getResponse.Status.ToString());
                Console.WriteLine("Message: " + getResponse.Message.ToString());
                Console.WriteLine("Code: " + getResponse.Code.ToString());
                Console.WriteLine("Results Length: " + getResponse.Results.Length);
                while (getResponse.MoreResults == true)
                {

                    foreach (ET_Subscriber sub in getResponse.Results)
                    {
                        Console.WriteLine("SubscriberKey: " + sub.SubscriberKey);

                        // Add to our list
                        dctAllSubscribers.Add(sub.SubscriberKey, sub.EmailAddress);
                    }

                    getResponse = getSub.GetMoreResults();
                }

                foreach (KeyValuePair<string, string> entry in dctAllSubscribers)
                {
                    strSubscriberKey = entry.Key;
                    strEmail = entry.Value;
                    // Add to duplicates if email already exists
                    if (dctSubscribers.ContainsValue(strEmail) == true)
                    {
                        // Get customer number from duplicate if duplicate hasn't been logged
                        if (dctDuplicateSubscribers.ContainsValue(strEmail) == false)
                        {
                            strCustomerNumber = dctSubscribers.FirstOrDefault(x => x.Value == strEmail).Key;

                            // Add (both) duplicate entries
                            dctDuplicateSubscribers.Add(strSubscriberKey, strEmail);
                            dctDuplicateSubscribers.Add(strCustomerNumber, strEmail);
                        }
                        else
                        {
                            dctDuplicateSubscribers.Add(strSubscriberKey, strEmail);
                        }
                    }
                    else
                    {
                        // Add to our list
                        dctSubscribers.Add(strSubscriberKey, strEmail);
                    }
                }

            }
            catch (Exception excError)
            {
                // Display Error
                Console.WriteLine("Error: " + excError.ToString());
            }

            return dctDuplicateSubscribers;
        }
Example #11
0
        static void Main(string[] args)
        {
            {
                C[] tableC = new C[10];
                Array.ForEach(tableC, c => { c = new C(); });

                Console.WriteLine("Objects Created ");
                Console.WriteLine("Press enter to Destroy it");
                Console.ReadLine();
                //Array.ForEach(tableC, c => { c = null; });
                tableC = null;

                Console.WriteLine("Call GC.Collect");
                GC.Collect();
            }
            
            //Test codes
            int spaceX = 0, spaceY = 0;
            Dictionary<int, int> mts = new Dictionary<int, int>();
            //mts.Any(k => { return k.Key == iTest && Math.Abs(k.Value - iTest) == 1; });
            bool isApproach = mts.Any(
                p => 
                { 
                    bool isApproachNow = ((p.Key == spaceX));
                    if (isApproachNow == true)
                    {
                        var nextL = mts.FirstOrDefault(p_ => { return (spaceY - p_.Value) <= 1; });

                        if (nextL.Equals(default(KeyValuePair<int, int>)) == true)
                        {
                            return true;
                        }
                        else 
                        {
                            return nextL.Key == spaceX;
                        }
                    }
                    else
                    {
                        return false;
                    }
                });

            //Any routines for call Object destructors.
            Console.Read();
            //Console.ReadLine();


            int n = int.Parse(Console.ReadLine()); // the number of temperatures to analyse
            string temps = Console.ReadLine(); // the n temperatures expressed as integers ranging from -273 to 5526

            // Write an action using Console.WriteLine()
            // To debug: Console.Error.WriteLine("Debug messages...");
            string[] tempsStr = temps.Split(' ');
            int[] tempsNum = new int[tempsStr.Count()];
            string.IsNullOrEmpty(temps);
            

            int tempNearst = tempsNum[0];
            foreach (int temp in tempsNum)
            {
                int tnAbs = Math.Abs(tempNearst), tAbs = Math.Abs(temp);
                if (tnAbs == tAbs)
                {
                    tempNearst = (temp > 0) ? temp : tempNearst;
                }
                else if (tnAbs > tAbs)
                {
                    tempNearst = temp;
                }
            }



            //string outputDebug = "";
            //for (int i = 0; i < 10; ++i)
            //{
            //    outputDebug = outputDebug + "\nNumber:" + i;
            //}

            //System.Diagnostics.Trace.WriteLine(outputDebug);
        }
        // Adds item control to a group
        // (this item control will only be allowed to participate in d&d in this particular gorup)
        private static void Add(Dictionary<String, List<ItemsControl>> dictionary, object sender)
        {
            InitializeDragDropCollections();

            var dp = sender as DependencyObject;
            var itemsControl = sender as ItemsControl;
            var groupName = GetGroupName(dp);

            var foundGroup = dictionary.FirstOrDefault(p => p.Key == groupName);
            if (!foundGroup.Value.Contains(itemsControl))
                dictionary[groupName].Add(itemsControl);

            itemsControl.Unloaded += DropTarget_Unloaded;
            itemsControl.Loaded += DropTarget_Loaded;
        }
        // Removes item control from group
        private static void Remove(Dictionary<String, List<ItemsControl>> dictionary, object sender)
        {
            var dp = sender as DependencyObject;
            var itemsControl = sender as ItemsControl;
            var groupName = GetGroupName(dp);

            var foundGroup = dictionary.FirstOrDefault(p => p.Key == groupName);
            if (foundGroup.Value.Contains(itemsControl))
                dictionary[groupName].Remove(itemsControl);

            itemsControl.Unloaded -= DropTarget_Unloaded;
            itemsControl.Loaded -= DropTarget_Loaded;
        }
Example #14
0
        public static string GetState(string abbr = null, string state = null)
        {
            Dictionary<string, string> states = new Dictionary<string, string>();
            states.Add("AL", "alabama");
            states.Add("AK", "alaska");
            states.Add("AZ", "arizona");
            states.Add("AR", "arkansas");
            states.Add("CA", "california");
            states.Add("CO", "colorado");
            states.Add("CT", "connecticut");
            states.Add("DE", "delaware");
            states.Add("DC", "district of columbia");
            states.Add("FL", "florida");
            states.Add("GA", "georgia");
            states.Add("HI", "hawaii");
            states.Add("ID", "idaho");
            states.Add("IL", "illinois");
            states.Add("IN", "indiana");
            states.Add("IA", "iowa");
            states.Add("KS", "kansas");
            states.Add("KY", "kentucky");
            states.Add("LA", "louisiana");
            states.Add("ME", "maine");
            states.Add("MD", "maryland");
            states.Add("MA", "massachusetts");
            states.Add("MI", "michigan");
            states.Add("MN", "minnesota");
            states.Add("MS", "mississippi");
            states.Add("MO", "missouri");
            states.Add("MT", "montana");
            states.Add("NE", "nebraska");
            states.Add("NV", "nevada");
            states.Add("NH", "new hampshire");
            states.Add("NJ", "new jersey");
            states.Add("NM", "new mexico");
            states.Add("NY", "new york");
            states.Add("NC", "north carolina");
            states.Add("ND", "north dakota");
            states.Add("OH", "ohio");
            states.Add("OK", "oklahoma");
            states.Add("OR", "oregon");
            states.Add("PA", "pennsylvania");
            states.Add("RI", "rhode island");
            states.Add("SC", "south carolina");
            states.Add("SD", "south dakota");
            states.Add("TN", "tennessee");
            states.Add("TX", "texas");
            states.Add("UT", "utah");
            states.Add("VT", "vermont");
            states.Add("VA", "virginia");
            states.Add("WA", "washington");
            states.Add("WV", "west virginia");
            states.Add("WI", "wisconsin");
            states.Add("WY", "wyoming");

            if (abbr != null && states.ContainsKey(abbr.ToUpper()))
                return (states[abbr.ToUpper()]);

            if (state != null && states.Values.Contains(state.ToLower()))
                return states.FirstOrDefault(x => x.Value == state).Key;

            /* error handler is to return an empty string rather than throwing an exception */
            return "";
        }