Пример #1
0
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <remarks>
        /// Goes through all <see cref="PartNuspecFiles"/> and generates the temporary NuSpec files for source-only packages
        /// <para>The method get the partial NuSpec file, enriches it with data from parameters (properties) and saves the result to
        /// temporary NuSpec file (with additional extension ".tmp.nuspec"</para>
        /// </remarks>
        /// <returns>True</returns>
        public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (PartNuspecFiles == null)
            {
                Log.LogMessage("No source-only packages found");
                return(true); //nothing to process
            }

            //process the source files
            foreach (var sourceFile in PartNuspecFiles)
            {
                var partNuspecFileNameFull = sourceFile.GetMetadata("FullPath");

                //Get the partial (partnuspec) file
                var ns      = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = partNuspecFileNameFull + ".tmp.nuspec";
                Log.LogMessage($"Loading {partNuspecFileNameFull}");
                var partNuspecFileContent = File.ReadAllText(partNuspecFileNameFull);
                partNuspecFileContent = partNuspecFileContent.Replace("%%CURRENT_VERSION%%", PackageVersionFull);
                var outXDoc          = XDocument.Parse(partNuspecFileContent);
                var packageXElement  = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                //Check package ID
                var packageId = metadataXElement.Element(ns + "id")?.Value;
                if (packageId == null)
                {
                    throw new Exception($"Can't find the package ID for {partNuspecFileNameFull}");
                }

                //Process version - global version from solution of base version from partial file
                var versionOriginal = GetOrCreateElement(metadataXElement, "version", ns)?.Value;
                var version         = PackageVersionFull;
                if (!string.IsNullOrEmpty(versionOriginal))
                {
                    //base version set in NuProp
                    //get ext version from PackageVersionFull
                    //0.1.0-dev.441.181206212308+53.master.37f08fc-dirty
                    //0.1.0+442.181206212418.master.37f08fc-dirty
                    var idx = 0;
                    while (char.IsDigit(PackageVersionFull[idx]) || PackageVersionFull[idx] == '.')
                    {
                        idx++;
                    }

                    version = versionOriginal + PackageVersionFull.Substring(idx);
                }

                //Enrich the NuSpec
                SetOrCreateElement(metadataXElement, "version", ns, version);
                SetOrCreateElement(metadataXElement, "authors", ns, Authors);
                SetOrCreateElement(metadataXElement, "title", ns, packageId);
                SetOrCreateElement(metadataXElement, "owners", ns, Authors);
                SetOrCreateElement(metadataXElement, "description", ns, $"Source only package {packageId}", false); //don't override if exists
                SetOrCreateElement(metadataXElement, "requireLicenseAcceptance", ns, PackageRequireLicenseAcceptance);
                if (!string.IsNullOrEmpty(PackageLicense))
                {
                    SetOrCreateElement(metadataXElement, "license", ns, PackageLicense).
                    Add(new XAttribute("type", "expression"));
                }
                else
                {
                    SetOrCreateElement(metadataXElement, "licenseUrl", ns, PackageLicenseUrl);
                }
                SetOrCreateElement(metadataXElement, "projectUrl", ns, PackageProjectUrl);
                SetOrCreateElement(metadataXElement, "iconUrl", ns, PackageIconUrl);
                SetOrCreateElement(metadataXElement, "copyright", ns, Copyright);
                SetOrCreateElement(metadataXElement, "developmentDependency", ns, "true");
                GetEmptyOrCreateElement(metadataXElement, "repository", ns).
                Add(new XAttribute("url", RepositoryUrl),
                    new XAttribute("type", "git"),
                    new XAttribute("branch", GitBranch),
                    new XAttribute("commit", GitCommit));

                //Save the temporary NuSpec file
                var outXDocStr = outXDoc.ToString();
                File.WriteAllText(outFile, outXDocStr);
                Log.LogMessage($"Generated source only nuspec file {outFile}");
            }

            return(true);
        }
Пример #2
0
        public static IEnumerable <XElement> GetElementObjlist(this XElement inputElement, string elementName)
        {
            XNamespace defaultNamespace = XNamespace.Get("urn:hl7-org:v3");

            return(inputElement.Elements(defaultNamespace + elementName));
        }
Пример #3
0
        /// <summary>
        /// 建立新節點
        /// </summary>
        /// <param name="XmlDoc">XmlDocument</param>
        /// <param name="ParentNode">父節點</param>
        /// <param name="XmlNamesPace">命名空間</param>
        /// <param name="NodeName">節點名稱</param>
        /// <param name="InnerText">內容</param>
        /// <returns></returns>
        protected XElement CreateChildNode(XElement ParentNode, string XmlNamesPace, string NodeName, string InnerText)
        {
            XElement el = XmlNamesPace.Length == 0 ? new XElement(NodeName, InnerText) : new XElement(XNamespace.Get(XmlNamesPace) + NodeName, InnerText);

            ParentNode.Add(el);
            return(el);
        }
 protected override XNamespace GetSchema()
 {
     return(XNamespace.Get(WindowsAzureSchema));
 }
Пример #5
0
        public static XElement GetElement(this XElement inputElement, string elementName, string nameSpace = "urn:hl7-org:v3")
        {
            XNamespace defaultNamespace = XNamespace.Get(nameSpace);

            return(inputElement?.Element(defaultNamespace + elementName));
        }
Пример #6
0
        public void AllActivityAttributeProperties([Values("legacy", "manifestmerger.jar")] string manifestMerger)
        {
            string expectedOutput = manifestMerger == "legacy" ?
                                    "android:allowEmbedded=\"true\" android:allowTaskReparenting=\"true\" android:alwaysRetainTaskState=\"true\" android:autoRemoveFromRecents=\"true\" android:banner=\"@drawable/icon\" android:clearTaskOnLaunch=\"true\" android:colorMode=\"hdr\" android:configChanges=\"mcc\" android:description=\"@string/app_name\" android:directBootAware=\"true\" android:documentLaunchMode=\"never\" android:enabled=\"true\" android:enableVrMode=\"foo\" android:excludeFromRecents=\"true\" android:exported=\"true\" android:finishOnCloseSystemDialogs=\"true\" android:finishOnTaskLaunch=\"true\" android:hardwareAccelerated=\"true\" android:icon=\"@drawable/icon\" android:immersive=\"true\" android:label=\"TestActivity\" android:launchMode=\"singleTop\" android:lockTaskMode=\"normal\" android:logo=\"@drawable/icon\" android:maxAspectRatio=\"1.2\" android:maxRecents=\"1\" android:multiprocess=\"true\" android:name=\"com.contoso.TestActivity\" android:noHistory=\"true\" android:parentActivityName=\"unnamedproject.unnamedproject.MainActivity\" android:permission=\"com.contoso.permission.TEST_ACTIVITY\" android:persistableMode=\"persistNever\" android:process=\"com.contoso.process.testactivity_process\" android:recreateOnConfigChanges=\"mcc\" android:relinquishTaskIdentity=\"true\" android:resizeableActivity=\"true\" android:resumeWhilePausing=\"true\" android:rotationAnimation=\"crossfade\" android:roundIcon=\"@drawable/icon\" android:screenOrientation=\"portrait\" android:showForAllUsers=\"true\" android:showOnLockScreen=\"true\" android:showWhenLocked=\"true\" android:singleUser=\"true\" android:stateNotNeeded=\"true\" android:supportsPictureInPicture=\"true\" android:taskAffinity=\"com.contoso\" android:theme=\"@android:style/Theme.Light\" android:turnScreenOn=\"true\" android:uiOptions=\"splitActionBarWhenNarrow\" android:visibleToInstantApps=\"true\" android:windowSoftInputMode=\"stateUnchanged|adjustUnspecified\"" :
                                    "android:name=\"com.contoso.TestActivity\" android:allowEmbedded=\"true\" android:allowTaskReparenting=\"true\" android:alwaysRetainTaskState=\"true\" android:autoRemoveFromRecents=\"true\" android:banner=\"@drawable/icon\" android:clearTaskOnLaunch=\"true\" android:colorMode=\"hdr\" android:configChanges=\"mcc\" android:description=\"@string/app_name\" android:directBootAware=\"true\" android:documentLaunchMode=\"never\" android:enableVrMode=\"foo\" android:enabled=\"true\" android:excludeFromRecents=\"true\" android:exported=\"true\" android:finishOnCloseSystemDialogs=\"true\" android:finishOnTaskLaunch=\"true\" android:hardwareAccelerated=\"true\" android:icon=\"@drawable/icon\" android:immersive=\"true\" android:label=\"TestActivity\" android:launchMode=\"singleTop\" android:lockTaskMode=\"normal\" android:logo=\"@drawable/icon\" android:maxAspectRatio=\"1.2\" android:maxRecents=\"1\" android:multiprocess=\"true\" android:noHistory=\"true\" android:parentActivityName=\"unnamedproject.unnamedproject.MainActivity\" android:permission=\"com.contoso.permission.TEST_ACTIVITY\" android:persistableMode=\"persistNever\" android:process=\"com.contoso.process.testactivity_process\" android:recreateOnConfigChanges=\"mcc\" android:relinquishTaskIdentity=\"true\" android:resizeableActivity=\"true\" android:resumeWhilePausing=\"true\" android:rotationAnimation=\"crossfade\" android:roundIcon=\"@drawable/icon\" android:screenOrientation=\"portrait\" android:showForAllUsers=\"true\" android:showOnLockScreen=\"true\" android:showWhenLocked=\"true\" android:singleUser=\"true\" android:stateNotNeeded=\"true\" android:supportsPictureInPicture=\"true\" android:taskAffinity=\"com.contoso\" android:theme=\"@android:style/Theme.Light\" android:turnScreenOn=\"true\" android:uiOptions=\"splitActionBarWhenNarrow\" android:visibleToInstantApps=\"true\" android:windowSoftInputMode=\"stateUnchanged|adjustUnspecified\"";

            var proj = new XamarinAndroidApplicationProject {
                ManifestMerger = manifestMerger,
            };

            proj.Sources.Add(new BuildItem.Source("TestActivity.cs")
            {
                TextContent = () => @"using Android.App;
using Android.Content.PM;
using Android.Views;
[Activity (
	AllowEmbedded              = true,
	AllowTaskReparenting       = true,
	AlwaysRetainTaskState      = true,
	AutoRemoveFromRecents      = true,
	Banner                     = ""@drawable/icon"",
	ClearTaskOnLaunch          = true,
	ColorMode                  = ""hdr"",
	ConfigurationChanges       = ConfigChanges.Mcc,
	Description                = ""@string/app_name"",
	DirectBootAware            = true,
	DocumentLaunchMode         = DocumentLaunchMode.Never,
	Enabled                    = true,
	EnableVrMode               = ""foo"",
	ExcludeFromRecents         = true,
	Exported                   = true,
	FinishOnCloseSystemDialogs = true,
	FinishOnTaskLaunch         = true,
	HardwareAccelerated        = true,
	Icon                       = ""@drawable/icon"",
	Immersive                  = true,
	Label                      = ""TestActivity"",
	LaunchMode                 = LaunchMode.SingleTop,
	LockTaskMode               = ""normal"",
	Logo                       = ""@drawable/icon"",
	MaxAspectRatio             = 1.2F,
	MaxRecents                 = 1,
	MultiProcess               = true,
	Name                       = ""com.contoso.TestActivity"",
	NoHistory                  = true,
	ParentActivity             = typeof (UnnamedProject.MainActivity),
	Permission                 = ""com.contoso.permission.TEST_ACTIVITY"",
	PersistableMode            = ActivityPersistableMode.Never,
	Process                    = ""com.contoso.process.testactivity_process"",
	RecreateOnConfigChanges    = ConfigChanges.Mcc,
	RelinquishTaskIdentity     = true,
	ResizeableActivity         = true,
	ResumeWhilePausing         = true,
	RotationAnimation          = WindowRotationAnimation.Crossfade,
	RoundIcon                  = ""@drawable/icon"",
	ScreenOrientation          = ScreenOrientation.Portrait,
	ShowForAllUsers            = true,
	ShowOnLockScreen           = true,
	ShowWhenLocked             = true,
	SingleUser                 = true,
	StateNotNeeded             = true,
	SupportsPictureInPicture   = true,
	TaskAffinity               = ""com.contoso"",
	Theme                      = ""@android:style/Theme.Light"",
	TurnScreenOn               = true,
	UiOptions                  = UiOptions.SplitActionBarWhenNarrow,
	VisibleToInstantApps       = true,
	WindowSoftInputMode        = Android.Views.SoftInput.StateUnchanged)]
class TestActivity : Activity { }"
            });

            using (ProjectBuilder builder = CreateDllBuilder(Path.Combine("temp", TestName))) {
                Assert.IsTrue(builder.Build(proj), "Build should have succeeded");

                string manifest = builder.Output.GetIntermediaryAsText(Path.Combine("android", "AndroidManifest.xml"));
                var    doc      = XDocument.Parse(manifest);
                var    ns       = XNamespace.Get("http://schemas.android.com/apk/res/android");
                IEnumerable <XElement> activities = doc.Element("manifest")?.Element("application")?.Elements("activity");
                XElement e = activities.FirstOrDefault(x => x.Attribute(ns.GetName("label"))?.Value == "TestActivity");
                Assert.IsNotNull(e, "Manifest should contain an activity labeled TestActivity");
                Assert.AreEqual(expectedOutput, string.Join(" ", e.Attributes()));
            }
        }
