/// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(LinkCollection payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
            ExceptionUtilities.CheckObjectNotNull(this.currentXElement, "Current XElement is not defined");

            XElement feed = CreateAtomElement(this.currentXElement, "feed");

            if (payloadElement.InlineCount.HasValue)
            {
                XElement countElement = CreateMetadataElement(feed, "count");
                countElement.Value = payloadElement.InlineCount.Value.ToString(CultureInfo.InvariantCulture);
            }

            foreach (Link link in payloadElement)
            {
                this.VisitPayloadElement(link, feed);
            }

            if (payloadElement.NextLink != null)
            {
                XElement nextLink = CreateElement(feed, null, "next", ODataConstants.DataServicesNamespaceName);
                nextLink.Value = payloadElement.NextLink;
            }

            PostProcessXElement(payloadElement, feed);
        }
예제 #2
0
        public void Create(Node node, bool keepGroups,
                           bool ignoreArrowDirection, IFactory factory)
        {
            _node                 = node;
            _keepGroups           = keepGroups;
            _ignoreArrowDirection = ignoreArrowDirection;

            // If groups' layout is preserved, then, the underlying
            // node is always the highest-in-hierarchy group master.
            if (_keepGroups)
            {
                while (node.MasterGroup != null)
                {
                    if (!(node.MasterGroup.MainObject is Node))
                    {
                        break;
                    }

                    node = node.MasterGroup.MainObject as Node;
                }

                _node = node;
            }

            // Enumerate incoming and outgoing links
            _inLinks  = GetInLinks(factory);
            _outLinks = GetOutLinks(factory);
            _allLinks = new LinkCollection();
            _allLinks.AddRange(_inLinks);
            _allLinks.AddRange(_outLinks);
        }
예제 #3
0
 public LinkCollection FetchAll()
 {
     LinkCollection coll = new LinkCollection();
     Query qry = new Query(Link.Schema);
     coll.LoadAndCloseReader(qry.ExecuteReader());
     return coll;
 }
예제 #4
0
        public DirectedGraph()
        {
            Nodes = new NodeCollection(this);
            Links = new LinkCollection(this);

            PropertyDeclaration = new PropertyList();
        }
예제 #5
0
 public PersonDataEditor()
 {
     DataContext = this;
     IPList      = new LinkCollection();
     //InitializeComponent();
     InitializeComponent();
 }
예제 #6
0
        ProjectResource TestProject(bool gitProject, bool variablesAreInGit, string linkKey, string link)
        {
            var linkCollection = new LinkCollection {
                { linkKey, link }
            };

            PersistenceSettingsResource persistence = new DatabasePersistenceSettingsResource();


            if (gitProject)
            {
                persistence = new GitPersistenceSettingsResource
                {
                    ConversionState = new GitPersistenceSettingsConversionStateResource
                    {
                        VariablesAreInGit = variablesAreInGit
                    }
                };
            }

            return(new ProjectResource
            {
                PersistenceSettings = persistence,
                Links = linkCollection
            });
        }
        /// <summary>
        /// Deserializes a collection of links
        /// </summary>
        /// <param name="links">Xml element representing the links collection</param>
        /// <returns>Deserialized link collection</returns>
        private LinkCollection DeserializeLinks(XElement links)
        {
            LinkCollection collection = new LinkCollection();

            AddXmlBaseAnnotation(collection, links);

            // read the count, if present
            XElement count = links.Element(MetadataCount);

            if (count != null)
            {
                collection.InlineCount = long.Parse(count.Value, CultureInfo.InvariantCulture);
            }

            // read the next-link if present
            XElement nextLink = links.Element(DataServicesNext);

            if (nextLink != null)
            {
                collection.NextLink = nextLink.Value;
            }

            // deserialize each element as a link and add it to the collection
            foreach (var link in links.Elements(MetadataUri))
            {
                collection.Add(this.DeserializeLink(link));
            }

            return(collection);
        }
예제 #8
0
 public DeterminateForm(SettingsForm set_form)
 {
     InitializeComponent();
     this.set_form      = set_form;
     set_form.OK_event += Set_form_OK_event;
     links              = new LinkCollection();
 }
예제 #9
0
        public void ShouldUpdateExistingMachineWhenForceIsEnabled()
        {
            environments.Items.Add(new EnvironmentResource {
                Id = "environments-1", Name = "UAT", Links = LinkCollection.Self("/api/environments/environments-1").Add("Machines", "/api/environments/environments-1/machines")
            });
            environments.Items.Add(new EnvironmentResource {
                Id = "environments-2", Name = "Production", Links = LinkCollection.Self("/api/environments/environments-2").Add("Machines", "/api/environments/environments-2/machines")
            });

            machines.Items.Add(new MachineResource {
                Id = "machines/84", EnvironmentIds = new ReferenceCollection(new[] { "environments-1" }), Name = "Mymachine", Links = LinkCollection.Self("/machines/whatever/1")
            });

            operation.TentacleThumbprint = "ABCDEF";
            operation.TentaclePort       = 10930;
            operation.MachineName        = "Mymachine";
            operation.TentacleHostname   = "Mymachine.test.com";
            operation.CommunicationStyle = CommunicationStyle.TentaclePassive;
            operation.EnvironmentNames   = new[] { "Production" };
            operation.AllowOverwrite     = true;

            operation.Execute(serverEndpoint);

            client.Received().Update("/machines/whatever/1", Arg.Is <MachineResource>(m =>
                                                                                      m.Id == "machines/84" &&
                                                                                      m.Name == "Mymachine" &&
                                                                                      m.EnvironmentIds.First() == "environments-2"));
        }
예제 #10
0
        private static void SetupLinkGroup(LinkGroupCollection menuLinkGroups, LinkCollection titleLinks, LinkGroupData linkGroupData, ref Uri contentSource)
        {
            Uri firstUri  = null;
            var linkGroup = new LinkGroup {
                DisplayName = linkGroupData.DisplayName, GroupKey = linkGroupData.GroupKey
            };

            foreach (var link in linkGroupData.Links)
            {
                var assemblyPath = AssemblyToolkit.GetDll(linkGroupData.Assembly);
                var settingsLink = new Link {
                    DisplayName = link.DisplayName, Source = new Uri(assemblyPath + "+" + link.Source, UriKind.RelativeOrAbsolute)
                };
                linkGroup.Links.Add(settingsLink);
                firstUri = new Uri(assemblyPath + "+" + link.Source, UriKind.RelativeOrAbsolute);
                if (flag++ == 0)
                {
                    contentSource = new Uri(assemblyPath + "+" + link.Source, UriKind.RelativeOrAbsolute);
                }
            }
            if (linkGroupData.IsTitleLink)
            {
                titleLinks.Add(new Link {
                    DisplayName = linkGroupData.DisplayName, Source = firstUri
                });
            }
            menuLinkGroups.Add(linkGroup);
        }
예제 #11
0
        protected override void InternalExecute(object parameter)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                Links.Clear();
            });
            var result = LinkCollection.FromFile(InputFile);

            Processed = 0;
            Total     = result.Count;
            var no        = 0;
            var itemtasks = new List <Task>();
            var c         = CancelToken;

            foreach (var item in result)
            {
                Helper.Sleep();
                c.Token.ThrowIfCancellationRequested();
                var xx = item;
                Application.Current.Dispatcher.Invoke(delegate
                {
                    Links.Add((LinkModel)xx);
                });
                ++no;
                item.No = no;
                var x        = item;
                var itemtask = Task.Factory.StartNew(() => { x.CountAnchors(c); }, c.Token)
                               .ContinueWith(a =>
                                             TaskCompelted()
                                             );
                itemtasks.Add(itemtask);
            }
            Task.WaitAll(itemtasks.ToArray(), c.Token);
        }
