コード例 #1
0
 protected override void BecauseOf()
 {
     m_result = new HostInfo(
         m_networkAdapterId,
         new HostName("my-host-name"),
         IPAddress.Parse("4.3.2.1"));
 }
コード例 #2
0
        public static void SendMessage(byte[] data, HostInfo hostInfo, IMessageSerializer messageSerializer)
        {
            //IPHostEntry hostEntry = Dns.GetHostEntry(hostInfo.Hostname);
            //IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], hostInfo.Port);

            //Socket s = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
            //s.SendTo(data, endPoint);
            //s.Close();

            short netProtocolType = IPAddress.HostToNetworkOrder(messageSerializer.ProtocolType);
            short netProtocolVersion = IPAddress.HostToNetworkOrder(messageSerializer.ProtocolVersion);
            int netMessageLength = IPAddress.HostToNetworkOrder(data.Length);

            byte[] netProtocolTypeData = BitConverter.GetBytes(netProtocolType);
            byte[] netProtocolVersionData = BitConverter.GetBytes(netProtocolVersion);
            byte[] netMessageLengthData = BitConverter.GetBytes(netMessageLength);

            byte[] mergedData = new byte[netProtocolTypeData.Length + netProtocolVersionData.Length + netMessageLengthData.Length + data.Length];

            // Header
            Array.Copy(netProtocolTypeData, 0, mergedData, 0, netProtocolTypeData.Length);
            Array.Copy(netProtocolVersionData, 0, mergedData, netProtocolTypeData.Length, netProtocolVersionData.Length);
            Array.Copy(netMessageLengthData, 0, mergedData, netProtocolTypeData.Length + netProtocolVersionData.Length, netMessageLengthData.Length);
            // Data
            Array.Copy(data, 0, mergedData, netProtocolTypeData.Length + netProtocolVersionData.Length + netMessageLengthData.Length, data.Length);

            UdpClient client = new UdpClient();
            client.Send(mergedData, mergedData.Length, hostInfo.Hostname, hostInfo.Port);
            client.Close();
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: WinHuStudio/iTrip
        static void Main(string[] args)
        {
            MongoDBRepository.RegisterMongoDBContext(new TripperCenterDBContext());
            MongoDBRepository.RegisterMongoDBContext(new DeliveryCenterDBContext());
            MongoDBRepository.RegisterMongoDBContext(new StatusCenterDBContext());
            MongoDBRepository.RegisterMongoDBContext(new RelationCenterDBContext());
            MongoDBRepository.RegisterMongoIndex();

            var ass = WinAssemblyUtility.GetAssembly();
            HostInfo host = new HostInfo(ConfigurationManager.AppSettings["WcfHostAddress"]).LoadTypesFromAssemblies(ass);
            using (ServiceContainer container = new ServiceContainer())
            {
                container.Open(host);
                Console.WriteLine("press close to stop host");

                while (true)
                {
                    if ("close" == Console.ReadLine().ToLower())
                    {
                        container.Close(host);
                        break;
                    }
                }
                Console.WriteLine("press 'Enter' to quit");
                Console.ReadKey();
            }
        }
コード例 #4
0
 public ActivityLogImpl(HostInfo host, Guid executionId, string name, DateTime timestamp, TimeSpan duration)
 {
     ExecutionId = executionId;
     Name = name;
     Timestamp = timestamp;
     Duration = duration;
     Host = host;
 }
コード例 #5
0
        protected RoutingSlipEventDocument(DateTime timestamp, TimeSpan duration, HostInfo host = null)
        {
            Timestamp = timestamp;
            Duration = duration;

            if (host != null)
                Host = new HostDocument(host);
        }
コード例 #6
0
 public Result(Guid probeId, Guid resultId, DateTime startTimestamp, TimeSpan duration, HostInfo host, IDictionary<string, object> results)
 {
     ProbeId = probeId;
     ResultId = resultId;
     StartTimestamp = startTimestamp;
     Duration = duration;
     Host = host;
     Results = results;
 }
コード例 #7
0
        public ProbeResultBuilder(Guid probeId, CancellationToken cancellationToken)
            : base(cancellationToken)
        {
            _probeId = probeId;

            _resultId = NewId.NextGuid();
            _startTimestamp = DateTime.UtcNow;
            _host = HostMetadataCache.Host;
        }
コード例 #8
0
ファイル: HostDocument.cs プロジェクト: phatboyg/MassTransit
 public HostDocument(HostInfo host)
 {
     MachineName = host.MachineName;
     ProcessId = host.ProcessId;
     ProcessName = host.ProcessName;
     Assembly = host.Assembly;
     AssemblyVersion = host.AssemblyVersion;
     MassTransitVersion = host.MassTransitVersion;
     FrameworkVersion = host.FrameworkVersion;
     OperatingSystemVersion = host.OperatingSystemVersion;
 }
コード例 #9
0
ファイル: AggDefault.aspx.cs プロジェクト: euvin3582/Subtext
 protected override void OnInit(EventArgs e)
 {
     foreach (string controlName in _controls)
     {
         var     skin = HostInfo.GetAggregateSkin();
         var     skinControlLoader = new SkinControlLoader(this, skin);
         Control control           = skinControlLoader.LoadControl(controlName);
         CenterBodyControl.Controls.Add(control);
     }
     base.OnInit(e);
 }
コード例 #10
0
        private void StartReading(HostInfo hostInfo)
        {
            // Initialize comunication
            CreateAndConnect(hostInfo);


            // Start receiving
            ReadContext readContext = new ReadContext(4 * 1024, this.connectionVersion);

            ReadStream.BeginRead(readContext.Data, 0, readContext.Data.Length, new AsyncCallback(ReadCallback), readContext);
        }
コード例 #11
0
        public ActivityExceptionImpl(string activityName, HostInfo host, Guid executionId, DateTime timestamp, TimeSpan elapsed,
            ExceptionInfo exceptionInfo)
        {
            ExecutionId = executionId;

            Timestamp = timestamp;
            Elapsed = elapsed;
            Name = activityName;
            Host = host;
            ExceptionInfo = exceptionInfo;
        }
コード例 #12
0
        internal HostInfo CreateHostInfo(string hostName)
        {
            if (!string.IsNullOrWhiteSpace(hostName))
            {
                var hostInfo = new HostInfo {
                    HostEntry = hostName
                };
                return(hostInfo);
            }

            return(null);
        }
コード例 #13
0
        public void CanLoadHost()
        {
            SqlHelper.ExecuteNonQuery(Config.ConnectionString, CommandType.Text, "DELETE subtext_Host");

            HostInfo.LoadHost(false);

            Assert.IsNull(HostInfo.Instance, "HostInfo should be Null");

            HostInfo.CreateHost("test", "test", "*****@*****.**");

            Assert.IsNotNull(HostInfo.Instance, "Host should not be null.");
        }
コード例 #14
0
ファイル: AggDefault.aspx.cs プロジェクト: euvin3582/Subtext
        private void SetStyle()
        {
            const string style   = "<link href=\"{0}{1}\" type=\"text/css\" rel=\"stylesheet\">";
            string       apppath = HttpContext.Current.Request.ApplicationPath.EndsWith("/")
                                 ? HttpContext.Current.Request.ApplicationPath
                                 : HttpContext.Current.Request.ApplicationPath + "/";
            //TODO: This is hard-coded to look in the simple skin for aggregate blogs. We should change this later.
            string aggregateSkin = HostInfo.GetAggregateSkin().TemplateFolder;

            Style.Text = string.Format(style, apppath, "Skins/" + aggregateSkin + "/Style.css") + Environment.NewLine +
                         string.Format(style, apppath, "css/lightbox.css");
        }
コード例 #15
0
        public async Task <HostInfo> ResolveIpAsync(HostInfo hostInfo)
        {
            var uri = new Uri(hostInfo.Url);
            var res = await Dns.GetHostAddressesAsync(uri.Host);

            if (res.Any())
            {
                hostInfo.Ip = res.Select(x => x.ToString());
            }

            return(hostInfo);
        }
コード例 #16
0
 void m_host_Closing(object sender, EventArgs e)
 {
     if (this._host != null)
     {
         HostInfo info = _host.Extensions.Find <HostInfo>();
         if (info != null)
         {
             _host.Extensions.Remove(info);
             info.Dispose();
         }
     }
 }
コード例 #17
0
        public FaultEvent(T message, Guid?faultedMessageId, HostInfo host, IEnumerable <ExceptionInfo> exceptions, string[] faultMessageTypes)
        {
            Timestamp = DateTime.UtcNow;
            FaultId   = NewId.NextGuid();

            Message           = message;
            Host              = host;
            FaultMessageTypes = faultMessageTypes;
            FaultedMessageId  = faultedMessageId;

            Exceptions = exceptions.ToArray();
        }
コード例 #18
0
        public TestSceneMatchHostInfo()
        {
            HostInfo hostInfo;

            Child = hostInfo = new HostInfo
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre
            };

            hostInfo.Host.BindTo(host);
        }