Пример #7
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var distanceFromStart = LocationUtils.CalculateDistanceInMeters(
                session.Settings.DefaultLatitude, session.Settings.DefaultLongitude,
                session.Client.CurrentLatitude, session.Client.CurrentLongitude);

            // Edge case for when the client somehow ends up outside the defined radius
            if (session.LogicSettings.MaxTravelDistanceInMeters != 0 &&
                distanceFromStart > session.LogicSettings.MaxTravelDistanceInMeters)
            {
                Logger.Write(
                    session.Translation.GetTranslation(TranslationString.FarmPokestopsOutsideRadius, distanceFromStart),
                    LogLevel.Warning);

                await session.Navigation.Move(
                    new GeoCoordinate(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, LocationUtils.getElevation(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude)),
                    session.LogicSettings.WalkingSpeedInKilometerPerHour, null, cancellationToken, session.LogicSettings.DisableHumanWalking);
            }

            var pokestopList = await GetPokeStops(session);

            var stopsHit = 0;
            var rc       = new Random(); //initialize pokestop random cleanup counter first time

            storeRI = rc.Next(8, 15);
            var eggWalker = new EggWalker(1000, session);

            if (pokestopList.Count <= 0)
            {
                session.EventDispatcher.Send(new WarnEvent
                {
                    Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound)
                });
            }

            session.EventDispatcher.Send(new PokeStopListEvent {
                Forts = pokestopList
            });

            while (pokestopList.Any())
            {
                cancellationToken.ThrowIfCancellationRequested();

                //resort
                var pokestopListWithDetails = pokestopList
                                              .Select(p =>
                {
                    Boolean useNav   = session.LogicSettings.UseOsmNavigation && LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, p.Latitude, p.Longitude) > session.LogicSettings.OsmMinDistanceInMeter;
                    String uri       = useNav ? string.Format(_CultureEnglish, "http://www.yournavigation.org/api/1.0/gosmore.php?flat={0:0.000000}&flon={1:0.000000}&tlat={2:0.000000}&tlon={3:0.000000}&v=foot", session.Client.CurrentLatitude, session.Client.CurrentLongitude, p.Latitude, p.Longitude) : null;
                    XDocument doc    = useNav ? XDocument.Load(uri) : null;
                    XNamespace kmlns = useNav ? XNamespace.Get("http://earth.google.com/kml/2.0") : null;
                    var points       = !useNav ? null :
                                       doc.Element(kmlns + "kml")
                                       .Element(kmlns + "Document")
                                       .Element(kmlns + "Folder")
                                       .Element(kmlns + "Placemark")
                                       .Element(kmlns + "LineString")
                                       .Element(kmlns + "coordinates")
                                       .Value
                                       .Trim()
                                       .Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                                       .Select(pp =>
                    {
                        String[] parts = pp.Split(',');
                        return(new
                        {
                            Latitude = double.Parse(parts[1], _CultureEnglish),
                            Longitude = double.Parse(parts[0], _CultureEnglish),
                        });
                    })
                                       .ToArray();
                    Double dist = useNav ?
                                  new Func <double>(() =>
                    {
                        Double d = 0d;
                        for (int i = 1; i < points.Length; i++)
                        {
                            d += LocationUtils.CalculateDistanceInMeters
                                 (
                                points[i - 1].Latitude,
                                points[i - 1].Longitude,
                                points[i].Latitude,
                                points[i].Longitude
                                 );
                        }
                        return(d);
                    })() :
                                  LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, p.Latitude, p.Longitude);
                    return(new
                    {
                        PokeStop = p,
                        UseOSM = useNav,
                        Distance = dist,
                        NavigationDocumentUri = uri,
                        NavigationDocument = doc,
                        NavigationDocumentNamespace = kmlns,
                        Points = points
                    });
                })
                                              .OrderBy(p => p.Distance)
                                              .ToList();
                // randomize next pokestop between first and second by distance
                var pokestopListNum = 0;
                if (pokestopList.Count > 1)
                {
                    pokestopListNum = rc.Next(0, 2);
                }

                var pokeStop = pokestopListWithDetails[pokestopListNum];
                pokestopList.Remove(pokeStop.PokeStop);

                var distance = pokeStop.Distance;
                var fortInfo = await session.Client.Fort.GetFort(pokeStop.PokeStop.Id, pokeStop.PokeStop.Latitude, pokeStop.PokeStop.Longitude);

                session.EventDispatcher.Send(new FortTargetEvent {
                    Name = fortInfo.Name, Distance = distance
                });

                if (pokeStop.UseOSM)
                {
                    var points = pokeStop.Points;
                    if (points.Any())
                    {
                        foreach (var step in points)
                        {
                            await MoveToLocationAsync(session, cancellationToken, step.Latitude, step.Longitude);
                        }
                    }
                }
                //Why no else? Just to be sure =)
                await MoveToLocationAsync(session, cancellationToken, pokeStop.PokeStop.Latitude, pokeStop.PokeStop.Longitude);

                //Catch Lure Pokemon
                if (pokeStop.PokeStop.LureInfo != null)
                {
                    await CatchLurePokemonsTask.Execute(session, pokeStop.PokeStop, cancellationToken);
                }

                FortSearchResponse fortSearch;
                var       timesZeroXPawarded = 0;
                var       fortTry            = 0;  //Current check
                const int retryNumber        = 50; //How many times it needs to check to clear softban
                const int zeroCheck          = 5;  //How many times it checks fort before it thinks it's softban
                do
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    fortSearch =
                        await session.Client.Fort.SearchFort(pokeStop.PokeStop.Id, pokeStop.PokeStop.Latitude, pokeStop.PokeStop.Longitude);

                    if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                    {
                        timesZeroXPawarded = 0;
                    }
                    if (fortSearch.ExperienceAwarded == 0)
                    {
                        timesZeroXPawarded++;

                        if (timesZeroXPawarded > zeroCheck)
                        {
                            if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                            {
                                break;
                                // Check if successfully looted, if so program can continue as this was "false alarm".
                            }

                            fortTry += 1;

                            session.EventDispatcher.Send(new FortFailedEvent
                            {
                                Name   = fortInfo.Name,
                                Try    = fortTry,
                                Max    = retryNumber - zeroCheck,
                                Looted = false
                            });

                            if (!session.LogicSettings.FastSoftBanBypass)
                            {
                                DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                            }
                        }
                    }
                    else
                    {
                        if (fortTry != 0)
                        {
                            session.EventDispatcher.Send(new FortFailedEvent
                            {
                                Name   = fortInfo.Name,
                                Try    = fortTry + 1,
                                Max    = retryNumber - zeroCheck,
                                Looted = true
                            });
                        }

                        session.EventDispatcher.Send(new FortUsedEvent
                        {
                            Id            = pokeStop.PokeStop.Id,
                            Name          = fortInfo.Name,
                            Exp           = fortSearch.ExperienceAwarded,
                            Gems          = fortSearch.GemsAwarded,
                            Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                            Latitude      = pokeStop.PokeStop.Latitude,
                            Longitude     = pokeStop.PokeStop.Longitude,
                            InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull
                        });

                        if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                        {
                            storeRI = 1;
                        }

                        break; //Continue with program as loot was succesfull.
                    }
                } while (fortTry < retryNumber - zeroCheck);
                //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

                await eggWalker.ApplyDistance(distance, cancellationToken);

                if (++stopsHit >= storeRI)     //TODO: OR item/pokemon bag is full //check stopsHit against storeRI random without dividing.
                {
                    storeRI  = rc.Next(6, 12); //set new storeRI for new random value
                    stopsHit = 0;

                    await RecycleItemsTask.Execute(session, cancellationToken);

                    if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                        session.LogicSettings.EvolveAllPokemonAboveIv ||
                        session.LogicSettings.UseLuckyEggsWhileEvolving ||
                        session.LogicSettings.KeepPokemonsThatCanEvolve)
                    {
                        await EvolvePokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.UseLuckyEggConstantly)
                    {
                        await UseLuckyEggConstantlyTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.UseIncenseConstantly)
                    {
                        await UseIncenseConstantlyTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.TransferWeakPokemon)
                    {
                        await TransferWeakPokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.RenamePokemon)
                    {
                        await RenamePokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.AutoFavoritePokemon)
                    {
                        await FavoritePokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.AutomaticallyLevelUpPokemon)
                    {
                        await LevelUpPokemonTask.Execute(session, cancellationToken);
                    }

                    await GetPokeDexCount.Execute(session, cancellationToken);
                }

                if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer)
                {
                    await SnipePokemonTask.Execute(session, cancellationToken);
                }
            }
        }
