private void OnServerPortChanged()
        {
            Logging.Logging.LogInfo("Changing Server Port to " + ServerPort.ToString());

            Utility.AsynchronousSocketListener._port = ServerPort;

            _serverThread.Abort();
            Utility.AsynchronousSocketListener server = new Utility.AsynchronousSocketListener();
            _serverThread = new System.Threading.Thread(server.DoWork);
            _serverThread.Start();
        }
예제 #2
0
        public void Save()
        {
            var chest     = Chest.Get();
            var coreChest = new Chest("Massacre.Snv.Core");

            chest.Data[nameof(Name)]          = PreProcString(Name);
            chest.Data[nameof(ServerAddress)] = PreProcString(ServerAddress);
            chest.Data[nameof(ServerPort)]    = ServerPort.ToString();

            chest.Data[nameof(RecPrefix)]            = PreProcString(RecPrefix);
            chest.Data[nameof(RecSplitMaxMegabytes)] = RecSplitMaxMegabytes.ToString();
            chest.Data[nameof(RecSplitMaxCount)]     = RecSplitMaxCount.ToString();
        }
        private void InitNetwork()
        {
            Logging.Logging.LogInfo("Initializing Network with Server Port " + ServerPort.ToString() + " and Client Port " + ClientPort.ToString());

            Utility.AsynchronousSocketListener._port = ServerPort;
            Utility.AsynchronousSocketListener server = new Utility.AsynchronousSocketListener();
            Utility.AsynchronousSocketListener._onReadCallback  = new Utility.AsynchronousSocketListener.OnReadCallback(OnNetworkReadCallback);
            Utility.AsynchronousSocketListener._onErrorCallback = new Utility.AsynchronousSocketListener.OnReadCallback(OnNetworkErrorCallback);
            _serverThread = new System.Threading.Thread(server.DoWork);
            _serverThread.Start();

            Utility.AsynchronousClient._port            = ClientPort;
            Utility.AsynchronousClient._onErrorCallback = new Utility.AsynchronousSocketListener.OnReadCallback(OnNetworkErrorCallback);
        }
예제 #4
0
        public string ServerUrl()
        {
            string port;

            if ((IsHttps && ServerPort == 443) || (!IsHttps && ServerPort == 80))
            {
                port = "";
            }
            else
            {
                port = ":" + ServerPort.ToString();
            }
            string url = string.Format("{0}://{1}{2}", IsHttps ? "https" : "http", ServerHost, port);

            return(url);
        }
예제 #5
0
 /// <summary>
 /// 确定命令执行函数
 /// </summary>
 private void OnExecuteConfirmCommand()
 {
     try
     {
         Utility.ConfigHelper.AddAppSetting("ServerIp", ServerIp);
         Utility.ConfigHelper.AddAppSetting("ServerPort", ServerPort.ToString());
         Utility.ConfigHelper.AddAppSetting("ServerUri", ServerUri);
         Utility.ConfigHelper.AddAppSetting("PageSize", PageSize.ToString());
         Messenger.Default.Send <Boolean>(false, MessengerToken.ClosePopup);
     }
     catch (Exception ex)
     {
         Message = "修改设置失败!请与管理员联系!" + System.Environment.NewLine + ex.Message;
         Utility.LogHelper.Error(Message, ex);
     }
 }
