Ejemplo n.º 1
0
        private void buttonLoadAttrinuteTypes_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog()
                {
                    Filter = SerializationData.FileDialogFilter,
                    Title  = SerializationData.LoadAttributeTypesFileDialogTitle
                };

                Nullable <bool> ofdResult = ofd.ShowDialog();

                if (ofdResult == true)
                {
                    XDocument attributeTypesXDocument = XDocument.Load(ofd.FileName);
                    foreach (var attributeTypesXElement in attributeTypesXDocument.Elements())
                    {
                        if (attributeTypesXElement.Name.ToString().Equals(SerializationData.AttributeTypesNode))
                        {
                            foreach (var attributeTypeXElement in attributeTypesXElement.Elements())
                            {
                                if (attributeTypeXElement.Name.ToString().Equals(SerializationData.AttributeTypeNode))
                                {
                                    AttributeTypesDataGridItem item = new AttributeTypesDataGridItem();
                                    foreach (var attributeTypeXAttribute in attributeTypeXElement.Attributes())
                                    {
                                        if (attributeTypeXAttribute.Name.ToString().Equals(SerializationData.IsUse))
                                        {
                                            item.IsUse = Convert.ToBoolean(attributeTypeXAttribute.Value);
                                        }
                                        if (attributeTypeXAttribute.Name.ToString().Equals(SerializationData.AttributeTypeName))
                                        {
                                            item.Name = attributeTypeXAttribute.Value;
                                        }
                                        if (attributeTypeXAttribute.Name.ToString().Equals(SerializationData.AttrinuteTypeType))
                                        {
                                            switch (attributeTypeXAttribute.Value)
                                            {
                                            case "Boolean":
                                            {
                                                item.Type = Types.Boolean;
                                            }
                                            break;

                                            case "Integer":
                                            {
                                                item.Type = Types.Integer;
                                            }
                                            break;

                                            case "Float":
                                            {
                                                item.Type = Types.Float;
                                            }
                                            break;

                                            case "String":
                                            {
                                                item.Type = Types.String;
                                            }
                                            break;

                                            default:
                                            {
                                                throw new Exception();
                                            }
                                            break;
                                            }
                                        }
                                        if (attributeTypeXAttribute.Name.ToString().Equals(SerializationData.AttributeTypeValues))
                                        {
                                            item.Values += attributeTypeXAttribute.Value;
                                        }
                                    }
                                    _items.Add(item);
                                    if (!item.IsValid())
                                    {
                                        //todo сделать получение строки по элементу
                                    }
                                }
                            }
                        }
                    }

                    dataGrid.Items.Refresh();

                    if (OnFileLoaded != null)
                    {
                        OnFileLoaded(sender, "Типы тарибутов загружены из файла " + ofd.FileName + ".");
                    }
                }
            }
            catch (Exception ex)
            {
                if (OnErrorOccured != null)
                {
                    OnErrorOccured(this, ex.Message);
                }
            }
        }
Ejemplo n.º 2
0
        private async void build()
        {
            await Task.Run(() =>
            {
                listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] Building has started.");
                string packageName = textBox1.Text;
                int versionCode    = 10;
                string versionName = textBox2.Text;
                stringValueleriYaz();
                string msbuild = settings[0];//@"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\msbuild.exe";
                //var msbuild = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe";
                //@"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\msbuild.exe";
                string zipalign             = settings[1]; //@"C:\Program Files (x86)\Android\android-sdk\build-tools\29.0.2\zipalign.exe";
                string jarsigner            = settings[2]; //@"C:\Program Files\Java\jdk1.8.0_211\bin\jarsigner.exe";
                string buildManifest        = "Properties/AndroidManifest.xml";
                string androidProjectFolder = Environment.CurrentDirectory + @"\resources\ProjectFolder";
                string androidProject       = $"{androidProjectFolder}\\Camera.csproj";
                string outputPath           = Environment.CurrentDirectory + @"\outs\" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string abi = "tht";

                string specificManifest = $"Properties/AndroidManifest.{abi}_{versionCode}.xml";
                string binPath          = $"{outputPath}/{abi}/bin";
                string objPath          = $"{outputPath}/{abi}/obj";

                string keystorePath     = Environment.CurrentDirectory + "\\bocek.keystore";
                string keystorePassword = "******";
                string keystoreKey      = "bocek";

                XDocument xmlFile                = XDocument.Load($"{androidProjectFolder}/{buildManifest}");
                XElement mnfst                   = xmlFile.Elements("manifest").First();
                XNamespace androidNamespace      = mnfst.GetNamespaceOfPrefix("android");
                mnfst.Attribute("package").Value = packageName;
                mnfst.Attribute(androidNamespace + "versionName").Value = versionName;
                mnfst.Attribute(androidNamespace + "versionCode").Value = "10";
                xmlFile.Save($"{androidProjectFolder}/{buildManifest}");

                string unsignedApkPath = $"\"{binPath}/{packageName}.apk\"";
                string signedApkPath   = $"\"{binPath}/{packageName}_signed.apk\"";
                string alignedApkPath  = $"{binPath}/{textBox7.Text.Replace(" ", "_")}.apk";

                string mbuildArgs    = $"{androidProject} /t:PackageForAndroid /t:restore /p:AndroidSupportedAbis=\"armeabi-v7a;x86;arm64-v8a;x86_64\" /p:Configuration=Release /p:IntermediateOutputPath={objPath}/ /p:OutputPath={binPath}";
                string jarsignerArgs = $"-verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore {keystorePath} -storepass {keystorePassword} -signedjar \"{signedApkPath}\" {unsignedApkPath} {keystoreKey}";
                string zipalignArgs  = $"-f -v 4 {signedApkPath} {alignedApkPath}";


                RunProcess(msbuild, mbuildArgs);
                listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] Compiled.");

                RunProcess(jarsigner, jarsignerArgs);
                listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] APK signed.");

                //Google Play'de yayınlayabilmeniz için.
                RunProcess(zipalign, zipalignArgs);
                listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] Zipalign completed.");

                File.Copy($"{alignedApkPath}", $"{outputPath}/{Path.GetFileName(alignedApkPath)}", true);
                DirectoryInfo di = new DirectoryInfo(binPath);
                FileInfo[] fi    = di.GetFiles("*.*");
                foreach (FileInfo f in fi)
                {
                    if (!f.Name.Contains(textBox7.Text.Replace(" ", "_")))
                    {
                        f.Delete();
                    }
                }
                new DirectoryInfo(binPath).GetDirectories()[0].Delete(true);
                Process.Start($"{binPath}");

                listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] APK is ready.");
            });
        }