예제 #12
0
        public virtual LinkCollection GetLinkListBySourceId(Int32 sourceId ,LinkColumns orderBy, string orderDirection, int page, int pageSize, out int totalRecords)
        {
            try
            {
                Database database = DatabaseFactory.CreateDatabase();
                DbCommand dbCommand = database.GetStoredProcCommand("spLinkGetListBySource");

                database.AddInParameter(dbCommand, "@SourceId", DbType.Int32, sourceId);
                database.AddInParameter(dbCommand, "@OrderBy", DbType.AnsiString, orderBy.ToString());
                database.AddInParameter(dbCommand, "@OrderDirection", DbType.AnsiString, orderDirection.ToString());
                database.AddInParameter(dbCommand, "@Page", DbType.Int32, page);
                database.AddInParameter(dbCommand, "@PageSize", DbType.Int32, pageSize);
                database.AddOutParameter(dbCommand, "@TotalRecords", DbType.Int32, 4);

                LinkCollection linkCollection = new LinkCollection();
                using (IDataReader reader = database.ExecuteReader(dbCommand))
                {
                    while (reader.Read())
                    {
                        Link link = CreateLinkFromReader(reader);
                        linkCollection.Add(link);
                    }
                    reader.Close();
                }
                totalRecords = (int)database.GetParameterValue(dbCommand, "@TotalRecords");
                return linkCollection;
            }
            catch (Exception ex)
            {
                // log this exception
                log4net.Util.LogLog.Error(ex.Message, ex);
                // wrap it and rethrow
                throw new ApplicationException(SR.DataAccessGetLinkListException, ex);
            }
        }
예제 #13
0
        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            var directoryCatalog = (DirectoryModuleCatalog)moduleCatalog;

            directoryCatalog.Initialize();

            _linkCollection = new LinkCollection();
            var typeFilter = new TypeFilter(InterfaceFilter);

            foreach (var module in directoryCatalog.Items)
            {
                var mi  = (ModuleInfo)module;
                var asm = Assembly.LoadFrom(mi.Ref);

                foreach (Type t in asm.GetTypes())
                {
                    var myInterfaces = t.FindInterfaces(typeFilter, typeof(IModernLinkService).ToString());

                    if (myInterfaces.Length > 0)
                    {
                        var linkService = (IModernLinkService)asm.CreateInstance(t.FullName);
                        var modernLink  = linkService?.GetModernLink();
                        _linkCollection.Add(modernLink);
                    }
                }
            }
            moduleCatalog.AddModule <CoreModule>();
        }
        public async Task ShouldCreateWhenCantDeserializeMachines()
        {
            client.When(x => x.Paginate(Arg.Any <string>(), Arg.Any <object>(), Arg.Any <Func <ResourceCollection <MachineResource>, bool> >()))
            .Throw(new OctopusDeserializationException(1, "Can not deserialize"));

            environments.Items.Add(new EnvironmentResource {
                Id = "environments-1", Name = "UAT", Links = LinkCollection.Self("/api/environments/environments-1").Add("Machines", "/api/environments/environments-1/machines")
            });
            environments.Items.Add(new EnvironmentResource {
                Id = "environments-2", Name = "Production", Links = LinkCollection.Self("/api/environments/environments-2").Add("Machines", "/api/environments/environments-2/machines")
            });

            operation.TentacleThumbprint = "ABCDEF";
            operation.TentaclePort       = 10930;
            operation.MachineName        = "Mymachine";
            operation.TentacleHostname   = "Mymachine.test.com";
            operation.CommunicationStyle = CommunicationStyle.TentaclePassive;
            operation.EnvironmentNames   = new[] { "Production" };

            await operation.ExecuteAsync(serverEndpoint).ConfigureAwait(false);

            await client.Received().Create("/api/machines", Arg.Is <MachineResource>(m =>
                                                                                     m.Name == "Mymachine" &&
                                                                                     ((ListeningTentacleEndpointResource)m.Endpoint).Uri == "https://mymachine.test.com:10930/" &&
                                                                                     m.EnvironmentIds.First() == "environments-2")).ConfigureAwait(false);
        }
 public ListOfIP()
 {
     DataContext = this;
     InitializeComponent();
     IPList = new LinkCollection();
     testMethod(IPList);
 }
예제 #16
0
        public void EntityReferenceLinksReadingBaseUriTest()
        {
            EdmModel model = (EdmModel)Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            model.Fixup();

            LinkCollection linkCollection = PayloadBuilder.LinkCollection();

            linkCollection.Add(PayloadBuilder.DeferredLink("http://odata.org/dummy"));
            linkCollection.Add(PayloadBuilder.DeferredLink("http://odata.org/dummy"));
            linkCollection.Add(PayloadBuilder.DeferredLink("http://odata.org/dummy"));

            this.CombinatorialEngineProvider.RunCombinations(
                payloadUris,
                baseUriValues,
                resolvers,
                new bool[] { false, true },
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (payloadUri, baseUriValue, resolver, runInBatch, testConfiguration) =>
            {
                Action <LinkCollection, Uri, ReaderTestConfiguration> setLinkAction =
                    (links, uri, testConfig) => links[1].UriString = UriToString(uri);
                this.RunBaseUriReadingTest(linkCollection, setLinkAction, model, payloadUri, baseUriValue, resolver, testConfiguration, runInBatch);
            });
        }
        public async Task ShouldOverwriteMachinePolicyWhenPassed()
        {
            environments.Items.Add(new EnvironmentResource {
                Id = "environments-1", Name = "UAT", Links = LinkCollection.Self("/api/environments/environments-1").Add("Machines", "/api/environments/environments-1/machines")
            });
            environments.Items.Add(new EnvironmentResource {
                Id = "environments-2", Name = "Production", Links = LinkCollection.Self("/api/environments/environments-2").Add("Machines", "/api/environments/environments-2/machines")
            });

            machines.Items.Add(new MachineResource {
                Id = "machines/84", MachinePolicyId = "MachinePolicies-1", EnvironmentIds = new ReferenceCollection(new[] { "environments-1" }), Name = "Mymachine", Links = LinkCollection.Self("/machines/whatever/1")
            });
            machinePolicies.Items.Add(new MachinePolicyResource {
                Id = "MachinePolicies-2", Name = "Machine Policy 2"
            });
            operation.TentacleThumbprint = "ABCDEF";
            operation.TentaclePort       = 10930;
            operation.MachineName        = "Mymachine";
            operation.TentacleHostname   = "Mymachine.test.com";
            operation.CommunicationStyle = CommunicationStyle.TentaclePassive;
            operation.EnvironmentNames   = new[] { "Production" };
            operation.AllowOverwrite     = true;
            operation.MachinePolicy      = "Machine Policy 2";

            await operation.ExecuteAsync(serverEndpoint).ConfigureAwait(false);

            await client.Received().Update("/machines/whatever/1", Arg.Is <MachineResource>(m =>
                                                                                            m.Id == "machines/84" &&
                                                                                            m.Name == "Mymachine" &&
                                                                                            m.EnvironmentIds.First() == "environments-2" &&
                                                                                            m.MachinePolicyId == "MachinePolicies-2")).ConfigureAwait(false);
        }
 /// <summary>
 /// Visits a LinkCollection, if IncludeRelationshipLinks = true then this will be a V3 payload
 /// </summary>
 /// <param name="payloadElement">payload Element</param>
 public override void Visit(LinkCollection payloadElement)
 {
     ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
     this.IncreaseVersionIfIncludeRelationshipLinksIsTrue(payloadElement);
     this.IncreaseVersionIfNonNull(payloadElement.NextLink, DataServiceProtocolVersion.V4);
     base.Visit(payloadElement);
 }