예제 #6
0
 /// Start to connect TCP Server.
 public bool StartConnection()
 {
     try
     {
         /// disconnect first.
         Disconnect(ref ClientSocket);
         /// check if IncomingDataQueue is initialized.
         if (IncomingDataQueue == null)
         {
             Logger?.Error("TCP Client finds that IncomingDataQueue is not initialized. Stop connection. Server socket = {0}:{1}", ServerHost, ServerPort);
             return(false);
         }
         /// connect.
         ClientSocket = Connect(ServerHost, ServerPort);
         if (ClientSocket == null || ClientSocket.Connected == false)
         {
             Disconnect(ref ClientSocket);
             return(false);
         }
         /// thread to receive data.
         ThreadToReceiveData = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessReceiveData))
         {
             Name = "ProcessReceiveData-" + ServerHost + ":" + ServerPort.ToString()
         };
         ThreadToReceiveData.Start();/// This "start" statement can be divided from this function.
         /// thread to analyze the incoming buffer.
         ThreadToAnalyzeIncomingBuffer = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessAnalyzeIncomingBuffer))
         {
             Name = "ProcessAnalyzeIncomingBuffer-" + ServerHost + ":" + ServerPort.ToString()
         };
         ThreadToAnalyzeIncomingBuffer.Start();
         /// thread to other processes.
         ThreadToOtherProcesses = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessOtherProcesses))
         {
             Name = "ProcessOtherProcesses-" + ServerHost + ":" + ServerPort.ToString()
         };
         ThreadToOtherProcesses.Start();
         ///
         return(true);
     }
     catch (Exception ex)
     {
         Logger?.Error("Server socket = {0}:{1}", ServerHost, ServerPort);
         Logger?.Error(ex);
         return(false);
     }
 }