Ejemplo n.º 3
0
 internal static XElement Root(this XDocument xmlDocument)
 {
     return(xmlDocument.Elements(SoftwareIdentity).FirstOrDefault());
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Removes personal information from the document.
        /// </summary>
        /// <param name="document"></param>
        public static OpenXmlPowerToolsDocument RemovePersonalInformation(WmlDocument doc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XNamespace x = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
                    XDocument  extendedFileProperties = document.ExtendedFilePropertiesPart.GetXDocument();
                    extendedFileProperties.Elements(x + "Properties").Elements(x + "Company").Remove();
                    XElement totalTime = extendedFileProperties.Elements(x + "Properties").Elements(x + "TotalTime").FirstOrDefault();
                    if (totalTime != null)
                    {
                        totalTime.Value = "0";
                    }
                    document.ExtendedFilePropertiesPart.PutXDocument();

                    XNamespace dc = "http://purl.org/dc/elements/1.1/";
                    XNamespace cp = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
                    XDocument  coreFileProperties = document.CoreFilePropertiesPart.GetXDocument();
                    foreach (var textNode in coreFileProperties.Elements(cp + "coreProperties")
                             .Elements(dc + "creator")
                             .Nodes()
                             .OfType <XText>())
                    {
                        textNode.Value = "";
                    }
                    foreach (var textNode in coreFileProperties.Elements(cp + "coreProperties")
                             .Elements(cp + "lastModifiedBy")
                             .Nodes()
                             .OfType <XText>())
                    {
                        textNode.Value = "";
                    }
                    foreach (var textNode in coreFileProperties.Elements(cp + "coreProperties")
                             .Elements(dc + "title")
                             .Nodes()
                             .OfType <XText>())
                    {
                        textNode.Value = "";
                    }
                    XElement revision = coreFileProperties.Elements(cp + "coreProperties").Elements(cp + "revision").FirstOrDefault();
                    if (revision != null)
                    {
                        revision.Value = "1";
                    }
                    document.CoreFilePropertiesPart.PutXDocument();

                    // add w:removePersonalInformation, w:removeDateAndTime to DocumentSettingsPart
                    XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
                    XDocument  documentSettings = document.MainDocumentPart.DocumentSettingsPart.GetXDocument();
                    // add the new elements in the right position.  Add them after the following three elements
                    // (which may or may not exist in the xml document).
                    XElement settings   = documentSettings.Root;
                    XElement lastOfTop3 = settings.Elements()
                                          .Where(e => e.Name == w + "writeProtection" ||
                                                 e.Name == w + "view" ||
                                                 e.Name == w + "zoom")
                                          .InDocumentOrder()
                                          .LastOrDefault();
                    if (lastOfTop3 == null)
                    {
                        // none of those three exist, so add as first children of the root element
                        settings.AddFirst(
                            settings.Elements(w + "removePersonalInformation").Any() ?
                            null :
                            new XElement(w + "removePersonalInformation"),
                            settings.Elements(w + "removeDateAndTime").Any() ?
                            null :
                            new XElement(w + "removeDateAndTime")
                            );
                    }
                    else
                    {
                        // one of those three exist, so add after the last one
                        lastOfTop3.AddAfterSelf(
                            settings.Elements(w + "removePersonalInformation").Any() ?
                            null :
                            new XElement(w + "removePersonalInformation"),
                            settings.Elements(w + "removeDateAndTime").Any() ?
                            null :
                            new XElement(w + "removeDateAndTime")
                            );
                    }
                    document.MainDocumentPart.DocumentSettingsPart.PutXDocument();
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
Ejemplo n.º 5
0
        private void xmlToVertex()
        {
            string token = "";

            try {
                var svgElement = svgXMLDoc.Elements().Where(s => s.Name.LocalName == "svg").FirstOrDefault();
                int width      = (int)float.Parse(Regex.Replace(svgElement.Attribute("width").Value, "[^0-9\\-\\.]", ""));
                int height     = (int)float.Parse(Regex.Replace(svgElement.Attribute("height").Value, "[^0-9\\-\\.]", ""));
                svgView           = new Bitmap(width, height);
                pictureBox1.Image = svgView;
                System.Diagnostics.Debug.WriteLine(width + "x" + height);
                float translateX = 0, translateY = 0, scaleX = 1, scaleY = 1;
                var   paths = svgElement.Descendants().Where(s => s.Name.LocalName == "path");
                vertexList.Clear();
                edgeList.Clear();
                foreach (var path in paths)
                {
                    if (path.Parent.Name.LocalName == "g")
                    {
                        System.Diagnostics.Debug.WriteLine(path.Parent.Name);
                        string transform      = path.Parent.Attribute("transform").Value;
                        Match  translateMatch = Regex.Match(transform, "translate[^\\)]+\\)");
                        if (translateMatch != null)
                        {
                            string translate = translateMatch.ToString().Substring("translate(".Length);
                            translate = translate.Substring(0, translate.Length - 1);
                            string[] args = translate.Split(",".ToCharArray());
                            translateX = float.Parse(args[0].Trim());
                            translateY = float.Parse(args[1].Trim());
                        }
                        Match scaleMatch = Regex.Match(transform, "scale[^\\)]+\\)");
                        if (scaleMatch != null)
                        {
                            string scale = scaleMatch.ToString().Substring("scale(".Length);
                            scale = scale.Substring(0, scale.Length - 1);
                            string[] args = scale.Split(",".ToCharArray());
                            scaleX = float.Parse(args[0].Trim());
                            scaleY = float.Parse(args[1].Trim());
                        }
                    }

                    string d = path.Attribute("d").Value.Replace(',', ' ').Replace("\r", "").Replace("\n", "").Replace("\t", " ");
                    d = Regex.Replace(d, "\\s+", " ");
                    Match match;
                    while ((match = Regex.Match(d, "\\d\\-")).Success)
                    {
                        d = d.Substring(0, match.Index + 1) + " " + d.Substring(match.Index + 1);
                    }
                    System.Diagnostics.Debug.WriteLine(d);
                    System.Diagnostics.Debug.WriteLine(translateX + ", " + translateY + " - " + scaleX + ", " + scaleY);
                    float cursorX = 0;
                    float cursorY = 0;
                    token = "";
                    string previousToken = "";

                    PointFloat lastStartPoint = new PointFloat();
                    PointFloat lastEndPoint   = new PointFloat();
                    int        loopStart      = vertexList.Count;
                    while (d.Length > 0)
                    {
                        //System.Diagnostics.Debug.WriteLine(d);
                        readNextToken(ref d, "\\S");
                        if (Regex.IsMatch(d.Substring(0, 1), "[^0-9\\-\\.]"))
                        {
                            token = d.Substring(0, 1);
                            d     = d.Substring(1);
                        }
                        else
                        {
                            token = previousToken;
                        }
                        switch (token)
                        {
                        case "M":
                            cursorX = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                            readNextToken(ref d, "[^\\s]");
                            cursorY = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            vertexList.Add(new PointFloat(cursorX, cursorY));
                            break;

                        case "m":
                            cursorX += float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                            readNextToken(ref d, "[^\\s]");
                            cursorY += float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            vertexList.Add(new PointFloat(cursorX, cursorY));
                            break;

                        case "L":
                        case "l": {
                            float x = 0, y = 0;
                            if (token == "L")
                            {
                                x = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            }
                            else
                            {
                                x = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y = cursorY + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            }
                            cursorX = x;
                            cursorY = y;
                            lineTo(cursorX, cursorY);
                            break;
                        }

                        case "H":
                        case "h": {
                            float x = 0;
                            if (token == "H")
                            {
                                x = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleX + translateX;
                            }
                            else
                            {
                                x = cursorX + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleX;
                            }
                            cursorX = x;
                            lineTo(cursorX, cursorY);
                            break;
                        }

                        case "V":
                        case "v": {
                            float y = 0;
                            if (token == "V")
                            {
                                y = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            }
                            else
                            {
                                y = cursorY + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            }
                            cursorY = y;
                            lineTo(cursorX, cursorY);
                            break;
                        }

                        case "C":
                        case "c": {
                            float x = 0, y = 0, x1 = 0, y1 = 0, x2 = 0, y2 = 0;
                            if (token == "C")
                            {
                                x1 = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y1 = float.Parse(readNextToken(ref d, "\\s")) * scaleY + translateY;
                                readNextToken(ref d, "[^\\s]");
                                x2 = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y2 = float.Parse(readNextToken(ref d, "\\s")) * scaleY + translateY;
                                readNextToken(ref d, "[^\\s]");
                                x = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            }
                            else
                            {
                                x1 = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y1 = cursorY + float.Parse(readNextToken(ref d, "\\s")) * scaleY;
                                readNextToken(ref d, "[^\\s]");
                                x2 = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y2 = cursorY + float.Parse(readNextToken(ref d, "\\s")) * scaleY;
                                readNextToken(ref d, "[^\\s]");
                                x = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y = cursorY + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            }
                            cursorX = x;
                            cursorY = y;
                            curveToCubic(x1, y1, x2, y2, x, y);
                            lastStartPoint.x = x1;
                            lastStartPoint.y = y1;
                            lastEndPoint.x   = x2;
                            lastEndPoint.y   = y2;
                            break;
                        }

                        case "Q":
                        case "q": {
                            float x = 0, y = 0, x1 = 0, y1 = 0;
                            if (token == "Q")
                            {
                                x1 = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y1 = float.Parse(readNextToken(ref d, "\\s")) * scaleY + translateY;
                                readNextToken(ref d, "[^\\s]");
                                x = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            }
                            else
                            {
                                x1 = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y1 = cursorY + float.Parse(readNextToken(ref d, "\\s")) * scaleY;
                                readNextToken(ref d, "[^\\s]");
                                x = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y = cursorY + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            }
                            cursorX          = x;
                            cursorY          = y;
                            lastStartPoint.x = x1;
                            lastStartPoint.y = y1;
                            curveToQuad(x1, y1, x, y);
                            break;
                        }

                        case "S":
                        case "s": {
                            float x = 0, y = 0, x2 = 0, y2 = 0;
                            if (token == "S")
                            {
                                x2 = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y2 = float.Parse(readNextToken(ref d, "\\s")) * scaleY + translateY;
                                readNextToken(ref d, "[^\\s]");
                                x = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            }
                            else
                            {
                                x2 = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y2 = cursorY + float.Parse(readNextToken(ref d, "\\s")) * scaleY;
                                readNextToken(ref d, "[^\\s]");
                                x = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y = cursorY + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            }
                            cursorX = x;
                            cursorY = y;
                            curveToCubic(lastEndPoint.x, lastEndPoint.y, x2, y2, x, y);
                            lastEndPoint.x = x2;
                            lastEndPoint.y = y2;
                            break;
                        }

                        case "T":
                        case "t": {
                            float x = 0, y = 0;
                            if (token == "T")
                            {
                                x = float.Parse(readNextToken(ref d, "\\s")) * scaleX + translateX;
                                readNextToken(ref d, "[^\\s]");
                                y = float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY + translateY;
                            }
                            else
                            {
                                x = cursorX + float.Parse(readNextToken(ref d, "\\s")) * scaleX;
                                readNextToken(ref d, "[^\\s]");
                                y = cursorY + float.Parse(readNextToken(ref d, "[^0-9\\-\\.]")) * scaleY;
                            }
                            cursorX = x;
                            cursorY = y;
                            curveToCubic(lastStartPoint.x, lastStartPoint.y, lastEndPoint.x, lastEndPoint.y, x, y);
                            break;
                        }

                        case "z":
                        case "Z":
                            lineTo(vertexList[loopStart].x, vertexList[loopStart].y);
                            loopStart = vertexList.Count;
                            break;

                        default:
                            System.Diagnostics.Debug.WriteLine("doodster");
                            readNextToken(ref d, "[^a-zA-Z]");
                            break;
                        }
                        previousToken = token;
                        //System.Diagnostics.Debug.WriteLine(d);
                    }
                }
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace + "\n" + token);
            }
        }
Ejemplo n.º 6
0
    public static XDocument Adjust(CodeClass codeClass, string workPlace, string csprojPath, List <FileInfo> files)
    {
        DirectoryInfo workPlaceDir = new DirectoryInfo(workPlace);

        workPlace = workPlaceDir.FullName.Replace("/", "\\");
        XDocument doc      = XDocument.Load(csprojPath);
        XElement  project  = doc.Elements().First(e => e.Name.LocalName == "Project");
        var       comments = doc.Nodes().Where(n => n.NodeType == System.Xml.XmlNodeType.Comment).ToList();

        foreach (var c in comments)
        {
            c.Remove();
        }
        var             itemGroups = project.Elements().Where(e => e.Name.LocalName == "ItemGroup");
        List <XElement> delCompile = new List <XElement>();

        foreach (XElement itemGroup in itemGroups)
        {
            foreach (var element in itemGroup.Elements())
            {
                if (element.Name.LocalName == "Compile")
                {
                    delCompile.Add(element);
                }
                if (element.Name.LocalName == "ProjectReference")
                {
                    XAttribute includeAttr = element.Attribute("Include");
                    if (includeAttr != null && includeAttr.Value == analyzerPath)
                    {
                        delCompile.Add(element);
                    }
                }
            }
        }
        foreach (XElement item in delCompile)
        {
            item.Remove();
        }
        foreach (var csFile in files)
        {
            string   fullPath       = csFile.FullName.Replace("/", "\\");
            XElement firstItemGroup = project.Elements().First(e => e.Name.LocalName == "ItemGroup");
            XElement compile        = new XElement(project.Name.ToString().Replace("Project", "Compile"), new XAttribute("Include", fullPath));
            XElement link           = new XElement(project.Name.ToString().Replace("Project", "Link"));
            link.SetValue(fullPath.Substring(workPlace.Length + 1));
            compile.Add(link);
            firstItemGroup.Add(compile);
        }
        XElement lastItemGroup    = project.Elements().Last(e => e.Name.LocalName == "ItemGroup");
        XElement projectReference = new XElement(project.Name.ToString().Replace("Project", "ProjectReference"));

        projectReference.SetAttributeValue("Include", analyzerPath);
        projectReference.SetAttributeValue("OutputItemType", @"Analyzer");
        projectReference.SetAttributeValue("ReferenceOutputAssembly", @"false");
        if (codeClass == CodeClass.Client)
        {
            XElement projectItem = new XElement(project.Name.ToString());
            projectItem.Value = @"{d1f2986b-b296-4a2d-8f12-be9f470014c3}";
            projectReference.Add(projectItem);
        }
        lastItemGroup.Add(projectReference);
        return(doc);
    }
Ejemplo n.º 7
0
        private void UpdateStitchAndOverlaysInDoc()
        {
            bool Error = false;

            // Let's see if one stich button is enabled
            bool stich_on    = false;
            bool voverlay_on = false;
            bool aoverlay_on = false;


            foreach (Control c in this.tableLayoutPanelIAssets.Controls)
            {
                if (c.Text == strStitch)
                {
                    if (((CheckBox)c).Checked)
                    {
                        stich_on = true;
                        break;
                    }
                }
            }

            foreach (Control c in this.tableLayoutPanelIAssets.Controls)
            {
                if (c.Text == strVisualoverlay)
                {
                    if (((CheckBox)c).Checked)
                    {
                        voverlay_on = true;
                        break;
                    }
                }
            }

            foreach (Control c in this.tableLayoutPanelIAssets.Controls)
            {
                if (c.Text == strAudiooverlay)
                {
                    if (((CheckBox)c).Checked)
                    {
                        aoverlay_on = true;
                        break;
                    }
                }
            }



            if (stich_on || voverlay_on || aoverlay_on || !xmlOpenedNotYetStiched) // on stich checkbox is checked, or checkbox as been selected in the past for this file, so let's modify the xml doc
            {
                XDocument docbackup = doc;

                try
                {
                    var test = doc.Element("Presets");

                    if (test == null) // It's an "old" preset file without the Presets attribute
                    {
                        var presets = doc.Elements("Preset");
                        if (presets.Count() == 0)
                        {
                            throw new Exception();
                        }

                        foreach (var preset in presets)
                        {
                            // WE DELETE ALL IN ORDER TO REBUILD
                            if ((preset.Descendants("Sources").Count()) > 0)
                            {
                                preset.Descendants("Sources").Remove();
                            }

                            if ((preset.Descendants("Sources").Count()) == 0)
                            {
                                preset
                                .Element("MediaFile")
                                .AddFirst(new XElement("Sources"));
                            }


                            for (int row = 0; row < tableLayoutPanelIAssets.RowCount; row++)
                            {
                                for (int col = 0; col < tableLayoutPanelIAssets.ColumnCount; col++)
                                {
                                    Control c = tableLayoutPanelIAssets.GetControlFromPosition(col, row);
                                    if (c.Text == strStitch)
                                    {
                                        if (((CheckBox)c).Checked)
                                        {
                                            string f = string.Format("%{0}%", (int)c.Tag);

                                            // We should not add MediaFile attribute for asset #0
                                            if ((int)c.Tag == 0)
                                            {
                                                preset.Descendants("Sources").FirstOrDefault().Add(new XElement("Source", new XAttribute("AudioStreamIndex", 0)));
                                            }
                                            else
                                            {
                                                preset.Descendants("Sources").FirstOrDefault().Add(new XElement("Source", new XAttribute("AudioStreamIndex", 0), new XAttribute("MediaFile", f)));
                                            }

                                            CheckBox edittimes = (CheckBox)c.Parent.GetNextControl(c, true);
                                            if (edittimes.Checked)
                                            {
                                                preset.Descendants("Source").LastOrDefault().AddFirst(new XElement("Clips"));
                                                TextBox startime = (TextBox)c.Parent.GetNextControl(edittimes, true);
                                                TextBox endtime  = (TextBox)c.Parent.GetNextControl(startime, true);
                                                preset.Descendants("Clips").LastOrDefault().Add(new XElement("Clip", new XAttribute("StartTime", startime.Text), new XAttribute("EndTime", endtime.Text)));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else // new preset file with the Presets attribute
                    {
                        var presets = doc.Element("Presets").Elements("Preset");
                        if (presets.Count() == 0)
                        {
                            throw new Exception();
                        }

                        foreach (var preset in presets)
                        {
                            // WE DELETE ALL IN ORDER TO REBUILD
                            if ((preset.Descendants("Sources").Count()) > 0)
                            {
                                preset.Descendants("Sources").Remove();
                            }

                            if ((preset.Descendants("Sources").Count()) == 0)
                            {
                                preset
                                .Element("MediaFile")
                                .AddFirst(new XElement("Sources"));
                            }
                            var mediafile = preset.Descendants("MediaFile");
                            if (mediafile.Attributes("OverlayFileName").Count() > 0)
                            {
                                mediafile.Attributes("OverlayFileName").Remove();
                            }
                            if (mediafile.Attributes("OverlayRect").Count() > 0)
                            {
                                mediafile.Attributes("OverlayRect").Remove();
                            }
                            if (mediafile.Attributes("OverlayOpacity").Count() > 0)
                            {
                                mediafile.Attributes("OverlayOpacity").Remove();
                            }
                            if (mediafile.Attributes("OverlayFadeInDuration").Count() > 0)
                            {
                                mediafile.Attributes("OverlayFadeInDuration").Remove();
                            }
                            if (mediafile.Attributes("OverlayFadeOutDuration").Count() > 0)
                            {
                                mediafile.Attributes("OverlayFadeOutDuration").Remove();
                            }
                            if (mediafile.Attributes("OverlayLayoutMode").Count() > 0)
                            {
                                mediafile.Attributes("OverlayLayoutMode").Remove();
                            }
                            if (mediafile.Attributes("OverlayStartTime").Count() > 0)
                            {
                                mediafile.Attributes("OverlayStartTime").Remove();
                            }
                            if (mediafile.Attributes("OverlayEndTime").Count() > 0)
                            {
                                mediafile.Attributes("OverlayEndTime").Remove();
                            }

                            if (mediafile.Attributes("AudioOverlayFileName").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayFileName").Remove();
                            }
                            if (mediafile.Attributes("AudioOverlayLoop").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayLoop").Remove();
                            }
                            if (mediafile.Attributes("AudioOverlayLoopingGap").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayLoopingGap").Remove();
                            }
                            if (mediafile.Attributes("AudioOverlayLayoutMode").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayLayoutMode").Remove();
                            }
                            if (mediafile.Attributes("AudioOverlayGainLevel").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayGainLevel").Remove();
                            }
                            if (mediafile.Attributes("AudioOverlayFadeInDuration").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayFadeInDuration").Remove();
                            }
                            if (mediafile.Attributes("AudioOverlayFadeOutDuration").Count() > 0)
                            {
                                mediafile.Attributes("AudioOverlayFadeOutDuration").Remove();
                            }

                            for (int row = 0; row < tableLayoutPanelIAssets.RowCount; row++)
                            {
                                for (int col = 0; col < tableLayoutPanelIAssets.ColumnCount; col++)
                                {
                                    Control c = tableLayoutPanelIAssets.GetControlFromPosition(col, row);
                                    if (c.Text == strStitch)
                                    {
                                        if (((CheckBox)c).Checked)
                                        {
                                            string f = string.Empty;
                                            if (bMultiAssetMode)
                                            {
                                                f = string.Format("%{0}%", (int)c.Tag);
                                                if ((int)c.Tag == 0) // We should not add MediaFile attribute for asset #0
                                                {
                                                    preset.Descendants("Sources").FirstOrDefault().Add(new XElement("Source", new XAttribute("AudioStreamIndex", 0)));
                                                }
                                                else
                                                {
                                                    preset.Descendants("Sources").FirstOrDefault().Add(new XElement("Source", new XAttribute("AudioStreamIndex", 0), new XAttribute("MediaFile", f)));
                                                }
                                            }
                                            else // mono asset mode
                                            {
                                                if ((int)c.Tag == 0) // We should not add MediaFile attribute for assetfile #0
                                                {
                                                    preset.Descendants("Sources").FirstOrDefault().Add(new XElement("Source", new XAttribute("AudioStreamIndex", 0)));
                                                }
                                                else
                                                {
                                                    preset.Descendants("Sources").FirstOrDefault().Add(new XElement("Source", new XAttribute("AudioStreamIndex", 0), new XAttribute("MediaFile", SelectedAssets.FirstOrDefault().AssetFiles.Skip((int)c.Tag).Take(1).FirstOrDefault().Name)));
                                                }
                                            }

                                            CheckBox edittimes = (CheckBox)c.Parent.GetNextControl(c, true);
                                            if (edittimes.Checked)
                                            {
                                                preset.Descendants("Source").LastOrDefault().AddFirst(new XElement("Clips"));
                                                TextBox startime = (TextBox)c.Parent.GetNextControl(edittimes, true);
                                                TextBox endtime  = (TextBox)c.Parent.GetNextControl(startime, true);
                                                preset.Descendants("Clips").LastOrDefault().Add(new XElement("Clip", new XAttribute("StartTime", startime.Text), new XAttribute("EndTime", endtime.Text)));
                                            }
                                        }
                                    }
                                    if (c.Text == strVisualoverlay)
                                    {
                                        if (((CheckBox)c).Checked)
                                        {
                                            string f = string.Empty;
                                            if (bMultiAssetMode)
                                            {
                                                f = string.Format("%{0}%", (int)c.Tag);
                                                if ((int)c.Tag == 0)
                                                {
                                                    mediafile.FirstOrDefault().Add(new XAttribute("OverlayFileName", 0));
                                                }
                                                else
                                                {
                                                    mediafile.FirstOrDefault().Add(new XAttribute("OverlayFileName", f));
                                                }
                                            }
                                            else // mono asset mode
                                            {
                                                mediafile.FirstOrDefault().Add(new XAttribute("OverlayFileName", SelectedAssets.FirstOrDefault().AssetFiles.Skip((int)c.Tag).Take(1).FirstOrDefault().Name));
                                            }

                                            mediafile.FirstOrDefault().Add(new XAttribute("OverlayRect", string.Format("{0}, {1}, {2}, {3}", numericUpDownVOverlayRectX.Value, numericUpDownVOverlayRectY.Value, numericUpDownVOverlayRectW.Value, numericUpDownVOverlayRectH.Value)));
                                            mediafile.FirstOrDefault().Add(new XAttribute("OverlayOpacity", numericUpDownVOverlayOpacity.Value));
                                            mediafile.FirstOrDefault().Add(new XAttribute("OverlayFadeInDuration", textBoxVOverlayFadeIn.Text));
                                            mediafile.FirstOrDefault().Add(new XAttribute("OverlayFadeOutDuration", textBoxVOverlayFadeOut.Text));
                                            mediafile.FirstOrDefault().Add(new XAttribute("OverlayLayoutMode", comboBoxVOverlayMode.SelectedItem));
                                            if ((string)comboBoxVOverlayMode.SelectedItem == "Custom")
                                            {
                                                mediafile.FirstOrDefault().Add(new XAttribute("OverlayStartTime", textBoxVOverlayStartTime.Text));
                                                mediafile.FirstOrDefault().Add(new XAttribute("OverlayEndTime", textBoxVOverlayEndTime.Text));
                                            }
                                        }
                                    }
                                    if (c.Text == strAudiooverlay)
                                    {
                                        if (((CheckBox)c).Checked)
                                        {
                                            string f = string.Empty;
                                            if (bMultiAssetMode)
                                            {
                                                f = string.Format("%{0}%", (int)c.Tag);
                                                if ((int)c.Tag == 0)
                                                {
                                                    mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayFileName", 0));
                                                }
                                                else
                                                {
                                                    mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayFileName", f));
                                                }
                                            }
                                            else // mono asset mode
                                            {
                                                mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayFileName", SelectedAssets.FirstOrDefault().AssetFiles.Skip((int)c.Tag).Take(1).FirstOrDefault().Name));
                                            }


                                            mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayLoop", CheckBoxAOverlayLoop.Checked));
                                            if (CheckBoxAOverlayLoop.Checked)
                                            {
                                                mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayLoopingGap", textBoxAOverlayGap.Text));
                                            }
                                            mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayGainLevel", numericUpDownAOverlayGain.Value));
                                            mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayFadeInDuration", textBoxAOverlayFadeIn.Text));
                                            mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayFadeOutDuration", textBoxAOverlayFadeOut.Text));
                                            mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayLayoutMode", comboBoxAOverlayMode.SelectedItem));
                                            if ((string)comboBoxAOverlayMode.SelectedItem == "Custom")
                                            {
                                                mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayStartTime", textBoxAOverlayStart.Text));
                                                mediafile.FirstOrDefault().Add(new XAttribute("AudioOverlayEndTime", textBoxAOverlayEnd.Text));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("Error when processing the XML preset. Is it a AME preset?");
                    doc   = docbackup;
                    Error = true;
                }
                textBoxConfiguration.Text = doc.ToString();
                if (!Error)
                {
                    xmlOpenedNotYetStiched = false;
                }
            }
        }
Ejemplo n.º 8
0
        //Восстанавливаем из xml
        public void LoadAll(string fileName)
        {
            deleteAll();
            XDocument xdoc = XDocument.Load(fileName);

            var xElements = xdoc.Elements("vertex");

            foreach (XElement el in xdoc.Root.Elements())
            {
                if (el.Name == "vertexs")
                {
                    foreach (XElement ell in el.Elements())
                    {
                        if (ell.Name == "vertex")
                        {
                            TextBox loadTxtBox = new TextBox();
                            loadTxtBox.Multiline = true;
                            loadTxtBox.Parent    = sheet;
                            loadTxtBox.BackColor = Color.Silver;
                            loadTxtBox.Left      = Int32.Parse(ell.Attribute("Left").Value);
                            loadTxtBox.Top       = Int32.Parse(ell.Attribute("Top").Value);
                            loadTxtBox.Width     = Int32.Parse(ell.Attribute("Width").Value);
                            loadTxtBox.Height    = Int32.Parse(ell.Attribute("Height").Value);
                            loadTxtBox.Text      = ell.Attribute("Text").Value;
                            loadTxtBox.TextAlign = HorizontalAlignment.Center; //To Do по центру надо а тут сверху
                            System.Drawing.Drawing2D.GraphicsPath myPath =
                                new System.Drawing.Drawing2D.GraphicsPath();
                            myPath.AddEllipse(0, 0, loadTxtBox.Width - 1, loadTxtBox.Height - 1);
                            Region myRegion = new Region(myPath);
                            loadTxtBox.Region = myRegion;
                            // Пропушим себя ещё чтоб знать чо кликать
                            loadTxtBox.MouseDown += delegate(object sender, MouseEventArgs e)
                            { clickVertex(sender, e); };
                            loadTxtBox.MouseMove += delegate(object sender, MouseEventArgs e)
                            { setMouseMove(sender, e); };
                            loadTxtBox.MouseUp += delegate(object sender, MouseEventArgs e)
                            { isDragOff(sender, e); };
                            V.Add(new Vertex(loadTxtBox));
                        }
                    }
                }
                if (el.Name == "lines")
                {
                    foreach (XElement ell in el.Elements())
                    {
                        if (ell.Name == "Line")
                        {
                            float x1 = float.Parse(ell.Attribute("x1").Value);
                            float x2 = float.Parse(ell.Attribute("x2").Value);
                            float y1 = float.Parse(ell.Attribute("y1").Value);
                            float y2 = float.Parse(ell.Attribute("y2").Value);
                            float k;
                            float b;
                            try
                            {
                                k = float.Parse(ell.Attribute("k").Value);
                                b = float.Parse(ell.Attribute("b").Value);
                            }
                            catch
                            {
                                k = 0;
                                b = 0;
                            }
                            int from = Int32.Parse(ell.Attribute("From").Value);
                            int To   = Int32.Parse(ell.Attribute("To").Value);
                            PropertyCategories line = new PropertyCategories();
                            E.Add(new Edge(k, b, x1, x2, y1, y2,
                                           V[from].txtBoxVertex,
                                           V[To].txtBoxVertex,
                                           line));
                        }
                    }
                }
            }
            reDrawAll();
        }
Ejemplo n.º 9
0
        /// <nodoc />
        private bool TryParseDependenciesFromNuSpec(XDocument nuSpec)
        {
            var dependencyNodes = nuSpec
                                  .Elements()
                                  .Where(el => string.Equals(el.Name.LocalName, "package", StringComparison.Ordinal))
                                  .Elements()
                                  .Where(el => string.Equals(el.Name.LocalName, "metadata", StringComparison.Ordinal))
                                  .Elements()
                                  .Where(el => string.Equals(el.Name.LocalName, "dependencies", StringComparison.Ordinal))
                                  .Elements();

            // Namespace independent query, nuget has about 6 different namespaces as of may 2016.
            var  skipIdLookupTable     = new HashSet <string>(DependentPackageIdsToSkip);
            var  ignoreIdLookupTable   = new HashSet <string>(DependentPackageIdsToIgnore);
            bool skipAllDependencies   = skipIdLookupTable.Contains("*");
            bool ignoreAllDependencies = ignoreIdLookupTable.Contains("*");

            foreach (var dependency in dependencyNodes.Where(el => string.Equals(el.Name.LocalName, "dependency", StringComparison.Ordinal)))
            {
                var genericDependency = ReadDependencyElement(dependency);
                if (genericDependency == null && !(ignoreAllDependencies || ignoreIdLookupTable.Contains(dependency.Attribute("id")?.Value?.Trim())))
                {
                    return(false);
                }

                if (genericDependency != null && !skipAllDependencies && !skipIdLookupTable.Contains(genericDependency.GetPackageIdentity()))
                {
                    m_dependencies.Add(genericDependency);
                }
            }

            var groups = dependencyNodes.Where(el => string.Equals(el.Name.LocalName, "group", StringComparison.Ordinal));

            foreach (var group in groups)
            {
                if (group.Attribute("targetFramework") != null && NugetFrameworkMonikers.TargetFrameworkNameToMoniker.TryGetValue(group.Attribute("targetFramework").Value, out Moniker targetFramework))
                {
                    if (group.Elements().Any())
                    {
                        // If there is at least one valid dependency for a known framework, then the package is defined as managed
                        IsManagedPackage = true;

                        // Only add the group dependency target framework if the nuget package itself also contains specific assemblies of the same version
                        if (!TargetFrameworks.Contains(targetFramework) && (References.Keys.Any(tfm => tfm.Moniker == targetFramework) || Libraries.Keys.Any(tfm => tfm.Moniker == targetFramework)))
                        {
                            TargetFrameworks.Add(targetFramework);
                        }

                        // If the package has a pinned tfm and the groups tfm does not match, skip the groups dependency resolution
                        if (!string.IsNullOrEmpty(this.Tfm) && NugetFrameworkMonikers.TargetFrameworkNameToMoniker.TryGetValue(this.Tfm, out Moniker pinnedTfm) && !PathAtom.Equals(pinnedTfm, targetFramework))
                        {
                            continue;
                        }

                        foreach (
                            var dependency in
                            group.Elements().Where(
                                el => string.Equals(el.Name.LocalName, "dependency", StringComparison.Ordinal)))
                        {
                            var grouppedDependency = ReadDependencyElement(dependency);
                            if (grouppedDependency == null && !(ignoreAllDependencies || ignoreIdLookupTable.Contains(dependency.Attribute("id")?.Value?.Trim())))
                            {
                                return(false);
                            }

                            if (grouppedDependency != null && !skipAllDependencies && !skipIdLookupTable.Contains(grouppedDependency.GetPackageIdentity()))
                            {
                                DependenciesPerFramework.Add(targetFramework, grouppedDependency);
                            }
                        }
                    }
                }
            }

            IsNetStandardPackageOnly =
                !TargetFrameworks.Any(tfm => NugetFrameworkMonikers.FullFrameworkVersionHistory.Contains(tfm)) &&
                !TargetFrameworks.Any(tfm => NugetFrameworkMonikers.NetCoreAppVersionHistory.Contains(tfm));

            return(true);
        }
Ejemplo n.º 10
0
 //Read
 public object Read()
 {
     return(xdoc.Elements("bookstore").Single().ToString());
 }
Ejemplo n.º 11
0
        public static void RetrieveSettings()
        {
            try
            {
                XDocument xDoc = XDocument.Load(path);

                /* Load CloudPanel Settings */
                log.Debug("Populating settings from config file");
                var settings = from s in xDoc.Elements("cloudpanel").Elements("Settings")
                               select s;

                foreach (var s in settings)
                {
                    Settings.CompanyName       = s.Element("CompanyName").Value;
                    Settings.HostingOU         = s.Element("HostingOU").Value;
                    Settings.PrimaryDC         = s.Element("DomainController").Value;
                    Settings.Username          = s.Element("Username").Value;
                    Settings.EncryptedPassword = s.Element("Password").Value;
                    Settings.SuperAdmins       = s.Element("SuperAdmins").Value.Split(',');
                    Settings.BillingAdmins     = s.Element("BillingAdmins").Value.Split(',');
                    Settings.SaltKey           = s.Element("SaltKey").Value;

                    bool enabled = false;
                    bool.TryParse(s.Element("ResellersEnabled").Value, out enabled);
                    Settings.ResellersEnabled = enabled;
                }


                /* Load Exchange Settings */
                log.Debug("Loading Exchange settings from config file");
                var exchange = from s in xDoc.Elements("cloudpanel").Elements("Exchange")
                               select s;

                foreach (var s in exchange)
                {
                    Settings.ExchangeServer   = s.Element("Server").Value;
                    Settings.ExchangePFServer = s.Element("PFServer").Value;

                    int defaultVersion = 2013;
                    int.TryParse(s.Element("Version").Value, out defaultVersion);
                    Settings.ExchangeVersion = defaultVersion;

                    bool defaultBool = true;
                    bool.TryParse(s.Element("SSL").Value, out defaultBool);
                    Settings.ExchangeSSL = defaultBool;

                    bool.TryParse(s.Element("PFEnabled").Value, out defaultBool);
                    Settings.ExchangePFEnabled = defaultBool;

                    Settings.ExchangeConnection   = s.Element("Connection").Value;
                    Settings.ExchangeDatabases    = s.Element("Databases").Value.Split(',');
                    Settings.ExchangeGALName      = s.Element("ExchangeGALName").Value;
                    Settings.ExchangeABPName      = s.Element("ExchangeABPName").Value;
                    Settings.ExchangeOALName      = s.Element("ExchangeOALName").Value;
                    Settings.ExchangeUSERSName    = s.Element("ExchangeUSERSName").Value;
                    Settings.ExchangeCONTACTSName = s.Element("ExchangeCONTACTSName").Value;
                    Settings.ExchangeROOMSName    = s.Element("ExchangeROOMSName").Value;
                    Settings.ExchangeGROUPSName   = s.Element("ExchangeGROUPSName").Value;
                    Settings.ExchangeOU           = s.Element("ExchangeOU").Value;
                }

                /* Load Module Settings */
                log.Debug("Loading module settings from config file");
                var modules = from s in xDoc.Element("cloudpanel").Elements("Modules")
                              select s;

                foreach (var s in modules)
                {
                    bool enabled = false;

                    bool.TryParse(s.Element("Exchange").Value, out enabled);
                    Settings.ExchangeModule = enabled;

                    bool.TryParse(s.Element("Citrix").Value, out enabled);
                    Settings.CitrixModule = enabled;

                    bool.TryParse(s.Element("Lync").Value, out enabled);
                    Settings.LyncModule = enabled;
                }

                /* Load Advanced Settings */
                log.Debug("Loading advanced settings from config file");
                var advanced = from s in xDoc.Element("cloudpanel").Elements("Advanced")
                               select s;

                foreach (var a in advanced)
                {
                    Settings.ApplicationsOU = a.Element("ApplicationsOU").Value;
                }
            }
            catch (Exception ex)
            {
                log.Error("Error loading settings", ex);

                // Set error value so people can't login // TODO
            }
        }
 /// <summary>
 /// Exports the Xml content as a Linq-queryable XElement
 /// </summary>
 /// <returns>Linq-queryable XElement</returns>
 public XElement ToXElement()
 {
     return(root.Elements().FirstOrDefault());
 }
            public static bool Prefix(ProfilesCore __instance)
            {
                if (__instance == null)
                {
                    throw new Exception("Instance was null, PANIC");
                }

                List <DuckPersona> personas = Persona.all as List <DuckPersona>;

                if (personas == null)
                {
                    throw new Exception("personas is null");
                }

                __instance._profiles = new List <Profile>()
                {
                    new Profile("Player1", InputProfile.Get("MPPlayer1"), Teams.Player1, Persona.Duck1, false, "PLAYER1"),
                    new Profile("Player2", InputProfile.Get("MPPlayer2"), Teams.Player2, Persona.Duck2, false, "PLAYER2"),
                    new Profile("Player3", InputProfile.Get("MPPlayer3"), Teams.Player3, Persona.Duck3, false, "PLAYER3"),
                    new Profile("Player4", InputProfile.Get("MPPlayer4"), Teams.Player4, Persona.Duck4, false, "PLAYER4"),
                    new Profile("Player5", InputProfile.Get("MPPlayer5"), Teams.core.teams[4], personas[4], false, "PLAYER5"),
                    new Profile("Player6", InputProfile.Get("MPPlayer6"), Teams.core.teams[5], personas[5], false, "PLAYER6"),
                    new Profile("Player7", InputProfile.Get("MPPlayer7"), Teams.core.teams[6], personas[6], false, "PLAYER7"),
                    new Profile("Player8", InputProfile.Get("MPPlayer8"), Teams.core.teams[7], personas[7], false, "PLAYER8")
                };

                Profile.loading = true;
                string[]       files        = DuckFile.GetFiles(DuckFile.profileDirectory, "*.*");
                List <Profile> profileList1 = new List <Profile>();

                foreach (string path in files)
                {
                    XDocument xdocument = DuckFile.LoadXDocument(path);
                    if (xdocument != null)
                    {
                        string  name = xdocument.Element((XName)"Profile").Element((XName)"Name").Value;
                        bool    flag = false;
                        Profile p    = __instance._profiles.FirstOrDefault <Profile>((Func <Profile, bool>)(pro => pro.name == name));
                        if (p == null || !Profiles.IsDefault(p))
                        {
                            p          = new Profile("", (InputProfile)null, (Team)null, (DuckPersona)null, false, (string)null);
                            p.fileName = path;
                            flag       = true;
                        }
                        IEnumerable <XElement> source = xdocument.Elements((XName)"Profile");
                        if (source != null)
                        {
                            foreach (XElement element1 in source.Elements <XElement>())
                            {
                                if (element1.Name.LocalName == "ID" && !Profiles.IsDefault(p))
                                {
                                    p.SetID(element1.Value);
                                }
                                else if (element1.Name.LocalName == "Name")
                                {
                                    p.name = element1.Value;
                                }
                                else if (element1.Name.LocalName == "Mood")
                                {
                                    p.funslider = Change.ToSingle((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "NS")
                                {
                                    p.numSandwiches = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "MF")
                                {
                                    p.milkFill = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "LML")
                                {
                                    p.littleManLevel = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "NLM")
                                {
                                    p.numLittleMen = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "LMB")
                                {
                                    p.littleManBucks = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "RSXP")
                                {
                                    p.roundsSinceXP = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "TimesMet")
                                {
                                    p.timesMetVincent = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "TimesMet2")
                                {
                                    p.timesMetVincentSale = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "TimesMet3")
                                {
                                    p.timesMetVincentSell = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "TimesMet4")
                                {
                                    p.timesMetVincentImport = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "TimeOfDay")
                                {
                                    p.timeOfDay = Change.ToSingle((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "CD")
                                {
                                    p.currentDay = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "XtraPoints")
                                {
                                    p.xp = Change.ToInt32((object)element1.Value);
                                }
                                else if (element1.Name.LocalName == "FurniPositions")
                                {
                                    p.furniturePositionData = BitBuffer.FromString(element1.Value);
                                }
                                else if (element1.Name.LocalName == "Fowner")
                                {
                                    p.furnitureOwnershipData = BitBuffer.FromString(element1.Value);
                                }
                                else if (element1.Name.LocalName == "SteamID")
                                {
                                    p.steamID = Change.ToUInt64((object)element1.Value);
                                    if ((long)p.steamID != 0L)
                                    {
                                        profileList1.Add(p);
                                    }
                                }
                                else if (element1.Name.LocalName == "LastKnownName")
                                {
                                    p.lastKnownName = element1.Value;
                                }
                                else if (element1.Name.LocalName == "Stats")
                                {
                                    p.stats.Deserialize(element1);
                                }
                                else if (element1.Name.LocalName == "Unlocks")
                                {
                                    string[] strArray = element1.Value.Split('|');
                                    p.unlocks = new List <string>((IEnumerable <string>)strArray);
                                }
                                else if (element1.Name.LocalName == "Tickets")
                                {
                                    p.ticketCount = Convert.ToInt32(element1.Value);
                                }
                                else if (element1.Name.LocalName == "Mappings" && !MonoMain.defaultControls)
                                {
                                    p.inputMappingOverrides.Clear();
                                    foreach (XElement element2 in element1.Elements())
                                    {
                                        if (element2.Name.LocalName == "InputMapping")
                                        {
                                            DeviceInputMapping deviceInputMapping = new DeviceInputMapping();
                                            deviceInputMapping.Deserialize(element2);
                                            p.inputMappingOverrides.Add(deviceInputMapping);
                                        }
                                    }
                                }
                            }
                        }
                        if (flag)
                        {
                            __instance._profiles.Add(p);
                        }
                    }
                }
                byte    localFlippers = Profile.CalculateLocalFlippers();
                Profile p1            = (Profile)null;

                if (Profiles.allCustomProfiles == null)
                {
                    throw new Exception("Custom Profiles null.");
                }

                if (Steam.user != null && (long)Steam.user.id != 0L)
                {
                    string str = Steam.user.id.ToString();
                    foreach (Profile allCustomProfile in Profiles.allCustomProfiles)
                    {
                        if ((long)allCustomProfile.steamID == (long)Steam.user.id && allCustomProfile.id == str && allCustomProfile.rawName == str)
                        {
                            p1 = allCustomProfile;
                            break;
                        }
                    }
                    if (p1 == null)
                    {
                        p1 = new Profile(Steam.user.id.ToString(), (InputProfile)null, (Team)null, (DuckPersona)null, false, Steam.user.id.ToString())
                        {
                            steamID = Steam.user.id
                        };
                        Profiles.Add(p1);
                        __instance.Save(p1);
                    }
                }
                if (p1 != null)
                {
                    __instance._profiles.Remove(p1);
                    __instance._profiles.Insert(8, p1);
                    List <Profile> source       = new List <Profile>();
                    List <Profile> profileList2 = new List <Profile>();
                    foreach (Profile allCustomProfile in Profiles.allCustomProfiles)
                    {
                        string str = allCustomProfile.steamID.ToString();
                        if ((long)allCustomProfile.steamID != 0L)
                        {
                            if (allCustomProfile.id == str && allCustomProfile.rawName == str)
                            {
                                source.Add(allCustomProfile);
                            }
                            else
                            {
                                profileList2.Add(allCustomProfile);
                            }
                        }
                    }
                    using (List <Profile> .Enumerator enumerator = profileList2.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            Profile pro = enumerator.Current;
                            Profile p2  = source.FirstOrDefault <Profile>((Func <Profile, bool>)(x => (long)x.steamID == (long)pro.steamID));
                            if (p2 == null)
                            {
                                p2         = new Profile(pro.steamID.ToString(), (InputProfile)null, (Team)null, (DuckPersona)null, false, pro.steamID.ToString());
                                p2.steamID = pro.steamID;
                                Profiles.Add(p2);
                            }
                            p2.stats = (ProfileStats)((DataClass)p2.stats + (DataClass)pro.stats);
                            foreach (KeyValuePair <string, List <ChallengeSaveData> > keyValuePair in (MultiMap <string, ChallengeSaveData, List <ChallengeSaveData> >)Challenges.saveData)
                            {
                                ChallengeSaveData        challengeSaveData1    = (ChallengeSaveData)null;
                                List <ChallengeSaveData> challengeSaveDataList = new List <ChallengeSaveData>();
                                foreach (ChallengeSaveData challengeSaveData2 in keyValuePair.Value)
                                {
                                    if (challengeSaveData2.profileID == pro.id || challengeSaveData2.profileID == p2.id)
                                    {
                                        challengeSaveData2.profileID = p2.id;
                                        if (challengeSaveData1 == null)
                                        {
                                            challengeSaveData1 = challengeSaveData2;
                                        }
                                        else if (challengeSaveData2.trophy > challengeSaveData1.trophy)
                                        {
                                            challengeSaveDataList.Add(challengeSaveData1);
                                            challengeSaveData1 = challengeSaveData2;
                                        }
                                        else
                                        {
                                            challengeSaveDataList.Add(challengeSaveData2);
                                        }
                                    }
                                }
                                foreach (ChallengeSaveData challengeSaveData2 in challengeSaveDataList)
                                {
                                    string str = challengeSaveData2.profileID + "OBSOLETE";
                                    challengeSaveData2.profileID = str;
                                }
                                if (challengeSaveData1 != null)
                                {
                                    Challenges.Save(keyValuePair.Key);
                                }
                            }
                            __instance._profiles.Remove(pro);
                            DuckFile.Delete(pro.fileName);
                            __instance.Save(p2);
                        }
                    }
                }
                foreach (Profile profile in __instance._profiles)
                {
                    profile.flippers    = localFlippers;
                    profile.ticketCount = Challenges.GetTicketCount(profile);
                    if (profile.ticketCount < 0)
                    {
                        profile.ticketCount = 0;
                    }
                }
                Profile.loading = false;

                return(false);
            }
Ejemplo n.º 14
0
        /// <summary>
        /// Načte kategorie alarmů z XML dokumentu do kolekce, nebo vyhodí vyjímku.
        /// </summary>
        /// <param name="xmlXDoc"></param>
        /// <returns></returns>
        private Dictionary <int, KategorieAlarmu> NacistKategorieZXlm(XDocument xmlXDoc, string strRootElement)
        {
            Dictionary <int, KategorieAlarmu> vsechnyKategorie = new Dictionary <int, KategorieAlarmu>();

            try
            {
                var query = from c in xmlXDoc.Elements(strRootElement).Elements("KategorieAlarmu") select c;

                foreach (XElement book in query)
                {
                    KategorieAlarmu kat = new KategorieAlarmu();

                    int?   cislo        = (int?)book.Attribute("Kategorie");
                    string nazev        = (string)book.Attribute("Nazev");
                    string strBarva     = (string)book.Attribute("Barva");
                    int?   sortPriority = (int?)book.Attribute("SortPriority");

                    if (cislo == null)
                    {
                        throw new Exception("U \"KategorieAlarmu\" se nepodařilo načíst attribut \"Kategorie\"");
                    }
                    if (nazev == null)
                    {
                        throw new Exception(String.Format("U \"KategorieAlarmu\" Kategorie={0} se nepodařilo načíst attribut \"Nazev\"", cislo.Value));
                    }
                    if (strBarva == null)
                    {
                        throw new Exception(String.Format("U \"KategorieAlarmu\" Kategorie={0} se nepodařilo načíst attribut \"Barva\"", cislo.Value));
                    }
                    if (sortPriority == null)
                    {
                        throw new Exception(String.Format("U \"KategorieAlarmu\" Kategorie={0} se nepodařilo načíst attribut \"SortPriority\"", cislo.Value));
                    }

                    kat.Cislo        = cislo.Value;
                    kat.Nazev        = nazev;
                    kat.SortPriority = sortPriority.Value;
                    try //parsování barvy
                    {
                        Color col = (Color)ColorConverter.ConvertFromString(strBarva);
                        kat.Barva = new SolidColorBrush(col);
                    }
                    catch
                    {
                        throw new Exception(String.Format("U \"KategorieAlarmu\" Kategorie={0} je špatný formát attributu \"Barva\"", cislo.Value));
                    }

                    try //Vložení kategorie do hash tabulky
                    {
                        vsechnyKategorie.Add(kat.Cislo, kat);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(String.Format("U \"KategorieAlarmu\" Kategorie={0} je špatné číslo kategorie ({1}).", cislo.Value, ex.Message));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Chyba při načítání kategorií alarmů: " + ex.Message);
            }

            return(vsechnyKategorie);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Exports the batches.
        /// </summary>
        /// <param name="modifiedSince">The modified since.</param>
        public override void ExportFinancialBatches(DateTime modifiedSince)
        {
            try
            {
                // first, we need to find out what batch types are available
                _client.Authenticator = OAuth1Authenticator.ForProtectedResource(ApiConsumerKey, ApiConsumerSecret, OAuthToken, OAuthSecret);
                _request = new RestRequest(API_BATCH_TYPES, Method.GET);
                _request.AddHeader("content-type", "application/xml");
                var batchTypeResponse = _client.Execute(_request);
                ApiCounter++;

                XDocument xBatchTypeDoc = XDocument.Parse(batchTypeResponse.Content);
                var       batchTypes    = xBatchTypeDoc.Elements("batchTypes");

                // process all batches for each batch type
                foreach (var batchType in batchTypes.Elements())
                {
                    int  batchCurrentPage = 1;
                    int  batchLoopCounter = 0;
                    bool moreBatchesExist = true;

                    while (moreBatchesExist)
                    {
                        _request = new RestRequest(API_BATCHES, Method.GET);
                        _request.AddQueryParameter("lastUpdatedDate", modifiedSince.ToShortDateString());
                        _request.AddQueryParameter("batchTypeID", batchType.Attribute("id").Value);
                        _request.AddQueryParameter("recordsPerPage", "1000");
                        _request.AddQueryParameter("page", batchCurrentPage.ToString());
                        _request.AddHeader("content-type", "application/xml");

                        var batchRepsonse = _client.Execute(_request);
                        ApiCounter++;

                        XDocument xBatchDoc = XDocument.Parse(batchRepsonse.Content);

                        if (F1Api.DumpResponseToXmlFile)
                        {
                            xBatchDoc.Save(Path.Combine(ImportPackage.PackageDirectory, $"API_FINANCIAL_BATCHES_ResponseLog_{batchLoopCounter++}.xml"));
                        }

                        var batches = xBatchDoc.Element("results");

                        if (batches != null)
                        {
                            var batchReturnCount     = batches.Attribute("count")?.Value.AsIntegerOrNull();
                            var batchAdditionalPages = batches.Attribute("additionalPages").Value.AsInteger();

                            if (batchReturnCount.HasValue)
                            {
                                // process all batches
                                foreach (var batchNode in batches.Elements())
                                {
                                    var importBatch = F1FinancialBatch.Translate(batchNode);

                                    if (importBatch != null)
                                    {
                                        ImportPackage.WriteToPackage(importBatch);
                                    }
                                }

                                if (batchAdditionalPages <= 0)
                                {
                                    moreBatchesExist = false;
                                }
                                else
                                {
                                    batchCurrentPage++;
                                }
                            }
                        }
                        else
                        {
                            moreBatchesExist = false;
                        }

                        // developer safety blanket (prevents eating all the api calls for the day)
                        if (batchLoopCounter > loopThreshold)
                        {
                            break;
                        }
                        batchLoopCounter++;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
        }
Ejemplo n.º 16
0
        private void BuildData(SimpleDataSource dataSource, DataParsePluginInfo info)
        {
            string        serialnumber = string.Empty;
            string        name         = string.Empty;
            string        manufacture  = string.Empty;
            string        model        = string.Empty;
            string        OSType       = string.Empty;
            string        OSVersion    = string.Empty;
            string        root         = string.Empty;
            string        IMEI         = string.Empty;
            string        IMSI         = string.Empty;
            string        WiFiAddress  = string.Empty;
            string        BMac         = string.Empty;
            string        TMac         = string.Empty;
            List <string> listsimdata  = new List <string>();

            //从设备获取相关信息
            var device = info.Phone;

            if (null != device)
            {
                serialnumber = device.SerialNumber;
                name         = device.Name;
                manufacture  = device.Manufacture;
                model        = device.Model;
                OSType       = device.OSType.GetDescription();
                OSVersion    = device.OSVersion;
                root         = device.IsRootDesc;
                IMEI         = device.IMEI;
                IMSI         = device.IMSI;
                BMac         = device.BMac;
                TMac         = device.TMac;

                if (device.Properties.IsValid() && device.Properties.Keys.Contains("WiFiAddress"))
                {
                    WiFiAddress = device.Properties["WiFiAddress"];
                }
            }

            //获取设备名称
            try
            {
                // /data/misc/wifi/p2p_supplicant.conf
                if (FileHelper.IsValid(info.SourcePath[9].Local))
                {
                    string fileContent = File.ReadAllText(info.SourcePath[9].Local, Encoding.ASCII);
                    if (fileContent.IsValid())
                    {
                        foreach (var line in fileContent.Split('\n', '\r'))
                        {
                            if (line.StartsWith("model_name", StringComparison.OrdinalIgnoreCase))
                            {
                                name = line.Split('=')[1];
                                break;
                            }
                        }
                    }
                }

                // /etc/config/model-config.xml
                if (FileHelper.IsValid(info.SourcePath[13].Local))
                {
                    XDocument doc     = XDocument.Load(info.SourcePath[13].Local);
                    var       nameStr = doc.Elements("settings").First().Elements("setting").FirstOrDefault(e => e.Attribute("name") != null &&
                                                                                                            e.Attribute("name").Value == "device_name").Attribute("value").Value;
                    if (name.IsValid())
                    {
                        name = nameStr;
                    }
                }
            }
            catch { }

            //获取IMEI
            try
            {
                // /data/com.tencent.mm/MicroMsg/CompatibleInfo.cfg
                if (IMEI.IsInvalid() && FileHelper.IsValid(info.SourcePath[10].Local))
                {
                    var fileBytes = File.ReadAllBytes(info.SourcePath[10].Local);
                    int index     = GetIndexOf(fileBytes, 0, new byte[] { 0x73, 0x71, 0x00, 0x7E, 0x00, 0x02 });
                    if (index > 0)
                    {
                        index = GetIndexOf(fileBytes, index + 6, new byte[] { 0x00, 0x00, 0x01, 0x02, 0x74, 0x00 });
                        if (index > 0)
                        {
                            IMEI = Encoding.ASCII.GetString(fileBytes, index + 7, fileBytes[index + 6]);   //标记后1位为长度,随后的字节为imei
                        }
                    }
                }

                // 从QQ数据中获取imei,com.tencent.mobileqq/shared_prefs/DENGTA_META.xml
                if (IMEI.IsInvalid() && FileHelper.IsValid(info.SourcePath[11].Local))
                {
                    var doc = new XmlDocument();
                    doc.Load(info.SourcePath[11].Local);
                    XmlNodeList userInfoNodeList = doc.SelectNodes("map//string[@name='IMEI_DENGTA']");
                    if (userInfoNodeList != null && userInfoNodeList.Count > 0)
                    {
                        string key = userInfoNodeList[0].InnerText;
                        if (key.IsValid())
                        {
                            IMEI = key;
                        }
                    }
                }

                // 从QQ数据中获取imei,com.tencent.mobileqq/shared_prefs/MSF.C.Util.xml
                if (IMEI.IsInvalid() && FileHelper.IsValid(info.SourcePath[12].Local))
                {
                    var doc = new XmlDocument();
                    doc.Load(info.SourcePath[11].Local);
                    XmlNodeList userInfoNodeList = doc.SelectNodes("map//string[@name='sp_imei']");
                    if (userInfoNodeList != null && userInfoNodeList.Count > 0)
                    {
                        string key = userInfoNodeList[0].InnerText;
                        if (key.IsValid())
                        {
                            IMEI = key;
                        }
                    }
                }
            }
            catch { }

            //获取蓝牙MAC属性
            try
            {
                // /data/data/com.oppo.safe/shared_prefs/TMSProperties.xml
                if (FileHelper.IsValid(info.SourcePath[1].Local))
                {//其它手机
                    XDocument doc  = XDocument.Load(info.SourcePath[1].Local);
                    var       maps = doc.Elements("map").ToList().FirstOrDefault();
                    var       mac  = maps.Elements("string").ToList();
                    mac = mac.Where(p => p.Attribute("name").Value == "wup.mac").ToList();

                    BMac = mac.FirstOrDefault().ToSafeString().ToUpper();
                }
                // /data/misc/bluetoothd
                else if (FileHelper.IsValidDictory(info.SourcePath[2].Local))
                {//三星手机
                    string cfgFile = Directory.GetFiles(info.SourcePath[2].Local, "names", SearchOption.AllDirectories).FirstOrDefault();
                    if (cfgFile.IsValid())
                    {
                        string macFolder = Path.GetDirectoryName(cfgFile).Split('\\')[Path.GetDirectoryName(cfgFile).Split('\\').Length - 1];

                        BMac = macFolder.Replace("_", ":").ToUpper();
                    }
                }
                // /data/misc/bluedroid/bt_config.xml
                else if (FileHelper.IsValid(info.SourcePath[3].Local))
                {//华为手机
                    XDocument doc  = XDocument.Load(info.SourcePath[3].Local);
                    var       list = doc.Descendants().ToList();
                    var       mac  = list.Where(p => (p.Attribute("Tag") != null) && (p.Attribute("Tag").Value == "Address"));
                    if (mac.Count() != 0)
                    {
                        BMac = mac.ToList().FirstOrDefault().Value.ToUpper();
                    }
                }
            }
            catch { }

            //获取Wifi的MAC属性
            try
            {
                string wifiConfigPath = "";
                // /data/misc/dhcp/dhcpcd-wlan0.lease
                if (FileHelper.IsValid(info.SourcePath[4].Local))
                {
                    wifiConfigPath = info.SourcePath[4].Local;
                }
                // /data/misc/dhcp/dhcpcd-wlan0.lease_0
                else if (FileHelper.IsValid(info.SourcePath[5].Local))
                {
                    wifiConfigPath = info.SourcePath[5].Local;
                }

                if (wifiConfigPath.IsValid())
                {
                    using (FileStream myStream = new FileStream(wifiConfigPath, FileMode.Open, FileAccess.Read))
                    {
                        string       wifiMac = "";
                        string       wifiIP  = "";
                        BinaryReader read    = new BinaryReader(myStream);
                        int          count   = (int)myStream.Length;
                        byte[]       buffer  = new byte[count];
                        read.Read(buffer, 0, buffer.Length);
                        for (int i = 28; i < 34; i++)
                        {
                            if (i == 28)
                            {
                                wifiMac = string.Format("{0:X}", buffer[i]).PadLeft(2, '0');
                            }
                            else
                            {
                                wifiMac += ":" + string.Format("{0:X}", buffer[i]).PadLeft(2, '0');
                            }
                        }
                        for (int i = 16; i < 20; i++)
                        {
                            if (i == 16)
                            {
                                wifiIP = buffer[i].ToString();
                            }
                            else
                            {
                                wifiIP += "." + buffer[i].ToString();
                            }
                        }

                        TMac = wifiMac.ToUpper();
                    }
                }
            }
            catch { }

            //获取手机号,imsi,iccid信息
            try
            {
                // /data/data/com.android.providers.telephony/databases/telephony.db
                if (FileHelper.IsValid(info.SourcePath[6].Local))
                {
                    string simdata = "";

                    using (var context = new SqliteContext(info.SourcePath[6].Local))
                    {
                        var siminfo = context.FindByName("siminfo").Distinct();
                        foreach (var sim in siminfo)
                        {
                            simdata = "ICCID:" + sim.icc_id + ",";
                            if (!string.IsNullOrEmpty(sim.number))
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_PhoneNumber) + sim.number + ",";
                            }
                            else
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_PhoneNumber) + ":NA";
                            }

                            if (!string.IsNullOrEmpty(sim.display_name))
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_CarrierOperator) + sim.display_name;
                            }
                            else
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_CarrierOperator) + ":NA";
                            }

                            listsimdata.Add(simdata);
                        }
                    }
                }

                // /data/data/com.samsung.simcardmanagement/databases/simcardmanagement.db
                if (FileHelper.IsValid(info.SourcePath[7].Local))
                {
                    string simdata = "";

                    using (var context = new SqliteContext(info.SourcePath[7].Local))
                    {
                        var siminfo = (from u in context.FindByName("registerinfo") select new { u.card_iccid, u.card_number, u.card_name, u.card_id }).Distinct();
                        foreach (var sim in siminfo)
                        {
                            simdata = "ICCID:" + sim.card_iccid + ",";
                            if (!string.IsNullOrEmpty(sim.card_number))
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_PhoneNumber) + sim.card_number + ",";
                            }
                            else
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_PhoneNumber) + ":NA";
                            }

                            if (!string.IsNullOrEmpty(sim.card_name))
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_CarrierOperator) + sim.card_name;
                            }
                            else
                            {
                                simdata += LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_CarrierOperator) + ":NA";
                            }

                            if (!string.IsNullOrEmpty(sim.card_id))
                            {
                                simdata += "IMSI" + sim.card_id;
                            }
                            else
                            {
                                simdata += "IMSI:NA";
                            }

                            listsimdata.Add(simdata);
                        }
                    }
                }
            }
            catch { }

            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_Serialnumber), serialnumber));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_DeviceName), name));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_Manufacture), manufacture));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_Model), model));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_OSType), OSType));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_OSVersion), OSVersion));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_Root), root));
            dataSource.Items.Add(new KeyValueItem("IMEI", IMEI));
            dataSource.Items.Add(new KeyValueItem("IMSI", IMSI));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_WiFiAddress), WiFiAddress));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_BMac), BMac));
            dataSource.Items.Add(new KeyValueItem(LanguageHelper.GetString(Languagekeys.PluginDeviceProperty_TMac), TMac));

            int id = 0;

            foreach (var sim in listsimdata)
            {
                dataSource.Items.Add(new KeyValueItem("SIM" + (id++).ToString(), sim));
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Exports the groups.
        /// </summary>
        /// <param name="selectedGroupTypes">The selected group types.</param>
        /// <param name="modifiedSince">The modified since.</param>
        /// <param name="perPage">The people per page.</param>
        public override void ExportGroups(List <int> selectedGroupTypes)
        {
            // write out the group types
            WriteGroupTypes(selectedGroupTypes);

            // get groups
            try
            {
                int loopCounter = 0;

                foreach (var selectedGroupType in selectedGroupTypes)
                {
                    _client.Authenticator = OAuth1Authenticator.ForProtectedResource(ApiConsumerKey, ApiConsumerSecret, OAuthToken, OAuthSecret);
                    _request = new RestRequest(API_GROUPS + selectedGroupType.ToString() + "/groups", Method.GET);
                    _request.AddHeader("content-type", "application/xml");

                    var response = _client.Execute(_request);
                    ApiCounter++;

                    XDocument xdoc = XDocument.Parse(response.Content);

                    var groups = xdoc.Elements("groups");

                    if (groups.Elements().Any())
                    {
                        // since we don't have a group heirarchy to work with, add a parent
                        //  group for each group type for organizational purposes
                        int parentGroupId = 99 + groups.Elements().FirstOrDefault().Element("groupType").Attribute("id").Value.AsInteger();

                        ImportPackage.WriteToPackage(new Group()
                        {
                            Id          = parentGroupId,
                            Name        = groups.Elements().FirstOrDefault().Element("groupType").Element("name").Value,
                            GroupTypeId = groups.Elements().FirstOrDefault().Element("groupType").Attribute("id").Value.AsInteger(),
                            IsActive    = true
                        });

                        foreach (var groupNode in groups.Elements())
                        {
                            string groupId = groupNode.Attribute("id").Value;

                            _client.Authenticator = OAuth1Authenticator.ForProtectedResource(ApiConsumerKey, ApiConsumerSecret, OAuthToken, OAuthSecret);
                            _request = new RestRequest(API_GROUP_MEMBERS + groupId + "/members", Method.GET);
                            _request.AddHeader("content-type", "application/xml");

                            response = _client.Execute(_request);
                            ApiCounter++;

                            xdoc = XDocument.Parse(response.Content);

                            if (F1Api.DumpResponseToXmlFile)
                            {
                                xdoc.Save(Path.Combine(ImportPackage.PackageDirectory, $"API_GROUPS_ResponseLog_{loopCounter}.xml"));
                            }

                            var membersNode = xdoc.Elements("members");

                            var importGroup = F1Group.Translate(groupNode, parentGroupId, membersNode);

                            if (importGroup != null)
                            {
                                ImportPackage.WriteToPackage(importGroup);
                            }

                            // developer safety blanket (prevents eating all the api calls for the day)
                            if (loopCounter > loopThreshold)
                            {
                                break;
                            }
                            loopCounter++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
        }
Ejemplo n.º 18
0
 public static void PrintChangeResults(XObjectChangeEventArgs e)
 {
     Console.WriteLine(string.Format("Change was {0}, Document now has {1} elements",
                                     e.ObjectChange, doc.Elements().First().Elements().Count()));
 }
Ejemplo n.º 19
0
        public void Import(ref int gooseItems, Control.ControlCollection cc, PacketDevice netDev)
        {
            using (OpenFileDialog importOpenFileDialog = new OpenFileDialog())
            {
                importOpenFileDialog.Title  = "Select XML File";
                importOpenFileDialog.Filter = "Xml File(*.xml)|*.xml";

                if (DialogResult.OK == importOpenFileDialog.ShowDialog())
                {
                    XDocument xmlDoc = XDocument.Load(importOpenFileDialog.FileName);
                    XElement  gooses = xmlDoc.Element("Gooses");

                    if (gooses != null && xmlDoc.Elements("Gooses").Count() == 1)
                    {
                        if (gooses.Elements().Count() > 0)
                        {
                            foreach (XElement goose in gooses.Elements())
                            {
                                GooseControl gc = new GooseControl("Goose " + gooseItems++.ToString() + ":", "00:00:00:00:00:00", netDev);

                                XElement parameters = goose.Element("Parameters");
                                if (parameters != null && goose.Elements("Parameters").Count() == 1)
                                {
                                    if (parameters.Elements().Count() == 17)
                                    {
                                        foreach (XElement parameter in parameters.Elements())
                                        {
                                            if (parameter.Attribute("Value") != null)
                                            {
                                                gc.gooseParameters[parameter.Name.ToString()] = parameter.Attribute("Value").Value.ToString();
                                            }
                                            else
                                            {
                                                MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                return;
                                            }
                                        }

                                        gc.updateComponents();
                                    }
                                    else
                                    {
                                        MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        return;
                                    }

                                    XElement dataset = goose.Element("DataSet");

                                    if (dataset != null && goose.Elements("DataSet").Count() == 1)
                                    {
                                        if (dataset.Elements("Data").Count() > 0)
                                        {
                                            foreach (XElement data in dataset.Elements("Data"))
                                            {
                                                recursiveCreateDataList(gc.dataList, data);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        return;
                                    }

                                    XElement seqdata = goose.Element("SeqData");

                                    if (seqdata != null && goose.Elements("SeqData").Count() == 1)
                                    {
                                        if (seqdata.Elements("Data").Count() > 0)
                                        {
                                            NodeGVL gvl = new NodeGVL("Data");

                                            GooseDataEdit gde = new GooseDataEdit();

                                            int i = 0;

                                            foreach (GOOSE_ASN1_Model.Data dataListCn in gc.dataList)
                                            {
                                                i = gde.recursiveReadData(null, dataListCn, gvl, i, DateTime.Now);
                                            }

                                            gc.seqData.Clear();

                                            foreach (XElement seqd in seqdata.Elements("Data"))
                                            {
                                                if (seqd.Attribute("Name") != null)
                                                {
                                                    if (gvl.GetChildNodes().Length > 0)
                                                    {
                                                        foreach (NodeGData ngdcn in gvl.GetChildNodes())
                                                        {
                                                            NodeGData fngd;
                                                            if ((fngd = recursiveFindNodeGData(ngdcn, seqd.Attribute("Name").Value)) != null)
                                                            {
                                                                if (seqd.Attribute("Duration") != null && seqd.Attribute("Value") != null)
                                                                {
                                                                    gc.seqData.Add(new SeqData(fngd, seqd.Attribute("Value").Value, Convert.ToInt32(seqd.Attribute("Duration").Value)));
                                                                }
                                                                else
                                                                {
                                                                    MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                                    return;
                                                                }

                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                    return;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                gc.Dock = DockStyle.Top;
                                cc.Add(gc);
                                cc.SetChildIndex(gc, 0);
                            }
                        }
                        else
                        {
                            MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Invalid XML file !", "Import from Xml", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public IHttpActionResult Get(string txt)
        {
            SerkoResponse resp = new SerkoResponse()
            {
                response = new Response()
                {
                    Vendor = new VendorDetail()
                },
                status = new Status()
                {
                    success = false, detail = new Detail()
                    {
                    }
                }
            };
            VendorDetail Vendor = new VendorDetail {
                Expense = new ExpenseDetail()
            };

            try
            {
                // add xml tags to make it standard xml document
                txt = "<?xml version='1.0' encoding='utf-8' ?> " + "<body>" + txt + "</body>";

                // remove emails addresses from the text as it has '<' and '>'  which is interpreted as tags
                txt = Utility.RemoveEmails(txt);

                XDocument xmldoc = XDocument.Load(new System.IO.StringReader(txt));
                var       odata  = from o in xmldoc.Elements("body")
                                   select o;



                double total, gst, amount;
                bool   IsTotalNull = false;
                foreach (var item in odata)
                {
                    if (item.Element("vendor") != null)
                    {
                        Vendor.Vendor = item.Element("vendor").Value;
                    }
                    if (item.Element("description") != null)
                    {
                        Vendor.Description = item.Element("description").Value;
                    }
                    if (item.Element("date") != null)
                    {
                        Vendor.Date = item.Element("date").Value;
                    }

                    var odata1 = from o in item.Elements("expense")
                                 select o;
                    foreach (var item1 in odata1)
                    {
                        if (item1.Element("cost_centre") != null)
                        {
                            Vendor.Expense.CostCentre = item1.Element("cost_centre").Value;
                        }
                        if (string.IsNullOrEmpty(Vendor.Expense.CostCentre))
                        {
                            Vendor.Expense.CostCentre = "UNKNOWN";
                        }
                        if (item1.Element("payment_method") != null)
                        {
                            Vendor.Expense.PaymentMethod = item1.Element("payment_method").Value;
                        }
                        if (item1.Element("total") != null)
                        {
                            total = Convert.ToDouble(item1.Element("total").Value);
                            Vendor.Expense.Total = total;
                            amount = total / 1.1; //10% gst
                            gst    = total - amount;

                            Vendor.Expense.Amount = amount;
                            Vendor.Expense.GST    = gst;
                        }
                        else
                        {
                            IsTotalNull = true;
                        }
                    }
                }

                resp.response.Vendor = Vendor;
                if (IsTotalNull)
                {
                    resp.status.success = false;
                    resp.status.detail  = new Detail {
                        errormessage = " total is null"
                    };
                }
                else
                {
                    resp.status.success = true;
                }
            }
            catch (Exception)
            {
                resp.status.success = false;
                resp.status.detail  = new Detail {
                    errormessage = "problem with strating or ending tags "
                };
                resp.response.Vendor = Vendor;
            }
            return(Ok(resp));
        }
Ejemplo n.º 21
0
        private MoveDictionary readInMoveFromXML(string m)
        {
            if (m != null)
            {
                var doc = new XDocument();

                using (Stream isoStream = this.GetType().Assembly.GetManifestResourceStream("SilverlightApplication3.moves.xml"))
                {
                    using (StreamReader sw = new StreamReader(isoStream))
                    {
                        doc = XDocument.Load(sw);
                    }
                }

                MoveDictionary md    = null;
                var            query = (from mo in doc.Elements("Moves").Elements("Move") where mo.Element("Name").Value == m select mo).ToArray()[0];


                if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.Attacking)
                {
                    md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("Damage").Value), int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), Parser.parseMoveCategory(query.Element("StatusValue").Value), Parser.tryParseInteger(query.Element("Accuracy").Value, 100), int.Parse(query.Element("Priority").Value), query.Element("ToFoe").Value);
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.StatChange)
                {
                    int val = 0;
                    List <Pokemon.Stat> stats = new List <Pokemon.Stat>();
                    foreach (var v in query.Elements("StatChanges"))
                    {
                        val = int.Parse(v.Element("StatAmount").Value);
                        stats.Add(Parser.parsePokemonStat(v.Element("StatToChange").Value));
                    }
                    md = new MoveDictionary(query.Element("Name").Value, val, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Speciality.Null, MoveCategory.StatChange, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), stats, query.Element("ToFoe").Value, int.Parse(query.Element("Priority").Value));
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.DamageAndLower || Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.DamageAndRaise)
                {
                    int val = 0;
                    List <Pokemon.Stat> stats = new List <Pokemon.Stat>();
                    val = int.Parse(query.Element("StatChanges").Element("StatAmount").Value);
                    foreach (var v in query.Element("StatChanges").Elements("StatToChange"))
                    {
                        stats.Add(Parser.parsePokemonStat(v.Value));
                    }

                    if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.DamageAndLower)
                    {
                        md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("Damage").Value), val, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.DamageAndLower, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), stats, "foe", "foe", int.Parse(query.Element("StatChance").Value), int.Parse(query.Element("Priority").Value));
                    }
                    else
                    {
                        md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("Damage").Value), val, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.DamageAndRaise, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), stats, "foe", "user", int.Parse(query.Element("StatChance").Value), int.Parse(query.Element("Priority").Value));
                    }
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.Status)
                {
                    md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Speciality.Null, MoveCategory.Status, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), Parser.parseStatus(query.Element("Status").Value), query.Element("ToFoe").Value, int.Parse(query.Element("Priority").Value));
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.DamageAndAilement)
                {
                    md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("Damage").Value), int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.DamageAndAilement, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), Parser.parseStatus(query.Element("Status").Value), query.Element("ToFoe").Value, int.Parse(query.Element("StatusChance").Value), int.Parse(query.Element("Priority").Value));
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.Healing)
                {
                    md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("Healing").Value), int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.Healing, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), int.Parse(query.Element("Priority").Value), query.Element("ToFoe").Value);
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.StatusAndRaiseStats)
                {
                    int val = 0;
                    List <Pokemon.Stat> stats = new List <Pokemon.Stat>();
                    val = Parser.tryParseInteger(query.Element("StatChanges").Element("StatAmount").Value, 1);
                    foreach (var v in query.Element("StatChanges").Elements("StatToChange"))
                    {
                        stats.Add(Parser.parsePokemonStat(v.Value));
                    }
                    if (stats.Count == 0)
                    {
                        stats.Add(Pokemon.Stat.Speed);
                    }
                    md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.StatusAndRaiseStats, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), Parser.parseStatus(query.Element("Status").Value), "foe", stats, val, "foe", int.Parse(query.Element("Priority").Value));
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.Absorbing)
                {
                    md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("Damage").Value), int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), Parser.parseMoveCategory(query.Element("StatusValue").Value), Parser.tryParseInteger(query.Element("Accuracy").Value, 100), query.Element("ToFoe").Value, int.Parse(query.Element("Drain").Value), int.Parse(query.Element("Priority").Value));
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.KO)
                {
                    md = new MoveDictionary(query.Element("Name").Value, 0, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.KO, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), int.Parse(query.Element("Priority").Value), query.Element("ToFoe").Value);
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.Field)
                {
                    if (query.Name == "Haze") //bit more unique than others in the same group
                    {
                        md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.Field, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), PerformUniqueMove(query.Element("Name").Value), int.Parse(query.Element("Priority").Value));
                    }
                    else
                    {
                        md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.Field, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), (bool b) => { b = true; }, int.Parse(query.Element("Priority").Value));
                    }
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.SideField)
                {
                    if (query.Element("Name").Value == "spikes" || query.Element("Name").Value == "toxic-spikes" || query.Element("Name").Value == "stealth-rock" || query.Element("Name").Value == "sticky-web" || query.Element("Name").Value == "light-screen" || query.Element("Name").Value == "reflect" || query.Element("Name").Value == "mist" || query.Element("Name").Value == "safeguard" || query.Element("Name").Value == "tailwind" || query.Element("Name").Value == "lucky-chant" || query.Element("Name").Value == "aurora-veil")
                    {
                        md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.SideField, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), query.Element("ToFoe").Value, getUniqueActionOnePokemon(query.Element("Name").Value), int.Parse(query.Element("Priority").Value));
                    }
                    else
                    {
                        md = new MoveDictionary(query.Element("Name").Value, int.Parse(query.Element("PP").Value), Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.SideField, Parser.tryParseInteger(query.Element("Accuracy").Value, 100), getUniqueProtectionAction(query.Element("Name").Value), int.Parse(query.Element("Priority").Value));
                    }
                }
                else if (Parser.parseMoveCategory(query.Element("StatusValue").Value) == MoveCategory.Switch)
                {
                    md = new MoveDictionary(query.Element("Name").Value, Parser.parsePokeType(query.Element("Type").Value), Parser.parseSpeciality(query.Element("Speciality").Value), MoveCategory.Switch, int.Parse(query.Element("PP").Value), Parser.tryParseInteger(query.Element("Accuracy").Value, 100), int.Parse(query.Element("Priority").Value));
                }

                return(md);
            }
            else
            {
                return(struggleMove);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="archivo_guardar"></param>
        /// <param name="ruta_archivo"></param>
        public DataTable Genera_RDLC(ref string archivo_guardar, string ruta_archivo)
        {
            XDocument xml_reporte = XDocument.Load(ruta_archivo);

            //NOMBRES DE ESPACIO PARA EL XDOCUMENT
            XNamespace namspac_def = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition";
            XNamespace namspac_rd  = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";

            //TOMAMOS EL NOM BRE DE LAS SEMANAS QUE VAN REPOTEARSE
            string nombre_semana = "";

            SqlConnection connection = new SqlConnection("Data Source = (local); Initial Catalog = db_sporting_gym; Persist Security Info = True; User ID = usuario_sa; Password = sistemas");
            DataTable     dt         = new DataTable();

            try
            {
                connection.Open();

                SqlCommand command = new SqlCommand("sp_Rpt_Proyeccion_ingresos", connection);
                command.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                connection.Close();
                connection = null;
            }

            for (int x = 0; x < dt.Columns.Count; x++)
            {
                nombre_semana = dt.Columns[x].ColumnName.Trim().Replace(' ', '_');
                string nombre_semana_replace = nombre_semana.Replace('c', ' ').Replace('_', ' ');

                //
                // DATASET
                //
                XElement xDataSets = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "DataSets").Elements().ElementAt(0);
                if (x > 1)
                {
                    XElement xdata_original    = new XElement(xDataSets.Elements(namspac_def + "Fields").Elements().ElementAt(1));
                    XElement xDataSets_agregar = xDataSets.Elements(namspac_def + "Fields").ElementAt(0);
                    xDataSets_agregar.Add(new XElement(xdata_original));
                }
                xDataSets.Elements(namspac_def + "Fields").Elements(namspac_def + "Field").ElementAt(x).Attribute("Name").Value = nombre_semana;
                xDataSets.Elements(namspac_def + "Fields").Elements(namspac_def + "Field").ElementAt(x).Elements(namspac_def + "DataField").First().Value = nombre_semana;

                //
                // COLUMNAS
                //
                XElement xTablix_Columns = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "Body").Elements(namspac_def + "ReportItems").Elements(namspac_def + "Tablix").Elements(namspac_def + "TablixBody").Elements().ElementAt(0);
                if (x > 1)
                {
                    XElement xdata_original = new XElement(xTablix_Columns.Elements().ElementAt(1));
                    xTablix_Columns.Add(new XElement(xdata_original));
                }
                xTablix_Columns.Elements(namspac_def + "TablixColumn").ElementAt(0).Elements(namspac_def + "Width").First().Value = "2cm";

                //
                // RENGLONES (TablixRows)
                //
                // (1) RENGLON DE ENCABEZADO
                XElement xTablixRow_encabezado = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "Body").Elements(namspac_def + "ReportItems").Elements(namspac_def + "Tablix").Elements(namspac_def + "TablixBody").Elements(namspac_def + "TablixRows").Elements().ElementAt(0);
                // COLUMNAS DE ENCABEZADO
                IEnumerable <XElement> xencabezados = xTablixRow_encabezado.Elements(namspac_def + "TablixCells").Elements();
                // NOMBRE TEXTBOX
                if (x > 1)
                {
                    XElement xdata_original  = new XElement(xTablixRow_encabezado.Elements(namspac_def + "TablixCells").Elements().ElementAt(1));//new XElement(xencabezados.ElementAt(1));
                    XElement xtablix_agregar = xTablixRow_encabezado.Elements().ElementAt(1);
                    xtablix_agregar.Add(new XElement(xdata_original));
                }
                if (x > 0)
                {
                    XElement textBox_encabezado = xencabezados.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").ElementAt(0);
                    textBox_encabezado.Attribute("Name").Value = nombre_semana.Replace(' ', '_') + "_encab_" + x.ToString();
                    //ENCABEZADO DE LA COLUMNA (NOMBRE DE LA SEMANA)
                    xencabezados.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").Elements(namspac_def + "Paragraphs").Elements(namspac_def + "Paragraph").Elements(namspac_def + "TextRuns").Elements(namspac_def + "TextRun").Elements(namspac_def + "Value").First().Value = nombre_semana_replace;
                }

                //(2) RENGLON DE CAMPOS
                XElement xTablixRow_campos = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "Body").Elements(namspac_def + "ReportItems").Elements(namspac_def + "Tablix").Elements(namspac_def + "TablixBody").Elements(namspac_def + "TablixRows").Elements().ElementAt(1);
                //COLUMNA DE CAMPOS
                IEnumerable <XElement> xcampos = xTablixRow_campos.Elements(namspac_def + "TablixCells").Elements();
                //NOMBRE DEL TEXTBOX
                if (x > 1)
                {
                    XElement xdata_original  = new XElement(xTablixRow_campos.Elements(namspac_def + "TablixCells").Elements().ElementAt(1));//new XElement(xcampos.ElementAt(0));
                    XElement xtablix_agregar = xTablixRow_campos.Elements().ElementAt(1);
                    xtablix_agregar.Add(new XElement(xdata_original));
                }
                if (x > 0)
                {
                    XElement textBox_campos = xcampos.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").ElementAt(0);
                    textBox_campos.Attribute("Name").Value = nombre_semana.Replace(' ', '_') + "_Textbox_" + x.ToString();
                    //NOMBRE DEL TEXTBOX (NOMBRE DE LA SEMANA)
                    xcampos.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").Elements(namspac_def + "Paragraphs").Elements(namspac_def + "Paragraph").Elements(namspac_def + "TextRuns").Elements(namspac_def + "TextRun").Elements(namspac_def + "Value").First().Value = "=Fields!" + nombre_semana + ".Value";
                }

                //(3) RENGLON
                XElement xTablixRow_espacio = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "Body").Elements(namspac_def + "ReportItems").Elements(namspac_def + "Tablix").Elements(namspac_def + "TablixBody").Elements(namspac_def + "TablixRows").Elements().ElementAt(2);
                // COLUMNAS DE ENCABEZADO
                IEnumerable <XElement> xespacios = xTablixRow_espacio.Elements(namspac_def + "TablixCells").Elements();
                // NOMBRE DEL TEXTBOX
                if (x > 1)
                {
                    XElement xdata_original  = new XElement(xTablixRow_espacio.Elements(namspac_def + "TablixCells").Elements().ElementAt(1));//new XElement(xespacios.ElementAt(0));
                    XElement xtablix_agregar = xTablixRow_espacio.Elements().ElementAt(1);
                    xtablix_agregar.Add(new XElement(xdata_original));
                }
                if (x > 0)
                {
                    XElement textBox_espacio = xespacios.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").ElementAt(0);
                    textBox_espacio.Attribute("Name").Value = nombre_semana.Replace(' ', '_') + "_espacio_" + x.ToString();
                }

                //(4) RENGLON TOTALES
                XElement xTablixRow_totales = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "Body").Elements(namspac_def + "ReportItems").Elements(namspac_def + "Tablix").Elements(namspac_def + "TablixBody").Elements(namspac_def + "TablixRows").Elements().ElementAt(3);
                //COLUMNAS DE ENCABEZADO
                IEnumerable <XElement> xtotales = xTablixRow_totales.Elements(namspac_def + "TablixCells").Elements();
                // NOMBRE DEL TEXTBOX
                if (x > 1)
                {
                    XElement xdata_original  = new XElement(xTablixRow_totales.Elements(namspac_def + "TablixCells").Elements().ElementAt(1));//new XElement(xtotales.ElementAt(0));
                    XElement xtablix_agregar = xTablixRow_totales.Elements().ElementAt(1);
                    xtablix_agregar.Add(new XElement(xdata_original));
                }
                if (x > 0)
                {
                    XElement textBox_totales = xtotales.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").ElementAt(0);
                    textBox_totales.Attribute("Name").Value = nombre_semana.Replace(' ', '_') + "_total_" + x.ToString();
                    xtotales.ElementAt(x).Elements(namspac_def + "CellContents").Elements(namspac_def + "Textbox").Elements(namspac_def + "Paragraphs").Elements(namspac_def + "Paragraph").Elements(namspac_def + "TextRuns").Elements(namspac_def + "TextRun").Elements(namspac_def + "Value").First().Value = "=sum(Fields!" + nombre_semana + ".Value)";
                }

                //
                // <TablixColumnHierarchy>
                //
                XElement xColumnHierarchy = xml_reporte.Elements(namspac_def + "Report").Elements(namspac_def + "Body").Elements(namspac_def + "ReportItems").Elements(namspac_def + "Tablix").Elements(namspac_def + "TablixColumnHierarchy").Elements().ElementAt(0);
                if (x > 1)
                {
                    XElement xdata_original  = new XElement(xColumnHierarchy.Elements().ElementAt(0));
                    XElement xColumn_agregar = xColumnHierarchy;
                    xColumn_agregar.Add(new XElement(xdata_original));
                }
            }

            xml_reporte.Save(archivo_guardar);

            return(dt);
        }