コード例 #19
0
        public override bool IsApplicable()
        {
            // confing key to work around MES installation requirement
            HostInfo hostInfo = new HostInfo();

            if (hostInfo.InstalledApplications.AvailableSoft.
                Contains(SupportedSoftware.MultiEcuScan))
            {
                return(true);
            }
            return(false);
        }
コード例 #20
0
        internal void DistributedService
        (
            [Description("Cache name")] string cacheName,
            [Description("Cache root path")] string cachePath,
            [DefaultValue(ServiceConfiguration.GrpcDisabledPort), Description(GrpcPortDescription)] int grpcPort,
            [Description("Name of the memory mapped file used to share GRPC port. 'CASaaS GRPC port' if not specified.")] string grpcPortFileName,
            [DefaultValue(null), Description("Writable directory for service operations (use CWD if null)")] string dataRootPath,
            [DefaultValue(null), Description("Identifier for the stamp this service will run as")] string stampId,
            [DefaultValue(null), Description("Identifier for the ring this service will run as")] string ringId,
            [DefaultValue(Constants.OneMB), Description("Max size quota in MB")] int maxSizeQuotaMB,
            [DefaultValue(false), Description("Whether or not GRPC is used for file copies")] bool useDistributedGrpc,
            [DefaultValue(false), Description("Whether or not GZip is used for GRPC file copies")] bool useCompressionForCopies,
            [DefaultValue(null), Description("Buffer size for streaming GRPC copies")] int?bufferSizeForGrpcCopies
        )
        {
            Initialize();

            try
            {
                var cancellationTokenSource = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, args) =>
                {
                    cancellationTokenSource.Cancel();
                };

                var host = new HostInfo(stampId, ringId, new List <string>());

                if (grpcPort == 0)
                {
                    grpcPort = Helpers.GetGrpcPortFromFile(_logger, grpcPortFileName);
                }

                var arguments = CreateDistributedCacheServiceArguments(
                    copier: useDistributedGrpc ? new GrpcFileCopier(new Interfaces.Tracing.Context(_logger), grpcPort, useCompressionForCopies) : (IAbsolutePathFileCopier) new DistributedCopier(),
                    pathTransformer: useDistributedGrpc ? new GrpcDistributedPathTransformer() : (IAbsolutePathTransformer) new DistributedPathTransformer(),
                    host: host,
                    cacheName: cacheName,
                    cacheRootPath: cachePath,
                    grpcPort: (uint)grpcPort,
                    maxSizeQuotaMB: maxSizeQuotaMB,
                    dataRootPath: dataRootPath,
                    ct: cancellationTokenSource.Token,
                    bufferSizeForGrpcCopies: bufferSizeForGrpcCopies);

                DistributedCacheServiceFacade.RunAsync(arguments).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
コード例 #21
0
ファイル: MainWindow.xaml.cs プロジェクト: mylovsz/NPN
 void bwRealData_DoWork(object sender, DoWorkEventArgs e)
 {
     //throw new NotImplementedException();
     while (true)
     {
         if (bwRealData.CancellationPending)
         {
             break;
         }
         if (!bwLoadData.IsBusy)
         {
             // 请求最新的数据
             this.Dispatcher.Invoke((Action)(() =>
             {
                 ShowState("更新后台数据中...");
             }));
             Thread.Sleep(1000);
             List <HostInfo> list = new HostInfoBLL().GetModelByPrjGUID(appState.CurrentUserInfo.ProjectGUID);
             if (list != null && list.Count > 0)
             {
                 LightInfoBLL liBLL = new LightInfoBLL();
                 foreach (HostInfo hi in list)
                 {
                     HostInfo h = appState.TreeDatas.ListHostInfo.FirstOrDefault(a => a.GUID == hi.GUID);
                     if (h != null)
                     {
                         h.Online = hi.Online;
                     }
                     // 更新单灯
                     List <LightInfo> listLI = liBLL.GetModelByHost(h);
                     if (listLI != null && listLI.Count > 0)
                     {
                         foreach (LightInfo li in listLI)
                         {
                             LightInfo l = appState.TreeDatas.ListLightInfo.FirstOrDefault(b => b.GUID == li.GUID);
                             if (l != null)
                             {
                                 l.LightStateInfo = li.LightStateInfo;
                                 //Debug.WriteLine(l.LightStateInfo.ToString());
                             }
                         }
                     }
                 }
             }
             this.Dispatcher.Invoke((Action)(() =>
             {
                 ShowState("更新后台数据成功");
             }));
         }
         Thread.Sleep(10000);
     }
 }
コード例 #22
0
            public HostInfo GetNext()
            {
                HostInfo result = new HostInfo(this.delaySetting, this.logger);

                [email protected]();

                result.count    = this.Count + 1;
                result.lastCall = this.lastCall;

                [email protected]();

                return(result);
            }
コード例 #23
0
        public void HeartbeatFailDisconnect()
        {
            Disconn_Click(null, null);
            try
            {
                HostInfoLabel.Invoke((MethodInvoker) delegate { HostInfoLabel.Text = "Lost connection to host!"; });
                ServerInfoBox.Invoke((MethodInvoker) delegate { ServerInfoBox.Text = "Lost connection to host!"; });
            }
            catch (InvalidOperationException) { }

            selectedServer = null;
            connectedHost  = null;
        }
コード例 #24
0
        public RoutingSlipTerminatedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid executionId, DateTime timestamp, TimeSpan duration,
                                            IDictionary <string, object> variables, IEnumerable <Activity> discardedItinerary)
        {
            Host      = host;
            Duration  = duration;
            Timestamp = timestamp;

            TrackingNumber     = trackingNumber;
            ActivityName       = activityName;
            Variables          = variables;
            DiscardedItinerary = discardedItinerary.ToArray();
            ExecutionId        = executionId;
        }