예제 #7
0
 public bool IsValid()
 {
     if (!string.IsNullOrWhiteSpace(ServerName) &&
         !string.IsNullOrWhiteSpace(ServerClient) &&
         !string.IsNullOrWhiteSpace(ServerIP) &&
         !string.IsNullOrWhiteSpace(ServerPort.ToString()) &&
         !string.IsNullOrWhiteSpace(ServerVersion) &&
         GlobalFuncs.IsClientValid(ServerClient) &&
         GlobalFuncs.IsIPValid(ServerIP) &&
         (!ServerIP.Equals("localhost") || !ServerIP.Equals("127.0.0.1")))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #8
0
        public void Save(string fileName)
        {
            using (XmlTextWriter xml = new XmlTextWriter(fileName, Encoding.UTF8))
            {
                xml.Formatting = System.Xml.Formatting.Indented;
                xml.WriteStartDocument(true);
                xml.WriteStartElement("configuration");
                xml.WriteStartElement("settings");

                xml.WriteStartElement("server");
                xml.WriteAttributeString("ip", ServerIP.ToString());
                xml.WriteAttributeString("port", ServerPort.ToString());
                xml.WriteEndElement();

                xml.WriteEndElement();
                xml.WriteEndElement();
                xml.WriteEndDocument();
            }
        }
예제 #9
0
            private void Listen()
            {
#if UNITY_WSA_10_0 && WINDOWS_UWP
                // TODO: implement UWP version
#else
                httpListener = new HttpListener();
                httpListener.Prefixes.Add("http://*:" + ServerPort.ToString() + "/");
                httpListener.Start();
                print("Listening...");
                try
                {
                    while (httpListener != null && httpListener.IsListening)
                    {
                        context = httpListener.GetContext();
                        print("Request from " + context.Request.Url);
                        try
                        {
                            Process(context);
                        }
                        catch (IOException e)
                        {
                            print(e.Message);
                            httpListener.Stop();
                            httpListener.Start();
                        }
                    }
                }
                catch (Exception e)
                {
                    print(e);
                }
                finally
                {
                    TerminateListener();
                }
#endif
            }
예제 #10
0
        public void UpdateSettings()
        {
            Log.Debug("Begin saving app settings");

            var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            configuration.AppSettings.Settings[nameof(ServerAddress)].Value = ServerAddress;
            Log.Trace($"{nameof(ServerAddress)}='{ServerAddress}'");

            configuration.AppSettings.Settings[nameof(ServerPort)].Value = ServerPort.ToString();
            Log.Trace($"{nameof(ServerPort)}='{ServerPort}'");

            configuration.AppSettings.Settings[nameof(ServerLogin)].Value = ServerLogin;
            Log.Trace($"{nameof(ServerLogin)}='{ServerLogin}'");

            configuration.AppSettings.Settings[nameof(ServerPassword)].Value = ServerPassword;
            Log.Trace($"{nameof(ServerPassword)}='{ServerPassword}'");

            configuration.AppSettings.Settings[nameof(CashierName)].Value = CashierName;
            Log.Trace($"{nameof(CashierName)}='{CashierName}'");

            configuration.AppSettings.Settings[nameof(CashierVatin)].Value = CashierVatin;
            Log.Trace($"{nameof(CashierVatin)}='{CashierVatin}'");

            configuration.AppSettings.Settings[nameof(CompanyMail)].Value = CompanyMail;
            Log.Trace($"{nameof(CompanyMail)}='{CompanyMail}'");

            configuration.AppSettings.Settings[nameof(ServerDeviceId)].Value = ServerDeviceId.ToString();
            Log.Trace($"{nameof(ServerDeviceId)}='{ServerDeviceId}'");


            configuration.Save(ConfigurationSaveMode.Full, true);
            ConfigurationManager.RefreshSection("appSettings");
            Log.Debug("End saving app settings");
            Log.Info("Настройки сохранены!");
        }
예제 #11
0
        public CrmServiceClient GetCrmServiceClient(bool forceNewService = false)
        {
            if (forceNewService == false && crmSvc != null)
            {
                return(crmSvc);
            }

            //return new CrmServiceClient(GetOrganizationCrmConnectionString());

            if (UseOnline)
            {
                var tasks = new List <Task <CrmServiceClient> >
                {
                    Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, true)),
                    Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, false))
                };

                tasks[0].Wait();
                tasks[1].Wait();

                crmSvc = tasks.FirstOrDefault(t => t.Result != null && t.Result.IsReady)?.Result;
                if (crmSvc == null)
                {   // None of the attempts above were successful, so get a failed one to be able to display correct error message
                    crmSvc = tasks.FirstOrDefault(t => t.Result != null).Result;
                }

                // crmSvc = ConnectOnline(UseOsdp);

                AuthType = AuthenticationProviderType.OnlineFederation;
            }
            else if (UseIfd)
            {
                var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                                                     ConnectionManager.CryptoSaltValue,
                                                     ConnectionManager.CryptoHashAlgorythm,
                                                     ConnectionManager.CryptoPasswordIterations,
                                                     ConnectionManager.CryptoInitVector,
                                                     ConnectionManager.CryptoKeySize);

                crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), UserDomain, HomeRealmUrl,
                                              ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl);

                AuthType = AuthenticationProviderType.Federation;
            }
            else
            {
                NetworkCredential credential;
                if (!IsCustomAuth)
                {
                    credential = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                                                         ConnectionManager.CryptoSaltValue,
                                                         ConnectionManager.CryptoHashAlgorythm,
                                                         ConnectionManager.CryptoPasswordIterations,
                                                         ConnectionManager.CryptoInitVector,
                                                         ConnectionManager.CryptoKeySize);

                    credential = new NetworkCredential(UserName, password, UserDomain);
                }
                crmSvc = new CrmServiceClient(credential, AuthenticationType.AD, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl);

                AuthType = AuthenticationProviderType.ActiveDirectory;
            }

            if (!crmSvc.IsReady)
            {
                var error = crmSvc.LastCrmError;
                crmSvc = null;
                throw new Exception(error);
            }

            return(crmSvc);
        }