Ejemplo n.º 23
0
        private string ConvertXdf(XDocument doc)
        {
            string retVal = "";

            try
            {
                //List<string> categories = new List<string>();
                Dictionary <int, string> categories   = new Dictionary <int, string>();
                List <TableLink>         tableLinks   = new List <TableLink>();
                List <TableLink>         tableTargets = new List <TableLink>();

                foreach (XElement element in doc.Elements("XDFFORMAT").Elements("XDFHEADER"))
                {
                    foreach (XElement cat in element.Elements("CATEGORY"))
                    {
                        string catTxt = cat.Attribute("name").Value;
                        int    catId  = Convert.ToInt32(cat.Attribute("index").Value.Replace("0x", ""), 16);
                        categories.Add(catId, catTxt);
                    }
                }
                foreach (XElement element in doc.Elements("XDFFORMAT").Elements("XDFTABLE"))
                {
                    TableData xdf = new TableData();
                    xdf.OS     = PCM.OS;
                    xdf.Origin = "xdf";
                    xdf.Min    = double.MinValue;
                    xdf.Max    = double.MaxValue;
                    string RowHeaders  = "";
                    string ColHeaders  = "";
                    string size        = "";
                    string math        = "";
                    int    elementSize = 0;
                    bool   Signed      = false;
                    bool   Floating    = false;

                    List <string> multiMath = new List <string>();
                    List <string> multiAddr = new List <string>();

                    foreach (XElement axle in element.Elements("XDFAXIS"))
                    {
                        if (axle.Attribute("id").Value == "x")
                        {
                            xdf.Columns = Convert.ToUInt16(axle.Element("indexcount").Value);
                            foreach (XElement lbl in axle.Elements("LABEL"))
                            {
                                ColHeaders += lbl.Attribute("value").Value + ",";
                            }
                            ColHeaders        = ColHeaders.Trim(',');
                            xdf.ColumnHeaders = ColHeaders;
                        }
                        if (axle.Attribute("id").Value == "y")
                        {
                            xdf.Rows = Convert.ToUInt16(axle.Element("indexcount").Value);
                            foreach (XElement lbl in axle.Elements("LABEL"))
                            {
                                RowHeaders += lbl.Attribute("value").Value + ",";
                            }
                            RowHeaders     = RowHeaders.Trim(',');
                            xdf.RowHeaders = RowHeaders;
                        }
                        if (axle.Attribute("id").Value == "z")
                        {
                            if (axle.Element("EMBEDDEDDATA").Attribute("mmedaddress") != null)
                            {
                                xdf.Address = axle.Element("EMBEDDEDDATA").Attribute("mmedaddress").Value.Trim();
                            }
                            //xdf.addrInt = Convert.ToUInt32(addr, 16);
                            string tmp = axle.Element("EMBEDDEDDATA").Attribute("mmedelementsizebits").Value.Trim();
                            size        = (Convert.ToInt32(tmp) / 8).ToString();
                            elementSize = (byte)(Convert.ToInt32(tmp) / 8);
                            math        = axle.Element("MATH").Attribute("equation").Value.Trim().Replace("*.", "*0.");
                            xdf.Math    = math.Replace("/.", "/0.").ToLower();
                            xdf.Math    = xdf.Math.Replace("+ -", "-").Replace("+-", "-").Replace("++", "+").Replace("+ + ", "+");
                            //xdf.SavingMath = convertMath(xdf.Math);
                            xdf.Decimals = Convert.ToUInt16(axle.Element("decimalpl").Value);
                            if (axle.Element("outputtype") != null)
                            {
                                xdf.OutputType = (OutDataType)Convert.ToUInt16(axle.Element("outputtype").Value);
                            }
                            if (axle.Element("EMBEDDEDDATA") != null && axle.Element("EMBEDDEDDATA").Attribute("mmedtypeflags") != null)
                            {
                                byte flags = Convert.ToByte(axle.Element("EMBEDDEDDATA").Attribute("mmedtypeflags").Value, 16);
                                Signed = Convert.ToBoolean(flags & 1);
                                if ((flags & 0x10000) == 0x10000)
                                {
                                    Floating = true;
                                }
                                else
                                {
                                    Floating = false;
                                }
                                if ((flags & 4) == 4)
                                {
                                    xdf.RowMajor = false;
                                }
                                else
                                {
                                    xdf.RowMajor = true;
                                }
                            }

                            foreach (XElement rowMath in axle.Elements("MATH"))
                            {
                                if (rowMath.Element("VAR").Attribute("address") != null)
                                {
                                    //Table have different address for every (?) row
                                    Debug.WriteLine(rowMath.Element("VAR").Attribute("address").Value);
                                    Debug.WriteLine(rowMath.Attribute("equation").Value);
                                    multiAddr.Add(rowMath.Element("VAR").Attribute("address").Value);
                                    multiMath.Add(rowMath.Attribute("equation").Value);
                                }
                                foreach (XElement mathVar in rowMath.Elements("VAR"))
                                {
                                    if (mathVar.Attribute("id") != null)
                                    {
                                        string mId = mathVar.Attribute("id").Value.ToLower();
                                        if (mId != "x")
                                        {
                                            if (mathVar.Attribute("type") != null && mathVar.Attribute("type").Value == "link")
                                            {
                                                //Get math values from other table
                                                string    linktable = mathVar.Attribute("linkid").Value;
                                                TableLink tl        = new TableLink();
                                                tl.tdId     = tdList.Count;
                                                tl.variable = mId;
                                                tl.xdfId    = linktable;
                                                tableLinks.Add(tl);
                                            }
                                            if (mathVar.Attribute("type") != null && mathVar.Attribute("type").Value == "address")
                                            {
                                                string addrStr  = mathVar.Attribute("address").Value.ToLower().Replace("0x", "");
                                                string bits     = "8";
                                                bool   lsb      = false;
                                                bool   isSigned = false;
                                                if (mathVar.Attribute("sizeinbits") != null)
                                                {
                                                    bits = mathVar.Attribute("sizeinbits").Value;
                                                }
                                                if (mathVar.Attribute("flags") != null)
                                                {
                                                    byte flags = Convert.ToByte(mathVar.Attribute("flags").Value, 16);
                                                    isSigned = Convert.ToBoolean(flags & 1);
                                                    if ((flags & 4) == 4)
                                                    {
                                                        lsb = true;
                                                    }
                                                    else
                                                    {
                                                        lsb = false;
                                                    }
                                                }
                                                InDataType idt        = convertToDataType(bits, isSigned, false);
                                                string     replaceStr = "raw:" + addrStr + ":" + idt.ToString();
                                                if (lsb)
                                                {
                                                    replaceStr += ":lsb ";
                                                }
                                                else
                                                {
                                                    replaceStr += ":msb ";
                                                }
                                                xdf.Math = xdf.Math.Replace(mId, replaceStr);
                                                xdf.Math = xdf.Math.Replace("+ -", "-").Replace("+-", "-").Replace("++", "+").Replace("+ + ", "+");
                                                //xdf.SavingMath = xdf.SavingMath.Replace(mId, replaceStr);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    xdf.TableName = element.Element("title").Value;
                    if (element.Element("units") != null)
                    {
                        xdf.Units = element.Element("units").Value;
                    }

                    /*if (element.Element("datatype") != null)
                     *  xdf.DataType = Convert.ToByte(element.Element("datatype").Value);*/
                    if (element.Element("CATEGORYMEM") != null && element.Element("CATEGORYMEM").Attribute("category") != null)
                    {
                        int catid = 0;
                        foreach (XElement catEle in element.Elements("CATEGORYMEM"))
                        {
                            catid = Convert.ToInt16(catEle.Attribute("category").Value);
                            Debug.WriteLine(catid);
                            if (xdf.Category.Length > 0)
                            {
                                xdf.Category += " - ";
                            }
                            xdf.Category += categories[catid - 1];
                        }
                    }
                    if (element.Element("description") != null)
                    {
                        xdf.TableDescription = element.Element("description").Value;
                    }
                    xdf.DataType = convertToDataType(elementSize, Signed, Floating);

                    if (multiMath.Count > 0 && xdf.Rows == multiMath.Count)
                    {
                        string[] rowHdr = xdf.RowHeaders.Replace(".", "").Split(',');
                        for (int m = 0; m < multiMath.Count; m++)
                        {
                            TableData tdNew = new TableData();
                            tdNew         = xdf.ShallowCopy();
                            tdNew.Rows    = 1; //Convert to single-row, multitable
                            tdNew.Math    = multiMath[m];
                            tdNew.Address = multiAddr[m];
                            if (rowHdr.Length >= m - 1)
                            {
                                tdNew.TableName += "." + rowHdr[m];
                            }
                            else
                            {
                                tdNew.TableName += "." + m.ToString();
                            }
                            tdList.Add(tdNew);
                        }
                    }
                    else
                    {
                        tdList.Add(xdf);
                    }
                }
                foreach (XElement element in doc.Elements("XDFFORMAT").Elements("XDFCONSTANT"))
                {
                    TableData xdf = new TableData();
                    xdf.OS     = PCM.OS;
                    xdf.Origin = "xdf";
                    xdf.Min    = double.MinValue;
                    xdf.Max    = double.MaxValue;
                    int  elementSize = 0;
                    bool Signed      = false;
                    bool Floating    = false;
                    if (element.Attribute("uniqueid") != null)
                    {
                        TableLink tl = new TableLink();
                        tl.xdfId = element.Attribute("uniqueid").Value;
                        tl.tdId  = tdList.Count;
                        tableTargets.Add(tl);
                    }
                    if (element.Element("EMBEDDEDDATA").Attribute("mmedaddress") != null)
                    {
                        xdf.TableName = element.Element("title").Value;
                        //xdf.AddrInt = Convert.ToUInt32(element.Element("EMBEDDEDDATA").Attribute("mmedaddress").Value.Trim(), 16);
                        xdf.Address = element.Element("EMBEDDEDDATA").Attribute("mmedaddress").Value.Trim();
                        elementSize = (byte)(Convert.ToInt32(element.Element("EMBEDDEDDATA").Attribute("mmedelementsizebits").Value.Trim()) / 8);
                        xdf.Math    = element.Element("MATH").Attribute("equation").Value.Trim().Replace("*.", "*0.").Replace("/.", "/0.");
                        xdf.Math    = xdf.Math.Replace("+ -", "-").Replace("+-", "-").Replace("++", "+").Replace("+ + ", "+");
                        //xdf.SavingMath = convertMath(xdf.Math);
                        if (element.Element("units") != null)
                        {
                            xdf.Units = element.Element("units").Value;
                        }
                        if (element.Element("EMBEDDEDDATA").Attribute("mmedtypeflags") != null)
                        {
                            byte flags = Convert.ToByte(element.Element("EMBEDDEDDATA").Attribute("mmedtypeflags").Value, 16);
                            Signed = Convert.ToBoolean(flags & 1);
                            if ((flags & 0x10000) == 0x10000)
                            {
                                Floating = true;
                            }
                            else
                            {
                                Floating = false;
                            }
                        }
                        xdf.Columns  = 1;
                        xdf.Rows     = 1;
                        xdf.RowMajor = false;
                        if (element.Element("CATEGORYMEM") != null && element.Element("CATEGORYMEM").Attribute("category") != null)
                        {
                            int catid = 0;
                            foreach (XElement catEle in element.Elements("CATEGORYMEM"))
                            {
                                catid = Convert.ToInt16(catEle.Attribute("category").Value);
                                if (xdf.Category.Length > 0)
                                {
                                    xdf.Category += " - ";
                                }
                                xdf.Category += categories[catid - 1];
                            }
                        }
                        if (element.Element("description") != null)
                        {
                            xdf.TableDescription = element.Element("description").Value;
                        }
                        xdf.DataType = convertToDataType(elementSize, Signed, Floating);

                        tdList.Add(xdf);
                    }
                }
                foreach (XElement element in doc.Elements("XDFFORMAT").Elements("XDFFLAG"))
                {
                    TableData xdf = new TableData();
                    xdf.OS     = PCM.OS;
                    xdf.Origin = "xdf";
                    xdf.Min    = double.MinValue;
                    xdf.Max    = double.MaxValue;
                    if (element.Element("EMBEDDEDDATA").Attribute("mmedaddress") != null)
                    {
                        xdf.TableName = element.Element("title").Value;
                        //xdf.AddrInt = Convert.ToUInt32(element.Element("EMBEDDEDDATA").Attribute("mmedaddress").Value.Trim(), 16);
                        xdf.Address = element.Element("EMBEDDEDDATA").Attribute("mmedaddress").Value.Trim();
                        int elementSize = (byte)(Convert.ToInt32(element.Element("EMBEDDEDDATA").Attribute("mmedelementsizebits").Value.Trim()) / 8);
                        xdf.Math       = "X";
                        xdf.BitMask    = element.Element("mask").Value;
                        xdf.OutputType = OutDataType.Flag;
                        xdf.Columns    = 1;
                        xdf.Rows       = 1;
                        xdf.RowMajor   = false;
                        if (element.Element("CATEGORYMEM") != null && element.Element("CATEGORYMEM").Attribute("category") != null)
                        {
                            int catid = 0;
                            foreach (XElement catEle in element.Elements("CATEGORYMEM"))
                            {
                                catid = Convert.ToInt16(catEle.Attribute("category").Value);
                                if (xdf.Category.Length > 0)
                                {
                                    xdf.Category += " - ";
                                }
                                xdf.Category += categories[catid - 1];
                            }
                        }
                        if (element.Element("description") != null)
                        {
                            xdf.TableDescription = element.Element("description").Value;
                        }
                        xdf.DataType = convertToDataType(elementSize, false, false);
                        tdList.Add(xdf);
                    }
                }
                for (int i = 0; i < tableLinks.Count; i++)
                {
                    TableLink tl     = tableLinks[i];
                    TableData linkTd = tdList[tl.tdId];
                    for (int t = 0; t < tableTargets.Count; t++)
                    {
                        if (tableTargets[t].xdfId == tl.xdfId)
                        {
                            TableData targetTd = tdList[tableTargets[t].tdId];
                            linkTd.Math = linkTd.Math.Replace(tl.variable, "TABLE:'" + targetTd.TableName + "'");
                            //linkTd.SavingMath = linkTd.SavingMath.Replace(tl.variable, "TABLE:'" + targetTd.TableName + "'");
                            break;
                        }
                    }
                }

                for (int i = 0; i < PCM.tableDatas.Count; i++)
                {
                    if (!PCM.tableCategories.Contains(PCM.tableDatas[i].Category))
                    {
                        PCM.tableCategories.Add(PCM.tableDatas[i].Category);
                    }
                }
            }
            catch (Exception ex)
            {
                var st = new StackTrace(ex, true);
                // Get the top stack frame
                var frame = st.GetFrame(st.FrameCount - 1);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                retVal += "XdfImport, line " + line + ": " + ex.Message + Environment.NewLine;
            }
            return(retVal);
        }
Ejemplo n.º 24
0
        void parseXML(string filePath)
        {
            XDocument xDoc = XDocument.Load(filePath);

            List <XElement> element = xDoc.Elements("locale").ToList();

            if (element != null)
            {
                lManager.Enter(Sender.MANAGER, Level.DEBUG, "<locale/> found for locale:{0}", key);

                Locale locale = new Locale();

                if (!element[0].HasAttributes)
                {
                    lManager.Enter(Sender.MANAGER, Level.ERROR, "<locale/> element does not have expected attributes!");
                    return;
                }

                locale.Name = element[0].FirstAttribute.Value;

                List <XElement> childNodes = element[0].Elements().ToList();
                locale.DisplayName = childNodes[0].Value;
                locale.Encoding    = Convert.ToInt32(childNodes[1].Value);

                FontConfig globalFont = new FontConfig();
                System.Windows.Forms.RightToLeft rightToLeft = System.Windows.Forms.RightToLeft.No;

                if (childNodes.Count == 4) // Global font is likely defined
                {
                    if (childNodes[2].Name == "font")
                    {
                        List <XElement> fontElements = childNodes[2].Elements().ToList();

                        globalFont.Style = (System.Drawing.FontStyle)Enum.Parse(typeof(System.Drawing.FontStyle), fontElements[0].Value);
                        globalFont.Size  = Convert.ToDouble(fontElements[1].Value, CultureInfo.InvariantCulture);

                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "Global <font/> is defined.\nFamily:{0}\nStyle:{1}\nSize:{2}", globalFont.Name,
                                       globalFont.Style.ToString(),
                                       globalFont.Size);
                    }
                }
                else if (childNodes.Count == 5) // Global right to left is likely defined
                {
                    if (childNodes[3].Name == "rightToLeft")
                    {
                        rightToLeft = (System.Windows.Forms.RightToLeft)Enum.Parse(typeof(System.Windows.Forms.RightToLeft), childNodes[3].Value);

                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "Global <rightToLeft/> defined.");
                    }
                }

                // Get the <control/> nodes in the <controls/> elemenent
                childNodes = childNodes[childNodes.Count - 1].Elements().ToList();

                lManager.Enter(Sender.MANAGER, Level.DEBUG, "{0} <control/> nodes found.", childNodes.Count);

                List <ControlConfig> controls = new List <ControlConfig>();
                for (int c = 0; c < childNodes.Count; c++)
                {
                    ControlConfig control = new ControlConfig();

                    if (childNodes[c].HasAttributes)
                    {
                        List <XAttribute> attributes = childNodes[c].Attributes().ToList();
                        if (attributes.Count >= 1)
                        {
                            control.Name = attributes[0].Value;
                        }

                        if (attributes.Count >= 2)
                        {
                            control.Comment = attributes[1].Value;
                        }

                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "<control/> {0} has expected attributes.", control.Name);
                    }
                    else
                    {
                        string msg = string.Format("<control/> at index: {0} does not have attributes! Ignoring!", c);
                        lManager.Enter(Sender.MANAGER, Level.WARNING, msg);
                        System.Windows.Forms.MessageBox.Show(msg, "XML Exception", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    }

                    FontConfig controlFont = null;

                    List <XElement> fontElements = childNodes[c].Elements("font").ToList();
                    if (fontElements.Count > 0)
                    {
                        controlFont      = new FontConfig();
                        controlFont.Name = fontElements[0].FirstAttribute.Value;

                        fontElements      = fontElements[0].Elements().ToList();
                        controlFont.Style = (System.Drawing.FontStyle)Enum.Parse(typeof(System.Drawing.FontStyle), fontElements[0].Value);
                        controlFont.Size  = Convert.ToDouble(fontElements[1].Value, CultureInfo.InvariantCulture);

                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "<font/> detected.\nFamily:{0}\nStyle:{2}\nSize:{1}", controlFont.Name,
                                       controlFont.Style.ToString(),
                                       controlFont.Size);
                    }
                    else
                    {
                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "No <font/> detected for control: {0}", control.Name);
                    }

                    control.Font = (controlFont != null) ? controlFont : globalFont;

                    List <XElement> locationElements = childNodes[c].Elements("location").ToList();
                    if (locationElements.Count == 1)
                    {
                        string[] location = childNodes[c].Elements("location").ToList()[0].Value.Split(',');
                        control.Location = new System.Drawing.Point(int.Parse(location[0]), int.Parse(location[1]));

                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "<location/> detected.\nx:{0}\ny:{1}", control.Location.X,
                                       control.Location.Y);
                    }
                    else
                    {
                        control.Location = new System.Drawing.Point(0, 0);
                    }

                    List <XElement> sizeElements = childNodes[c].Elements("size").ToList();
                    if (sizeElements.Count == 1)
                    {
                        string[] size = childNodes[c].Elements("size").ToList()[0].Value.Split(',');
                        control.Size = new System.Drawing.Size(int.Parse(size[0]), int.Parse(size[1]));

                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "<size/> detected. \nheight:{0}\nwidth:{1}", control.Size.Height,
                                       control.Size.Width);
                    }
                    else
                    {
                        control.Size = new System.Drawing.Size(0, 0);
                    }

                    TextConfig text = new TextConfig();
                    text.Alignment = System.Drawing.ContentAlignment.MiddleLeft;

                    List <XElement> textElements = childNodes[c].Elements("text").ToList();

                    if (textElements.Count > 0)
                    {
                        lManager.Enter(Sender.MANAGER, Level.DEBUG, "<text/> element detected!");

                        if (textElements[0].HasAttributes)
                        {
                            List <XAttribute> attributes = textElements[0].Attributes().ToList();

                            XAttribute attribute = attributes.Find(a => a.Name == "align");
                            if (attribute != null)
                            {
                                text.Alignment = (System.Drawing.ContentAlignment)Enum.Parse(typeof(System.Drawing.ContentAlignment), attribute.Value);
                            }

                            attribute = attributes.Find(a => a.Name == "rightToLeft");
                            if (attribute != null)
                            {
                                text.RightToLeft = (System.Windows.Forms.RightToLeft)Enum.Parse(typeof(System.Windows.Forms.RightToLeft), attribute.Value);
                            }
                        }

                        text.Text = textElements[0].Value;
                    }
                    else
                    {
                        text.Text = string.Empty;
                    }

                    control.Text = text;

                    if (control.Populated)
                    {
                        controls.Add(control);
                    }
                }

                locale.Controls = controls;

                if (locale.Populated)
                {
                    locales.Add(locale);
                }

                lManager.Enter(Sender.MANAGER, Level.DEBUG, string.Format("{0} controls configurations loaded from locale: {1} from\n\t- {2}", locale.Controls.Count, locale.Name, filePath));
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Get the IdP Authn Response and extract metadata to the returned DTO class
        /// </summary>
        /// <param name="base64Response"></param>
        /// <returns>IdpSaml2Response</returns>
        public static IdpAuthnResponse GetAuthnResponse(string base64Response)
        {
            const string VALUE_NOT_AVAILABLE = "N/A";
            string       idpResponse;

            if (String.IsNullOrEmpty(base64Response))
            {
                throw new ArgumentNullException("The base64Response parameter can't be null or empty.");
            }

            try
            {
                idpResponse = Encoding.UTF8.GetString(Convert.FromBase64String(base64Response));
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Unable to converto base64 response to ascii string.", ex);
            }

            try
            {
                // Verify signature
                XmlDocument xml = new XmlDocument {
                    PreserveWhitespace = true
                };
                xml.LoadXml(idpResponse);
                if (!XmlSigningHelper.VerifySignature(xml))
                {
                    throw new Exception("Unable to verify the signature of the IdP response.");
                }

                // Parse XML document
                XDocument xdoc = new XDocument();
                xdoc = XDocument.Parse(idpResponse);

                string         destination                         = VALUE_NOT_AVAILABLE;
                string         id                                  = VALUE_NOT_AVAILABLE;
                string         inResponseTo                        = VALUE_NOT_AVAILABLE;
                DateTimeOffset issueInstant                        = DateTimeOffset.MinValue;
                string         version                             = VALUE_NOT_AVAILABLE;
                string         statusCodeValue                     = VALUE_NOT_AVAILABLE;
                string         statusCodeInnerValue                = VALUE_NOT_AVAILABLE;
                string         statusMessage                       = VALUE_NOT_AVAILABLE;
                string         statusDetail                        = VALUE_NOT_AVAILABLE;
                string         assertionId                         = VALUE_NOT_AVAILABLE;
                DateTimeOffset assertionIssueInstant               = DateTimeOffset.MinValue;
                string         assertionVersion                    = VALUE_NOT_AVAILABLE;
                string         assertionIssuer                     = VALUE_NOT_AVAILABLE;
                string         subjectNameId                       = VALUE_NOT_AVAILABLE;
                string         subjectConfirmationMethod           = VALUE_NOT_AVAILABLE;
                string         subjectConfirmationDataInResponseTo = VALUE_NOT_AVAILABLE;
                DateTimeOffset subjectConfirmationDataNotOnOrAfter = DateTimeOffset.MinValue;
                string         subjectConfirmationDataRecipient    = VALUE_NOT_AVAILABLE;
                DateTimeOffset conditionsNotBefore                 = DateTimeOffset.MinValue;
                DateTimeOffset conditionsNotOnOrAfter              = DateTimeOffset.MinValue;
                string         audience                            = VALUE_NOT_AVAILABLE;
                DateTimeOffset authnStatementAuthnInstant          = DateTimeOffset.MinValue;
                string         authnStatementSessionIndex          = VALUE_NOT_AVAILABLE;
                Dictionary <string, string> spidUserInfo           = new Dictionary <string, string>();

                // Extract response metadata
                XElement responseElement = xdoc.Elements("{urn:oasis:names:tc:SAML:2.0:protocol}Response").Single();
                destination  = responseElement.Attribute("Destination").Value;
                id           = responseElement.Attribute("ID").Value;
                inResponseTo = responseElement.Attribute("InResponseTo").Value;
                issueInstant = DateTimeOffset.Parse(responseElement.Attribute("IssueInstant").Value);
                version      = responseElement.Attribute("Version").Value;

                // Extract Issuer metadata
                string issuer = responseElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}Issuer").Single().Value.Trim();

                // Extract Status metadata
                XElement StatusElement = responseElement.Descendants("{urn:oasis:names:tc:SAML:2.0:protocol}Status").Single();
                IEnumerable <XElement> statusCodeElements = StatusElement.Descendants("{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode");
                statusCodeValue      = statusCodeElements.First().Attribute("Value").Value.Replace("urn:oasis:names:tc:SAML:2.0:status:", "");
                statusCodeInnerValue = statusCodeElements.Count() > 1 ? statusCodeElements.Last().Attribute("Value").Value.Replace("urn:oasis:names:tc:SAML:2.0:status:", "") : VALUE_NOT_AVAILABLE;
                statusMessage        = StatusElement.Elements("{urn:oasis:names:tc:SAML:2.0:protocol}StatusMessage").SingleOrDefault()?.Value ?? VALUE_NOT_AVAILABLE;
                statusDetail         = StatusElement.Elements("{urn:oasis:names:tc:SAML:2.0:protocol}StatusDetail").SingleOrDefault()?.Value ?? VALUE_NOT_AVAILABLE;

                if (statusCodeValue == "Success")
                {
                    // Extract Assertion metadata
                    XElement assertionElement = responseElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}Assertion").Single();
                    assertionId           = assertionElement.Attribute("ID").Value;
                    assertionIssueInstant = DateTimeOffset.Parse(assertionElement.Attribute("IssueInstant").Value);
                    assertionVersion      = assertionElement.Attribute("Version").Value;
                    assertionIssuer       = assertionElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}Issuer").Single().Value.Trim();

                    // Extract Subject metadata
                    XElement subjectElement = assertionElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}Subject").Single();
                    subjectNameId             = subjectElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}NameID").Single().Value.Trim();
                    subjectConfirmationMethod = subjectElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation").Single().Attribute("Method").Value;
                    XElement confirmationDataElement = subjectElement.Descendants("{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData").Single();
                    subjectConfirmationDataInResponseTo = confirmationDataElement.Attribute("InResponseTo").Value;
                    subjectConfirmationDataNotOnOrAfter = DateTimeOffset.Parse(confirmationDataElement.Attribute("NotOnOrAfter").Value);
                    subjectConfirmationDataRecipient    = confirmationDataElement.Attribute("Recipient").Value;

                    // Extract Conditions metadata
                    XElement conditionsElement = assertionElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}Conditions").Single();
                    conditionsNotBefore    = DateTimeOffset.Parse(conditionsElement.Attribute("NotBefore").Value);
                    conditionsNotOnOrAfter = DateTimeOffset.Parse(conditionsElement.Attribute("NotOnOrAfter").Value);
                    audience = conditionsElement.Descendants("{urn:oasis:names:tc:SAML:2.0:assertion}Audience").Single().Value.Trim();

                    // Extract AuthnStatement metadata
                    XElement authnStatementElement = assertionElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement").Single();
                    authnStatementAuthnInstant = DateTimeOffset.Parse(authnStatementElement.Attribute("AuthnInstant").Value);
                    authnStatementSessionIndex = authnStatementElement.Attribute("SessionIndex").Value;

                    // Extract SPID user info
                    foreach (XElement attribute in xdoc.Descendants("{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement").Elements())
                    {
                        spidUserInfo.Add(
                            attribute.Attribute("Name").Value,
                            attribute.Elements().Single(a => a.Name == "{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue").Value.Trim()
                            );
                    }
                }

                return(new IdpAuthnResponse(destination, id, inResponseTo, issueInstant, version, issuer,
                                            statusCodeValue, statusCodeInnerValue, statusMessage, statusDetail,
                                            assertionId, assertionIssueInstant, assertionVersion, assertionIssuer,
                                            subjectNameId, subjectConfirmationMethod, subjectConfirmationDataInResponseTo,
                                            subjectConfirmationDataNotOnOrAfter, subjectConfirmationDataRecipient,
                                            conditionsNotBefore, conditionsNotOnOrAfter, audience,
                                            authnStatementAuthnInstant, authnStatementSessionIndex,
                                            spidUserInfo));
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Unable to read AttributeStatement attributes from SAML2 document.", ex);
            }
        }