コード例 #25
0
        public RoutingSlipActivityCompensatedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid activityTrackingNumber,
                                                     DateTime timestamp, TimeSpan duration, IDictionary <string, object> variables, IDictionary <string, object> data)
        {
            Host      = host;
            Duration  = duration;
            Timestamp = timestamp;

            TrackingNumber         = trackingNumber;
            ActivityTrackingNumber = activityTrackingNumber;
            ActivityName           = activityName;
            Data      = data;
            Variables = variables;
        }
コード例 #26
0
        public ReceiveFaultEvent(HostInfo host, Exception exception, string contentType, Guid? faultedMessageId)
        {
            Timestamp = DateTime.UtcNow;
            FaultId = NewId.NextGuid();

            Host = host;
            ContentType = contentType;
            FaultedMessageId = faultedMessageId;

            var aggregateException = exception as AggregateException;
            Exceptions = aggregateException?.InnerExceptions.Select(x => ((ExceptionInfo)new FaultExceptionInfo(x))).ToArray()
                ?? new ExceptionInfo[] {new FaultExceptionInfo(exception)};
        }
コード例 #27
0
ファイル: FaultEvent.cs プロジェクト: jacobpovar/MassTransit
        public FaultEvent(T message, HostInfo host, Exception exception)
        {
            Timestamp = DateTime.UtcNow;
            FaultId   = NewId.NextGuid();

            Message = message;
            Host    = host;

            var aggregateException = exception as AggregateException;

            Exceptions = aggregateException?.InnerExceptions.Select(x => ((ExceptionInfo) new FaultExceptionInfo(x))).ToArray()
                         ?? new ExceptionInfo[] { new FaultExceptionInfo(exception) };
        }
コード例 #28
0
        public RoutingSlipTerminatedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid executionId, DateTime timestamp, TimeSpan duration,
            IDictionary<string, object> variables, IEnumerable<Activity> discardedItinerary)
        {
            Host = host;
            Duration = duration;
            Timestamp = timestamp;

            TrackingNumber = trackingNumber;
            ActivityName = activityName;
            Variables = variables;
            DiscardedItinerary = discardedItinerary.ToArray();
            ExecutionId = executionId;
        }
コード例 #29
0
        public async Task PauseIfNecessary(string host, CancellationToken token)
        {
            DateTime enterTime      = DateTime.Now;
            string   firstLevelHost = string.Join('.', host.Split('.').Reverse().Take(2).Reverse());

            HostInfo currentHost = hostsInfos.AddOrUpdate(
                firstLevelHost,
                new HostInfo(this.delaySetting, this.Logger),
                (s, info) => info.GetNext()
                );

            await currentHost.Delay(enterTime, token).ConfigureAwait(false);
        }
コード例 #30
0
        public MockServiceProvider(MockServiceProviderOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            m_settingsPropertyStore = options.SettingsPropertyStore;
            m_hostInfo        = options.HostInfo;
            m_connectionInfo  = options.ConnectionInfo;
            m_dhcpInfo        = options.DhcpInfo;
            m_externalAddress = options.ExternalAddress;
        }
コード例 #31
0
        public RoutingSlipActivityCompensatedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid executionId,
            DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, IDictionary<string, object> data)
        {
            Host = host;
            Duration = duration;
            Timestamp = timestamp;

            TrackingNumber = trackingNumber;
            ExecutionId = executionId;
            ActivityName = activityName;
            Data = data;
            Variables = variables;
        }
コード例 #32
0
        public static void RemovePrivateKey(HostInfo host)
        {
            List <PrivateKey> values;

            if (_keysCache.TryGetValue(host, out values))
            {
                foreach (var key in values)
                {
                    key.Dispose();
                }
                _keysCache.Remove(host);
            }
        }
コード例 #33
0
        public async Task AnalyzeTreeHostReturnSuccessTwo()
        {
            // arrange
            var goodHost1 = new HostInfo()
            {
                Url = "https://rambler.ru"
            };
            var goodHost2 = new HostInfo()
            {
                Url = "https://goodhost.ru"
            };
            var badHost = new HostInfo()
            {
                Url = "https://badhost.rrr"
            };
            var data = new List <HostInfo>()
            {
                goodHost1, goodHost2, badHost
            };

            var moqWriter = new Mock <IHostInfoWriter>();
            var moqLogger = new Mock <ILoggerFacade>();

            var moqReader = new Mock <IHostInfoReader>();

            moqReader
            .Setup(x => x.ReadAsync())
            .Returns(Task.FromResult(data));

            var moqResolver = new Mock <IIpResolver>();

            moqResolver
            .Setup(x => x.ResolveIpAsync(goodHost1))
            .Returns(Task.FromResult(goodHost1));
            moqResolver
            .Setup(x => x.ResolveIpAsync(goodHost2))
            .Returns(Task.FromResult(goodHost2));
            moqResolver
            .Setup(x => x.ResolveIpAsync(badHost))
            .ThrowsAsync(new SocketException());

            var service = new HostInfoService(moqReader.Object, moqWriter.Object, moqResolver.Object, moqLogger.Object);

            // act
            var res = await service.AnalyzeHostsAsync();

            // assert
            Assert.Equal(3, res.HostsCount);
            Assert.Equal(2, res.SuccessAnalyzedHostCount);
            Assert.True(res.HostInfoSuccessSaved);
        }