예제 #12
0
        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            StringBuilder transportString = new StringBuilder();

            transportString.Append(Transport.ToString());
            transportString.Append('/');
            transportString.Append(Profile.ToString());
            transportString.Append('/');
            transportString.Append(LowerTransport.ToString());
            if (LowerTransport == LowerTransportType.TCP)
            {
                transportString.Append(";unicast");
            }
            if (LowerTransport == LowerTransportType.UDP)
            {
                transportString.Append(';');
                transportString.Append(IsMulticast ? "multicast" : "unicast");
            }
            if (Destination != null)
            {
                transportString.Append(";destination=");
                transportString.Append(Destination);
            }
            if (Source != null)
            {
                transportString.Append(";source=");
                transportString.Append(Source);
            }
            if (Interleaved != null)
            {
                transportString.Append(";interleaved=");
                transportString.Append(Interleaved.ToString());
            }
            if (IsAppend)
            {
                transportString.Append(";append");
            }
            if (TTL > 0)
            {
                transportString.Append(";ttl=");
                transportString.Append(TTL);
            }
            if (Layers > 0)
            {
                transportString.Append(";layers=");
                transportString.Append(Layers);
            }
            if (Port != null)
            {
                transportString.Append(";port=");
                transportString.Append(Port.ToString());
            }
            if (ClientPort != null)
            {
                transportString.Append(";client_port=");
                transportString.Append(ClientPort.ToString());
            }
            if (ServerPort != null)
            {
                transportString.Append(";server_port=");
                transportString.Append(ServerPort.ToString());
            }
            if (SSrc != null)
            {
                transportString.Append(";ssrc=");
                transportString.Append(SSrc);
            }
            if (Mode != null && Mode != "PLAY")
            {
                transportString.Append(";mode=");
                transportString.Append(Mode);
            }
            return(transportString.ToString());
        }
예제 #13
0
        private void StartupServices()
        {
            try
            {
                LastMessage = "搜索可提供的服务...";
                RaisePropertyChanged("LastMessage");

                _bootstrapper = new ServiceHostBootstrapper();
                _bootstrapper.Run();

                //DatabaseInitializer.Initialize();

                IServiceLocator serviceLocator = _bootstrapper._container.GetExportedValue <IServiceLocator>();
                _manager            = serviceLocator.GetInstance <IServiceHostManager>() as ServiceHostManager;
                _manager._container = _bootstrapper._container;
                _manager.LookupServices();

                LastMessage = "找到服务" + _manager.Services.Count <ExportServiceHost>().ToString() + "个";
                RaisePropertyChanged("LastMessage");

                _lighterServerContext = _bootstrapper._container.GetExportedValue <ILighterServerContext>();
                Users = _lighterServerContext.LoginedAccounts;

                foreach (ExportServiceHost host in _manager.Services)
                {
                    if (!host.UpdateAddressPort(ServerPort))
                    {
                        LastMessage = "Hosting Service: " + host.Meta.Name + " UpdateAddressPort " + ServerPort.ToString() + " failure.";
                        RaisePropertyChanged("LastMessage");
                    }

                    Debug.Assert(host.Description.Endpoints.Count == 1);
                    var address = host.Description.Endpoints[0];

                    host.Open();
                    host.Opened += delegate
                    {
                        LastMessage = "服务已启动: " + host.Meta.Name + " at " + address.Address.Uri;
                        RaisePropertyChanged("LastMessage");
                    };

                    //foreach (var address in host.Description.Endpoints)
                    {
                        LastMessage = "正在初始化服务 " + host.Meta.Name + " ... ";
                        RaisePropertyChanged("LastMessage");

                        //OperationContext operationContext = OperationContext.Current;
                        //InstanceContext instanceContext = operationContext.InstanceContext;
                        //ILighterService service = instanceContext.GetServiceInstance() as ILighterService;
                        //service.Initialize();

                        ServiceInfo info = new ServiceInfo(host.Meta.Description, address.Address.Uri);
                        Services.Add(info);
                        RaisePropertyChanged("Services");
                    }
                }

                LastMessage = "服务已提供";
                RaisePropertyChanged("LastMessage");

                IEventAggregator _eventAggregator = _manager._container.GetExportedValue <IEventAggregator>();
                _eventAggregator.GetEvent <AccountLoginEvent>().Subscribe(AccountLogined);
                _eventAggregator.GetEvent <AccountLogoutEvent>().Subscribe(AccountLogouted);
            }
            catch (Exception e)
            {
                LastMessage = ExceptionMessage.GetExceptionMessage(e);
                RaisePropertyChanged("LastMessage");
            }
        }
예제 #14
0
        public override string GetTreeNodeHeader()
        {
            string sPort = (ServerPort == DEFAULT_PGSQL_PORT) ? string.Empty : ":" + ServerPort.ToString();

            return(string.Format("{0}@{1}{2}", UserName, ServerName, sPort));
        }