Ejemplo n.º 26
0
    //
    // GET: /Auth/Login
    public ActionResult Login(string ticket, string ReturnUrl)
    {
        // Make sure CasHost is specified in web.config
        if (String.IsNullOrEmpty(_casHost))
        {
            Logger.Fatal("Could not find CasHost in web.config. Please specify this value for authentication.");
        }

        string strService = Request.Url.GetLeftPart(UriPartial.Path);

        // First time through there is no ticket=, so redirect to CAS login
        if (String.IsNullOrWhiteSpace(ticket))
        {
            if (!String.IsNullOrWhiteSpace(ReturnUrl))
            {
                Session["ReturnUrl"] = ReturnUrl;
            }

            string strRedirect = _casHost + "login?" + "service=" + strService;

            Logger.Debug("Initializing handshake with CAS");
            Logger.DebugFormat("Redirecting to: {0}", strRedirect);

            return(Redirect(strRedirect));
        }

        // Second time (back from CAS) there is a ticket= to validate
        string strValidateUrl = _casHost + "serviceValidate?" + "ticket=" + ticket + "&" + "service=" + strService;

        Logger.DebugFormat("Validating ticket from CAS at: {0}", strValidateUrl);

        XmlReader  reader = XmlReader.Create(new WebClient().OpenRead(strValidateUrl));
        XDocument  xdoc   = XDocument.Load(reader);
        XNamespace xmlns  = _casXMLNS;

        Logger.DebugFormat("CAS Response: {0}", xdoc.ToString());
        Logger.Debug("Parsing XML response from CAS");

        var element = (from serviceResponse in xdoc.Elements(xmlns + "serviceResponse")
                       from authenticationSuccess in serviceResponse.Elements(xmlns + "authenticationSuccess")
                       from user in authenticationSuccess.Elements(xmlns + "user")
                       select user).FirstOrDefault();

        string strNetId = String.Empty;

        if (element != null)
        {
            strNetId = element.Value;
        }

        if (!String.IsNullOrEmpty(strNetId))
        {
            Logger.DebugFormat("User '{0}' was validated successfully", strNetId);
            Logger.DebugFormat("Loading user data for '{0}'", strNetId);

            // Get banner data
            var bannerUser = _bannerIdentityService.GetBannerIdentityByNetId(strNetId);

            // Make sure banner user isnt null
            if (bannerUser == null)
            {
                throw new ArgumentOutOfRangeException(String.Format("Could not found any banner records for the Net ID ({0}).", strNetId));
            }

            Logger.DebugFormat("Logging in user '{0}' as a system user.", strNetId);

            Response.Cookies.Add(GetFormsAuthenticationCookie(bannerUser));
        }
        else
        {
            return(HttpNotFound());
        }

        if (Session["ReturnUrl"] != null)
        {
            ReturnUrl            = Session["ReturnUrl"].ToString();
            Session["ReturnUrl"] = null;
        }

        if (String.IsNullOrEmpty(ReturnUrl) && Request.UrlReferrer != null)
        {
            ReturnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
        }

        if (Url.IsLocalUrl(ReturnUrl) && !String.IsNullOrEmpty(ReturnUrl))
        {
            return(Redirect(ReturnUrl));
        }
        else
        {
            return(RedirectToAction("Index", "Home", new { area = "" }));
        }
    }