コード例 #34
0
ファイル: Host.cs プロジェクト: zhangandding/dp2
        void CloseHosts()
        {
            StringBuilder debugInfo = new StringBuilder();

            debugInfo.AppendFormat("{0}开始停止 {1} 个 host\r\n", GetTime(), this.m_hosts.Count);

            List <Task>     tasks = new List <Task>();
            List <HostInfo> infos = new List <HostInfo>();

            {
                foreach (ServiceHost host in this.m_hosts)
                {
                    HostInfo info = host.Extensions.Find <HostInfo>();
                    if (info != null)
                    {
                        infos.Add(info);
                        host.Extensions.Remove(info);
                    }
                    tasks.Add(Task.Factory.FromAsync(host.BeginClose, host.EndClose, null));

                    //debugInfo.AppendFormat("{0} 开始停止 host {1}\r\n", GetTime(), host.GetHashCode());
                    //host.Close();
                    //debugInfo.AppendFormat("{0} 完成停止 host {1}\r\n", GetTime(), host.GetHashCode());
                }

                this.m_hosts.Clear();
            }

            // 用多线程集中 Dispose()
            if (infos.Count > 0)
            {
                //debugInfo.AppendFormat("{0} 开始停止 {1} 个 Application\r\n", GetTime(), infos.Count);
                foreach (HostInfo info in infos)
                {
                    Task.Run(() => info.Dispose());
                }
                //debugInfo.AppendFormat("{0} 完成停止 {1} 个 Application\r\n", GetTime(), infos.Count);
            }

            int timeout = 10000;

            while (!Task.WaitAll(tasks.ToArray(), timeout))
            {
                RequestAdditionalTime(timeout);
            }

            debugInfo.AppendFormat("{0}完成停止 hosts\r\n", GetTime());

            this.Log.WriteEntry("dp2Kernel CloseHosts() debugInfo: \r\n" + debugInfo.ToString(),
                                EventLogEntryType.Information);
        }
コード例 #35
0
ファイル: DocsClient.cs プロジェクト: AleXr64/DBSizeChecker
        /// <summary>
        ///     Prepare data and write to sheet
        /// </summary>
        /// <param name="info"></param>
        private void MakeNewData(HostInfo info)
        {
            var freeSpace = info.TotalSpace;

            PrepareSheet(info.HostID);
            var data = new ValueRange();

            data.Range = $"{info.HostID}!A:D";

            data.Values = new List <IList <object> >();

            //header
            var head = new List <object>();

            head.AddRange(new[] { "Сервер", "База данных", "Размер в GB", "Дата обновления" });
            data.Values.Add(head);

            //Database stats records
            foreach (var infoDataBase in info.DataBases)
            {
                freeSpace = freeSpace - infoDataBase.SizeOnDiskInGB;

                var row = new List <object>();
                row.Add(info.HostID);
                row.Add(infoDataBase.DBName);
                row.Add(infoDataBase.SizeOnDiskInGB);
                row.Add(DateTime.Today.ToString("dd.MM.yyyy",
                                                CultureInfo.InvariantCulture));
                data.Values.Add(row);
            }

            data.Values.Add(new List <object>()); //spacer

            //"total space left" report
            var sizeReport = new List <object>();

            sizeReport.AddRange(new[]
            {
                info.HostID, "Свободно", Math.Round(freeSpace, 3).ToString(),
                DateTime.Today.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)
            });

            data.Values.Add(sizeReport);

            // Add data to sheet
            var appendRequest = _sheets.Spreadsheets.Values.Append(data, _ownSpreadsheetId, data.Range);

            appendRequest.ValueInputOption =
                SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
            var appendReponse = appendRequest.Execute();
        }
コード例 #36
0
 internal ServerRunspacePoolDriver(
     Guid clientRunspacePoolId,
     int minRunspaces,
     int maxRunspaces,
     PSThreadOptions threadOptions,
     ApartmentState apartmentState,
     HostInfo hostInfo,
     InitialSessionState initialSessionState,
     PSPrimitiveDictionary applicationPrivateData,
     ConfigurationDataFromXML configData,
     AbstractServerSessionTransportManager transportManager,
     bool isAdministrator,
     RemoteSessionCapability serverCapability)
 {
     using (ServerRunspacePoolDriver.tracer.TraceConstructor((object)this))
     {
         this.serverCapability = serverCapability;
         ServerRemoteHost serverRemoteHost = new ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, (AbstractServerTransportManager)transportManager);
         this.remoteHost             = serverRemoteHost;
         this.configData             = configData;
         this.applicationPrivateData = applicationPrivateData;
         this.localRunspacePool      = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, (PSHost)serverRemoteHost);
         PSThreadOptions psThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread;
         if (threadOptions == PSThreadOptions.Default || threadOptions == psThreadOptions)
         {
             this.localRunspacePool.ThreadOptions = psThreadOptions;
         }
         else
         {
             if (!isAdministrator)
             {
                 throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.MustBeAdminToOverrideThreadOptions));
             }
             this.localRunspacePool.ThreadOptions = threadOptions;
         }
         ApartmentState apartmentState1 = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown;
         this.localRunspacePool.ApartmentState = apartmentState == ApartmentState.Unknown || apartmentState == apartmentState1 ? apartmentState1 : apartmentState;
         this.clientRunspacePoolId             = clientRunspacePoolId;
         this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager);
         this.localRunspacePool.StateChanged          += new EventHandler <RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged);
         this.localRunspacePool.ForwardEvent          += new EventHandler <PSEventArgs>(this.HandleRunspacePoolForwardEvent);
         this.localRunspacePool.RunspaceCreated       += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreated);
         this.localRunspacePool.RunspaceCreated       += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable);
         this.dsHandler.CreateAndInvokePowerShell     += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleCreateAndInvokePowerShell);
         this.dsHandler.GetCommandMetadata            += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleGetCommandMetadata);
         this.dsHandler.HostResponseReceived          += new EventHandler <RemoteDataEventArgs <RemoteHostResponse> >(this.HandleHostResponseReceived);
         this.dsHandler.SetMaxRunspacesReceived       += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMaxRunspacesReceived);
         this.dsHandler.SetMinRunspacesReceived       += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMinRunspacesReceived);
         this.dsHandler.GetAvailableRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleGetAvailalbeRunspacesReceived);
     }
 }