예제 #15
0
        /// <summary>
        /// 通讯连接
        /// </summary>
        /// <param name="serverIp">待连接的主机地址(IP地址)</param>
        /// <param name="portStr">待连接的端口号</param>
        /// <param name="connType">连接类型(UDP, TCP)</param>
        /// <returns>假如连接成功,返回1,否则返回0</returns>
        public int Connect(string serverIp, string portStr, ConnTypes connType)
        {
            string _class       = MethodBase.GetCurrentMethod().ReflectedType.FullName;                      //命名空间+类名
            string _method      = string.Format("Int32 {0}", new StackTrace().GetFrame(0).GetMethod().Name); //方法名称
            string connTypeName = Enum.GetName(typeof(ConnTypes), (int)connType);                            //连接类型的名称

            //假如已连接,返回错误信息
            if (IsConnected)
            {
                LastErrorCode    = "001";
                LastErrorMessage = string.Format("已与主机 {0} 在端口 {1} 建立{2}连接,无法再次连接!", ServerIp, ServerPort.ToString(), connTypeName);
                FileClient.WriteFailureInfo(new string[] { LastErrorMessage, string.Format("类名称:{0},方法名称:{1}", _class, _method) });
                return(0);
            }

            //假如两个参数中有一个参数为空,则生成错误信息并抛出异常
            string param = string.Empty; //参数名称

            if (string.IsNullOrWhiteSpace(serverIp))
            {
                param            = "string serverIp";
                LastErrorCode    = "002";
                LastErrorMessage = string.Format("建立{0}连接的主机地址不得为空!", connTypeName);
            }
            else if (string.IsNullOrWhiteSpace(portStr))
            {
                param            = "string portStr";
                LastErrorCode    = "003";
                LastErrorMessage = string.Format("建立{0}连接的端口不得为空!", connTypeName);
            }

            if (!string.IsNullOrWhiteSpace(LastErrorCode))
            {
                FileClient.WriteFailureInfo(new string[] { LastErrorMessage, string.Format("类名称:{0},方法名称:{1}", _class, _method) });
                throw new ArgumentException(LastErrorMessage, param); //假如不需要抛出异常,注释此行
                //return 0;
            }

            serverIp = serverIp.Equals("localhost", StringComparison.OrdinalIgnoreCase) ? "127.0.0.1" : serverIp; //判断localhost
            int port   = int.Parse(portStr);                                                                      //端口转换为数值类型
            int result = 1;

            //判断连接类型并进行相应的连接,保存主机地址、端口与连接状态;假如报错,获取错误信息
            if (connType == ConnTypes.TCP)
            {
                try
                {
                    this.TcpClient   = new DerivedTcpClient(serverIp, port);
                    this.ServerIp    = this.TcpClient.ServerIp;
                    this.ServerPort  = this.TcpClient.ServerPort;
                    this.IsConnected = this.TcpClient.IsConnected;
                }
                catch (Exception) { this.LastErrorMessage = this.TcpClient.LastErrorMessage; throw; }
            }
            //TODO 编写其它连接方式的连接方法
            else
            {
                //try
                //{
                //    result = BaseUdpClient.Connect(serverIp, port);
                //    ServerIp = BaseUdpClient.ServerIp;
                //    ServerPort = BaseUdpClient.ServerPort;
                //    IsConnected = BaseUdpClient.IsConnected;
                //}
                //catch (Exception) { LastErrorMessage = BaseUdpClient.LastErrorMessage; throw; }
            }

            ConnType = connType;
            return(result);
        }
예제 #16
0
 public string WriteCommand()
 {
     return(String.Concat("AT+", CommandPrefix, "=\"", APNName, "\",\"", APNLogin, "\",\"", APNPassword, "\",", ServerPort.ToString(), ",\"", DataCenterIP.ToString(), "\"," + DataCenterPort.ToString()));
 }