Ejemplo n.º 27
0
        /// <summary>
        /// Get the IdP Logout Response and extract metadata to the returned DTO class
        /// </summary>
        /// <param name="base64Response"></param>
        /// <returns></returns>
        public static IdpLogoutResponse GetLogoutResponse(string base64Response)
        {
            const string VALUE_NOT_AVAILABLE = "N/A";
            string       idpResponse;

            if (String.IsNullOrEmpty(base64Response))
            {
                throw new ArgumentNullException("The base64Response parameter can't be null or empty.");
            }

            try
            {
                idpResponse = Encoding.UTF8.GetString(Convert.FromBase64String(base64Response));
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Unable to converto base64 response to ascii string.", ex);
            }

            try
            {
                // Verify signature
                XmlDocument xml = new XmlDocument {
                    PreserveWhitespace = true
                };
                xml.LoadXml(idpResponse);
                if (!XmlSigningHelper.VerifySignature(xml))
                {
                    throw new Exception("Unable to verify the signature of the IdP response.");
                }

                // Parse XML document
                XDocument xdoc = new XDocument();
                xdoc = XDocument.Parse(idpResponse);

                string         destination          = VALUE_NOT_AVAILABLE;
                string         id                   = VALUE_NOT_AVAILABLE;
                string         inResponseTo         = VALUE_NOT_AVAILABLE;
                DateTimeOffset issueInstant         = DateTimeOffset.MinValue;
                string         version              = VALUE_NOT_AVAILABLE;
                string         statusCodeValue      = VALUE_NOT_AVAILABLE;
                string         statusCodeInnerValue = VALUE_NOT_AVAILABLE;
                string         statusMessage        = VALUE_NOT_AVAILABLE;
                string         statusDetail         = VALUE_NOT_AVAILABLE;

                // Extract response metadata
                XElement responseElement = xdoc.Elements("{urn:oasis:names:tc:SAML:2.0:protocol}LogoutResponse").Single();
                destination  = responseElement.Attribute("Destination").Value;
                id           = responseElement.Attribute("ID").Value;
                inResponseTo = responseElement.Attribute("InResponseTo").Value;
                issueInstant = DateTimeOffset.Parse(responseElement.Attribute("IssueInstant").Value);
                version      = responseElement.Attribute("Version").Value;

                // Extract Issuer metadata
                string issuer = responseElement.Elements("{urn:oasis:names:tc:SAML:2.0:assertion}Issuer").Single().Value.Trim();

                // Extract Status metadata
                XElement StatusElement = responseElement.Descendants("{urn:oasis:names:tc:SAML:2.0:protocol}Status").Single();
                IEnumerable <XElement> statusCodeElements = StatusElement.Descendants("{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode");
                statusCodeValue      = statusCodeElements.First().Attribute("Value").Value.Replace("urn:oasis:names:tc:SAML:2.0:status:", "");
                statusCodeInnerValue = statusCodeElements.Count() > 1 ? statusCodeElements.Last().Attribute("Value").Value.Replace("urn:oasis:names:tc:SAML:2.0:status:", "") : VALUE_NOT_AVAILABLE;
                statusMessage        = StatusElement.Elements("{urn:oasis:names:tc:SAML:2.0:protocol}StatusMessage").SingleOrDefault()?.Value ?? VALUE_NOT_AVAILABLE;
                statusDetail         = StatusElement.Elements("{urn:oasis:names:tc:SAML:2.0:protocol}StatusDetail").SingleOrDefault()?.Value ?? VALUE_NOT_AVAILABLE;

                return(new IdpLogoutResponse(destination, id, inResponseTo, issueInstant, version, issuer,
                                             statusCodeValue, statusCodeInnerValue, statusMessage, statusDetail));
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Unable to read AttributeStatement attributes from SAML2 document.", ex);
            }
        }