Пример #8
0
        public static void Log(IServiceProvider serviceProvider, string path)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));

            Assumes.Present(componentModel);
            var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(SDTE));

            var workspace = componentModel.GetService <VisualStudioWorkspace>();
            var solution  = workspace.CurrentSolution;

            var threadedWaitDialog = (IVsThreadedWaitDialog3)serviceProvider.GetService(typeof(SVsThreadedWaitDialog));

            Assumes.Present(threadedWaitDialog);
            var threadedWaitCallback = new ThreadedWaitCallback();

            int projectsProcessed = 0;

            threadedWaitDialog.StartWaitDialogWithCallback(RoslynLoggingResources.ProjectSystemTools, RoslynLoggingResources.LoggingRoslynWorkspaceStructure, null, null, null, true, 0, true, solution.ProjectIds.Count, 0, threadedWaitCallback);

            try
            {
                var document         = new XDocument();
                var workspaceElement = new XElement("workspace");
                document.Add(workspaceElement);

                foreach (var project in solution.GetProjectDependencyGraph().GetTopologicallySortedProjects(threadedWaitCallback.CancellationToken).Select(solution.GetProject))
                {
                    // Dump basic project attributes
                    var projectElement = new XElement("project");
                    workspaceElement.Add(projectElement);

                    projectElement.SetAttributeValue("id", SanitizePath(project.Id.ToString()));
                    projectElement.SetAttributeValue("name", project.Name);
                    projectElement.SetAttributeValue("assemblyName", project.AssemblyName);
                    projectElement.SetAttributeValue("language", project.Language);
                    projectElement.SetAttributeValue("path", SanitizePath(project.FilePath ?? "(none)"));
                    projectElement.SetAttributeValue("outputPath", SanitizePath(project.OutputFilePath ?? "(none)"));

                    var hasSuccesfullyLoaded = TryGetHasSuccessfullyLoaded(project, threadedWaitCallback.CancellationToken);

                    if (hasSuccesfullyLoaded.HasValue)
                    {
                        projectElement.SetAttributeValue("hasSuccessfullyLoaded", hasSuccesfullyLoaded.Value);
                    }

                    // Dump MSBuild <Reference> nodes
                    if (project.FilePath != null)
                    {
                        var msbuildProject   = XDocument.Load(project.FilePath);
                        var msbuildNamespace = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");

                        var msbuildReferencesElement = new XElement("msbuildReferences");
                        projectElement.Add(msbuildReferencesElement);

                        msbuildReferencesElement.Add(msbuildProject.Descendants(msbuildNamespace + "ProjectReference"));
                        msbuildReferencesElement.Add(msbuildProject.Descendants(msbuildNamespace + "Reference"));
                        msbuildReferencesElement.Add(msbuildProject.Descendants(msbuildNamespace + "ReferencePath"));
                    }

                    // Dump DTE references
                    var langProjProject = TryFindLangProjProject(dte, project);

                    if (langProjProject != null)
                    {
                        var dteReferences = new XElement("dteReferences");
                        projectElement.Add(dteReferences);

                        foreach (var reference in langProjProject.References.Cast <VSLangProj.Reference>())
                        {
                            if (reference.SourceProject != null)
                            {
                                dteReferences.Add(new XElement("projectReference", new XAttribute("projectName", reference.SourceProject.Name)));
                            }
                            else
                            {
                                dteReferences.Add(new XElement("metadataReference",
                                                               reference.Path != null ? new XAttribute("path", SanitizePath(reference.Path)) : null,
                                                               new XAttribute("name", reference.Name)));
                            }
                        }
                    }

                    // Dump the actual metadata references in the workspace
                    var workspaceReferencesElement = new XElement("workspaceReferences");
                    projectElement.Add(workspaceReferencesElement);

                    foreach (var metadataReference in project.MetadataReferences)
                    {
                        workspaceReferencesElement.Add(CreateElementForPortableExecutableReference(metadataReference));
                    }

                    // Dump project references in the workspace
                    foreach (var projectReference in project.AllProjectReferences)
                    {
                        var referenceElement = new XElement("projectReference", new XAttribute("id", SanitizePath(projectReference.ProjectId.ToString())));

                        if (!project.ProjectReferences.Contains(projectReference))
                        {
                            referenceElement.SetAttributeValue("missingInSolution", "true");
                        }

                        workspaceReferencesElement.Add(referenceElement);
                    }

                    // Dump references from the compilation; this should match the workspace but can help rule out
                    // cross-language reference bugs or other issues like that
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits -- this is fine since it's a Roslyn API
                    var compilation = project.GetCompilationAsync(threadedWaitCallback.CancellationToken).Result;
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits
                    var compilationReferencesElement = new XElement("compilationReferences");
                    projectElement.Add(compilationReferencesElement);

                    foreach (var reference in compilation.References)
                    {
                        compilationReferencesElement.Add(CreateElementForPortableExecutableReference(reference));
                    }

                    projectElement.Add(CreateElementForCompilation(compilation));

                    // Dump all diagnostics
                    var diagnosticsElement = new XElement("diagnostics");
                    projectElement.Add(diagnosticsElement);

                    foreach (var diagnostic in compilation.GetDiagnostics(threadedWaitCallback.CancellationToken))
                    {
                        diagnosticsElement.Add(
                            new XElement("diagnostic",
                                         new XAttribute("severity", diagnostic.Severity.ToString()),
                                         diagnostic.GetMessage()));
                    }

                    projectsProcessed++;

                    bool cancelled;
                    threadedWaitDialog.UpdateProgress(null, null, null, projectsProcessed, solution.ProjectIds.Count, false, out cancelled);
                }

                document.Save(path);
            }
            catch (OperationCanceledException)
            {
                // They cancelled
            }
            finally
            {
                int cancelled;
                threadedWaitDialog.EndWaitDialog(out cancelled);
            }
        }
Пример #9
0
 public RosterItem()
     : base(XNamespace.Get(Namespaces.JabberRoster) + "item")
 {
 }