예제 #17
0
        public void UpdateSettings()
        {
            Log.Debug("Begin saving app settings");

            var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            configuration.AppSettings.Settings[nameof(AtolOnlineINN)].Value = AtolOnlineINN;
            Log.Trace($"{nameof(AtolOnlineINN)}='{AtolOnlineINN}'");

            configuration.AppSettings.Settings[nameof(AtolOnlineGroupID)].Value = AtolOnlineGroupID;
            Log.Trace($"{nameof(AtolOnlineGroupID)}='{AtolOnlineGroupID}'");

            configuration.AppSettings.Settings[nameof(AtolOnlineHostname)].Value = AtolOnlineHostname;
            Log.Trace($"{nameof(AtolOnlineHostname)}='{AtolOnlineHostname}'");

            configuration.AppSettings.Settings[nameof(AtolOnlineLogin)].Value = AtolOnlineLogin;
            Log.Trace($"{nameof(AtolOnlineLogin)}='{AtolOnlineLogin}'");

            configuration.AppSettings.Settings[nameof(AtolOnlinePassword)].Value = AtolOnlinePassword;
            Log.Trace($"{nameof(AtolOnlinePassword)}='{AtolOnlinePassword}'");

            configuration.AppSettings.Settings[nameof(AtolOnlineDelay)].Value = AtolOnlineDelay.ToString();
            Log.Trace($"{nameof(AtolOnlineDelay)}='{AtolOnlineDelay}'");

            configuration.AppSettings.Settings[nameof(ServerAddress)].Value = ServerAddress;
            Log.Trace($"{nameof(ServerAddress)}='{ServerAddress}'");

            configuration.AppSettings.Settings[nameof(ServerPort)].Value = ServerPort.ToString();
            Log.Trace($"{nameof(ServerPort)}='{ServerPort}'");

            configuration.AppSettings.Settings[nameof(ServerLogin)].Value = ServerLogin;
            Log.Trace($"{nameof(ServerLogin)}='{ServerLogin}'");

            configuration.AppSettings.Settings[nameof(ServerPassword)].Value = ServerPassword;
            Log.Trace($"{nameof(ServerPassword)}='{ServerPassword}'");

            configuration.AppSettings.Settings[nameof(CashierName)].Value = CashierName;
            Log.Trace($"{nameof(CashierName)}='{CashierName}'");

            configuration.AppSettings.Settings[nameof(CashierVatin)].Value = CashierVatin;
            Log.Trace($"{nameof(CashierVatin)}='{CashierVatin}'");

            configuration.AppSettings.Settings[nameof(CompanyMail)].Value = CompanyMail;
            Log.Trace($"{nameof(CompanyMail)}='{CompanyMail}'");

            configuration.AppSettings.Settings[nameof(ServerDeviceId)].Value = ServerDeviceId.ToString();
            Log.Trace($"{nameof(ServerDeviceId)}='{ServerDeviceId}'");

            configuration.AppSettings.Settings[nameof(FolderPath)].Value = FolderPath;
            Log.Trace($"{nameof(FolderPath)}='{FolderPath}'");

            configuration.AppSettings.Settings[nameof(IncludeSubfolders)].Value = IncludeSubfolders.ToString();
            Log.Trace($"{nameof(IncludeSubfolders)}='{IncludeSubfolders}'");

            configuration.AppSettings.Settings[nameof(AtolHost)].Value = AtolHost;
            Log.Trace($"{nameof(AtolHost)}='{AtolHost}'");

            configuration.AppSettings.Settings[nameof(DefaultPositionName)].Value = DefaultPositionName;
            Log.Trace($"{nameof(DefaultPositionName)}='{DefaultPositionName}'");

            configuration.AppSettings.Settings[nameof(PositionEnabled)].Value = PositionEnabled.ToString();
            Log.Trace($"{nameof(PositionEnabled)}='{PositionEnabled}'");

            configuration.AppSettings.Settings[nameof(AutosumEnabled)].Value = AutosumEnabled.ToString();
            Log.Trace($"{nameof(AutosumEnabled)}='{AutosumEnabled}'");

            configuration.AppSettings.Settings[nameof(ForceAutosumEnabled)].Value = ForceAutosumEnabled.ToString();
            Log.Trace($"{nameof(ForceAutosumEnabled)}='{ForceAutosumEnabled}'");

            configuration.Save(ConfigurationSaveMode.Full, true);
            ConfigurationManager.RefreshSection("appSettings");
            Log.Debug("End saving app settings");
            Log.Info("Настройки сохранены!");
        }
        public CrmServiceClient GetCrmServiceClient(bool forceNewService = false)
        {
            if (forceNewService == false && crmSvc != null)
            {
                return(crmSvc);
            }

            if (UseConnectionString)
            {
                if (ConnectionString.IndexOf("RequireNewInstance=", StringComparison.Ordinal) < 0)
                {
                    if (!ConnectionString.EndsWith(";"))
                    {
                        ConnectionString += ";";
                    }
                    ConnectionString += "RequireNewInstance=True;";
                }

                crmSvc = new CrmServiceClient(ConnectionString);

                if (crmSvc.IsReady)
                {
                    OrganizationFriendlyName   = crmSvc.ConnectedOrgFriendlyName;
                    OrganizationDataServiceUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.OrganizationDataService];
                    OrganizationServiceUrl     = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.OrganizationService];
                    WebApplicationUrl          = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.WebApplication];
                    Organization        = crmSvc.ConnectedOrgUniqueName;
                    OrganizationVersion = crmSvc.ConnectedOrgVersion.ToString();

                    var webAppURi = new Uri(WebApplicationUrl);
                    ServerName = webAppURi.Host;
                    ServerPort = webAppURi.Port;

                    UseOnline = crmSvc.CrmConnectOrgUriActual.Host.Contains(".dynamics.com");
                    UseOsdp   = crmSvc.CrmConnectOrgUriActual.Host.Contains(".dynamics.com");
                    UseSsl    = crmSvc.CrmConnectOrgUriActual.AbsoluteUri.ToLower().StartsWith("https");
                    UseIfd    = crmSvc.ActiveAuthenticationType == AuthenticationType.IFD;

                    switch (crmSvc.ActiveAuthenticationType)
                    {
                    case AuthenticationType.AD:
                    case AuthenticationType.Claims:
                        AuthType = AuthenticationProviderType.ActiveDirectory;
                        break;

                    case AuthenticationType.IFD:
                        AuthType = AuthenticationProviderType.Federation;
                        break;

                    case AuthenticationType.Live:
                        AuthType = AuthenticationProviderType.LiveId;
                        break;

                    case AuthenticationType.OAuth:
                        // TODO add new property in ConnectionDetail class?
                        break;

                    case AuthenticationType.Office365:
                        AuthType = AuthenticationProviderType.OnlineFederation;
                        break;
                    }

                    IsCustomAuth = ConnectionString.ToLower().Contains("username=");
                }

                return(crmSvc);
            }

            if (UseOnline)
            {
                var tasks = new List <Task <CrmServiceClient> >
                {
                    Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, true)),
                    Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, false))
                };

                tasks[0].Wait();
                tasks[1].Wait();

                crmSvc = tasks.FirstOrDefault(t => t.Result.IsReady)?.Result;
                if (crmSvc == null)
                {
                    var uniqueName = ResolveCrmOnlineUniqueOrg();

                    crmSvc = ConnectOnline(UseOsdp, true, uniqueName);

                    if (crmSvc == null)
                    {
                        // None of the attempts above were successful, so get a failed one to be able to display correct error message
                        crmSvc = tasks.FirstOrDefault(t => t.Result != null).Result;
                    }
                }

                // crmSvc = ConnectOnline(UseOsdp);

                AuthType = AuthenticationProviderType.OnlineFederation;
            }
            else if (UseIfd)
            {
                var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                                                     ConnectionManager.CryptoSaltValue,
                                                     ConnectionManager.CryptoHashAlgorythm,
                                                     ConnectionManager.CryptoPasswordIterations,
                                                     ConnectionManager.CryptoInitVector,
                                                     ConnectionManager.CryptoKeySize);

                crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), UserDomain, HomeRealmUrl,
                                              ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl);

                AuthType = AuthenticationProviderType.Federation;
            }
            else
            {
                NetworkCredential credential;
                if (!IsCustomAuth)
                {
                    credential = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                                                         ConnectionManager.CryptoSaltValue,
                                                         ConnectionManager.CryptoHashAlgorythm,
                                                         ConnectionManager.CryptoPasswordIterations,
                                                         ConnectionManager.CryptoInitVector,
                                                         ConnectionManager.CryptoKeySize);

                    credential = new NetworkCredential(UserName, password, UserDomain);
                }
                crmSvc = new CrmServiceClient(credential, AuthenticationType.AD, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl);

                AuthType = AuthenticationProviderType.ActiveDirectory;
            }

            if (!crmSvc.IsReady)
            {
                var error = crmSvc.LastCrmError;
                crmSvc = null;
                throw new Exception(error);
            }

            if (crmSvc.OrganizationServiceProxy != null)
            {
                crmSvc.OrganizationServiceProxy.Timeout = Timeout;
            }

            return(crmSvc);
        }