コード例 #37
0
ファイル: InterSettingDlg.xaml.cs プロジェクト: mylovsz/NPN
        public InterSettingDlg(string title, HostInfo hi)
            : this()
        {
            this.Title = title;
            hostInfo   = hi;
            DateTime dtNow = DateTime.Now;

            hsStart = hsBLL.GetAllByHostGUIDKey(hi.GUID, "IntervalStart");
            if (hsStart == null)
            {
                hsStart            = new HostSet();
                hsStart.GUID       = Guid.NewGuid().ToString();
                hsStart.Key        = "IntervalStart";
                hsStart.Value      = "1";
                hsStart.Desc       = "区间开始节点";
                hsStart.HostGUID   = hi.GUID;
                hsStart.CreateDate = dtNow;
                hsStart.UpdateDate = dtNow;
                hsBLL.Add(hsStart);
            }
            txtStart.Text = hsStart.Value;
            hsLen         = hsBLL.GetAllByHostGUIDKey(hi.GUID, "IntervalLen");
            if (hsLen == null)
            {
                hsLen            = new HostSet();
                hsLen.GUID       = Guid.NewGuid().ToString();
                hsLen.Key        = "IntervalLen";
                hsLen.Value      = "1";
                hsLen.Desc       = "每个区间长度";
                hsLen.HostGUID   = hi.GUID;
                hsLen.CreateDate = dtNow;
                hsLen.UpdateDate = dtNow;
                hsBLL.Add(hsLen);
            }
            txtLen.Text = hsLen.Value;
            hsCount     = hsBLL.GetAllByHostGUIDKey(hi.GUID, "IntervalCount");
            if (hsCount == null)
            {
                hsCount            = new HostSet();
                hsCount.GUID       = Guid.NewGuid().ToString();
                hsCount.Key        = "IntervalCount";
                hsCount.Value      = "1";
                hsCount.Desc       = "区间个数";
                hsCount.HostGUID   = hi.GUID;
                hsCount.CreateDate = dtNow;
                hsCount.UpdateDate = dtNow;
                hsBLL.Add(hsCount);
            }
            txtCount.Text = hsCount.Value;
        }
コード例 #38
0
        public static void CreatePuttyInstance(HostInfo puttyInfo)
        {
            var psi = new ProcessStartInfo
            {
                FileName  = _puttyFullPath,
                Arguments = PuttyArguments(puttyInfo)
            };
            var proc = Process.Start(psi);

            proc.WaitForInputIdle();
            var hwnd = proc.MainWindowHandle;

            WinApi.ShowWindowAsync(hwnd, WinApi.SW_HIDE);
        }
コード例 #39
0
        public void CanLoadHost()
        {
            var repository = new DatabaseObjectProvider();

            SqlHelper.ExecuteNonQuery(Config.ConnectionString, CommandType.Text, "DELETE subtext_Host");

            HostInfo.LoadHostInfoFromDatabase(repository, suppressException: false);

            Assert.IsNull(HostInfo.Instance, "HostInfo should be Null");

            HostInfo.CreateHost(repository, "test", "test", "*****@*****.**");

            Assert.IsNotNull(HostInfo.Instance, "Host should not be null.");
        }
コード例 #40
0
 public RoutingSlipActivityFaultedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid activityTrackingNumber,
     DateTime timestamp, TimeSpan duration, ExceptionInfo exceptionInfo, IDictionary<string, object> variables,
     IDictionary<string, object> arguments)
 {
     Host = host;
     TrackingNumber = trackingNumber;
     Timestamp = timestamp;
     Duration = duration;
     ActivityTrackingNumber = activityTrackingNumber;
     ActivityName = activityName;
     Variables = variables;
     Arguments = arguments;
     ExceptionInfo = exceptionInfo;
 }
コード例 #41
0
 public RoutingSlipActivityFaultedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid executionId,
                                          DateTime timestamp, TimeSpan duration, ExceptionInfo exceptionInfo, IDictionary <string, object> variables,
                                          IDictionary <string, object> arguments)
 {
     Host           = host;
     TrackingNumber = trackingNumber;
     Timestamp      = timestamp;
     Duration       = duration;
     ExecutionId    = executionId;
     ActivityName   = activityName;
     Variables      = variables;
     Arguments      = arguments;
     ExceptionInfo  = exceptionInfo;
 }
コード例 #42
0
        public static string PuttyArguments(HostInfo host)
        {
            // example: -ssh username@domainName -P 22 -pw password -D 5000 -L 44333:username.dyndns.org:44333

            var args = String.Format(@"-ssh {0}@{1} -P {2} -pw {3}", host.Username, host.Hostname, host.Port, host.Password);
            var sb   = new StringBuilder(args);

            foreach (var arg in host.Tunnels.Select(PuttyTunnelArguments))
            {
                sb.AppendFormat(@" {0}", (object)arg);
            }
            args = sb.ToString();
            return(args);
        }
コード例 #43
0
        public ActivityCompensationFailed(HostInfo host, Guid trackingNumber, string activityName, Guid executionId, DateTime timestamp, TimeSpan duration,
                                          ExceptionInfo exceptionInfo, IDictionary <string, object> variables, IDictionary <string, object> data)
        {
            Host       = host;
            _duration  = duration;
            _timestamp = timestamp;

            TrackingNumber = trackingNumber;
            ExecutionId    = executionId;
            ActivityName   = activityName;
            Data           = data;
            Variables      = variables;
            ExceptionInfo  = exceptionInfo;
        }
コード例 #44
0
        public CompensationFailed(HostInfo host, Guid trackingNumber, string activityName, Guid executionId,
            DateTime timestamp, TimeSpan duration, DateTime failureTimestamp, TimeSpan routingSlipDuration,
            ExceptionInfo exceptionInfo, IDictionary<string, object> variables, IDictionary<string, object> data)
        {
            _failureTimestamp = failureTimestamp;
            _routingSlipDuration = routingSlipDuration;
            Host = host;
            _duration = duration;
            _timestamp = timestamp;

            TrackingNumber = trackingNumber;
            ExecutionId = executionId;
            ActivityName = activityName;
            Data = data;
            Variables = variables;
            ExceptionInfo = exceptionInfo;
        }
コード例 #45
0
        /// <summary>
        /// Checks the installation status and redirects if necessary.
        /// </summary>
        public string GetInstallationRedirectUrl(BlogRequest blogRequest, HostInfo hostInfo)
        {
            const string installUrl = "~/install/default.aspx";

            // Bypass for static files.
            if(blogRequest.RawUrl.IsStaticFileRequest())
            {
                return null;
            }

            if(hostInfo == null && blogRequest.RequestLocation != RequestLocation.Installation)
            {
                return installUrl;
            }

            // Want to redirect to install if installation is required,
            // or if we're missing a HostInfo record.
            if((InstallationManager.InstallationActionRequired(VersionInfo.CurrentAssemblyVersion, null) || hostInfo == null))
            {
                InstallationState state = InstallationManager.GetInstallationStatus(VersionInfo.CurrentAssemblyVersion);
                if(state == InstallationState.NeedsInstallation
                   && !blogRequest.IsHostAdminRequest
                   && blogRequest.RequestLocation != RequestLocation.Installation)
                {
                    return installUrl;
                }

                if(state == InstallationState.NeedsUpgrade)
                {
                    if(blogRequest.RequestLocation != RequestLocation.Upgrade
                       && blogRequest.RequestLocation != RequestLocation.LoginPage
                       && blogRequest.RequestLocation != RequestLocation.SystemMessages
                       && blogRequest.RequestLocation != RequestLocation.HostAdmin)
                    {
                        return "~/SystemMessages/UpgradeInProgress.aspx";
                    }
                }
            }
            return null;
        }