Ejemplo n.º 28
0
    /// <summary>
    /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed.
    /// </summary>
    /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param>
    /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param>
    /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param>
    /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param>
    /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param>
    /// <returns></returns>
    public static Dictionary <string, object> GetFeed(string feedUrl, string detailPage, int cacheDuration, ref Dictionary <string, string> message, ref bool isError)
    {
        Dictionary <string, object> feedDictionary = new Dictionary <string, object>();

        if (message == null)
        {
            message = new Dictionary <string, string>();
        }

        if (String.IsNullOrEmpty(feedUrl))
        {
            message.Add("Feed URL not provided.", "The RSS Feed URL has not been provided. Please update the \"RSS Feed URL\" attribute in the block settings.");
            return(feedDictionary);
        }
        if (!System.Text.RegularExpressions.Regex.IsMatch(feedUrl, @"^(http://|https://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
        {
            message.Add("Feed URL not valid.", "The Feed URL is not formatted properly. Please verify the \"RSS Feed URL\" attribute in block settings.");
            isError = false;
            return(feedDictionary);
        }

        ObjectCache feedCache = MemoryCache.Default;

        if (feedCache[GetFeedCacheKey(feedUrl)] != null)
        {
            feedDictionary = (Dictionary <string, object>)feedCache[GetFeedCacheKey(feedUrl)];
        }
        else
        {
            XDocument feed = null;

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(feedUrl);

            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            {
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    XmlReader feedReader = XmlReader.Create(resp.GetResponseStream());
                    feed = XDocument.Load(feedReader);

                    feedReader.Close();
                }
                else
                {
                    message.Add("Error loading feed.", string.Format("An error has occurred while loading the feed.  Status Code: {0} - {1}", (int)resp.StatusCode, resp.StatusDescription));
                    isError = true;
                }
            }

            if (feed != null)
            {
                string detailPageBaseUrl = string.Empty;
                int    detailPageID      = 0;

                if (!String.IsNullOrEmpty(detailPage))
                {
                    detailPageID = new Rock.Model.PageService(new Rock.Data.RockContext()).Get(new Guid(detailPage)).Id;

                    detailPageBaseUrl = new PageReference(detailPageID).BuildUrl();
                }

                if (detailPageID > 0)
                {
                    detailPageBaseUrl = new PageReference(detailPageID).BuildUrl();
                }

                Dictionary <string, XNamespace> namespaces = feed.Root.Attributes()
                                                             .Where(a => a.IsNamespaceDeclaration)
                                                             .GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName,
                                                                      a => XNamespace.Get(a.Value))
                                                             .ToDictionary(g => g.Key, g => g.First());


                feedDictionary = BuildElementDictionary(feed.Elements().First(), namespaces);

                if (feedDictionary.Count == 1 && feedDictionary.First().Value.GetType() == typeof(Dictionary <string, object>))
                {
                    feedDictionary = (Dictionary <string, object>)feedDictionary.First().Value;
                }

                if (feedDictionary.ContainsKey("lastBuildDate"))
                {
                    feedDictionary["lastBuildDate"] = DateTimeOffset.Parse(feedDictionary["lastBuildDate"].ToString()).LocalDateTime;
                }

                if (feedDictionary.ContainsKey("updated"))
                {
                    feedDictionary["updated"] = DateTimeOffset.Parse(feedDictionary["updated"].ToString()).LocalDateTime;
                }

                if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry"))
                {
                    List <Dictionary <string, object> > articles = (List <Dictionary <string, object> >)feedDictionary.Where(x => x.Key == "item" || x.Key == "entry").FirstOrDefault().Value;

                    foreach (var article in articles)
                    {
                        string idEntry       = String.Empty;
                        string idEntryHashed = string.Empty;
                        if (article.ContainsKey("id"))
                        {
                            idEntry = article["id"].ToString();
                        }

                        if (article.ContainsKey("guid"))
                        {
                            if (article["guid"].GetType() == typeof(Dictionary <string, object>))
                            {
                                idEntry = ((Dictionary <string, object>)article["guid"])["value"].ToString();
                            }
                            else
                            {
                                idEntry = article["guid"].ToString();
                            }
                        }

                        if (!String.IsNullOrWhiteSpace(idEntry))
                        {
                            System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create();
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            foreach (byte b in hashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(idEntry)))
                            {
                                sb.Append(b.ToString("X2"));
                            }

                            idEntryHashed = sb.ToString();

                            Dictionary <string, string> queryString = new Dictionary <string, string>();
                            queryString.Add("feedItemId", idEntryHashed);

                            if (detailPageID > 0)
                            {
                                article.Add("detailPageUrl", new PageReference(detailPageID, 0, queryString).BuildUrl());
                            }

                            article.Add("articleHash", idEntryHashed);
                        }

                        if (article.ContainsKey("pubDate"))
                        {
                            article["pubDate"] = DateTimeOffset.Parse(article["pubDate"].ToString()).LocalDateTime;
                        }

                        if (article.ContainsKey("updated"))
                        {
                            article["updated"] = DateTimeOffset.Parse(article["updated"].ToString()).LocalDateTime;
                        }
                    }
                }

                if (!String.IsNullOrEmpty(detailPageBaseUrl))
                {
                    feedDictionary.Add("DetailPageBaseUrl", detailPageBaseUrl);
                }
            }

            if (feedDictionary != null)
            {
                feedCache.Set(GetFeedCacheKey(feedUrl), feedDictionary, DateTimeOffset.Now.AddMinutes(cacheDuration));
            }
        }

        return(feedDictionary);
    }