예제 #19
0
        private LinkCollection GetUriMatches(string text)
        {
            LinkCollection uriCollection = null;
            Uri            currentUri    = null;

            Regex           uriLocator = new Regex(this.UriPattern);
            MatchCollection uriMatches = uriLocator.Matches(text);

            // no uris found
            if (uriMatches == null || uriMatches.Count == 0)
            {
                return(null);
            }

            foreach (Match uri in uriMatches)
            {
                // not valid uri - continue with next match
                if (!Uri.TryCreate(uri.Value, UriKind.RelativeOrAbsolute, out currentUri))
                {
                    continue;
                }

                if (uriCollection == null)
                {
                    uriCollection = new LinkCollection();
                }

                uriCollection.Add(new Link(uri.Value.Trim(), currentUri));
            }

            return(uriCollection);
        }
예제 #20
0
 private void papulateList(LinkCollection IPList)
 {
     IPList.Add(new Link()
     {
         DisplayName = "Şəxsi məlumatlar", Source = new Uri("/PersonalDataPages/personalData.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Vəzifə", Source = new Uri("/PersonalDataPages/personalPosition.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Təhsil", Source = new Uri("/PersonalDataPages/personalEducation.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Əmək fəaliyyəti", Source = new Uri("/PersonalDataPages/personalWorkHistory.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Əməkhaqqı", Source = new Uri("/PersonalDataPages/personaSalary.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Təltif və cəzalar", Source = new Uri("/PersonalDataPages/personalActivity.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Digər məlumatlar", Source = new Uri("/PersonalDataPages/personalRegData.xaml#" + selectedID, UriKind.Relative)
     });
     IPList.Add(new Link()
     {
         DisplayName = "Ailə tərkibi", Source = new Uri("/PersonalDataPages/personalFamily.xaml#" + selectedID, UriKind.Relative)
     });
 }
        private static LinkCollection ProcessLinks(object target, IDictionary <string, object> rtn, out string selfHref)
        {
            var links = target.GetType()
                        .GetProperties().FirstOrDefault(p => p.Name == "Relations");

            LinkCollection linkCollection = null;

            selfHref = "";
            if (links != null)
            {
                linkCollection = links.GetValue(target) as LinkCollection;
                if (linkCollection != null)
                {
                    var collectionLink = linkCollection.FirstOrDefault(lc => lc.Key == "collection");
                    if (collectionLink.Value != null)
                    {
                        rtn.Add("href", collectionLink.Value.Href);
                    }

                    var selfLink = linkCollection.FirstOrDefault(lc => lc.Key == "self");
                    if (selfLink.Value != null)
                    {
                        selfHref = selfLink.Value.Href;
                    }
                }
            }
            return(linkCollection);
        }
예제 #22
0
        private void ResponseRecieved(object sender, ResponseEventArgs e)
        {
            if (e.Response.ContentType == 60) // 60 -> cbor
            {
                try
                {
                    CborModel = CBORObject.DecodeFromBytes(e.Response.Payload);
                }
                catch (PeterO.Cbor.CBORException)
                {
                    //Take some action
                }
                BeginInvoke(new Action(() => PayloadDataTextBox.Text = CborModel.ToJSONString()));
            }
            else if (e.Response.ContentType == 0) // 0 - text/plain
            {
                BeginInvoke(new Action(() => PayloadDataTextBox.Text = e.Response.Payload.ToString()));
            }

            else if (e.Response.ContentType == 40)
            {
                LinkCollection collection    = new LinkCollection(e.Response.PayloadString);
                StringBuilder  stringBuilder = new StringBuilder();
                foreach (var item in collection)
                {
                    stringBuilder.AppendLine(item.Uri);
                }
                BeginInvoke(new Action(() => PayloadDataTextBox.Text = stringBuilder.ToString()));
            }
        }
        static Crt GetCACertificate(CertificateProvider cp, CertificateRequest certRequest)
        {
            var links  = new LinkCollection(certRequest.Links);
            var upLink = links.GetFirstOrDefault("up");

            var temporaryFileName = Path.GetTempFileName();

            try
            {
                var uri = new Uri(new Uri(Program.GlobalConfiguration.AcmeServerBaseUri), upLink.Uri);
                TheWebClient.DownloadFile(uri, temporaryFileName);

                var cacert   = new X509Certificate2(temporaryFileName);
                var serverSN = cacert.GetSerialNumberString();


                using (Stream source = new FileStream(temporaryFileName, FileMode.Open))
                {
                    return(cp.ImportCertificate(EncodingFormat.DER, source));
                }
            }
            finally
            {
                if (File.Exists(temporaryFileName))
                {
                    File.Delete(temporaryFileName);
                }
            }
        }
        public void SetUp()
        {
            runRunbookCommand = new RunRunbookCommand(RepositoryFactory,
                                                      FileSystem,
                                                      ClientFactory,
                                                      CommandOutputProvider,
                                                      ExecutionResourceWaiterFactory);

            var links = new LinkCollection {
                { "CreateRunbookRun", "test" }
            };
            var project = new ProjectResource();
            var runbook = new RunbookResource {
                Links = links
            };
            var runbookRun = new RunbookRunResource {
                TaskId = "Task-1"
            };

            taskResource = new TaskResource {
                Id = "Task-1"
            };

            Repository.Projects.FindByName(ProjectName).Returns(project);
            Repository.Runbooks.FindByName(project, RunbookName).Returns(runbook);

            Repository.Runbooks.Run(runbook, Arg.Any <RunbookRunParameters>()).Returns(Task.FromResult(new[] { runbookRun }));
            Repository.Tasks.Get(runbookRun.TaskId).Returns(taskResource);

            Repository.Tasks
            .When(x => x.WaitForCompletion(Arg.Any <TaskResource[]>(), Arg.Any <int>(), TimeSpan.FromSeconds(1), Arg.Any <Func <TaskResource[], Task> >()))
            .Do(x => throw new TimeoutException());
        }
예제 #25
0
        public string GetIssuerCertificate(CertificateRequest certificate, CertificateProvider cp)
        {
            var linksEnum = certificate.Links;

            if (linksEnum != null)
            {
                var links  = new LinkCollection(linksEnum);
                var upLink = links.GetFirstOrDefault("up");
                if (upLink != null)
                {
                    var tmp = Path.GetTempFileName();
                    try
                    {
                        using (var web = new WebClient())
                        {
                            var uri = new Uri(new Uri(this.baseURI), upLink.Uri);
                            web.DownloadFile(uri, tmp);
                        }

                        var cacert = new X509Certificate2(tmp);
                        var sernum = cacert.GetSerialNumberString();
                        var tprint = cacert.Thumbprint;
                        var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                        var sigval = cacert.GetCertHashString();

                        var cacertDerFile = Path.Combine(configPath, $"ca-{sernum}-crt.der");
                        var cacertPemFile = Path.Combine(configPath, $"ca-{sernum}-crt.pem");

                        if (!File.Exists(cacertDerFile))
                        {
                            File.Copy(tmp, cacertDerFile, true);
                        }

                        Console.WriteLine($" Saving Issuer Certificate to {cacertPemFile}");
                        Trace.TraceInformation("Saving Issuer Certificate to {0}", cacertPemFile);
                        if (!File.Exists(cacertPemFile))
                        {
                            using (FileStream source = new FileStream(cacertDerFile, FileMode.Open),
                                   target = new FileStream(cacertPemFile, FileMode.Create))
                            {
                                var caCrt = cp.ImportCertificate(EncodingFormat.DER, source);
                                cp.ExportCertificate(caCrt, EncodingFormat.PEM, target);
                            }
                        }

                        return(cacertPemFile);
                    }
                    finally
                    {
                        if (File.Exists(tmp))
                        {
                            File.Delete(tmp);
                        }
                    }
                }
            }

            return(null);
        }
예제 #26
0
 private void GetTreeViewFromCollection(TreeView view, LinkCollection collection)
 {
     view.Nodes.Clear();
     foreach (var link in collection)
     {
         view.Nodes.Add(link.Uri);
     }
 }
예제 #27
0
파일: Bucket.cs 프로젝트: bubbafat/Hebo
 internal Bucket(RiakClient client, string bucketName)
 {
     Streaming = true;
     Client = client;
     Name = bucketName;
     _keys = new List<string>();
     Links = new LinkCollection();
 }
예제 #28
0
        /// <summary>
        /// Constructs an empty graph.
        /// </summary>
        public FCGraph(FlowChart chart)
        {
            _chart   = chart;
            directed = true;

            _nodes = new NodeCollection();
            _links = new LinkCollection();
        }
예제 #29
0
        public MainWindow()
        {
            InitializeComponent();

            Style = (Style)FindResource(typeof(ModernWindow));

            links = this.MenuLinkGroups[0].Links;
            instance = this;
        }
예제 #30
0
        public void AddTitleLinks(LinkCollection linkCollection)
        {
            // CreateMenuLinkGroup();

            foreach (var link in linkCollection)
            {
                this.TitleLinks.Add(link);
            }
        }/*
예제 #31
0
 internal FsFileData(long length)
 {
     if (length < 0)
     {
         throw new ArgumentOutOfRangeException("length");
     }
     Length = length;
     Links  = new LinkCollection(_links);
 }
예제 #32
0
 private bool IsDuplicateWorkItemLink(LinkCollection links, RelatedLink relatedLink)
 {
     if (links.Contains(relatedLink))
     {
         Logger.Log(LogLevel.Warning, $"Duplicate work item link, related workitem id: {relatedLink.RelatedWorkItemId}");
         return(true);
     }
     return(false);
 }
        public MainWindow()
        {
            InitializeComponent();

            Style = (Style)FindResource(typeof(ModernWindow));

            links    = this.MenuLinkGroups[0].Links;
            instance = this;
        }
예제 #34
0
        static string DownloadIssuerCertificate(CertificateProvider provider,
                                                CertificateRequest request, string api, string certificatesFolder)
        {
            var linksEnum  = request.Links;
            var isuPemFile = string.Empty;

            if (linksEnum != null)
            {
                var links  = new LinkCollection(linksEnum);
                var upLink = links.GetFirstOrDefault(SERVER_UP_STRING);
                if (upLink != null)
                {
                    var temporaryFileName = Path.GetTempFileName();
                    try
                    {
                        using (var web = new WebClient())
                        {
                            var apiUri = new Uri(new Uri(api), upLink.Uri);
                            web.DownloadFile(apiUri, temporaryFileName);
                        }

                        var cacert = new X509Certificate2(temporaryFileName);
                        var sernum = cacert.GetSerialNumberString();

                        var cacertDerFile = Path.Combine(certificatesFolder, $"ca-{sernum}-crt.der");
                        var cacertPemFile = Path.Combine(certificatesFolder, $"ca-{sernum}-crt.pem");

                        if (!File.Exists(cacertDerFile))
                        {
                            File.Copy(temporaryFileName, cacertDerFile, true);
                        }

                        if (!File.Exists(cacertPemFile))
                        {
                            using (FileStream source = new FileStream(cacertDerFile, FileMode.Open),
                                   target = new FileStream(cacertPemFile, FileMode.Create))
                            {
                                var caCrt = provider.ImportCertificate(EncodingFormat.DER, source);
                                provider.ExportCertificate(caCrt, EncodingFormat.PEM, target);
                            }
                        }

                        isuPemFile = cacertPemFile;
                    }
                    finally
                    {
                        if (File.Exists(temporaryFileName))
                        {
                            File.Delete(temporaryFileName);
                        }
                    }
                }
            }

            return(isuPemFile);
        }
예제 #35
0
 public LinkSettings()
 {
     Links = new LinkCollection();
     Links.Add(new Link());
     Links[0].ImageUrlSrc = UrlUtil.JoinUrl(Globals.GetRelativeUrl(SystemDirecotry.Assets_LinkIcon), "bbsmax.gif");
     Links[0].Name = "bbsMax";
     Links[0].Url = "http://www.bbsmax.com";
     Links[0].Index = 0;
     Links[0].ID = 1;
     MaxID = 100;
 }
예제 #36
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var hrefs = serializer.Deserialize<Dictionary<string, string>>(reader);
     if (hrefs == null) return existingValue;
     var result = new LinkCollection();
     foreach (var href in hrefs)
     {
         result.Add(href.Key, new Link(href.Value));
     }
     return result;
 }
        public void changeLinks(List<Order> orders)
        {
            _links = new LinkCollection();

            foreach (var order in orders)
            {
                _links.Add(new Link() { DisplayName = "Order " + order.Id, Source = new Uri("StorageManager/Views/OrderProductsDetailsControl.xaml#" + order.Id, UriKind.Relative) });
            }

            tabOrders.Links = _links;
        }
예제 #38
0
 private void OnLinksChanged(LinkCollection oldValue, LinkCollection newValue)
 {
     //if (oldValue != null) {
     //    // detach old event handler
     //    oldValue.CollectionChanged -= OnLinkChanged;
     //}
     
     //if (newValue != null) {
     //    // ensures the menu is rebuild when changes in the LinkGroups occur
     //    newValue.CollectionChanged += OnLinkChanged;
     //}
 }
 public OperationTypesViewModel([ImportMany]IEnumerable<Lazy<IContent, IViewMetadata>> views)
 {
     var collection = from view in views
                      where !string.IsNullOrEmpty(view.Metadata.DisplayName)
                      select
                          new Link
                          {
                              DisplayName = view.Metadata.DisplayName,
                              Source = new Uri(view.Metadata.ContentUri, UriKind.Relative)
                          };
     _operations = new LinkCollection(collection);
 }
예제 #40
0
        public RubriqueVM()
        {
            current = main;
            _links = new LinkCollection();
            Pages = new List<string>();
            PageSize = 20;
            Search = new RelayCommand<string>((a) =>
           {
               Service.getRubrique().Pattern = a.Trim();
               Messenger.Default.Send(ActionEvent.ReloadBooks);
           });

        }
예제 #41
0
        public NetListViewModel()
        {
            Info = "This is Net List";
            PingAll();
            List<Link> tempList = new List<Link>();
            foreach (string item in theList)
            {
                tempList.Add(new Link { DisplayName = item, Source = new Uri("http://google.co.uk") });
            }

            IEnumerable<Link> newList = tempList;

            IPList = new LinkCollection(newList);
        }
예제 #42
0
 public SettingsViewModel()
 {
     TabLinks = new LinkCollection(new[]
     {
         new Link
         {
             DisplayName = "appearance",
             Source = new Uri("/Views/SettingsAppearanceView.xaml", UriKind.Relative)
         },
         new Link
         {
             DisplayName = "about",
             Source = new Uri("/Views/AboutView.xaml", UriKind.Relative)
         }
     });
 }
        public void LinkCollectionTestRemoveRetry()
        {
            var data = new AssetData { };

            var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed);

            var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 2, data);
            _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);

            data.SetMediaContext(_mediaContext);

            var target = new LinkCollection<IAsset, AssetData>(dataContextMock.Object, data, "", new IAsset[] { data });

            target.RemoveAt(0);

            dataContextMock.Verify((ctxt) => ctxt.SaveChanges(), Times.Exactly(2));
        }
예제 #44
0
        public void NewLink(string displayname, string source, bool gotoLink = true)
        {
            //does it exist already
            var prel = from link in this.MenuLinkGroups[0].Links where link.DisplayName == displayname select link;
            if (prel.Count() != 0)
            {
                GoToLink(this.MenuLinkGroups[0].Links.IndexOf(prel.First()));
                return;
            }

            Link l = new Link();
            l.Source = new System.Uri(source, UriKind.RelativeOrAbsolute);
            l.DisplayName = displayname;

            this.MenuLinkGroups[0].Links.Add(l);

            links = this.MenuLinkGroups[0].Links;
            if (gotoLink)
                GoToLink(links.Count-1);
        }
예제 #45
0
        /// <summary>
        /// Gets a collection of mod categories
        /// </summary>
        /// <returns></returns>
        public async Task<LinkCollection> GetCategories()
        {

            var webClient = new HttpClient();
            var result = await webClient.GetStringAsync("http://api.factoriomods.com/categories");
            var categories = JsonConvert.DeserializeObject<Category[]>(result);

            var lCollection = new LinkCollection(from c in categories
                select new Link
                {
                    DisplayName = c.Title,
                    Source = new Uri($"http://api.factoriomods.com/mods?category={c.Name}")
                });
            lCollection.Add(new Link
            {
                DisplayName = "All",
                Source = new Uri("http://api.factoriomods.com/mods")
            });
            var orderedCollection = lCollection.OrderBy(x => x.DisplayName).ToList();
            return new LinkCollection(from n in orderedCollection select n);
        }
예제 #46
0
        /// <summary>
        /// Replaces the empty collection property with a more specific type
        /// </summary>
        /// <param name="payloadElement">The payload element to potentially replace</param>
        /// <returns>The original element or a copy to replace it with</returns>
        public override ODataPayloadElement Visit(EmptyUntypedCollection payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
            var expectedTypeAnnotatation = payloadElement.Annotations.OfType<ExpectedPayloadElementTypeAnnotation>().SingleOrDefault();
            if (expectedTypeAnnotatation != null && expectedTypeAnnotatation.ExpectedType == ODataPayloadElementType.LinkCollection)
            {
                var linkCollection = new LinkCollection();
                linkCollection.InlineCount = payloadElement.InlineCount;
                linkCollection.NextLink = payloadElement.NextLink;
                return payloadElement.ReplaceWith(linkCollection);
            }

            var entitySetAnnotation = payloadElement.Annotations.OfType<EntitySetAnnotation>().SingleOrDefault();
            if (entitySetAnnotation != null)
            {
                var entitySet = new EntitySetInstance();
                entitySet.InlineCount = payloadElement.InlineCount;
                entitySet.NextLink = payloadElement.NextLink;
                return payloadElement.ReplaceWith(entitySet);
            }

            var functionAnnotation = payloadElement.Annotations.OfType<FunctionAnnotation>().SingleOrDefault();
            if (functionAnnotation != null && expectedTypeAnnotatation != null)
            {
                if (expectedTypeAnnotatation.ExpectedType == ODataPayloadElementType.ComplexInstanceCollection)
                {
                    return payloadElement.ReplaceWith(new ComplexInstanceCollection());
                }

                if (expectedTypeAnnotatation.ExpectedType == ODataPayloadElementType.PrimitiveCollection)
                {
                    return payloadElement.ReplaceWith(new PrimitiveCollection());
                }
            }

            return base.Visit(payloadElement);
        }
예제 #47
0
파일: LinkTests.cs 프로젝트: bubbafat/Hebo
        public void LinkCollectionOperationalTests()
        {
            LinkCollection c = new LinkCollection();
            Link link1 = new Link();

            c.Add(new Link());
            c.Add(link1);
            c.Add(new Link());

            Assert.AreEqual(3, c.Count);

            Assert.IsTrue(c.Contains(link1));
            c.Remove(link1);
            Assert.IsFalse(c.Contains(link1));

            Assert.AreEqual(2, c.Count);

            Link[] linkarray = new Link[2];
            c.CopyTo(linkarray, 0);

            c.Clear();
            Assert.AreEqual(0, c.Count);

            c = new LinkCollection(linkarray);
            Assert.AreEqual(2, c.Count);

            Assert.IsFalse(c.IsReadOnly);

            foreach (Link link in c)
            {
                Assert.IsNotNull(link);
            }

            c[0] = link1;

            Assert.AreSame(link1, c[0]);
        }
예제 #48
0
파일: Entity.cs 프로젝트: bbrandt/seq-api
 protected Entity()
 {
     Links = new LinkCollection();
 }
예제 #49
0
 public MainViewModel(IstarLogic context)
 {
     _context = context;
     if (_context.GetJobs().Count == 0)
     {
         _context.AddNewJob(new Job { Jobdate = DateTime.Today, Jobtitle = "ВНИМАНИЕ! Необходимо обновить базу данных.", Jobtext = "Перед началом работы с программой требуется выполнить скрипт для обновления базы данных.", Ismonthly = true, Iscomplete = false });
     }
     TitleLinks = new LinkCollection();
     SettingsLink = new Link { DisplayName = "Настройки", Source = new Uri("/Shared/Settings.xaml", UriKind.Relative) };
     AboutLink = new Link { DisplayName = "О программе", Source = new Uri("cmd://AboutThis", UriKind.Absolute) };
     SchemaLink = new Link { DisplayName = "Подготовить базу", Source = new Uri("cmd://GoSchema", UriKind.Absolute) };
     ScriptLink = new Link { DisplayName = "Заполнить базу", Source = new Uri("cmd://GoScript", UriKind.Absolute) };
     SoundLink = new Link { DisplayName = "Выключить звук", Source = new Uri("cmd://GoSound", UriKind.Absolute) };
     ExitLink = new Link { DisplayName = "Выход", Source = new Uri("cmd://GoExit", UriKind.Absolute) };
     TitleLinks.Add(SettingsLink);
     TitleLinks.Add(AboutLink);
     if (CanExecuteSchema)
     {
         TitleLinks.Add(SchemaLink);
     }
     else
     {
         if (CanExecuteScript)
         {
             TitleLinks.Add(ScriptLink);
         }
     }
     TitleLinks.Add(SoundLink);
     TitleLinks.Add(ExitLink);
     MainWin = Application.Current.MainWindow;
     MainWin.Closing += (sender, cancelEventArgs) => GoExit();
 }
 /// <summary>
 /// Throws a NotSupportedException as the ODataWriter does not support link collections.
 /// </summary>
 /// <param name="payloadElement">The link collection to process.</param>
 public override void Visit(LinkCollection payloadElement)
 {
     throw new NotSupportedException("A link collection is not supported.");
 }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                    throw new InvalidOperationException("No registrations found");

                var ri = v.Registrations[0];
                var r = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                    throw new InvalidOperationException("No certificates found");

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                    throw new Exception("Unable to find a Certificate for the given reference");

                if (!LocalOnly)
                {
                    if (ci.CertificateRequest == null)
                        throw new Exception("Certificate has not been submitted yet; cannot update status");

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        c.RefreshCertificateRequest(ci.CertificateRequest, UseBaseURI);
                    }

                    if ((Repeat || string.IsNullOrEmpty(ci.CrtPemFile))
                            && !string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        var crtDerAsset = vp.ListAssets(crtDerFile, VaultAssetType.CrtDer).FirstOrDefault();
                        var crtPemAsset = vp.ListAssets(crtPemFile, VaultAssetType.CrtPem).FirstOrDefault();

                        if (crtDerAsset == null)
                            crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        if (crtPemAsset == null)
                            crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                        using (var s = vp.SaveAsset(crtDerAsset))
                        {
                            ci.CertificateRequest.SaveCertificate(s);
                            ci.CrtDerFile = crtDerFile;
                        }

                        using (Stream source = vp.LoadAsset(crtDerAsset), target = vp.SaveAsset(crtPemAsset))
                        {
                            CsrHelper.Crt.ConvertDerToPem(source, target);
                            ci.CrtPemFile = crtPemFile;
                        }

                        var crt = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber = crt.SerialNumber;
                        ci.Thumbprint = crt.Thumbprint;
                        ci.SignatureAlgorithm = crt.SignatureAlgorithm?.FriendlyName;
                        ci.Signature = crt.GetCertHashString();
                    }

                    if (Repeat || string.IsNullOrEmpty(ci.IssuerSerialNumber))
                    {
                        var linksEnum = ci.CertificateRequest.Links;
                        if (linksEnum != null)
                        {
                            var links = new LinkCollection(linksEnum);
                            var upLink = links.GetFirstOrDefault("up");
                            if (upLink != null)
                            {
                                var tmp = Path.GetTempFileName();
                                try
                                {
                                    using (var web = new WebClient())
                                    {
                                        if (v.Proxy != null)
                                            web.Proxy = v.Proxy.GetWebProxy();

                                        var uri = new Uri(new Uri(v.BaseURI), upLink.Uri);
                                        web.DownloadFile(uri, tmp);
                                    }

                                    var cacert = new X509Certificate2(tmp);
                                    var sernum = cacert.GetSerialNumberString();
                                    var tprint = cacert.Thumbprint;
                                    var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                                    var sigval = cacert.GetCertHashString();

                                    if (v.IssuerCertificates == null)
                                        v.IssuerCertificates = new OrderedNameMap<IssuerCertificateInfo>();
                                    if (Repeat || !v.IssuerCertificates.ContainsKey(sernum))
                                    {
                                        var cacertDerFile = $"ca-{sernum}-crt.der";
                                        var cacertPemFile = $"ca-{sernum}-crt.pem";
                                        var issuerDerAsset = vp.ListAssets(cacertDerFile,
                                                VaultAssetType.IssuerDer).FirstOrDefault();
                                        var issuerPemAsset = vp.ListAssets(cacertPemFile,
                                                VaultAssetType.IssuerPem).FirstOrDefault();

                                        if (Repeat || issuerDerAsset == null)
                                        {
                                            if (issuerDerAsset == null)
                                            issuerDerAsset = vp.CreateAsset(VaultAssetType.IssuerDer, cacertDerFile);
                                                using (Stream fs = new FileStream(tmp, FileMode.Open),
                                                    s = vp.SaveAsset(issuerDerAsset))
                                            {
                                                fs.CopyTo(s);
                                            }
                                        }
                                        if (Repeat || issuerPemAsset == null)
                                        {
                                            if (issuerPemAsset == null)
                                                issuerPemAsset = vp.CreateAsset(VaultAssetType.IssuerPem, cacertPemFile);
                                            using (Stream source = vp.LoadAsset(issuerDerAsset),
                                                    target = vp.SaveAsset(issuerPemAsset))
                                            {
                                                CsrHelper.Crt.ConvertDerToPem(source, target);
                                            }
                                        }

                                        v.IssuerCertificates[sernum] = new IssuerCertificateInfo
                                        {
                                            SerialNumber = sernum,
                                            Thumbprint  = tprint,
                                            SignatureAlgorithm = sigalg,
                                            Signature = sigval,
                                            CrtDerFile = cacertDerFile,
                                            CrtPemFile = cacertPemFile,
                                        };
                                    }

                                    ci.IssuerSerialNumber = sernum;
                                }
                                finally
                                {
                                    if (File.Exists(tmp))
                                        File.Delete(tmp);
                                }
                            }
                        }
                    }
                }

                v.Alias = StringHelper.IfNullOrEmpty(Alias);
                v.Label = StringHelper.IfNullOrEmpty(Label);
                v.Memo = StringHelper.IfNullOrEmpty(Memo);

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
예제 #52
0
 /// <summary>
 /// Обновить тайл с информацией об избранных тредах.
 /// </summary>
 /// <param name="favorites">Избранные треды.</param>
 /// <returns>Таск.</returns>
 // ReSharper disable once CSharpWarnings::CS1998
 public async Task UpdateFavoritesTile(LinkCollection favorites)
 {
     var sysInfo = Services.GetServiceOrThrow<ISystemInfo>();
     var linkTransformService = Services.GetServiceOrThrow<ILinkTransformService>();
     var linkHashService = Services.GetServiceOrThrow<ILinkHashService>();
     var dateService = Services.GetServiceOrThrow<IDateService>();
     var favorites2 = favorites as ThreadLinkCollection;
     Tuple<BoardLinkBase, FavoriteThreadInfo>[] updated;
     if (favorites2 == null || favorites2.Links == null || favorites2.ThreadInfo == null)
     {
         updated = new Tuple<BoardLinkBase, FavoriteThreadInfo>[0];
     }
     else
     {
         var links = favorites.Links.WithKeys(linkHashService.GetLinkHash).ToArray();
         updated = links
             .Where(l => favorites2.ThreadInfo.ContainsKey(l.Key))
             .Select(l => new Tuple<BoardLinkBase, FavoriteThreadInfo>(l.Value, favorites2.ThreadInfo[l.Key] as FavoriteThreadInfo))
             .Where(l => l.Item2 != null && IsUpdated(l.Item2))
             .Where(l => l.Item2.CountInfo != null)
             .OrderByDescending(l => l.Item2.CountInfo.LastChange)
             .ToArray();
     }
     var lastUpdate = updated.FirstOrDefault();
     var count = updated.Length;
     ITileNotificationContent notification;
     switch (sysInfo.Platform)
     {
         case AppPlatform.WindowsPhone:
             var n = TileContentFactory.CreateTileWide310x150IconWithBadgeAndText();
             n.ImageIcon.Src = sysInfo.AppIcon;
             n.TextHeading.Text = lastUpdate != null ? linkTransformService.GetLinkDisplayString(lastUpdate.Item1) : null;
             n.TextBody1.Text = lastUpdate != null ? lastUpdate.Item2.Title : null;
             n.TextBody2.Text = lastUpdate != null ? dateService.ToUserString(lastUpdate.Item2.CountInfo.LastChange) : null;
             var n2 = TileContentFactory.CreateTileSquare150x150IconWithBadge();
             n2.ImageIcon.Src = sysInfo.AppIcon;
             n.Square150x150Content = n2;
             var n3 = TileContentFactory.CreateTileSquare71x71IconWithBadge();
             n3.ImageIcon.Src = sysInfo.SmallAppIcon;
             n2.Square71x71Content = n3;
             notification = n;
             break;
         case AppPlatform.Windows:
             var nw = TileContentFactory.CreateTileSquare310x310TextList01();
             nw.Branding = TileBranding.Logo;
             var lastUpdates = updated.Take(3).ToArray();
             for (int i = 0; i < Math.Min(lastUpdates.Length, 3); i++)
             {
                 switch (i)
                 {
                     case 0:
                         nw.TextHeading1.Text = linkTransformService.GetBackLinkDisplayString(lastUpdates[i].Item1);
                         nw.TextBodyGroup1Field1.Text = lastUpdates[i].Item2.Title;
                         nw.TextBodyGroup1Field2.Text = dateService.ToUserString(lastUpdates[i].Item2.CountInfo.LastChange);
                         break;
                     case 1:
                         nw.TextHeading2.Text = linkTransformService.GetBackLinkDisplayString(lastUpdates[i].Item1);
                         nw.TextBodyGroup2Field1.Text = lastUpdates[i].Item2.Title;
                         nw.TextBodyGroup2Field2.Text = dateService.ToUserString(lastUpdates[i].Item2.CountInfo.LastChange);
                         break;
                     case 2:
                         nw.TextHeading3.Text = linkTransformService.GetBackLinkDisplayString(lastUpdates[i].Item1);
                         nw.TextBodyGroup3Field1.Text = lastUpdates[i].Item2.Title;
                         nw.TextBodyGroup3Field2.Text = dateService.ToUserString(lastUpdates[i].Item2.CountInfo.LastChange);
                         break;
                 }
             }
             var nw2 = TileContentFactory.CreateTileWide310x150Text01();
             nw2.Branding = TileBranding.Logo;
             nw2.TextHeading.Text = lastUpdate != null ? linkTransformService.GetLinkDisplayString(lastUpdate.Item1) : null;
             nw2.TextBody1.Text = lastUpdate != null ? lastUpdate.Item2.Title : null;
             nw2.TextBody2.Text = lastUpdate != null ? dateService.ToUserString(lastUpdate.Item2.CountInfo.LastChange) : null;
             nw.Wide310x150Content = nw2;
             var nw3 = TileContentFactory.CreateTileSquare150x150Text01();
             nw3.Branding = TileBranding.Logo;
             nw3.TextHeading.Text = lastUpdate != null ? linkTransformService.GetLinkDisplayString(lastUpdate.Item1) : null;
             nw3.TextBody1.Text = lastUpdate != null ? lastUpdate.Item2.Title : null;
             nw3.TextBody2.Text = lastUpdate != null ? dateService.ToUserString(lastUpdate.Item2.CountInfo.LastChange) : null;
             nw2.Square150x150Content = nw3;
             var nw4 = TileContentFactory.CreateTileSquare71x71Image();
             nw4.Branding = TileBranding.Name;
             nw4.Image.Src = sysInfo.AppIcon;
             nw3.Square71x71Content = nw4;
             notification = nw;
             break;
         default:
             notification = null;
             break;
     }
     if (notification != null)
     {
         var tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
         tileUpdater.Update(notification.CreateNotification());
     }
     var badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
     var badgeContent = new BadgeNumericNotificationContent((uint)count);
     badgeUpdater.Update(badgeContent.CreateNotification());
 }
예제 #53
0
        public static void ConvertLinks()
        {

            string sql = @"

IF EXISTS (SELECT * FROM sysobjects WHERE [type] = N'U' AND [name] = N'bbsMax_Links') BEGIN
    SELECT * FROM bbsMax_Links;
END
ELSE
    SELECT -9999 AS LinkID;
";
            LinkSettings linkSetting = new LinkSettings();
            LinkCollection links = new LinkCollection();

            using (SqlConnection connection = new SqlConnection(Settings.Current.IConnectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sql, connection);
                command.CommandTimeout = 60;
                try
                {
                    bool hasCreateErrorLog = false;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            int linkID = reader.GetInt32(reader.GetOrdinal("LinkID"));

                            if (linkID == -9999)
                                return;

                            Link link = new Link();
                            link.ID = linkID;
                            link.Name = reader.GetString(reader.GetOrdinal("LinkName"));
                            link.Description = reader.GetString(reader.GetOrdinal("LinkDescription"));
                            link.Url = reader.GetString(reader.GetOrdinal("Url"));


                            string imgUrl = reader.GetString(reader.GetOrdinal("LogoUrl")).Replace("\\", "/").Trim();

                            if (imgUrl.StartsWith("http://"))
                                link.ImageUrlSrc = imgUrl;
                            else
                            {
                                int i = imgUrl.LastIndexOf("/") + 1;

                                string iconName = string.Empty;
                                if (imgUrl.Length > i)
                                {
                                    iconName = imgUrl.Substring(i, imgUrl.Length - i);


                                    string targetDir = MaxLabs.bbsMax.UrlUtil.JoinUrl(MaxLabs.bbsMax.Globals.ApplicationPath, "/max-assets/logo-link/");
                                    string targetIconUrl = targetDir + iconName;

                                    imgUrl = MaxLabs.bbsMax.UrlUtil.JoinUrl(MaxLabs.bbsMax.Globals.ApplicationPath, imgUrl);
                                    if (File.Exists(imgUrl))
                                    {
                                        if (File.Exists(targetIconUrl))
                                        {
                                        }
                                        else
                                        {
                                            try
                                            {
                                                if (Directory.Exists(targetDir) == false)
                                                    Directory.CreateDirectory(targetDir);
                                                File.Move(imgUrl, targetIconUrl);
                                            }
                                            catch
                                            {
                                                if (hasCreateErrorLog == false)
                                                {
                                                    hasCreateErrorLog = true;
                                                    ErrorMessages.Add("�ƶ���������ͼ��ʧ��,���ֶ��ѡ�/Images/Logos/��Ŀ¼�µ�����ͼ�긴�Ƶ���/max-assets/logo-link/��Ŀ¼��");
                                                }
                                            }
                                        }
                                    }

                                    link.ImageUrlSrc = "~/max-assets/logo-link/" + iconName;
                                }
                                else
                                    link.ImageUrlSrc = string.Empty;

                            }

                            link.Index = reader.GetInt32(reader.GetOrdinal("SortOrder"));

                            links.Add(link);

                            if (linkSetting.MaxID < link.ID)
                                linkSetting.MaxID = link.LinkID;
                        }
                    }

                    linkSetting.Links = links;

                    sql = @"
UPDATE bx_Settings SET [Value] = @LinkString WHERE TypeName = 'MaxLabs.bbsMax.Settings.LinkSettings' AND [Key] = '*';
IF @@ROWCOUNT = 0
    INSERT INTO bx_Settings ([Key], [Value], [TypeName]) VALUES ('*', @LinkString, 'MaxLabs.bbsMax.Settings.LinkSettings');


DROP TABLE bbsMax_Links;
";
                    command.CommandText = sql;

                    SqlParameter param = new SqlParameter("@LinkString", SqlDbType.NText);
                    param.Value = linkSetting.ToString();
                    command.Parameters.Add(param);

                    command.ExecuteNonQuery();


                }
                catch (Exception ex)
                {
                    CreateLog(ex);
                    throw new Exception("����������������ʧ��" + ex.Message + sql);
                }
                finally
                {
                    connection.Close();
                }
            }
        }
            /// <summary>
            /// Visits a payload element whose root is a LinkCollection.
            /// </summary>
            /// <param name="payloadElement">The root node of payload element being visited.</param>
            public void Visit(LinkCollection payloadElement)
            {
                this.isRootElement = false;
                this.writer.StartArrayScope();
                for (int i = 0; i < payloadElement.Count(); i++)
                {
                    payloadElement[i].Accept(this);
                }

                this.writer.EndScope();
            }
예제 #55
0
파일: TFWI.DBI.cs 프로젝트: hopenbr/HopDev
        private bool DoesLinkCollectionsContainBBI(LinkCollection _links)
        {
            bool _foundIt = false;
            foreach (Link _ln in _links)
            {
                if (_ln.ArtifactLinkType.Name.Contains("Related"))
                {
                    RelatedLink _rl = (RelatedLink)_ln;
                    WorkItem _rwi = GetWorkItem(_rl.RelatedWorkItemId);
                    if (_rwi.Type.Name.Equals("Build Backlog Item", StringComparison.CurrentCultureIgnoreCase))
                    {
                        _foundIt = true;
                    }
                }

            }

            return _foundIt;
        }
예제 #56
0
        public static string GetIssuerCertificate(CertificateRequest certificate, CertificateProvider cp)
        {
            var linksEnum = certificate.Links;
            if (linksEnum != null)
            {
                var links = new LinkCollection(linksEnum);
                var upLink = links.GetFirstOrDefault("up");
                if (upLink != null)
                {
                    var tmp = Path.GetTempFileName();
                    try
                    {
                        using (var web = new WebClient())
                        {

                            var uri = new Uri(new Uri(BaseURI), upLink.Uri);
                            web.DownloadFile(uri, tmp);
                        }

                        var cacert = new X509Certificate2(tmp);
                        var sernum = cacert.GetSerialNumberString();
                        var tprint = cacert.Thumbprint;
                        var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                        var sigval = cacert.GetCertHashString();

                        var cacertDerFile = Path.Combine(certificatePath, $"ca-{sernum}-crt.der");
                        var cacertPemFile = Path.Combine(certificatePath, $"ca-{sernum}-crt.pem");

                        if (!File.Exists(cacertDerFile))
                            File.Copy(tmp, cacertDerFile, true);

                        Console.WriteLine($" Saving Issuer Certificate to {cacertPemFile}");
                        Log.Information("Saving Issuer Certificate to {cacertPemFile}", cacertPemFile);
                        if (!File.Exists(cacertPemFile))
                            using (FileStream source = new FileStream(cacertDerFile, FileMode.Open),
                                    target = new FileStream(cacertPemFile, FileMode.Create))
                            {
                                var caCrt = cp.ImportCertificate(EncodingFormat.DER, source);
                                cp.ExportCertificate(caCrt, EncodingFormat.PEM, target);
                            }

                        return cacertPemFile;
                    }
                    finally
                    {
                        if (File.Exists(tmp))
                            File.Delete(tmp);
                    }
                }
            }

            return null;
        }
예제 #57
0
            public AcmeHttpResponse(HttpWebResponse resp)
            {
                StatusCode = resp.StatusCode;
                Headers = resp.Headers;
                Links = new LinkCollection(Headers.GetValues(AcmeProtocol.HEADER_LINK));

                var rs = resp.GetResponseStream();
                using (var ms = new MemoryStream())
                {
                    rs.CopyTo(ms);
                    RawContent = ms.ToArray();
                }
            }
        private IEnumerable<NavigationPropertyInstance> DeserializeNavigationProperties(IEnumerable<XElement> links)
        {
            // get the links and convert them into navigation properties
            ILookup<string, XElement> linksByName = links
                .Select(link => link.Attribute(Rel))
                .Where(rel => rel != null)
                .Where(rel => rel.Value.StartsWith(ODataConstants.DataServicesRelatedNamespaceName, StringComparison.OrdinalIgnoreCase))
                .ToLookup(
                    rel => rel.Value.Substring(ODataConstants.DataServicesRelatedNamespaceName.Length),
                    rel => rel.Parent);

            List<NavigationPropertyInstance> results = new List<NavigationPropertyInstance>(linksByName.Count);
            foreach (var group in linksByName)
            {
                NavigationPropertyInstance navProp = new NavigationPropertyInstance();
                navProp.Name = group.Key;
                List<XElement> elements = group.ToList();

                if (elements.Count > 1)
                {
                    LinkCollection collection = new LinkCollection();
                    foreach (XElement link in elements)
                    {
                        ODataPayloadElement linkValue = this.DeserializeLink(link);
                        ExceptionUtilities.Assert(
                            linkValue.ElementType == ODataPayloadElementType.DeferredLink,
                            "Navigation property '" + group.Key + "' had multiple <link> elements which were not all deferred");

                        collection.Add(linkValue);
                    }

                    navProp.Value = collection;
                }
                else
                {
                    // Note: it is possible in cases where we are parsing an update payload, that this was really a collection of size one
                    // however, we cannot possibly detect this case here, so we will have to deal with it elsewhere should it arise
                    navProp.Value = this.DeserializeLink(elements[0]);
                }

                results.Add(navProp);
            }

            return results;
        }
        /// <summary>
        /// Deserializes a collection of links
        /// </summary>
        /// <param name="links">Xml element representing the links collection</param>
        /// <returns>Deserialized link collection</returns>
        private LinkCollection DeserializeLinks(XElement links)
        {
            LinkCollection collection = new LinkCollection();

            AddXmlBaseAnnotation(collection, links);

            // read the count, if present
            XElement count = links.Element(MetadataCount);
            if (count != null)
            {
                collection.InlineCount = long.Parse(count.Value, CultureInfo.InvariantCulture);
            }

            // read the next-link if present
            XElement nextLink = links.Element(DataServicesNext);
            if (nextLink != null)
            {
                collection.NextLink = nextLink.Value;
            }

            // deserialize each element as a link and add it to the collection
            foreach (var link in links.Elements(MetadataUri))
            {
                collection.Add(this.DeserializeLink(link));
            }

            return collection;
        }
예제 #60
0
        public bool SaveSettings()
        {
            MessageDisplay msgDisplay = CreateMessageDisplay("url", "name");
            int rowindex = 0;
            int[] linkids = StringUtil.Split<int>(_Request.Get("linkids", Method.Post));

            LinkSettings settings = SettingManager.CloneSetttings<LinkSettings>(AllSettings.Current.LinkSettings);

            LinkCollection links = new LinkCollection();
            
            Link temp;
            foreach (int id in linkids)
            {
                temp = new Link();
                temp.LinkID = id;
                temp.Url = _Request.Get("url." + id, Method.Post);
                temp.Name = _Request.Get("name." + id, Method.Post);
                temp.ImageUrlSrc = _Request.Get("imageurl." + id, Method.Post);
                temp.Description = _Request.Get("description." + id, Method.Post);
                temp.Index = _Request.Get<int>("index." + id, Method.Post, 0);
                temp.IsNew = _Request.Get<bool>("isnew." + id, Method.Post, false);
                ValidateLink(temp, msgDisplay, rowindex);
                rowindex++;
                links.Add(temp);
            }

            ///客户端无脚本
            if (_Request.Get("newlinkid", Method.Post) != null
                && _Request.Get("newlinkid").Contains("{0}"))
            {
                temp = settings.CreateLink();
                temp.Url = _Request.Get("url.new.{0}", Method.Post);
                temp.Name = _Request.Get("name.new.{0}", Method.Post);
                temp.ImageUrlSrc = _Request.Get("imageurl.new.{0}", Method.Post);
                temp.Description = _Request.Get("description.new.{0}", Method.Post);
                temp.Index = _Request.Get<int>("index.new.{0}", Method.Post, 0);
                rowindex++;
                if (!string.IsNullOrEmpty(temp.Name) && !string.IsNullOrEmpty(temp.Url)) links.Add(temp);
            }
            else
            {
                int[] newLinkArray = StringUtil.Split<int>(_Request.Get("newlinkid", Method.Post));
                foreach (int id in newLinkArray)
                {
                    temp = settings.CreateLink();
                    temp.IsNew = true;
                    temp.Url = _Request.Get("url.new." + id, Method.Post);
                    temp.Name = _Request.Get("name.new." + id, Method.Post);
                    temp.ImageUrlSrc = _Request.Get("imageurl.new." + id, Method.Post);
                    temp.Description = _Request.Get("description.new." + id, Method.Post);
                    temp.Index = _Request.Get<int>("index.new." + id, Method.Post, 0);
                    ValidateLink(temp, msgDisplay, rowindex);
                    rowindex++;
                    links.Add(temp);
                }
            }

            if (msgDisplay.HasAnyError())
            {
                msgDisplay.AddError(new DataNoSaveError());
                m_LinkList = links;
            }
            else
            {
                foreach (Link l in links) { l.IsNew = false; }

                settings.Links = links;

                SettingManager.SaveSettings(settings);
                m_LinkList = null;
            }
            return true;
        }