コード例 #46
0
ファイル: OpmlHandler.cs プロジェクト: ChrisPelatari/SubText
        public virtual void ProcessRequest(HostInfo hostInfo)
        {
            HttpResponseBase response = SubtextContext.HttpContext.Response;
            response.ContentType = "text/xml";

            IEnumerable<Blog> blogs = null;
            if(!hostInfo.BlogAggregationEnabled)
            {
                Blog blog = SubtextContext.Blog;
                if(blog != null)
                {
                    blogs = new[] {blog};
                }
            }
            else
            {
                int? groupId = GetGroupIdFromQueryString(SubtextContext.HttpContext.Request);
                blogs = SubtextContext.Repository.GetBlogsByGroup(SubtextContext.HttpContext.Request.Url.Host, groupId);
            }

            OpmlWriter.Write(blogs, response.Output, SubtextContext.UrlHelper);
        }
コード例 #47
0
ファイル: Host.cs プロジェクト: paopaofeng/dp2
        void ThreadMain()
        {
            CloseHosts();

            for (int i = 0; ; i++)
            {
                string strInstanceName = "";
                string strDataDir = "";
                string strCertSN = "";
                string[] existing_urls = null;
                string strSerialNumber = "";
                bool bRet = GetInstanceInfo("dp2Library",
                    i,
                    out strInstanceName,
                    out strDataDir,
                    out existing_urls,
                    out strCertSN,
                    out strSerialNumber);
                if (bRet == false)
                    break;

                int nMaxClients = 0;
                string strLicenseType = "";

#if SN
                //string strLocalString = OneInstanceDialog.GetEnvironmentString(strSerialNumber, strInstanceName);
                //string strSha1 = Cryptography.GetSHA1(StringUtil.SortParams(strLocalString) + "_reply");
                if (String.IsNullOrEmpty(strSerialNumber) == true)
                {
                    nMaxClients = SessionInfo.DEFAULT_MAX_CLIENTS;
                }
                else
                {
                    string strDebugInfo = "";
                    if (MatchLocalString(strSerialNumber, strInstanceName, out strDebugInfo) == false)
                    //if (strSha1 != SerialCodeForm.GetCheckCode(strSerialNumber))
                    {
                        this.Log.WriteEntry("dp2Library 实例 '"+strInstanceName+"' 序列号不合法,无法启动。\r\n调试信息如下:\r\n" + strDebugInfo,
    EventLogEntryType.Error);
                        continue;
                    }
                    string strMaxClients = GetMaxClients(strSerialNumber);
                    // 2015/1/7
                    if (string.IsNullOrEmpty(strMaxClients) == true)
                        nMaxClients = SessionInfo.DEFAULT_MAX_CLIENTS;
                    else
                    {
                        if (Int32.TryParse(strMaxClients, out nMaxClients) == false)
                        {
                            this.Log.WriteEntry("dp2Library 实例 '" + strInstanceName + "' 序列号 '" + strSerialNumber + "' 中 clients 参数值 '" + strMaxClients + "' 不合法,无法启动",
    EventLogEntryType.Error);
                            continue;
                        }
                    }

                    strLicenseType = GetLicenseType(strSerialNumber);
                }
#else
                nMaxClients = 100;
                strLicenseType = "server";
#endif

                ServiceHost host = new ServiceHost(typeof(LibraryService));
                this.m_hosts.Add(host);

                HostInfo info = new HostInfo();
                info.DataDir = strDataDir;
                info.MaxClients = nMaxClients;
                info.LicenseType = strLicenseType; 
                host.Extensions.Add(info);
                /// 

                bool bHasWsHttp = false;
                // 绑定协议
                foreach (string url in existing_urls)
                {
                    if (string.IsNullOrEmpty(url) == true)
                        continue;

                    Uri uri = null;
                    try
                    {
                        uri = new Uri(url);
                    }
                    catch (Exception ex)
                    {
                        this.Log.WriteEntry("dp2Library OnStart() 警告:发现不正确的协议URL '" + url + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。",
    EventLogEntryType.Error);
                        continue;
                    }

                    if (uri.Scheme.ToLower() == "http")
                    {
                        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryService),
    CreateWsHttpBinding1(),
    url);
                        bHasWsHttp = true;
                    }
                    else if (uri.Scheme.ToLower() == "rest.http")
                    {
                        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryServiceREST),
CreateWebHttpBinding1(),
url.Substring(5));
                        if (endpoint.Behaviors.Find<WebHttpBehavior>() == null)
                        {
                            WebHttpBehavior behavior = new WebHttpBehavior();
                            behavior.DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped;
                            behavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json;
                            behavior.AutomaticFormatSelectionEnabled = true;
                            behavior.HelpEnabled = true;
                            endpoint.Behaviors.Add(behavior);
                        }
                    }
                    else if (uri.Scheme.ToLower() == "basic.http")
                    {
                        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryServiceREST),
CreateBasicHttpBinding1(),
url.Substring(6));
#if NO
                        if (endpoint.Behaviors.Find<WebHttpBehavior>() == null)
                        {
                            WebHttpBehavior behavior = new WebHttpBehavior();
                            behavior.DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped;
                            behavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json;
                            behavior.AutomaticFormatSelectionEnabled = true;
                            behavior.HelpEnabled = true;
                            endpoint.Behaviors.Add(behavior);
                        }
#endif
                    }
                    else if (uri.Scheme.ToLower() == "net.pipe")
                    {
                        host.AddServiceEndpoint(typeof(ILibraryService),
                            CreateNamedpipeBinding0(),
                            url);
                    }
                    else if (uri.Scheme.ToLower() == "net.tcp")
                    {
                        host.AddServiceEndpoint(typeof(ILibraryService),
            CreateNetTcpBinding0(),
            url);
                    }
                    else
                    {
                        // 警告不能支持的协议
                        this.Log.WriteEntry("dp2Library OnStart() 警告:发现不能支持的协议类型 '" + url + "'",
                            EventLogEntryType.Information);
                    }

                    info.Protocol = uri.Scheme.ToLower();
                }

                // 如果具有ws1/ws2 binding,才启用证书
                if (bHasWsHttp == true)
                {
                    try
                    {
                        string strError = "";
                        X509Certificate2 cert = GetCertificate(strCertSN,
                            out strError);
                        if (cert == null)
                            this.Log.WriteEntry("dp2Library OnStart() 准备证书 时发生错误: " + strError,
EventLogEntryType.Error);
                        else
                            host.Credentials.ServiceCertificate.Certificate = cert;

                    }
                    catch (Exception ex)
                    {
                        this.Log.WriteEntry("dp2Library OnStart() 获取证书时发生错误: " + ExceptionUtil.GetExceptionMessage(ex),
        EventLogEntryType.Error);
                        return;
                    }
                }

                // 只有第一个host才有metadata能力
                if (i == 0 && host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    string strWsHostUrl = FindUrl("http", existing_urls);

                    string strMetadataUrl = strWsHostUrl;
                    if (String.IsNullOrEmpty(strMetadataUrl) == true)
                        strMetadataUrl = "http://localhost:8001/dp2library/";
                    if (strMetadataUrl[strMetadataUrl.Length - 1] != '/')
                        strMetadataUrl += "/";
                    strMetadataUrl += "metadata";

                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri(strMetadataUrl);
                    host.Description.Behaviors.Add(behavior);
                }



                if (host.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null)
                {
                    ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior();
                    behavior.MaxConcurrentCalls = 50;
                    behavior.MaxConcurrentInstances = 1000;
                    behavior.MaxConcurrentSessions = 1000;
                    host.Description.Behaviors.Add(behavior);
                }

                // IncludeExceptionDetailInFaults
                ServiceDebugBehavior debug_behavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                if (debug_behavior == null)
                {
                    host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
                }
                else
                {
                    if (debug_behavior.IncludeExceptionDetailInFaults == false)
                        debug_behavior.IncludeExceptionDetailInFaults = true;
                }