Ejemplo n.º 29
0
        private void button5_Click(object sender, EventArgs e)
        {
            DataSet1 testdataset = new DataSet1();

            //open file code
            openFileDialog1.Filter           = "nessus files (*.nessus)|*.nessus|All files (*.*)|*.*";
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Title            = "Please select a nessus file to open.";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
                // Read the files
                foreach (String file in openFileDialog1.FileNames)
                {
                    // Create a PictureBox.
                    try
                    {
                        //open nessus file
                        XDocument xml = XDocument.Load(file);

                        //for each report host that is high
                        var queryhosts = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost")
                                         select p;
                        foreach (var record in queryhosts)
                        {
                            string hostname = record.Attribute("name").Value;
                            if (!testedtargets.Items.Contains(hostname))
                            {
                                testedtargets.Items.Add(hostname);
                            }
                        }
                        string totalcount = testedtargets.Items.Count.ToString();
                        totaltargetstested.Text = totalcount;

                        //get high vulns out
                        if (chk_critical.Checked)
                        {
                            //for each report host that is high
                            var query1 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost")
                                         select p;
                            foreach (var record1 in query1)
                            {
                                string hostname = record1.Attribute("name").Value;
                                //for each reportitem in the nessus report for that host
                                var query2 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost").Elements("ReportItem")
                                             where (int)p.Attribute("severity") == 4 && (string)p.Parent.Attribute("name") == hostname
                                             select p;


                                foreach (var record in query2)
                                {
                                    string isvalid      = "1";
                                    string severity     = "4 Critical";
                                    string vulnname     = record.Element("plugin_name").Value.ToString();
                                    string port         = record.Attribute("port").Value.ToString();
                                    string pluginoutput = record.Element("plugin_output").ElementValueNull();
                                    string solutions    = record.Element("solution").ElementValueNull();

                                    foreach (var item in vulns)
                                    {
                                        if (item.VulnName == vulnname)
                                        {
                                            isvalid       = "2";
                                            item.Evidence = item.Evidence + "\n\n" + pluginoutput;
                                            item.Hostport = item.Hostport + ", " + hostname + ":" + port;

                                            if (!item.Host.Contains(hostname))
                                            {
                                                item.Host = item.Host + ", " + hostname;
                                            }

                                            if (!item.Port.Contains(port))
                                            {
                                                item.Port = item.Port + ", " + port;
                                            }
                                        }
                                    }

                                    if (isvalid == "1")
                                    {
                                        vulns.Add(new Vulnerability()
                                        {
                                            VulnName = vulnname,
                                            Severity = severity,
                                            Host     = hostname,
                                            Port     = port,
                                            Evidence = pluginoutput,
                                            Hostport = hostname + ":" + port,
                                            Solution = solutions
                                        });
                                    }
                                }
                            }
                        }
                        //get high vulns out
                        if (chk_high.Checked)
                        {
                            //for each report host that is high
                            var query1 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost")
                                         select p;
                            foreach (var record1 in query1)
                            {
                                string hostname = record1.Attribute("name").Value;
                                //for each reportitem in the nessus report for that host
                                var query2 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost").Elements("ReportItem")
                                             where (int)p.Attribute("severity") == 3 && (string)p.Parent.Attribute("name") == hostname
                                             select p;


                                foreach (var record in query2)
                                {
                                    string isvalid      = "1";
                                    string severity     = "3 High";
                                    string vulnname     = record.Element("plugin_name").Value.ToString();
                                    string port         = record.Attribute("port").Value.ToString();
                                    string pluginoutput = record.Element("plugin_output").ElementValueNull();
                                    string solutions    = record.Element("solution").ElementValueNull();
                                    foreach (var item in vulns)
                                    {
                                        if (item.VulnName == vulnname)
                                        {
                                            isvalid       = "2";
                                            item.Evidence = item.Evidence + "\n\n" + pluginoutput;
                                            item.Hostport = item.Hostport + ", " + hostname + ":" + port;
                                            if (!item.Host.Contains(hostname))
                                            {
                                                item.Host = item.Host + ", " + hostname;
                                            }

                                            if (!item.Port.Contains(port))
                                            {
                                                item.Port = item.Port + ", " + port;
                                            }
                                        }
                                    }

                                    if (isvalid == "1")
                                    {
                                        vulns.Add(new Vulnerability()
                                        {
                                            VulnName = vulnname,
                                            Severity = severity,
                                            Host     = hostname,
                                            Port     = port,
                                            Evidence = pluginoutput,
                                            Hostport = hostname + ":" + port,
                                            Solution = solutions
                                        });
                                    }
                                }
                            }
                        }

                        if (chk_medium.Checked)
                        {
                            //for each report host that is high
                            var query1 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost")
                                         select p;
                            foreach (var record1 in query1)
                            {
                                string hostname = record1.Attribute("name").Value;
                                //for each reportitem in the nessus report for that host
                                var query2 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost").Elements("ReportItem")
                                             where (int)p.Attribute("severity") == 2 && (string)p.Parent.Attribute("name") == hostname
                                             select p;


                                foreach (var record in query2)
                                {
                                    string isvalid      = "1";
                                    string severity     = "2 Medium";
                                    string vulnname     = record.Element("plugin_name").Value.ToString();
                                    string port         = record.Attribute("port").Value.ToString();
                                    string pluginoutput = record.Element("plugin_output").ElementValueNull();
                                    string solutions    = record.Element("solution").ElementValueNull();
                                    foreach (var item in vulns)
                                    {
                                        if (item.VulnName == vulnname)
                                        {
                                            isvalid       = "2";
                                            item.Evidence = item.Evidence + "\n\n" + pluginoutput;
                                            item.Hostport = item.Hostport + ", " + hostname + ":" + port;
                                            if (!item.Host.Contains(hostname))
                                            {
                                                item.Host = item.Host + ", " + hostname;
                                            }

                                            if (!item.Port.Contains(port))
                                            {
                                                item.Port = item.Port + ", " + port;
                                            }
                                        }
                                    }
                                    if (isvalid == "1")
                                    {
                                        vulns.Add(new Vulnerability()
                                        {
                                            VulnName = vulnname,
                                            Severity = severity,
                                            Host     = hostname,
                                            Port     = port,
                                            Evidence = pluginoutput,
                                            Hostport = hostname + ":" + port,
                                            Solution = solutions
                                        });
                                    }
                                }
                            }
                        }
                        if (chk_low.Checked)
                        {
                            //for each report host that is high
                            var query1 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost")
                                         select p;
                            foreach (var record1 in query1)
                            {
                                string hostname = record1.Attribute("name").Value;
                                //for each reportitem in the nessus report for that host
                                var query2 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost").Elements("ReportItem")
                                             where (int)p.Attribute("severity") == 1 && (string)p.Parent.Attribute("name") == hostname
                                             select p;


                                foreach (var record in query2)
                                {
                                    string isvalid      = "1";
                                    string severity     = "1 Low";
                                    string vulnname     = record.Element("plugin_name").Value.ToString();
                                    string port         = record.Attribute("port").Value.ToString();
                                    string pluginoutput = record.Element("plugin_output").ElementValueNull();
                                    string solutions    = record.Element("solution").ElementValueNull();
                                    foreach (var item in vulns)
                                    {
                                        if (item.VulnName == vulnname)
                                        {
                                            isvalid       = "2";
                                            item.Evidence = item.Evidence + "\n\n" + pluginoutput;
                                            item.Hostport = item.Hostport + ", " + hostname + ":" + port;
                                            if (!item.Host.Contains(hostname))
                                            {
                                                item.Host = item.Host + ", " + hostname;
                                            }

                                            if (!item.Port.Contains(port))
                                            {
                                                item.Port = item.Port + ", " + port;
                                            }
                                        }
                                    }
                                    if (isvalid == "1")
                                    {
                                        vulns.Add(new Vulnerability()
                                        {
                                            VulnName = vulnname,
                                            Severity = severity,
                                            Host     = hostname,
                                            Port     = port,
                                            Evidence = pluginoutput,
                                            Hostport = hostname + ":" + port,
                                            Solution = solutions
                                        });
                                    }
                                }
                            }
                        }
                        if (chk_info.Checked)
                        {
                            //for each report host that is high
                            var query1 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost")
                                         select p;
                            foreach (var record1 in query1)
                            {
                                string hostname = record1.Attribute("name").Value;
                                //for each reportitem in the nessus report for that host
                                var query2 = from p in xml.Elements("NessusClientData_v2").Elements("Report").Elements("ReportHost").Elements("ReportItem")
                                             where (int)p.Attribute("severity") == 0 && (string)p.Parent.Attribute("name") == hostname
                                             select p;


                                foreach (var record in query2)
                                {
                                    string isvalid      = "1";
                                    string severity     = "0 Lnfo";
                                    string vulnname     = record.Element("plugin_name").Value.ToString();
                                    string port         = record.Attribute("port").Value.ToString();
                                    string pluginoutput = record.Element("plugin_output").ElementValueNull();
                                    string solutions    = record.Element("solution").ElementValueNull();
                                    foreach (var item in vulns)
                                    {
                                        if (item.VulnName == vulnname)
                                        {
                                            isvalid       = "2";
                                            item.Evidence = item.Evidence + "\n\n" + pluginoutput;
                                            item.Hostport = item.Hostport + ", " + hostname + ":" + port;
                                            if (!item.Host.Contains(hostname))
                                            {
                                                item.Host = item.Host + ", " + hostname;
                                            }

                                            if (!item.Port.Contains(port))
                                            {
                                                item.Port = item.Port + ", " + port;
                                            }
                                        }
                                    }
                                    if (isvalid == "1")
                                    {
                                        vulns.Add(new Vulnerability()
                                        {
                                            VulnName = vulnname,
                                            Severity = severity,
                                            Host     = hostname,
                                            Port     = port,
                                            Evidence = pluginoutput,
                                            Hostport = hostname + ":" + port,
                                            Solution = solutions
                                        });
                                    }
                                }
                            }
                        }
                    }
                    catch (SecurityException ex)
                    {
                        // The user lacks appropriate permissions to read files, discover paths, etc.
                        MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                                        "Error message: " + ex.Message + "\n\n" +
                                        "Details (send to Support):\n\n" + ex.StackTrace
                                        );
                    }
                    catch (Exception ex)
                    {
                        // Could not load the image - probably related to Windows file system permissions.
                        MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                                        + ". You may not have permission to read the file, or " +
                                        "it may be corrupt.\n\nReported error: " + ex.Message);
                    }
                }
            }

            else
            {
                MessageBox.Show("No file selected");
                return;
            }



            //customers = customers.OrderBy(customer => customer.Name).ToList();

            vulns.Sort((left, right) => String.Compare(left.Severity, right.Severity, StringComparison.CurrentCulture));
            vulns.Reverse();
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = vulns;
        }