Пример #10
0
        public void CheckStructsInList()
        {
            StartService(typeof(StructService));
            var wsdl = GetWsdl();

            StopServer();
            var root = XElement.Parse(wsdl);
            var elementsWithEmptyName = GetElements(root, _xmlSchema + "element").Where(x => x.Attribute("name")?.Value == string.Empty);

            elementsWithEmptyName.ShouldBeEmpty();

            var elementsWithEmptyType = GetElements(root, _xmlSchema + "element").Where(x => x.Attribute("type")?.Value == "xs:");

            elementsWithEmptyType.ShouldBeEmpty();

            var structTypeElement  = GetElements(root, _xmlSchema + "complexType").Single(x => x.Attribute("name")?.Value == "AnyStruct");
            var annotationNode     = structTypeElement.Descendants(_xmlSchema + "annotation").SingleOrDefault();
            var isValueTypeElement = annotationNode.Descendants(_xmlSchema + "appinfo").Descendants(XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/") + "IsValueType").SingleOrDefault();

            Assert.IsNotNull(isValueTypeElement);
            Assert.AreEqual("true", isValueTypeElement.Value);
            Assert.IsNotNull(annotationNode);
        }
Пример #11
0
        private async Task <IList <AppxFile> > GetFiles(Stream appxBlockMap, CancellationToken cancellationToken, IProgress <ProgressData> progress = null)
        {
            progress?.Report(new ProgressData(0, "Reading AppxBlockMap.xml..."));
            IList <AppxFile> list = new List <AppxFile>();
            var document          = await XDocument.LoadAsync(appxBlockMap, LoadOptions.None, cancellationToken);

            var blockMap = document.Root;

            if (blockMap == null || blockMap.Name.LocalName != "BlockMap")
            {
                return(list);
            }

            var ns = XNamespace.Get("http://schemas.microsoft.com/appx/2010/blockmap");

            const int maxBlockSize = 64 * 1024; // 64 kilobytes

            progress?.Report(new ProgressData(50, "Reading files..."));
            foreach (var item in blockMap.Elements(ns + "File"))
            {
                long.TryParse(item.Attribute("Size")?.Value ?? "0", out var fileSize);

                ushort headerLength;
                var    headerSize = item.Attribute("LfhSize");
                if (headerSize == null)
                {
                    headerLength = 30;
                }
                else
                {
                    ushort.TryParse(headerSize.Value, out headerLength);
                }

                var fileName = item.Attribute("Name")?.Value;
                var file     = new AppxFile(fileName, fileSize, headerLength);

                foreach (var fileBlock in item.Elements(ns + "Block"))
                {
                    long blockLength;
                    var  blockSize = fileBlock.Attribute("Size");
                    if (blockSize == null)
                    {
                        // If this is null, the block is uncompressed.
                        if (fileSize > maxBlockSize)
                        {
                            blockLength = maxBlockSize;
                        }
                        else
                        {
                            blockLength = fileSize;
                        }

                        fileSize -= maxBlockSize;
                    }
                    else
                    {
                        long.TryParse(blockSize.Value, out blockLength);
                    }

                    file.Blocks.Add(new AppxBlock(fileBlock.Attribute("Hash")?.Value, blockLength)
                    {
                        Status = ComparisonStatus.Unchanged
                    });
                }

                list.Add(file);
            }

            return(list);
        }
Пример #12
0
        private async void ProcessRequest(HttpListenerContext httpRequest)
        {
            Console.WriteLine(string.Format("{0} Processing request", DateTime.Now.ToString("hh.mm.ss.ffffff")));
            HttpListenerRequest request = httpRequest.Request;

            if (httpRequest.Request.InputStream.CanRead)
            {
                using (Stream body = request.InputStream)
                {
                    using (StreamReader reader = new StreamReader(body, request.ContentEncoding))
                    {
                        Console.WriteLine(string.Format("{0} Reading XML", DateTime.Now.ToString("hh.mm.ss.ffffff")));

                        // Use task to get xml to avoid locking up
                        try
                        {
                            Task <string> task = Task.Run(() => GetXml(reader));
                            string        xml  = await task;
                            //Console.WriteLine(xml);
                            Console.WriteLine(string.Format("{0} XML read complete", DateTime.Now.ToString("hh.mm.ss.ffffff")));

                            if (xml != null && xml != string.Empty)
                            {
                                XDocument xDoc = XDocument.Load(new StringReader(xml));
                                Console.WriteLine(string.Format("{0} xDoc loaded", DateTime.Now.ToString("hh.mm.ss.ffffff")));

                                XNamespace onvifEvent = XNamespace.Get("http://docs.oasis-open.org/wsn/b-2");

                                //ScanElements(xDoc.Elements());

                                //var notificationMsg = xDoc.Descendants((XNamespace)"http://docs.oasis-open.org/wsn/b-2" + "Notify")
                                //    .First()
                                //    .FirstNode;
                                //Console.WriteLine(notificationMsg + "\n");

                                var notifications = xDoc.Descendants(onvifEvent + "Notify").Elements();
                                ParseNotifications(notifications);
                            }
                            else
                            {
                                Debug.Print("Null or empty Xml string received - don't process");
                                return;
                            }
                        }
                        catch (HttpListenerException e)
                        {
                            Debug.Print(e.Message);
                            return;
                        }
                    }
                }
            }

            Console.WriteLine(string.Format("{0} Sending response", DateTime.Now.ToString("hh.mm.ss.ffffff")));

            // Send response
            HttpListenerResponse response = httpRequest.Response;

            response.StatusCode = 202;  // 202 - Accepted
            Stream       output         = response.OutputStream;
            const string responseString = "";
            var          buffer         = Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            output.Write(buffer, 0, buffer.Length);
            output.Close();

            Console.WriteLine(string.Format("{0} Done processing", DateTime.Now.ToString("hh.mm.ss.ffffff")));
        }
        public void CreateXmlContent_Reader_Attributes()
        {
            XmlSyndicationContent content = SyndicationContent.CreateXmlContent(
                new XElement("ParentObject", new XAttribute("type", "CustomType"), new XAttribute(XNamespace.Xmlns + "name", "ignored"), new XAttribute("name1", "value1"), new XAttribute(XNamespace.Get("namespace") + "name2", "value2"),
                             new XElement("ExtensionObject", new XAttribute("ignored", "value"),
                                          new XElement("Value", 10)
                                          )
                             ).CreateReader()
                );

            Assert.Equal(2, content.AttributeExtensions.Count);
            Assert.Equal("value1", content.AttributeExtensions[new XmlQualifiedName("name1")]);
            Assert.Equal("value2", content.AttributeExtensions[new XmlQualifiedName("name2", "namespace")]);
            Assert.Equal("CustomType", content.Type);
            Assert.Null(content.Extension);
            Assert.Equal(0, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
Пример #14
0
 public void NamespaceGetNull()
 {
     Assert.Throws <ArgumentNullException>(() => XNamespace.Get(null));
 }
Пример #15
0
        private void Epub(FileSystemInfo file)
        {
            try
            {
                using (var zip = ZipFile.Open(file.FullName, ZipArchiveMode.Read))
                {
                    //Get location of the content file
                    var container    = zip.GetEntry("META-INF/container.xml");
                    var containerXml = XDocument.Load(container.Open());

                    if (containerXml.Root == null)
                    {
                        return;
                    }

                    XNamespace ns = containerXml.Root.Attribute("xmlns").Value;

                    var rootFile = containerXml
                                   .Root
                                   .Descendants(ns + "rootfile")
                                   .First()
                                   .Attribute("full-path")
                                   .Value;

                    //Get book info from the content file
                    var content    = zip.GetEntry(rootFile);
                    var contentXml = XDocument.Load(content.Open());

                    if (contentXml.Root == null)
                    {
                        return;
                    }

                    XNamespace contentNs = contentXml.Root.Attribute("xmlns").Value;
                    var        customNs  = XNamespace.Get("http://purl.org/dc/elements/1.1/");
                    var        metaData  = contentXml.Root.Descendants(contentNs + "metadata").FirstOrDefault();
                    var        manifest  = contentXml.Root.Descendants(contentNs + "manifest").FirstOrDefault();

                    if (manifest != null)
                    {
                        var cover = manifest.Elements(contentNs + "item")
                                    .FirstOrDefault(
                            x =>
                            (x.Attribute("id").Value.ToLower().Contains("cover") &&
                             (x.Attribute("href").Value.EndsWith(".jpg") ||
                              x.Attribute("href").Value.EndsWith(".jpeg"))));

                        if (cover != null)
                        {
                            var dir = new DirectoryInfo(rootFile);

                            var coverFullPath = ((rootFile.Contains("/") || rootFile.Contains("\\"))
                                ? dir.Parent + "/"
                                : "") + cover.Attribute("href").Value;

                            //zip.GetEntry(coverFullPath).ExtractToFile(DirName + "/cover.jpg", true);

                            using (var ms = new MemoryStream())
                            {
                                zip.GetEntry(coverFullPath).Open().CopyTo(ms);
                                List.Add("cover", ms.ToArray());
                            }
                        }
                    }

                    //3.4.6 The DCMES Optional Elements: contributor | coverage | creator | date | description | format | publisher | relation | rights | source | subject | type

                    if (metaData == null)
                    {
                        return;
                    }

                    var author      = metaData.Descendants(customNs + "creator").FirstOrDefault();
                    var contributor = metaData.Descendants(customNs + "contributor").FirstOrDefault();
                    var title       = metaData.Descendants(customNs + "title").FirstOrDefault();
                    var description = metaData.Descendants(customNs + "description").FirstOrDefault();
                    var categories  = metaData.Descendants(customNs + "subject").Select(category => category.Value).ToList();
                    var coverage    = metaData.Descendants(customNs + "coverage").FirstOrDefault();
                    var publisher   = metaData.Descendants(customNs + "publisher").FirstOrDefault();
                    var language    = metaData.Descendants(customNs + "language").FirstOrDefault();
                    var published   = metaData.Descendants(customNs + "date").FirstOrDefault();
                    var identifier  = metaData.Descendants(customNs + "identifier").FirstOrDefault();
                    var relation    = metaData.Descendants(customNs + "relation").FirstOrDefault();


                    if (author != null)
                    {
                        List.Add("author", author.Value);
                    }

                    if (contributor != null)
                    {
                        List.Add("contributor", contributor.Value);
                    }

                    if (title != null)
                    {
                        List.Add("title", title.Value);
                    }

                    if (description != null)
                    {
                        List.Add("description", description.Value);
                    }

                    if (categories.Count > 0)
                    {
                        List.Add("categories", categories);
                    }

                    if (coverage != null)
                    {
                        List.Add("coverage", coverage.Value);
                    }

                    if (publisher != null)
                    {
                        List.Add("publisher", publisher.Value);
                    }

                    if (language != null)
                    {
                        List.Add("language", language.Value);
                    }

                    if (published != null)
                    {
                        List.Add("published", DateTime.Parse(published.Value));
                    }

                    if (identifier != null)
                    {
                        List.Add("identifier", identifier.Value);
                    }

                    if (relation != null)
                    {
                        List.Add("relation", relation.Value);
                    }
                }
            }
            catch (Exception e)
            {
                DebugConsole.WriteLine("Problem occurred during info extraction from an epub file: " + e.Message);
                //MainWindow.Info(UiLang.Get("EpubCorrupted"), 1);
            }
        }
Пример #16
0
        /// <summary>
        /// Translates an array of strings from a source language to a target language.
        /// </summary>
        /// <param name="translateArraySourceTexts">The strings to translate.</param>
        /// <param name="from">The language code of the translation text. For example, "en" for English.</param>
        /// <param name="to">The language code to translate the text into.</param>
        /// <returns>An array of the translated documents.</returns>
        public async Task <List <TranslatedDocument> > TranslateArrayAsync(string[] translateArraySourceTexts, string from, string to)
        {
            var translatedDocuments = new List <TranslatedDocument>();
            var uri = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray2";

            for (var srcTxtIndx = 0; srcTxtIndx < translateArraySourceTexts.Length; srcTxtIndx++)
            {
                // Check for literal tag in input user message
                var currentTranslatedDocument = new TranslatedDocument(translateArraySourceTexts[srcTxtIndx]);
                translatedDocuments.Add(currentTranslatedDocument);
                PreprocessMessage(currentTranslatedDocument.SourceMessage, out var processedText, out var literanlNoTranslateList);
                currentTranslatedDocument.SourceMessage = processedText;
                translateArraySourceTexts[srcTxtIndx]   = processedText;
                currentTranslatedDocument.LiteranlNoTranslatePhrases = literanlNoTranslateList;
            }

            // body of http request
            var body = $"<TranslateArrayRequest>" +
                       "<AppId />" +
                       $"<From>{from}</From>" +
                       "<Options>" +
                       " <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" >generalnn</Category>" +
                       "<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">text/plain</ContentType>" +
                       "<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "</Options>" +
                       "<Texts>" +
                       string.Join(string.Empty, translateArraySourceTexts.Select(s => $"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{SecurityElement.Escape(s)}</string>\n"))
                       + "</Texts>" +
                       $"<To>{to}</To>" +
                       "</TranslateArrayRequest>";

            var accessToken = await _authToken.GetAccessTokenAsync().ConfigureAwait(false);

            using (var request = new HttpRequestMessage())
            {
                request.Method     = HttpMethod.Post;
                request.RequestUri = new Uri(uri);
                request.Content    = new StringContent(body, Encoding.UTF8, "text/xml");
                request.Headers.Add("Authorization", accessToken);

                using (var response = await _httpClient.SendAsync(request).ConfigureAwait(false))
                {
                    var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.OK:
                        Console.WriteLine("Request status is OK. Result of translate array method is:");
                        var doc       = XDocument.Parse(responseBody);
                        var ns        = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2");
                        var results   = new List <string>();
                        var sentIndex = 0;
                        foreach (var xe in doc.Descendants(ns + "TranslateArray2Response"))
                        {
                            var currentTranslatedDocument = translatedDocuments[sentIndex];
                            currentTranslatedDocument.RawAlignment  = xe.Element(ns + "Alignment").Value;
                            currentTranslatedDocument.TargetMessage = xe.Element(ns + "TranslatedText").Value;
                            if (!string.IsNullOrEmpty(currentTranslatedDocument.RawAlignment))
                            {
                                var alignments = currentTranslatedDocument.RawAlignment.Trim().Split(' ');
                                currentTranslatedDocument.SourceTokens     = PostProcessingUtilities.SplitSentence(currentTranslatedDocument.SourceMessage, alignments);
                                currentTranslatedDocument.TranslatedTokens = PostProcessingUtilities.SplitSentence(xe.Element(ns + "TranslatedText").Value, alignments, false);
                                currentTranslatedDocument.IndexedAlignment = PostProcessingUtilities.WordAlignmentParse(alignments, currentTranslatedDocument.SourceTokens, currentTranslatedDocument.TranslatedTokens);
                            }

                            sentIndex += 1;
                        }

                        return(translatedDocuments);

                    default:
                        throw new Exception(response.ReasonPhrase);
                    }
                }
            }
        }
Пример #17
0
        public void MergeLibraryManifest()
        {
            byte [] classesJar;
            using (var stream = typeof(XamarinAndroidCommonProject).Assembly.GetManifestResourceStream("Xamarin.ProjectTools.Resources.Base.classes.jar")) {
                classesJar = new byte [stream.Length];
                stream.Read(classesJar, 0, (int)stream.Length);
            }
            byte [] data;
            using (var ms = new MemoryStream()) {
                using (var zip = ZipArchive.Create(ms)) {
                    zip.AddEntry("AndroidManifest.xml", @"<?xml version='1.0'?>
<manifest xmlns:android='http://schemas.android.com/apk/res/android' package='com.xamarin.test'>
    <uses-sdk android:minSdkVersion='16'/>
    <permission android:name='${applicationId}.permission.C2D_MESSAGE' android:protectionLevel='signature' />
    <application>
        <activity android:name='.signin.internal.SignInHubActivity' />
        <provider
            android:authorities='${applicationId}.FacebookInitProvider'
            android:name='.internal.FacebookInitProvider'
            android:exported='false' />
        <meta-data android:name='android.support.VERSION' android:value='25.4.0' />
        <meta-data android:name='android.support.VERSION' android:value='25.4.0' />
    </application>
</manifest>
", encoding: System.Text.Encoding.UTF8);
                    zip.CreateDirectory("res");
                    zip.AddEntry(classesJar, "classes.jar");
                    zip.AddEntry("R.txt", " ", encoding: System.Text.Encoding.UTF8);
                }
                data = ms.ToArray();
            }
            var path = Path.Combine("temp", TestContext.CurrentContext.Test.Name);
            var lib  = new XamarinAndroidBindingProject()
            {
                ProjectName        = "Binding1",
                AndroidClassParser = "class-parse",
                Jars =
                {
                    new AndroidItem.LibraryProjectZip("Jars\\foo.aar")
                    {
                        BinaryContent = () => data,
                    }
                },
            };
            var proj = new XamarinAndroidApplicationProject()
            {
                PackageName = "com.xamarin.manifest",
                References  =
                {
                    new BuildItem.ProjectReference("..\\Binding1\\Binding1.csproj", lib.ProjectGuid)
                },
                PackageReferences =
                {
                    KnownPackages.SupportMediaCompat_27_0_2_1,
                    KnownPackages.SupportFragment_27_0_2_1,
                    KnownPackages.SupportCoreUtils_27_0_2_1,
                    KnownPackages.SupportCoreUI_27_0_2_1,
                    KnownPackages.SupportCompat_27_0_2_1,
                    KnownPackages.AndroidSupportV4_27_0_2_1,
                    KnownPackages.SupportV7AppCompat_27_0_2_1,
                },
            };

            proj.Sources.Add(new BuildItem.Source("TestActivity1.cs")
            {
                TextContent = () => @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using Android.Util;
[Activity (Label = ""TestActivity1"")]
[IntentFilter (new[]{Intent.ActionMain}, Categories = new[]{ ""com.xamarin.sample"" })]
public class TestActivity1 : FragmentActivity {
}
				"                ,
            });
            proj.Sources.Add(new BuildItem.Source("TestActivity2.cs")
            {
                TextContent = () => @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using Android.Util;
[Activity (Label = ""TestActivity2"")]
[IntentFilter (new[]{Intent.ActionMain}, Categories = new[]{ ""com.xamarin.sample"" })]
public class TestActivity2 : FragmentActivity {
}
				"                ,
            });
            using (var libbuilder = CreateDllBuilder(Path.Combine(path, "Binding1"))) {
                Assert.IsTrue(libbuilder.Build(lib), "Build should have succeeded.");
                using (var builder = CreateApkBuilder(Path.Combine(path, "App1"))) {
                    Assert.IsTrue(builder.Build(proj), "Build should have succeeded.");
                    var manifest = builder.Output.GetIntermediaryAsText(Root, "android/AndroidManifest.xml");
                    Assert.IsTrue(manifest.Contains("com.xamarin.manifest.permission.C2D_MESSAGE"),
                                  "${applicationId}.permission.C2D_MESSAGE was not replaced with com.xamarin.manifest.permission.C2D_MESSAGE");
                    Assert.IsTrue(manifest.Contains("com.xamarin.test.signin.internal.SignInHubActivity"),
                                  ".signin.internal.SignInHubActivity was not replaced with com.xamarin.test.signin.internal.SignInHubActivity");
                    Assert.IsTrue(manifest.Contains("com.xamarin.manifest.FacebookInitProvider"),
                                  "${applicationId}.FacebookInitProvider was not replaced with com.xamarin.manifest.FacebookInitProvider");
                    Assert.IsTrue(manifest.Contains("com.xamarin.test.internal.FacebookInitProvider"),
                                  ".internal.FacebookInitProvider was not replaced with com.xamarin.test.internal.FacebookInitProvider");
                    Assert.AreEqual(manifest.IndexOf("meta-data", StringComparison.OrdinalIgnoreCase),
                                    manifest.LastIndexOf("meta-data", StringComparison.OrdinalIgnoreCase), "There should be only one meta-data element");

                    var doc = XDocument.Parse(manifest);
                    var ns  = XNamespace.Get("http://schemas.android.com/apk/res/android");

                    var activities = doc.Element("manifest")?.Element("application")?.Elements("activity");
                    var e          = activities.FirstOrDefault(x => x.Attribute(ns.GetName("label"))?.Value == "TestActivity2");
                    Assert.IsNotNull(e, "Manifest should contain an activity for TestActivity2");
                    Assert.IsNotNull(e.Element("intent-filter"), "TestActivity2 should have an intent-filter");
                    Assert.IsNotNull(e.Element("intent-filter").Element("action"), "TestActivity2 should have an intent-filter/action");
                }
            }
        }
Пример #18
0
        public XDocument Export(IEnumerable <IContent> posts, BlogMLDocument document)
        {
            var nsContent = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
            var nsDsq     = XNamespace.Get("http://www.disqus.com/");
            var nsDc      = XNamespace.Get("http://purl.org/dc/elements/1.1/");
            var nsWp      = XNamespace.Get("http://wordpress.org/export/1.0/");

            var xChannel = new XElement("channel");

            var xDoc = new XDocument(
                new XElement("rss",
                             new XAttribute("version", "2.0"),
                             new XAttribute(XNamespace.Xmlns + "content", nsContent),
                             new XAttribute(XNamespace.Xmlns + "dsq", nsDsq),
                             new XAttribute(XNamespace.Xmlns + "dc", nsDc),
                             new XAttribute(XNamespace.Xmlns + "wp", nsWp),
                             xChannel));

            var umbHelper = new UmbracoHelper(UmbracoContext.Current);
            var markDown  = new MarkdownDeep.Markdown();

            foreach (var post in posts)
            {
                var blogMlPost = document.Posts.FirstOrDefault(x => x.Title.Content == post.Name);

                //TODO: Add logging here if we cant find it
                if (blogMlPost == null)
                {
                    continue;
                }

                //no comments to import
                if (blogMlPost.Comments.Any() == false)
                {
                    continue;
                }

                var body = post.GetValue <string>("richText");
                if (body.IsNullOrWhiteSpace())
                {
                    body = markDown.Transform(post.GetValue <string>("markdown"));
                }

                var xItem = new XElement("item",
                                         new XElement("title", post.Name),
                                         new XElement("link", umbHelper.NiceUrlWithDomain(post.Id)),
                                         new XElement(nsContent + "encoded", new XCData(body)),
                                         new XElement(nsDsq + "thread_identifier", post.Key.ToString()),
                                         new XElement(nsWp + "post_date_gmt", post.GetValue <DateTime>("publishedDate").ToUniversalTime().ToIsoString()),
                                         new XElement(nsWp + "comment_status", "open"));

                foreach (var comment in blogMlPost.Comments)
                {
                    string commentText = comment.Content.Content;

                    if (comment.Content.ContentType == BlogMLContentType.Base64)
                    {
                        commentText = Encoding.UTF8.GetString(Convert.FromBase64String(comment.Content.Content));
                    }

                    var xComment = new XElement(nsWp + "comment",
                                                new XElement(nsWp + "comment_id", comment.Id),
                                                new XElement(nsWp + "comment_author", comment.UserName),
                                                new XElement(nsWp + "comment_author_email", comment.UserEmailAddress),
                                                new XElement(nsWp + "comment_author_url", comment.UserUrl == null ? string.Empty : comment.UserUrl.ToString()),
                                                new XElement(nsWp + "comment_date_gmt", comment.CreatedOn.ToUniversalTime().ToIsoString()),
                                                new XElement(nsWp + "comment_content", commentText),
                                                new XElement(nsWp + "comment_approved", comment.ApprovalStatus == BlogMLApprovalStatus.Approved ? 1 : 0));

                    xItem.Add(xComment);
                }

                xChannel.Add(xItem);
            }

            return(xDoc);
        }
        /// <summary>
        /// Get an XML element containing data from the specified table + container combination,
        /// filtering according to the filter criteria specified by the caller.
        /// </summary>
        /// <param name="container">Alias of the container, pass null for all records.</param>
        /// <param name="tableName">EntitySet\Table name, pass null for all records.</param>
        /// <param name="filter">Filter criteria, in Azure Table Services query syntax.</param>
        /// <param name="pageSize">Number of rows to be fetched</param>
        /// <param name="nextPartitionKey">PartionKey to fetch next partion data</param>
        /// <param name="nextRowKey">RowKey to fetch row information</param>
        /// <returns>An XML element containing the results of the query.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="WebException"></exception>
        /// <exception cref="Exception"></exception>
        public override XElement GetData(string container, string tableName,
                                         string filter, int pageSize,
                                         string nextPartitionKey, string nextRowKey)
        {
            XElement xmlData = null;

            if (string.IsNullOrEmpty(tableName))
            {
                throw new ArgumentNullException(AzureResources.TableNameCannotBeNull);
            }

            if (pageSize < 0)
            {
                throw new ArgumentException(AzureResources.PagesizeNotZEROOrNegative);
            }

            Uri serviceUri = LoadServiceUri(container, tableName, filter, pageSize, nextPartitionKey, nextRowKey);

            // Store the partitionkey and rowkey as prevpartitionkey and prevrowkey before getting new set of data.
            string currentPartitionKeyStr = string.Empty;
            string currentRowKeyStr       = string.Empty;

            if (!string.IsNullOrEmpty(nextPartitionKey))
            {
                currentPartitionKeyStr = nextPartitionKey;
            }

            if (!string.IsNullOrEmpty(nextRowKey))
            {
                currentRowKeyStr = nextRowKey;
            }

            string nextPartitionKeyStr = string.Empty;
            string nextRowKeyStr       = string.Empty;

            var webRequest     = HttpWebRequest.Create(serviceUri);
            var response       = webRequest.GetResponse();
            var responseStream = response.GetResponseStream();

            if (response.Headers[AzureResources.continuation_nextPartionKey] != null)
            {
                nextPartitionKeyStr = response.Headers[AzureResources.continuation_nextPartionKey];
            }

            if (response.Headers[AzureResources.continuation_nextRowKey] != null)
            {
                nextRowKeyStr = response.Headers[AzureResources.continuation_nextRowKey];
            }

            var feed = XElement.Load(XmlReader.Create(responseStream));

            var propertiesElements = feed.Elements(XNamespace.Get(AzureResources.nsAtom) + "entry").Elements(XNamespace.Get(AzureResources.nsAtom) + "content").Elements(XNamespace.Get(AzureResources.nsMetadata) + "properties");

            // Remove PartitionKey, RowKey, and Timestamp because we don't want users to focus on these.
            // They are required by Azure Table storage, but will most likely go away
            // when we move to SDS.
            propertiesElements.Elements(XNamespace.Get(AzureResources.nsDataServices) + "PartitionKey").Remove();
            propertiesElements.Elements(XNamespace.Get(AzureResources.nsDataServices) + "RowKey").Remove();
            propertiesElements.Elements(XNamespace.Get(AzureResources.nsDataServices) + "Timestamp").Remove();

            // XmlDataSource doesn't support namespaces well
            // http://www.hanselman.com/blog/PermaLink,guid,8147b263-24fc-498d-83d1-546f4dde3fc3.aspx
            // Therefore, we will return XML that doesn't have any
            XElement root = new XElement("Root", propertiesElements);

            root.Add(new XAttribute("tableName", tableName));
            root.Add(new XAttribute("currentPartitionKey", currentPartitionKeyStr));
            root.Add(new XAttribute("currentRowKey", currentRowKeyStr));
            root.Add(new XAttribute("nextPartitionKey", nextPartitionKeyStr));
            root.Add(new XAttribute("nextRowKey", nextRowKeyStr));
            xmlData = StripNamespaces(root);
            return(xmlData);
        }
Пример #20
0
        public void Translate(List <ChattingLine> chattingLines)
        {
            try
            {
                // Build text
                var textBuilder = new StringBuilder();
                var settings    = new XmlWriterSettings {
                    OmitXmlDeclaration = true
                };
                var textWriter = XmlWriter.Create(textBuilder, settings);
                textWriter.WriteStartElement("TranslateArrayRequest");
                {
                    textWriter.WriteElementString("AppId", null);
                    textWriter.WriteElementString("From", _langFrom);

                    textWriter.WriteStartElement("Options");
                    {
                        textWriter.WriteElementString("Category", NsService, "general");
                        textWriter.WriteElementString("ContentType", NsService, "text/html");
                        textWriter.WriteElementString("ReservedFlags", NsService, null);
                        textWriter.WriteElementString("State", NsService, "0");
                        textWriter.WriteElementString("Uri", NsService, "all");
                        textWriter.WriteElementString("User", NsService, "all");

                        textWriter.WriteEndElement();
                    }

                    textWriter.WriteStartElement("Texts");
                    {
                        foreach (var line in chattingLines)
                        {
                            textWriter.WriteElementString("string", NsArrays,
                                                          WebUtility.HtmlEncode(TextProcessor.NaiveCleanText(line.RawContent)));
                        }

                        textWriter.WriteEndElement();
                    }

                    textWriter.WriteElementString("To", _langTo);

                    textWriter.WriteEndElement();
                }
                textWriter.Flush();
                textWriter.Close();
                var requestBody = textBuilder.ToString();
                Console.WriteLine("Request body is: {0}.", requestBody);

                // Call Microsoft translate API.
                DoRequest(GetAuthToken(), requestBody, out string responseBody, out HttpStatusCode statusCode);

                // Parse result
                switch (statusCode)
                {
                case HttpStatusCode.OK:
                    Console.WriteLine("Request status is OK. Response body is:");
                    Console.WriteLine(responseBody);
                    Console.WriteLine("Result of translate array method is:");
                    var doc = XDocument.Parse(responseBody);
                    var ns  = XNamespace.Get(NsService);
                    var sourceTextCounter = 0;
                    foreach (var xe in doc.Descendants(ns + "TranslateArrayResponse"))
                    {
                        foreach (var node in xe.Elements(ns + "TranslatedText"))
                        {
                            var result = WebUtility.HtmlDecode(node.Value);
                            Console.WriteLine("\n\nSource text: {0}\nTranslated Text: {1}",
                                              chattingLines[sourceTextCounter].RawContent, result);
                            chattingLines[sourceTextCounter].TranslatedContent = result;
                        }
                        sourceTextCounter++;
                    }
                    break;

                case HttpStatusCode.Unauthorized:
                    throw new TranslateException(TranslateException.ExceptionReason.InvalidApiKey,
                                                 "Invalid API key",
                                                 null);

                default:
                    Console.WriteLine("Request status code is: {0}.", statusCode);
                    Console.WriteLine("Request error message: {0}.", responseBody);
                    throw new TranslateException(TranslateException.ExceptionReason.GeneralServiceError,
                                                 responseBody, null);
                }
            }
            catch (TranslateException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new TranslateException(TranslateException.ExceptionReason.UnknownError, null, ex);
            }
        }
Пример #21
0
 public XName GetPseudoName(string name) => XNamespace.Get("https://github.com/0xd4d/dnSpy").GetName(name);
Пример #22
0
        private static IEnumerable <ImmersiveApp> GetApps()
        {
            Log.Raw("Begin GetApps. OsIs 8+ = " + Util.OsIs.EightOrMore);
            //Only for Win8+
            if (!Util.OsIs.EightOrMore)
            {
                yield break;
            }

            //Step 1. Getting initial package deployment info: package ids and related deployment paths and display names
            //This may include non-activateable or non-existing packages
            var pathCache = GetAppPackages();

            if (pathCache == null || pathCache.Count == 0)
            {
                yield break;
            }

            //Step 2. Scanning activateable classes repo to filter activatable package IDs
            var serverCache = GetExecutablePackages();

            if (serverCache == null || serverCache.Length == 0)
            {
                yield break;
            }

            //Step 3. Corellating package IDs to App families. We need this info because AppUserModelId is
            //(only for immersive apps) "<FamilyId>!<AppId>". As a side note, we will get App IDs further.
            var families = GetAppFamilies();

            if (families == null || families.Count == 0)
            {
                yield break;
            }

            //Step 4. Parse app manifest to get more visual information and corellate deployment and server caches,
            //and (the most important!) get the AppIds from which we'll construct the AppUserModelIds
            XNamespace m1 = XNamespace.Get("http://schemas.microsoft.com/appx/2010/manifest"), //W8 old
                       m2 = XNamespace.Get("http://schemas.microsoft.com/appx/2013/manifest"), //W8 new
                       m3 = XNamespace.Get("http://schemas.microsoft.com/appx/manifest/foundation/windows10"),
                       m4 = XNamespace.Get("http://schemas.microsoft.com/appx/manifest/uap/windows10"),
                       m0;

            foreach (var package in serverCache)// for all the activateable classes
            {
                PathCacheItem pathCacheItem;
                if (!pathCache.TryGetValue(package, out pathCacheItem))
                {
                    Log.Raw("Skipping activateable package (reason: path cache miss)", package);
                    continue;
                }

                string family;
                if (!families.TryGetValue(package, out family))
                {
                    Log.Raw("Skipping activateable package (reason: family cache miss)", package);
                    continue;
                }

                Log.Raw("Loading package data", package);
                var appxManifestPath = Path.Combine(pathCacheItem.RootPath, APPXMANIFEST_XML);
                if (!File.Exists(appxManifestPath))
                {
                    Log.Raw("Appx Manifest not found", appxManifestPath);
                    continue;
                }

                string company = null, logoTemplate = null;

                Log.Raw("Processing manifest " + appxManifestPath);
                var appManifest = XElement.Load(appxManifestPath);
                m0 = appManifest.Name.Namespace;
                var props = appManifest.Element(m0 + "Properties");
                if (props != null)
                {
                    company      = props.Element(m0 + "PublisherDisplayName").GetValueOrNull();
                    logoTemplate = props.Element(m0 + "Logo").GetValueOrNull();
                    //there's also display name but we already have it - in pathCacheItem
                }
                var apps = appManifest.Element(m0 + "Applications");
                if (apps == null)
                {
                    Log.Raw("Skipping activateable package (reason: no apps in manufest file)", package);
                    continue;
                }
                var appDataItems = apps.Elements()
                                   .Select(e =>
                {
                    var visual = e.Element(m1 + "VisualElements") ??
                                 e.Element(m2 + "VisualElements") ??
                                 e.Element(m3 + "VisualElements") ??
                                 e.Element(m4 + "VisualElements");
                    if (visual == null)
                    {
                        return(null);
                    }
                    var executable = e.Attribute("Executable") ?? e.Attribute("StartPage");
                    if (executable == null)
                    {
                        return(null);
                    }
                    return(new
                    {
                        Id = e.Attribute("Id").Value,
                        File = executable.Value,
                        Description = visual.GetValueOrNull("Description"),
                        DisplayName = visual.GetValueOrNull("DisplayName"),
                        AppListEntry = visual.GetValueOrNull("AppListEntry"),
                        Logos = visual.Attributes()
                                .Where(a => a.Name.LocalName.Contains("Logo"))
                                .Select(a => new
                        {
                            Name = a.Name.LocalName,
                            RelativePath = a.Value
                        }),
                        //BackgroundColor="#000000" ForegroundText="light"
                        ForegroundText = ParseColorBoolean(visual.GetValueOrNull("ForegroundText")),
                        BackgroundColor = ParseColor(visual.GetValueOrNull("BackgroundColor"))
                    });
                });
                var uriTemplates = appDataItems.Where(a => a != null)
                                   .Select(a => a.DisplayName)
                                   .Where(d => d != null && d.ToLower().Contains("ms-resource://"))
                                   .Union(new[] { pathCacheItem.DisplayName, "default" })
                                   .ToArray();

                for (int k = 0; k < uriTemplates.Length; k++)
                {
                    if (!uriTemplates[k].StartsWith("@{"))
                    {
                        //"@{FileManager_6.3.9600.16384_neutral_neutral_cw5n1h2txyewy?ms-resource://FileManager/Files/Assets/SkyDriveLogo.png}"
                        if (uriTemplates[k].StartsWith("ms-resource://")) //just wrap in resolvable format
                        {
                            uriTemplates[k] = string.Format("@{{{0}?{1}}}", package, uriTemplates[k]);
                        }
                        else //construct anew
                        {
                            int i = 0, j = package.Length - 1;
                            while (i < 4)
                            {
                                if (package[j] == '_')
                                {
                                    ++i;
                                }
                                --j;
                            }
                            var rootItem = package.Substring(0, j + 1);
                            uriTemplates[k] = string.Format("@{{{0}?ms-resource://{1}/resources/data}}", package, rootItem);
                        }
                    }
                }

                foreach (var appDataItem in appDataItems)
                {
                    if (appDataItem == null)
                    {
                        continue;
                    }
                    if (appDataItem.Id.Equals("Designer.App", StringComparison.OrdinalIgnoreCase))
                    {
                        Log.Raw("Skipping VisualStudio designer-generated app");
                        continue;
                    }
                    Log.Raw("Processing application with ID " + appDataItem.Id);
                    var appUserModelId = string.Format("{0}!{1}", family, appDataItem.Id);
                    Log.Raw("AppUserModelId constructed is " + appUserModelId);
                    yield return(new ImmersiveApp
                    {
                        PackageId = package,
                        File = appDataItem.File,
                        ApplicationName = Util.ExtractStringIndirect(pathCacheItem.DisplayName),
                        ApplicationDisplayName = ExtractStringFromPackageOptional(appDataItem.DisplayName, uriTemplates),
                        ApplicationCompany = ExtractStringFromPackageOptional(company, uriTemplates),
                        ApplicationDescription = ExtractStringFromPackageOptional(appDataItem.Description, uriTemplates),
                        AppUserModelID = appUserModelId,
                        Background = appDataItem.BackgroundColor,
                        Foreground = appDataItem.ForegroundText,
                        ApplicationPath = pathCacheItem.RootPath,
                        DisplayState = appDataItem.AppListEntry,
                        Logos = appDataItem.Logos
                                .ToDictionary(l => l.Name,
                                              l => LocateLogo(logoTemplate,
                                                              l.RelativePath,
                                                              uriTemplates,
                                                              pathCacheItem.RootPath))
                    });
                }
            }
        }
Пример #23
0
        public static List <XElement> GetDescendants(this XElement inputElement, string elementName, string nameSpace = "urn:hl7-org:v3")
        {
            XNamespace defaultNamespace = XNamespace.Get(nameSpace);

            return(inputElement?.Descendants(defaultNamespace + elementName).ToList());
        }
Пример #24
0
 public XMPPMessage()
     : base(XNamespace.Get(Namespaces.JabberClient) + "message")
 {
 }
Пример #25
0
        public static XElement GetElementObj(this XElement inputElement, string elementName)
        {
            XNamespace defaultNamespace = XNamespace.Get("urn:hl7-org:v3");

            return(inputElement.Element(defaultNamespace + elementName));
        }
Пример #26
0
        public void Inject(XDocument modifiedDocument)
        {
            XNamespace windows10Namespace = "http://schemas.microsoft.com/appx/manifest/foundation/windows10";
            XNamespace appxNamespace      = "http://schemas.microsoft.com/appx/2010/manifest";
            XNamespace uap4Namespace      = XNamespace.Get("http://schemas.microsoft.com/appx/manifest/uap/windows10/4");
            XNamespace buildNamespace     = XNamespace.Get("http://schemas.microsoft.com/developer/appx/2015/build");

            if (modifiedDocument.Root == null)
            {
                throw new ArgumentException("The XML file is corrupted. Root element is not present.");
            }

            var package = modifiedDocument.Element(windows10Namespace + "Package") ?? modifiedDocument.Element(appxNamespace + "Package");

            if (package == null)
            {
                return;
            }

            var namespaceAdded = false;

            var originalBuildNamespace = modifiedDocument.Root.Attribute(XNamespace.Xmlns + "build");

            if (originalBuildNamespace != null)
            {
                buildNamespace = originalBuildNamespace.Value;
            }
            else
            {
                modifiedDocument.Root.SetAttributeValue(XNamespace.Xmlns + "build", buildNamespace);
                namespaceAdded = true;
            }

            var originalUap4Namespace = modifiedDocument.Root.Attribute(XNamespace.Xmlns + "uap4");

            if (originalUap4Namespace != null)
            {
                uap4Namespace = originalUap4Namespace.Value;
            }
            else
            {
                modifiedDocument.Root.SetAttributeValue(XNamespace.Xmlns + "uap4", uap4Namespace);
                namespaceAdded = true;
            }

            if (namespaceAdded)
            {
                var ignorable = modifiedDocument.Root.Attribute("IgnorableNamespaces");
                if (ignorable == null)
                {
                    modifiedDocument.Root.Add(new XAttribute("IgnorableNamespaces", "build uap4"));
                }
                else
                {
                    modifiedDocument.Root.SetAttributeValue("IgnorableNamespaces", string.Join(" ", ignorable.Value.Split(' ').Union(new[] { "build", "uap4" })));
                }
            }

            var metaData = package.Element(buildNamespace + "Metadata");

            metaData?.Remove();

            metaData = new XElement(buildNamespace + "Metadata");
            package.Add(metaData);
            var version = NdDll.RtlGetVersion();

            var operatingSystem = new XElement(buildNamespace + "Item"); //(  "bu", "Item");

            metaData.Add(operatingSystem);
            operatingSystem.Add(new XAttribute("Name", "OperatingSystem"));
            operatingSystem.Add(new XAttribute("Version", version.ToString(4)));

            var msixHero = new XElement(buildNamespace + "Item");

            metaData.Add(msixHero);
            msixHero.Add(new XAttribute("Name", "MsixHero"));
            // ReSharper disable once PossibleNullReferenceException
            msixHero.Add(new XAttribute("Version", (Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly()).GetName().Version.ToString()));

            var signTool = new XElement(buildNamespace + "Item");

            metaData.Add(signTool);
            signTool.Add(new XAttribute("Name", "SignTool.exe"));
            signTool.Add(new XAttribute("Version", GetVersion("SignTool.exe")));

            // ReSharper disable once IdentifierTypo
            var makepri = new XElement(buildNamespace + "Item");

            metaData.Add(makepri);
            makepri.Add(new XAttribute("Name", "MakePri.exe"));
            makepri.Add(new XAttribute("Version", GetVersion("MakePri.exe")));

            // ReSharper disable once IdentifierTypo
            var makeappx = new XElement(buildNamespace + "Item");

            metaData.Add(makeappx);
            makeappx.Add(new XAttribute("Name", "MakeAppx.exe"));
            makeappx.Add(new XAttribute("Version", GetVersion("MakeAppx.exe")));
        }
Пример #27
0
        // --1--
        public datosPrincipales_E ConsultaSunatDPrinPide(string nroRucCons)
        {
            datosPrincipales_E objDp = new datosPrincipales_E();


            try
            {
                XDocument  xdoc = XDocument.Load("https://ws3.pide.gob.pe/Rest/Sunat/DatosPrincipales?numruc=" + nroRucCons);
                XNamespace xns  = XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/");
                //var SoapBody = xdoc.Descendants(xns + "Body").First().ToString();
                var SoapBody = xdoc.Descendants(xns + "Body").Elements();

                foreach (var item in SoapBody)
                {
                    objDp.ddp_ubigeo  = (string)item.Element("ddp_ubigeo");
                    objDp.cod_dep     = (string)item.Element("cod_dep");
                    objDp.desc_de     = (string)item.Element("desc_dep");
                    objDp.cod_prov    = (string)item.Element("cod_prov");
                    objDp.desc_prov   = (string)item.Element("desc_prov");
                    objDp.cod_dist    = (string)item.Element("cod_dist");
                    objDp.desc_dist   = (string)item.Element("desc_dist");
                    objDp.ddp_ciiu    = (string)item.Element("ddp_ciiu");
                    objDp.desc_ciiu   = (string)item.Element("desc_ciiu");
                    objDp.ddp_estado  = (string)item.Element("ddp_estado");
                    objDp.desc_estado = (string)item.Element("desc_estado");
                    objDp.ddp_fecact  = (string)item.Element("ddp_fecact");
                    objDp.ddp_fecalt  = (string)item.Element("ddp_fecalt");
                    objDp.ddp_fecbaj  = (string)item.Element("ddp_fecbaj");
                    objDp.ddp_identi  = (string)item.Element("ddp_identi");
                    objDp.desc_identi = (string)item.Element("desc_identi");
                    objDp.ddp_lllttt  = (string)item.Element("ddp_lllttt");
                    objDp.ddp_nombre  = (string)item.Element("ddp_nombre");
                    objDp.ddp_nomvia  = (string)item.Element("ddp_nomvia");
                    objDp.ddp_numer1  = (string)item.Element("ddp_numer1");
                    objDp.ddp_inter1  = (string)item.Element("ddp_inter1");
                    objDp.ddp_nomzon  = (string)item.Element("ddp_nomzon");
                    objDp.ddp_refer1  = (string)item.Element("ddp_refer1");
                    objDp.ddp_flag22  = (string)item.Element("ddp_flag22");
                    objDp.desc_flag22 = (string)item.Element("desc_flag22");
                    objDp.ddp_numreg  = (string)item.Element("ddp_numreg");
                    objDp.desc_numreg = (string)item.Element("desc_numreg");
                    objDp.ddp_numruc  = (string)item.Element("ddp_numruc");
                    objDp.ddp_tipvia  = (string)item.Element("ddp_tipvia");
                    objDp.desc_tipvia = (string)item.Element("desc_tipvia");
                    objDp.ddp_tipzon  = (string)item.Element("ddp_tipzon");
                    objDp.desc_tipzon = (string)item.Element("desc_tipzon");
                    objDp.ddp_tpoemp  = (string)item.Element("ddp_tpoemp");
                    objDp.desc_tpoemp = (string)item.Element("desc_tpoemp");

                    if (item.Element("esActivo") != null && item.Element("esHabido") != null)
                    {
                        objDp.esActivo = (bool)item.Element("esActivo");
                        objDp.esHabido = (bool)item.Element("esHabido");
                    }
                    else
                    {
                        objDp.esActivo = false;
                        objDp.esHabido = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error al obtener datos de PIDE-Sunat(1): " + ex.Message.ToString() + ex.StackTrace.ToString());
                ut.logsave(this, ex);
            }

            return(objDp);
        }
Пример #28
0
        public ParseWsdl(List <XmlDocument> xmls)
        {
            try
            {
                var xd = xmls.First().ToXDocument();
                Functions = new List <Function>();

                XNamespace wsdlNamespace = XNamespace.Get("http://schemas.xmlsoap.org/wsdl/");
                XNamespace xmlNamespace  = XNamespace.Get("http://www.w3.org/2001/XMLSchema");

                var definitions    = xd.Descendants(wsdlNamespace + "definitions");
                var types          = definitions.Descendants(wsdlNamespace + "types");
                var portType       = definitions.Descendants(wsdlNamespace + "portType");
                var operationsWSDL = portType.Descendants(wsdlNamespace + "operation");
                var messages       = definitions.Descendants(wsdlNamespace + "message");
                var schemas        = types.Descendants(xmlNamespace + "schema");
                var elements       = schemas.Elements(xmlNamespace + "element");
                foreach (var operation in operationsWSDL)
                {
                    var func = new Function();
                    var name = operation.Attribute("name").Value;
                    func.Name = name;

                    var input             = operation.Element(wsdlNamespace + "input").Attribute("message").Value.Split(':')[1];
                    var output            = operation.Element(wsdlNamespace + "output").Attribute("message").Value.Split(':')[1];
                    var messageInput      = messages.FirstOrDefault(a => a.Attribute("name").Value == input);
                    var messageOutput     = messages.FirstOrDefault(a => a.Attribute("name").Value == output);
                    var elementNameInput  = String.Empty;
                    var elementNameOutput = String.Empty;
                    if (messageInput != null && messageOutput != null)
                    {
                        elementNameInput = messageInput.Element(wsdlNamespace + "part").Attribute("element").Value
                                           .Split(':')[1];
                        elementNameOutput = messageOutput.Element(wsdlNamespace + "part").Attribute("element").Value
                                            .Split(':')[1];
                    }
                    var elementInput  = elements.FirstOrDefault(a => a.Attribute("name").Value == elementNameInput);
                    var elementOutput = elements.FirstOrDefault(a => a.Attribute("name").Value == elementNameOutput);

                    var index = 0;
                    foreach (var element in elementInput.Descendants(xmlNamespace + "element"))
                    {
                        var temp = Parameter.GetElementFromWSDL(element, xmlNamespace);
                        temp.Order = index;
                        func.Parameters.Add(temp);
                        index++;
                    }
                    var returnElements = elementOutput.Descendants(xmlNamespace + "element").ToList();
                    if (returnElements.Count == 0)
                    {
                        func.ReturnType = "void";
                    }
                    else
                    {
                        var returnElement = returnElements.FirstOrDefault(a => a.Attribute("name").Value.Contains(elementNameInput));
                        if (returnElement == null)
                        {
                            func.ReturnType = "void";
                        }
                        else
                        {
                            var attribute = returnElement.Attribute("type");
                            func.ReturnType = attribute == null ? "void" : Parameter.NormalizeVariable(attribute.Value);
                        }

                        var otherElements = returnElements.Where(a => a.Attribute("name") == null || !a.Attribute("name").Value.Contains(elementNameInput)).ToList();
                        if (otherElements != null && otherElements.Count > 0)
                        {
                            foreach (var elem in otherElements)
                            {
                                var parameterElem = Parameter.GetElementFromWSDL(elem, xmlNamespace);
                                if (parameterElem == null)
                                {
                                    continue;
                                }
                                var parameter = func.Parameters.FirstOrDefault(a => a.Name == parameterElem.Name);
                                if (parameter == null)
                                {
                                    var biggestOrder = func.Parameters.Max(a => a.Order);
                                    parameterElem.Order = biggestOrder + 1;
                                    parameterElem.Type  = "out " + parameterElem.Type;
                                    func.Parameters.Add(parameterElem);
                                }
                                else
                                {
                                    parameter.Type = "ref " + parameter.Type;
                                }
                            }
                        }
                    }
                    Functions.Add(func);
                }
                var serviceNode = definitions.Descendants(wsdlNamespace + "service").First();
                ServiceAddress    = serviceNode.Descendants(wsdlNamespace + "port").First().Attribute("name").Value;
                ServiceClientName = definitions.Descendants(wsdlNamespace + "portType").First().Attribute("name").Value;
                if (ServiceClientName[0] == 'I')
                {
                    ServiceClientName = ServiceClientName.Substring(1);
                }
            } catch (Exception e)
            {
                throw new Exception("Error on Parsing", e);
            }
        }
Пример #29
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            string sourceTile = txtImageFile.Text;

            if (sourceTile.Length > 0 && !System.IO.File.Exists(sourceTile))
            {
                MessageBox.Show("No TileImage selected.");
                return;
            }
            string targetExe = txtTarget.Text;

            if (!System.IO.File.Exists(targetExe))
            {
                MessageBox.Show("No Target selected.");
                return;
            }

            string sourceTileSmall = txtImageSmall.Text;

            if (sourceTileSmall.Length > 0)
            {
                if (!System.IO.File.Exists(sourceTileSmall))
                {
                    MessageBox.Show("Small Tile specified but does not exist.");
                    return;
                }
            }

            if (sourceTile.Length > 0)
            {
                if (txtTilename.Text.Equals("") || txtTilename.Text.Equals("tile.png"))
                {
                    txtTilename.Text = getDefaultTilename(targetExe);
                }

                //copy the image.
                string targetTile = Path.GetDirectoryName(targetExe) + @"\" + txtTilename.Text;
                if (!sourceTile.Equals(targetTile))
                {
                    System.IO.File.Copy(sourceTile, targetTile, true);
                }
            }

            if (sourceTileSmall.Length > 0)
            {
                if (sourceTileSmall.Length > 0 && (txtSmallTilename.Text.Equals("") || txtSmallTilename.Text.Equals("tile-small.png")))
                {
                    txtSmallTilename.Text = getDefaultSmalltileName(targetExe);
                }


                if (sourceTileSmall.Length > 0)
                {
                    //copy the image.
                    string targetTileSmall = Path.GetDirectoryName(targetExe) + @"\" + txtSmallTilename.Text;
                    if (!sourceTileSmall.Equals(targetTileSmall))
                    {
                        System.IO.File.Copy(sourceTileSmall, targetTileSmall, true);
                    }
                }
            }

            XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");

            XDocument doc =
                new XDocument(
                    new XElement("Application", new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                 new XElement("VisualElements",
                                              new XAttribute("ShowNameOnSquare150x150Logo", checkShowlabel.Checked ? "on" : "off"),
                                              new XAttribute("ForegroundText", radioDark.Checked ? "dark" : "light"),
                                              new XAttribute("BackgroundColor", txtBg.Text)
                                              )
                                 )
                    );

            var ve = doc.Element("Application").Element("VisualElements");

            if (sourceTile.Length > 0)
            {
                ve.Add(new XAttribute("Square150x150Logo", txtTilename.Text));

                if (!(sourceTileSmall.Length > 0))
                {
                    ve.Add(new XAttribute("Square70x70Logo", txtTilename.Text));
                }
            }

            if (sourceTileSmall.Length > 0)
            {
                ve.Add(new XAttribute("Square70x70Logo", txtSmallTilename.Text));
            }

            string targetTemplate = getTemplatePath(targetExe);

            doc.Save(targetTemplate);

            string lnkFile = lstStartmenu.SelectedItem.ToString();

            refreshLnk(lnkFile);
        }
Пример #30
0
 /// <summary>
 /// Initializes the <see cref="XmlUtil"/> class.
 /// </summary>
 static XmlUtil()
 {
     Xsi    = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
     _regex = new Regex(@"(?<selector>[//]+)?(?<namespace>[A-z0-9_]+:)?(?<element>[\@\*A-z0-9_\[\]]+)");
 }