#if NO
                host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
                host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new MyValidator();
#endif

                host.Opening += new EventHandler(host_Opening);
                host.Closing += new EventHandler(m_host_Closing);

                try
                {
                    host.Open();
                }
                catch (Exception ex)
                {
                    // 让调试器能感觉到
                    if (this.m_bConsoleRun == true)
                        throw ex;

                    this.Log.WriteEntry("dp2Library OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ExceptionUtil.GetExceptionMessage(ex),
    EventLogEntryType.Error);
                    return;
                }
            }
            this.Log.WriteEntry("dp2Library OnStart() end",
EventLogEntryType.Information);

            this.m_thread = null;
        }
コード例 #48
0
ファイル: Runner.cs プロジェクト: heliocentric/simplemesh
        public static int Read()
        {
            Info = new HostInfo();

            if (System.IO.File.Exists(SimpleMesh.Service.Runner.ConfigFile) == true)
            {
                string[] lines = System.IO.File.ReadAllLines(SimpleMesh.Service.Runner.ConfigFile);
                SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", SimpleMesh.Service.Runner.ConfigFile + " Contents:");
                foreach (string line in lines)
                {
                    string[] chunks = line.Split('!');
                    switch (chunks[0])
                    {
                        case "HOSTUUID":
                            SimpleMesh.Service.Runner.Info.UUID = new UUID(chunks[1]);
                            if (chunks.Length > 2)
                            {
                                SimpleMesh.Service.Runner.Info.Description = chunks[2];
                            }
                            SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\tUUID:\t\t" + SimpleMesh.Service.Runner.Info.UUID.ToString());
                            SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\tDescription:\t\t" + SimpleMesh.Service.Runner.Info.Description);
                            break;
                        case "HOSTKEY":
                            SimpleMesh.Service.Runner.Info.Key = new Key();
                            SimpleMesh.Service.Runner.Info.Key.Decode(line.Replace("HOSTKEY!",""));
                            SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\tHost Key:\t\t" + SimpleMesh.Service.Runner.Info.Key.ToString());
                            break;
                        case "PORT":
                            SimpleMesh.Service.Runner.Info.Ports.Add(chunks[1]);
                            break;
                        case "PROTOCOL":
                            SimpleMesh.Service.Runner.Info.Protocols.Add(chunks[1]);
                            break;
                    }
                }
            }
            else
            {
                // Get info from the actual client.
                HostInfo scratch = HostInfoCallback();
                DateTime Start = DateTime.Now;
                SimpleMesh.Service.Runner.Info = scratch;
                SimpleMesh.Service.Runner.Info.Key.Type = "RSA";
                SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "Generating " + SimpleMesh.Service.Runner.Info.Key.Length.ToString() + " bit RSA key pair starting on: " + DateTime.Now.ToString());
                RsaKeyPairGenerator r = new RsaKeyPairGenerator();
                r.Init(new KeyGenerationParameters(new SecureRandom(), SimpleMesh.Service.Runner.Info.Key.Length));
                AsymmetricCipherKeyPair test = r.GenerateKeyPair();
                SimpleMesh.Service.Runner.Info.Key.PrivateKey = test.Private;
                SimpleMesh.Service.Runner.Info.Key.PublicKey = test.Public;

                List<string> file = new List<string>();
                file.Add("I!1.1!!!");
                file.Add("HOSTUUID!" + Info.UUID.ToString() + "!" + SimpleMesh.Service.Runner.Info.Description);
                file.Add("HOSTKEY!" + Info.Key.Encode(true));
                foreach(string port in Info.Ports) {
                    file.Add("PORT!" + port);
                }
                foreach (string protocol in Info.Protocols)
                {
                    file.Add("PROTOCOL!" + protocol);
                }

                SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", SimpleMesh.Service.Runner.ConfigFile + " Contents:");
                foreach (string line in file)
                {
                    SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", "\t" + line);
                }
                if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(SimpleMesh.Service.Runner.ConfigFile)) == false)
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(SimpleMesh.Service.Runner.ConfigFile));
                }
                System.IO.File.WriteAllLines(SimpleMesh.Service.Runner.ConfigFile, file.ToArray());
            }
            return 0;
        }
コード例 #49
0
ファイル: VMController.cs プロジェクト: lausai/VmHelper
        public VMController(HostInfo hostInfo)
        {
            _host = new VMWareVirtualHost();

            _host.ConnectToVMWareVIServer(hostInfo.name, hostInfo.account, hostInfo.pwd);
        }
コード例 #50
0
		public Virtualization.VirtualNetworkInfo[] GetVirtualNetworkByHostInfo(HostInfo hostInfo)
		{
			List<Virtualization.VirtualNetworkInfo> result = new List<Virtualization.VirtualNetworkInfo>();

			using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
			{
				VirtualizationForPC.SVMMService.VirtualNetworkInfo[] networks = client.GetVirtualNetworkByHost(hostInfo);
				foreach (var item in networks)
				{
					result.Add(
						new Virtualization.VirtualNetworkInfo
						{
							BoundToVMHost = item.BoundToVMHost,
							DefaultGatewayAddress = item.DefaultGatewayAddress,
							Description = item.Description,
							DNSServers = item.DNSServers,
							EnablingIPAddress = item.EnablingIPAddress,
							HighlyAvailable = item.HighlyAvailable,
							HostBoundVlanId = item.HostBoundVlanId,
							Id = item.Id,
							Name = item.Name,
							NetworkAddress = item.NetworkAddress,
							NetworkMask = item.NetworkMask,
							Tag = item.Tag,
							VMHost = item.VMHost.ComputerName,
							VMHostId = item.VMHostId,
							WINServers = item.WINServers
						});
				}
			}

			return result.ToArray();

		}