예제 #19
0
        public void Login()
        {
            //validate the input strings here...
            if (!ValidateInput())
            {
                //show error message
                //set flag
                ConnectionParams.Instance.Status = LoginStatus.Disconncted;
            }

            //build the login url
            string url = "http://";

            url += ServerAddress;
            url += ":";
            url += ServerPort.ToString() + "/";
            url += ConsoleDefinitions.GlobalConf.EIB_CLIENT_AUTHENTICATE;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //EIB server should respond in 3 seconds...
            request.Timeout = 3000;
            request.Headers.Add(ConsoleDefinitions.GlobalConf.USER_NAME_HEADER, UserName);
            request.Headers.Add(ConsoleDefinitions.GlobalConf.PASSWORD_HEADER, Password);
            //allocate cookie containter instance
            request.CookieContainer = new CookieContainer();

            HttpWebResponse reply = null;

            try
            {
                reply = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    ConnectionParams.Instance.Status = LoginStatus.ServerDown;
                    return;
                }

                switch (((HttpWebResponse)e.Response).StatusCode)
                {
                case HttpStatusCode.Forbidden:
                    ConnectionParams.Instance.Status = LoginStatus.ConnectionDenied;
                    return;
                }
            }

            StreamReader sr     = new StreamReader(reply.GetResponseStream());
            string       result = sr.ReadToEnd();

            //validate reply
            if (result == ConsoleDefinitions.GlobalConf.EIB_CLIENT_AUTHENTICATE_SUCCESS)
            {
                if (reply.Cookies[ConsoleDefinitions.GlobalConf.EIB_SESSION_ID_COOKIE_NAME] != null)
                {
                    ConnectionParams.Instance.SessionID   = reply.Cookies[ConsoleDefinitions.GlobalConf.EIB_SESSION_ID_COOKIE_NAME].Value;
                    ConnectionParams.Instance.HttpAddress = "http://" + ServerAddress + ":" + ServerPort.ToString() + "/";
                    ConnectionParams.Instance.Domain      = ServerAddress;
                    ConnectionParams.Instance.Status      = LoginStatus.Connected;
                }
                else
                {
                    ConnectionParams.Instance.Status      = LoginStatus.Disconncted;
                    ConnectionParams.Instance.HttpAddress = String.Empty;
                    ConnectionParams.Instance.SessionID   = String.Empty;
                }
            }
            else if (result == ConsoleDefinitions.GlobalConf.EIB_CLIENT_AUTHENTICATE_FAILED)
            {
                ConnectionParams.Instance.Status      = LoginStatus.ConnectionDenied;
                ConnectionParams.Instance.HttpAddress = String.Empty;
                ConnectionParams.Instance.SessionID   = String.Empty;
            }
            else
            {
                throw new Exception("Incorrect reply to login request");
            }
        }