Ejemplo n.º 30
0
 public static void ElementsWithXNameOnXDocBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XElement> nodes = xDoc.Elements("A");
     Assert.Equal(1, nodes.Count());
     a.Remove();
     Assert.Equal(0, nodes.Count());
 }
Ejemplo n.º 31
0
        public void Search(string sSearchParamater, string type)
        {
            //type is to determine which of the 3 standard XML searchable types for user searching is possible

            List <string> lFoundStudent = new List <string>(); //this list will be used to send the found information to the next class

            lFoundStudent.Add("");                             //used to be a placeholder for number of courses a student has on record
            string sSearchedStudent = "";
            int    index            = 0;
            int    studentOffset    = 0;
            int    caseOffset       = 0;
            string sSearchedUID     = "";    //store variable to searching UID variable
            bool   bStudentFound    = false; //will be set to true if student is found
            int    iCourseCounter   = 0;
            var    rootpoint        = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
            var    spath            = rootpoint + @"\UserData.xml";
            //string xmlString = "<Root><Students><Student><SID>3-61-206</SID><FName>John</FName><LName>Smith</LName></Student><Student><SID>1-22-424</SID><FName>Jake</FName><LName>Johnson</LName></Student><Student><SID>1-61-397</SID><FName>Samantha</FName><LName>Robertson</LName></Student><Student><SID>123</SID><FName>Rick</FName><LName>Baker</LName></Student></Students><Courses><Course><UID>3-61-206</UID><CourseID>9380</CourseID><CourseNumber>MA-230</CourseNumber><CourseName>Calculus 2</CourseName><Credits>5</Credits><Year>2016</Year><Semester>spring</Semester><CourseType>general education</CourseType><CourseGrade>C-</CourseGrade></Course><Course><UID>3-61-206</UID><CourseID>7382</CourseID><CourseNumber>EN-315</CourseNumber><CourseName>Advanced English Composition</CourseName><Credits>3</Credits><Year>2015</Year><Semester>Fall</Semester><CourseType>General Education</CourseType><CourseGrade>D+</CourseGrade></Course><Course><UID>123</UID><CourseID>3139</CourseID><CourseNumber>ALC-120</CourseNumber><CourseName>Basic Alchemy</CourseName><Credits>3</Credits><Year>2016</Year><Semester>Fall</Semester><CourseType>Core</CourseType><CourseGrade>A</CourseGrade></Course><Course><UID>1-61-397</UID><CourseID>3139</CourseID><CourseNumber>ALC-120</CourseNumber><CourseName>Basic Alchemy</CourseName><Credits>8</Credits><Year>2016</Year><Semester>Fall</Semester><CourseType>Core</CourseType><CourseGrade>B-</CourseGrade></Course><Course><UID>1-61-397</UID><CourseID>7644</CourseID><CourseNumber>DBM-315</CourseNumber><CourseName>Advanced Blood Magic</CourseName><Credits>6</Credits><Year>2016</Year><Semester>Fall</Semester><CourseType>General Education</CourseType><CourseGrade>A+</CourseGrade></Course><Course><UID>1-22-424</UID><CourseID>9975</CourseID><CourseNumber>ALC-120</CourseNumber><CourseName>Basic Alchemy</CourseName><Credits>8</Credits><Year>2016</Year><Semester>Fall</Semester><CourseType>Core</CourseType><CourseGrade>B-</CourseGrade></Course><Course><UID>1-22-424</UID><CourseID>9266</CourseID><CourseNumber>EN-315</CourseNumber><CourseName>Advanced English Composition</CourseName><Credits>3</Credits><Year>2015</Year><Semester>Fall</Semester><CourseType>General Education</CourseType><CourseGrade>D+</CourseGrade></Course></Courses></Root>";//File.ReadAllText(spath);
            XDocument xmlArchive = XDocument.Load(spath);
            //xmlArchive.LoadXml(xmlString);//loads the precreated xml doc,takes the path string found in the XML_Creator class
            var XNList =
                from node in xmlArchive.Nodes()
                select node;
            var nodes = from node in xmlArchive.DescendantNodes()
                        select node;
            var           TypeElement = new XElement(type, sSearchParamater);
            List <string> SIDList     = xmlArchive.Elements("Students")
                                        .Elements("Student")
                                        .Descendants("SID")
                                        .Select(x => (string)x)
                                        .ToList();
            List <string> FNameList = xmlArchive.Elements("Students")
                                      .Elements("Student")
                                      .Descendants("FName")
                                      .Select(x => (string)x)
                                      .ToList();
            List <string> LNameList = xmlArchive.Elements("Students")
                                      .Elements("Student")
                                      .Descendants("LName")
                                      .Select(x => (string)x)
                                      .ToList();
            List <string> SearchList = xmlArchive.Elements("Students")
                                       .Elements("Student")
                                       .Descendants(type)
                                       .Select(x => (string)x)
                                       .ToList();
            List <string> UIDList = xmlArchive.Elements("Students")
                                    .Elements("Student")
                                    .Elements("Courses")
                                    .Elements("Course")
                                    .Descendants("UID")
                                    .Select(x => (string)x)
                                    .ToList();
            List <string> CIDList = xmlArchive.Elements("Students")
                                    .Elements("Student")
                                    .Elements("Courses")
                                    .Elements("Course")
                                    .Descendants("CourseID")
                                    .Select(x => (string)x)
                                    .ToList();
            List <string> CNumList = xmlArchive.Elements("Students")
                                     .Elements("Student")
                                     .Elements("Courses")
                                     .Elements("Course")
                                     .Descendants("CourseNumber")
                                     .Select(x => (string)x)
                                     .ToList();
            List <string> CNameList = xmlArchive.Elements("Students")
                                      .Elements("Student")
                                      .Elements("Courses")
                                      .Elements("Course")
                                      .Descendants("CourseName")
                                      .Select(x => (string)x)
                                      .ToList();
            List <string> CreditsList = xmlArchive.Elements("Students")
                                        .Elements("Student")
                                        .Elements("Courses")
                                        .Elements("Course")
                                        .Descendants("Credits")
                                        .Select(x => (string)x)
                                        .ToList();
            List <string> YearList = xmlArchive.Elements("Students")
                                     .Elements("Student")
                                     .Elements("Courses")
                                     .Elements("Course")
                                     .Descendants("Year")
                                     .Select(x => (string)x)
                                     .ToList();
            List <string> SemList = xmlArchive.Elements("Students")
                                    .Elements("Student")
                                    .Elements("Courses")
                                    .Elements("Course")
                                    .Descendants("Semester")
                                    .Select(x => (string)x)
                                    .ToList();
            List <string> CTList = xmlArchive.Elements("Students")
                                   .Elements("Student")
                                   .Elements("Courses")
                                   .Elements("Course")
                                   .Descendants("CourseType")
                                   .Select(x => (string)x)
                                   .ToList();
            List <string> CGList = xmlArchive.Elements("Students")
                                   .Elements("Student")
                                   .Elements("Courses")
                                   .Elements("Course")
                                   .Descendants("CourseGrade")
                                   .Select(x => (string)x)
                                   .ToList();

            foreach (var item in SearchList)
            {
                var node = item.ToLower();
                sSearchParamater = sSearchParamater.ToLower();
                if (node == sSearchParamater)
                {
                    bStudentFound = true;
                    sSearchedUID  = SIDList[index];
                    lFoundStudent.Add(SIDList[index]);
                    lFoundStudent.Add(FNameList[index]);
                    lFoundStudent.Add(LNameList[index]);
                    int CourseIndex = 0;
                    foreach (var cItem in UIDList)
                    {
                        if (cItem == sSearchedUID)
                        {
                            lFoundStudent.Add(CIDList[CourseIndex]);
                            lFoundStudent.Add(CNumList[CourseIndex]);
                            lFoundStudent.Add(CNameList[CourseIndex]);
                            lFoundStudent.Add(CreditsList[CourseIndex]);
                            lFoundStudent.Add(YearList[CourseIndex]);
                            lFoundStudent.Add(SemList[CourseIndex]);
                            lFoundStudent.Add(CTList[CourseIndex]);
                            lFoundStudent.Add(CGList[CourseIndex]);
                        }
                        CourseIndex++;
                    }
                    //break;
                }
                index++;
            }


            //loads the precreated xml doc,takes the path string found in the XML_Creator class
            if (bStudentFound == true)
            {
                studentsFoundInQuery = lFoundStudent;
            }
        }