コード例 #51
0
ファイル: DataHelper.cs プロジェクト: ayende/Subtext
 /// <summary>
 /// Loads the host from the data reader.
 /// </summary>
 /// <param name="reader">Reader.</param>
 /// <param name="info">HostInfo</param>
 /// <returns></returns>
 public static void LoadHost(IDataReader reader, HostInfo info)
 {
     info.HostUserName = ReadString(reader, "HostUserName");
     info.Password = ReadString(reader, "Password");
     info.Salt = ReadString(reader, "Salt");
     info.DateCreated = (DateTime)reader["DateCreated"];
 }
コード例 #52
0
 public void AddActivityLog(HostInfo host, string name, Guid activityTrackingNumber, DateTime timestamp, TimeSpan duration)
 {
     _activityLogs.Add(new ActivityLogImpl(host, activityTrackingNumber, name, timestamp, duration));
 }
コード例 #53
0
 public void HandleInstallationStatus(HttpContextBase context, BlogRequest blogRequest, HostInfo hostInfo)
 {
     string redirectUrl = GetInstallationRedirectUrl(blogRequest, hostInfo);
     if(!String.IsNullOrEmpty(redirectUrl))
     {
         context.Response.Redirect(redirectUrl);
     }
 }
コード例 #54
0
ファイル: ObjectProvider.cs プロジェクト: rsaladrigas/Subtext
 /// <summary>
 /// Returns the <see cref="HostInfo"/> for the Subtext installation.
 /// </summary>
 /// <returns>A <see cref="HostInfo"/> instance.</returns>
 public abstract HostInfo LoadHostInfo(HostInfo info);
コード例 #55
0
ファイル: ObjectProvider.cs プロジェクト: rsaladrigas/Subtext
 /// <summary>
 /// Updates the <see cref="HostInfo"/> instance.  If the host record is not in the 
 /// database, one is created. There should only be one host record.
 /// </summary>
 /// <param name="hostInfo">The host information.</param>
 public abstract bool UpdateHost(HostInfo hostInfo);
コード例 #56
0
        /// <summary>
        /// Adds an activity exception to the routing slip
        /// </summary>
        /// <param name="host"></param>
        /// <param name="name">The name of the faulted activity</param>
        /// <param name="activityTrackingNumber">The activity tracking number</param>
        /// <param name="timestamp">The timestamp of the exception</param>
        /// <param name="elapsed">The time elapsed from the start of the activity to the exception</param>
        /// <param name="exceptionInfo"></param>
        public void AddActivityException(HostInfo host, string name, Guid activityTrackingNumber, DateTime timestamp, TimeSpan elapsed,
            ExceptionInfo exceptionInfo)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (exceptionInfo == null)
                throw new ArgumentNullException(nameof(exceptionInfo));

            ActivityException activityException = new ActivityExceptionImpl(name, host, activityTrackingNumber, timestamp, elapsed,
                exceptionInfo);
            _activityExceptions.Add(activityException);
        }
コード例 #57
0
ファイル: HostRepository.cs プロジェクト: rsaladrigas/Subtext
 /// <summary>
 /// Returns the <see cref="HostInfo"/> for the Subtext installation.
 /// </summary>
 /// <returns>A <see cref="HostInfo"/> instance.</returns>
 public override HostInfo LoadHostInfo(HostInfo hostInfo)
 {
     try
     {
         using (IDataReader reader = _procedures.GetHost())
         {
             if (reader.Read())
             {
                 return reader.ReadObject(hostInfo);
             }
         }
     }
     catch (IndexOutOfRangeException)
     {
         //When upgrading, this may occur because the old version of the
         //database schema doesn't know about new properties.
         return new HostInfo(ConfigurationManager.AppSettings);
     }
     return null;
 }
コード例 #58
0
 public BlogLookupService(ObjectProvider repository, HostInfo host)
 {
     Repository = repository;
     _host = host;
 }
コード例 #59
0
ファイル: HostRepository.cs プロジェクト: rsaladrigas/Subtext
 /// <summary>
 /// Updates the <see cref="HostInfo"/> instance.  If the host record is not in the 
 /// database, one is created. There should only be one host record.
 /// </summary>
 /// <param name="host">The host information.</param>
 public override bool UpdateHost(HostInfo host)
 {
     return _procedures.UpdateHost(hostUserName: host.HostUserName, email: host.Email, password: host.Password, salt: host.Salt);
 }
コード例 #60
0
ファイル: KernelHost.cs プロジェクト: paopaofeng/dp2
        int Start(string strDataDir,
            out string strError)
        {
            strError = "";

            CloseHosts();

            string strInstanceName = "";
            string strUrl = "net.pipe://localhost/dp2kernel/xe";

            _host = new ServiceHost(typeof(KernelService));

            HostInfo info = new HostInfo();
            info.DataDir = strDataDir;
            _host.Extensions.Add(info);
            /// 

            // 绑定协议
            {
                Uri uri = null;
                try
                {
                    uri = new Uri(strUrl);
                }
                catch (Exception ex)
                {
                    strError = "dp2Kernel OnStart() 警告:发现不正确的协议URL '" + strUrl + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。";
                    return -1;
                }

                if (uri.Scheme.ToLower() == "net.pipe")
                {
                    _host.AddServiceEndpoint(typeof(IKernelService),
            CreateNamedpipeBinding0(),
            strUrl);
                }
                else
                {
                    // 警告不能支持的协议
                    strError = "dp2Kernel OnStart() 警告:发现不能支持的协议类型 '" + strUrl + "'";
                    return -1;
                }
            }

            {
                string strMetadataUrl = "http://localhost:8001/dp2kernel/xe/";
                if (strMetadataUrl[strMetadataUrl.Length - 1] != '/')
                    strMetadataUrl += "/";
                strMetadataUrl += "metadata";

                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                behavior.HttpGetUrl = new Uri(strMetadataUrl);
                _host.Description.Behaviors.Add(behavior);

                this.MetadataUrl = strMetadataUrl;
            }

            if (_host.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null)
            {
                ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior();
                behavior.MaxConcurrentCalls = 50;
                behavior.MaxConcurrentInstances = 1000;
                behavior.MaxConcurrentSessions = 1000;
                _host.Description.Behaviors.Add(behavior);
            }

            // IncludeExceptionDetailInFaults
            ServiceDebugBehavior debug_behavior = _host.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (debug_behavior == null)
            {
                _host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
            }
            else
            {
                if (debug_behavior.IncludeExceptionDetailInFaults == false)
                    debug_behavior.IncludeExceptionDetailInFaults = true;
            }

            _host.Opening += new EventHandler(host_Opening);
            _host.Closing += new EventHandler(m_host_Closing);

            try
            {
                _host.Open();
            }
            catch (Exception ex)
            {
                strError = "dp2Kernel OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ex.Message;
                return -1;
            }

            return 0;
        }