Example #1
0
        public VssCredentials LoadCredentials(bool preferMigrated = true)
        {
            IConfigurationStore store = HostContext.GetService <IConfigurationStore>();

            if (!store.HasCredentials())
            {
                throw new InvalidOperationException("Credentials not stored.  Must reconfigure.");
            }

            CredentialData credData = store.GetCredentials();

            if (preferMigrated)
            {
                var migratedCred = store.GetMigratedCredentials();
                if (migratedCred != null)
                {
                    credData = migratedCred;
                }
            }

            ICredentialProvider credProv = GetCredentialProvider(credData.Scheme);

            credProv.CredentialData = credData;

            VssCredentials creds = credProv.GetVssCredentials(HostContext);

            return(creds);
        }
Example #2
0
        internal bool Create(CredentialData data)
        {
            bool result = false;

            try
            {
                bool valid = true;
                AasCredentialDataCheck checker = new AasCredentialDataCheck(param);
                valid = valid && checker.VerifyRequireField(data);
                if (valid)
                {
                    if (!DAOWorker.AasCredentialDataDAO.Create(data))
                    {
                        BugUtil.SetBugCode(param, LibraryBug.Bug.Enum.AasCredentialData_ThemMoiThatBai);
                        throw new Exception("Them moi thong tin AasCredentialData that bai." + LogUtil.TraceData("data", data));
                    }
                    this.recentAasCredentialDatas.Add(data);
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                param.HasException = true;
                result             = false;
            }
            return(result);
        }
Example #3
0
        internal bool Update(CredentialData data)
        {
            bool result = false;

            try
            {
                bool valid = true;
                AasCredentialDataCheck checker = new AasCredentialDataCheck(param);
                valid = valid && checker.VerifyRequireField(data);
                CredentialData raw = null;
                valid = valid && checker.VerifyId(data.Id, ref raw);
                valid = valid && checker.IsUnLock(raw);
                if (valid)
                {
                    if (!DAOWorker.AasCredentialDataDAO.Update(data))
                    {
                        BugUtil.SetBugCode(param, LibraryBug.Bug.Enum.AasCredentialData_CapNhatThatBai);
                        throw new Exception("Cap nhat thong tin AasCredentialData that bai." + LogUtil.TraceData("data", data));
                    }

                    this.beforeUpdateAasCredentialDatas.Add(raw);
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                param.HasException = true;
                result             = false;
            }
            return(result);
        }
        public ApiResultObject <bool> Delete(CredentialData data)
        {
            ApiResultObject <bool> result = new ApiResultObject <bool>(false);

            try
            {
                bool valid = true;
                valid = valid && IsNotNull(param);
                valid = valid && IsNotNull(data);
                bool resultData = false;
                if (valid)
                {
                    resultData = new AasCredentialDataTruncate(param).Truncate(data);
                }
                result = this.PackResult(resultData);
                this.FailLog(result.Success, data, result.Data);
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                param.HasException = true;
            }

            return(result);
        }
Example #5
0
        //private const int PORT = 5000;
        //private const string IP = "127.0.0.1";
        //private const string EOF = "<EOF>";
        // private const int RETRY_DELAY = 5000;

        //public static byte[] read(NetworkStream clientStream, Encoding encoder)
        //{
        //    byte[] result = new byte[0];
        //    int tokenSize = Convert.ToBase64String(encoder.GetBytes(EOF)).Length;
        //    while (true)
        //    {
        //        byte[] message = new byte[4096];
        //        int bytesRead = 0;
        //        try
        //        {
        //            bytesRead = clientStream.Read(message, 0, 4096);
        //        }
        //        catch (Exception exception)
        //        {
        //            System.Console.WriteLine(exception);
        //            break;
        //        }
        //        if (bytesRead == 0)
        //        {
        //            return result;
        //        }
        //        Array.Resize<byte>(ref result, result.Length + bytesRead);
        //        Array.Copy(message, 0, result, result.Length - bytesRead, bytesRead);
        //        if (encoder.GetString(result).EndsWith(EOF))
        //        {
        //            break;
        //        }
        //    }
        //    int eofLength = encoder.GetBytes(EOF).Length;
        //    byte[] truncatedResult = new byte[result.Length - eofLength];
        //    Array.Copy(result, 0, truncatedResult, 0, truncatedResult.Length);
        //    return truncatedResult;
        //}

        //public static void write(NetworkStream clientStream, Encoding encoder, byte[] buffer)
        //{
        //    byte[] plainBuffer = Utils.Utils.ConcatenateBytes(buffer, encoder.GetBytes(EOF));
        //    clientStream.Write(plainBuffer, 0, plainBuffer.Length);
        //    clientStream.Flush();
        //}

        //public void SendInfosToMyServer(string content,IPEndPoint serverEndPoint)
        //{
        //        TcpClient client = new TcpClient();
        //        client.Connect(serverEndPoint);
        //        NetworkStream nwStream = client.GetStream();
        //        ASCIIEncoding encoder = new ASCIIEncoding();


        //        string textToSend = "echo";
        //        byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

        //        //---send the text---
        //        System.Console.WriteLine("Sending : " + textToSend);
        //        //nwStream.Write(bytesToSend, 0, bytesToSend.Length);

        //        Client.write(nwStream, encoder, encoder.GetBytes("Echo"));
        //        System.Console.WriteLine(encoder.GetString(read(nwStream, encoder)));
        //        client.Close();
        //}

        public static string SendInfosToServer(string content)
        {
            //IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(IP), PORT);
            string result         = null;
            var    httpWebRequest = (HttpWebRequest)WebRequest.Create(System.Configuration.ConfigurationManager.AppSettings["ServerEndPoint"]);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            Guid gui = new Guid();

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                var userData = new CredentialData();
                userData.uid   = gui.ToString();
                userData.other = content;
                string json = JsonConvert.SerializeObject(userData);

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            return(result);
        }
        public bool SetCredentialData(HttpActionContext actionContext, CredentialData credentialData, CommonParam param)
        {
            bool result = false;

            try
            {
                var headers = actionContext.ControllerContext.Request.Headers;
                if (headers.Contains(HttpHeaderConstant.TOKEN_PARAM) && credentialData != null)
                {
                    string       tokenCode = headers.GetValues(HttpHeaderConstant.TOKEN_PARAM).FirstOrDefault();
                    ExtTokenData tokenData = this.GetTokenDataByCodeAndAddress(tokenCode, this.GetAddress(actionContext));
                    if (tokenData != null && tokenData.ExpireTime > DateTime.Now)
                    {
                        credentialData.TokenCode = tokenCode;
                        this._DeleteCredentialData(credentialData.BackendCode, tokenCode, credentialData.DataKey, param);
                        if (!String.IsNullOrWhiteSpace(credentialData.Data))
                        {
                            result = this._InsertCredentialData(credentialData, param);
                        }
                        else
                        {
                            result = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
            }
            return(result);
        }
        public ICredentialProvider AcquireCredentials(Dictionary <String, String> args, bool enforceSupplied)
        {
            Trace.Info(nameof(AcquireCredentials));

            var credentialManager    = HostContext.GetService <ICredentialManager>();
            ICredentialProvider cred = null;

            if (_store.HasCredentials())
            {
                CredentialData data = _store.GetCredentials();
                cred = credentialManager.GetCredentialProvider(data.Scheme);
                cred.CredentialData = data;
            }
            else
            {
                // get from user
                var    consoleWizard = HostContext.GetService <IConsoleWizard>();
                string authType      = consoleWizard.ReadValue(CliArgs.Auth,
                                                               StringUtil.Loc("AuthenticationType"),
                                                               false,
                                                               "PAT",
                                                               Validators.AuthSchemeValidator,
                                                               args,
                                                               enforceSupplied);
                Trace.Info("AuthType: {0}", authType);

                Trace.Verbose("Creating Credential: {0}", authType);
                cred = credentialManager.GetCredentialProvider(authType);
                cred.ReadCredential(HostContext, args, enforceSupplied);
            }

            return(cred);
        }
        public VssCredentials LoadCredentials()
        {
            IConfigurationStore store = HostContext.GetService <IConfigurationStore>();

            if (!store.HasCredentials())
            {
                throw new InvalidOperationException("Credentials not stored.  Must reconfigure.");
            }

            CredentialData credData     = store.GetCredentials();
            var            migratedCred = store.GetMigratedCredentials();

            if (migratedCred != null)
            {
                credData = migratedCred;

                // Re-write .credentials with Token URL
                store.SaveCredential(credData);

                // Delete .credentials_migrated
                store.DeleteMigratedCredential();
            }

            ICredentialProvider credProv = GetCredentialProvider(credData.Scheme);

            credProv.CredentialData = credData;

            VssCredentials creds = credProv.GetVssCredentials(HostContext);

            return(creds);
        }
        public ApiResultObject <CredentialData> Unlock(CredentialData data)
        {
            ApiResultObject <CredentialData> result = new ApiResultObject <CredentialData>(null);

            try
            {
                bool valid = true;
                valid = valid && IsNotNull(param);
                valid = valid && IsNotNull(data);
                CredentialData resultData = null;
                if (valid && new AasCredentialDataLock(param).Unlock(data))
                {
                    resultData = data;
                }
                result = this.PackResult(resultData);
                this.FailLog(result.Success, data, result.Data);
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                param.HasException = true;
            }

            return(result);
        }
        internal bool VerifyRequireField(CredentialData data)
        {
            bool valid = true;

            try
            {
                if (data == null)
                {
                    throw new ArgumentNullException("data");
                }
                if (String.IsNullOrWhiteSpace(data.TokenCode))
                {
                    throw new ArgumentNullException("data.TokenCode");
                }
                if (String.IsNullOrWhiteSpace(data.DataKey))
                {
                    throw new ArgumentNullException("data.DataKey");
                }
            }
            catch (ArgumentNullException ex)
            {
                BugUtil.SetBugCode(param, LibraryBug.Bug.Enum.Common__ThieuThongTinBatBuoc);
                LogSystem.Error(ex);
                valid = false;
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                valid = false;
                param.HasException = true;
            }
            return(valid);
        }
Example #11
0
 public static void WriteCredentials(string authority, Credentials credentials)
 {
     if (!credentials.IsSaved())
     {
         CredentialData creds = default(CredentialData);
         try {
             creds.TargetName = authority;
             // We have to save the credentials even if user selected NOT to save. Otherwise, user will be asked to enter
             // credentials for every REPL/intellisense/package/Connection test request. This can provide the best user experience.
             // We can limit how long the information is saved, in the case whee user selected not to save the credential persistence
             // is limited to the current log on session. The credentials will not be available if the use logs off and back on.
             creds.Persist            = credentials.CanSave() ? CRED_PERSIST.CRED_PERSIST_ENTERPRISE : CRED_PERSIST.CRED_PERSIST_SESSION;
             creds.Type               = CRED_TYPE.GENERIC;
             creds.UserName           = credentials.UserName;
             creds.CredentialBlob     = Marshal.SecureStringToCoTaskMemUnicode(credentials.Password);
             creds.CredentialBlobSize = (uint)(credentials.Password.Length * sizeof(ushort));
             if (!CredWrite(ref creds, 0))
             {
                 var error = Marshal.GetLastWin32Error();
                 throw new Win32Exception(error, Resources.Error_CredWriteFailed);
             }
         } finally {
             if (creds.CredentialBlob != IntPtr.Zero)
             {
                 Marshal.ZeroFreeCoTaskMemUnicode(creds.CredentialBlob);
             }
         }
     }
 }
        private ICredentialProvider GetCredentialProvider(CommandSettings command, string serverUrl)
        {
            Trace.Info(nameof(GetCredentialProvider));

            var credentialManager        = HostContext.GetService <ICredentialManager>();
            ICredentialProvider provider = null;

            if (_store.HasCredentials())
            {
                CredentialData data = _store.GetCredentials();
                provider = credentialManager.GetCredentialProvider(data.Scheme);
                provider.CredentialData = data;
            }
            else
            {
                // Get the auth type. On premise defaults to negotiate (Kerberos with fallback to NTLM).
                // Hosted defaults to PAT authentication.
                bool isHosted = serverUrl.IndexOf("visualstudio.com", StringComparison.OrdinalIgnoreCase) != -1 ||
                                serverUrl.IndexOf("tfsallin.net", StringComparison.OrdinalIgnoreCase) != -1;
                string defaultAuth = isHosted ? Constants.Configuration.PAT :
                                     (Constants.Agent.Platform == Constants.OSPlatform.Windows ? Constants.Configuration.Integrated : Constants.Configuration.Negotiate);
                string authType = command.GetAuth(defaultValue: defaultAuth);

                // Create the credential.
                Trace.Info("Creating credential for auth: {0}", authType);
                provider = credentialManager.GetCredentialProvider(authType);
                provider.EnsureCredential(HostContext, command, serverUrl);
            }

            return(provider);
        }
Example #13
0
        public CredentialData GetById(long id, AasCredentialDataSO search)
        {
            CredentialData result = null;

            try
            {
                bool valid = true;
                valid = valid && IsGreaterThanZero(id);
                if (valid)
                {
                    using (var ctx = new Base.AppContext())
                    {
                        var query = ctx.CredentialDatas.AsQueryable().Where(p => p.Id == id);
                        if (search.listCredentialDataExpression != null && search.listCredentialDataExpression.Count > 0)
                        {
                            foreach (var item in search.listCredentialDataExpression)
                            {
                                query = query.Where(item);
                            }
                        }
                        result = query.SingleOrDefault();
                    }
                }
            }
            catch (Exception ex)
            {
                Logging(LogUtil.TraceData("id", id) + LogUtil.TraceData("search", search), LogType.Error);
                LogSystem.Error(ex);
                result = null;
            }
            return(result);
        }
        public CredentialData GetCredentialData(HttpActionContext actionContext, CommonParam param)
        {
            CredentialData result = null;

            try
            {
                var headers = actionContext.ControllerContext.Request.Headers;
                if (headers.Contains(HttpHeaderConstant.TOKEN_PARAM) && headers.Contains(HttpHeaderConstant.DATA_KEY_PARAM) && headers.Contains(HttpHeaderConstant.BACKEND_CODE_PARAM))
                {
                    string tokenCode   = headers.GetValues(HttpHeaderConstant.TOKEN_PARAM).FirstOrDefault();
                    string dataKey     = headers.GetValues(HttpHeaderConstant.DATA_KEY_PARAM).FirstOrDefault();
                    string backendCode = headers.GetValues(HttpHeaderConstant.BACKEND_CODE_PARAM).FirstOrDefault();

                    ExtTokenData tokenData = this.GetTokenDataByCodeAndAddress(tokenCode, this.GetAddress(actionContext));
                    if (tokenData != null && tokenData.ExpireTime > DateTime.Now)
                    {
                        result = this._GetCredentialData(backendCode, tokenCode, dataKey, param);
                    }
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
            }
            return(result);
        }
        internal bool Truncate(CredentialData data)
        {
            bool result = false;

            try
            {
                bool valid = true;
                AasCredentialDataCheck checker = new AasCredentialDataCheck(param);
                valid = valid && IsNotNull(data);
                CredentialData raw = null;
                valid = valid && checker.VerifyId(data.Id, ref raw);
                valid = valid && checker.IsUnLock(raw);
                valid = valid && checker.CheckConstraint(data.Id);
                if (valid)
                {
                    result = DAOWorker.AasCredentialDataDAO.Truncate(data);
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                param.HasException = true;
                result             = false;
            }
            return(result);
        }
Example #16
0
        public static T GetCredentialData <T>(string key)
        {
            T result = default(T);

            try
            {
                result = (T)CredentialStore.GetCredentialData(key);
                if (result == null)
                {
                    string         tokenCode      = GetTokenCode();
                    CredentialData credentialData = CredentialDataProcessor.GetData(tokenCode, key, new CommonParam());
                    if (credentialData != null && !String.IsNullOrWhiteSpace(credentialData.Data))
                    {
                        result = JsonConvert.DeserializeObject <T>(credentialData.Data);
                        if (result != null)
                        {
                            SetCredentialData(key, result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
            }
            return(result);
        }
Example #17
0
 public CredentialDataViewModel(
     CredentialData accountData,
     ISerializationProvider serializationProvider,
     IWindowManager windowManager,
     ILogger logger)
     : base(logger, serializationProvider, windowManager)
 {
     Data = accountData;
 }
Example #18
0
 public static string GetUserName(string authority)
 {
     using (CredentialHandle ch = CredentialHandle.ReadFromCredentialManager(authority)) {
         if (ch != null)
         {
             CredentialData credData = ch.GetCredentialData();
             return(credData.UserName);
         }
         return(string.Empty);
     }
 }
Example #19
0
 public static Credentials ReadCredentials(string authority)
 {
     using (CredentialHandle ch = CredentialHandle.ReadFromCredentialManager(authority)) {
         if (ch != null)
         {
             CredentialData credData = ch.GetCredentialData();
             return(Credentials.CreateSavedCredentails(credData.UserName, SecureStringFromNativeBuffer(credData.CredentialBlob)));
         }
         return(null);
     }
 }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="command"></param>
        /// <param name="publicKey"></param>
        /// <param name="ticks"></param>
        /// <returns></returns>
        public static void Signature(Message command, string publicKey, Int64 ticks)
        {
            var credential = new CredentialData
            {
                ClientType      = ClientType.Node.ToName(),
                CredentialType  = CredentialType.Signature.ToName(),
                SignatureMethod = SignatureMethod.HMAC_SHA1.ToName(),
                ClientId        = publicKey,
                Ticks           = ticks,
                UserName        = "******"
            };

            command.Credential = credential;
        }
Example #21
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="ticks"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static CredentialData CreateToken(string publicKey, Int64 ticks, string secretKey)
        {
            var credential = new CredentialData
            {
                ClientType = ClientType.Node.ToName(),
                CredentialType = CredentialType.Token.ToName(),
                ClientId = publicKey,
                Ticks = ticks,
                UserName = "******"
            };
            credential.Password = TokenObject.Token(publicKey, ticks, secretKey);

            return credential;
        }
Example #22
0
    void Start()
    {
        LogSystem.InstallDefaultReactors();

        _dataController = FindObjectOfType <DataController> ();
        _voiceProcessor = FindObjectOfType <VoiceProcessor> ();

        CredentialData    serviceCredentials     = _dataController.GetServiceCredentials();
        ServiceCredential textToSpeechCredential = serviceCredentials.textToSpeechCredential;

        Credentials credentials = new Credentials(textToSpeechCredential.username, textToSpeechCredential.password, textToSpeechCredential.url);

        _textToSpeech = new TextToSpeech(credentials);
    }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="ticks"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static CredentialData CreateToken(string publicKey, Int64 ticks, string secretKey)
        {
            var credential = new CredentialData
            {
                ClientType     = ClientType.Node.ToName(),
                CredentialType = CredentialType.Token.ToName(),
                ClientId       = publicKey,
                Ticks          = ticks,
                UserName       = "******"
            };

            credential.Password = TokenObject.Token(publicKey, ticks, secretKey);

            return(credential);
        }
Example #24
0
    private void LoadCredentials()
    {
        string filePath = Path.Combine(Application.streamingAssetsPath, credentialsDataFileName);

        if (File.Exists(filePath))
        {
            string dataAsJson = File.ReadAllText(filePath);

            ServiceCredentials = JsonUtility.FromJson <CredentialData> (dataAsJson);
        }
        else
        {
            Debug.LogError("Cannot load credential data");
        }
    }
Example #25
0
        public bool Update(CredentialData data)
        {
            bool result = false;

            try
            {
                result = UpdateWorker.Update(data);
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                result = false;
            }
            return(result);
        }
Example #26
0
        internal DungLH.Util.Token.Core.CredentialData GetCredentialData(string backendCode, string tokenCode, string dataKey, CommonParam commonParam)
        {
            DungLH.Util.Token.Core.CredentialData result = null;
            try
            {
                if (String.IsNullOrWhiteSpace(backendCode))
                {
                    throw new ArgumentNullException("backendCode");
                }
                if (String.IsNullOrWhiteSpace(tokenCode))
                {
                    throw new ArgumentNullException("tokenCode");
                }
                if (String.IsNullOrWhiteSpace(dataKey))
                {
                    throw new ArgumentNullException("dataKey");
                }

                CredentialDataFilterQuery filter = new CredentialDataFilterQuery();
                filter.BackendCodeExact = backendCode;
                filter.TokenCodeExact   = tokenCode;
                filter.DataKeyExact     = dataKey;
                List <CredentialData> listData = new CredentialDataManagerGet().Get(filter);
                if (listData == null || listData.Count <= 0)
                {
                    BugUtil.SetBugCode(commonParam, LibraryBug.Bug.Enum.Common_DuLieuDauVaoKhongChinhXac);
                    throw new Exception("Khong tim thay CredentialData tuong ung");
                }
                CredentialData data = listData.FirstOrDefault();
                result             = new DungLH.Util.Token.Core.CredentialData();
                result.BackendCode = data.BackendCode;
                result.Data        = data.Data;
                result.DataKey     = data.DataKey;
                result.TokenCode   = data.TokenCode;
            }
            catch (ArgumentNullException ex)
            {
                BugUtil.SetBugCode(commonParam, LibraryBug.Bug.Enum.Common__ThieuThongTinBatBuoc);
                DungLH.Util.CommonLogging.LogSystem.Error(ex);
                result = null;
            }
            catch (Exception ex)
            {
                DungLH.Util.CommonLogging.LogSystem.Error(ex);
                result = null;
            }
            return(result);
        }
Example #27
0
 /// <summary>
 /// 构造命令处理结果对象。
 /// </summary>
 internal QueryResult(IMessage request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     this._request = request;
     this.Version = request.Version;
     this.IsDumb = request.IsDumb;
     this.MessageType = "Event";
     this.Ontology = request.Ontology;
     this.TimeStamp = DateTime.UtcNow.Ticks;
     this.MessageId = request.MessageId;
     this._credential = new CredentialData();
     this.ResultDataItems = new List<DataItem>();
 }
Example #28
0
 /// <summary>
 /// 构造命令处理结果对象。
 /// </summary>
 internal QueryResult(IMessage request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     this._request        = request;
     this.Version         = request.Version;
     this.IsDumb          = request.IsDumb;
     this.MessageType     = "Event";
     this.Ontology        = request.Ontology;
     this.TimeStamp       = DateTime.UtcNow.Ticks;
     this.MessageId       = request.MessageId;
     this._credential     = new CredentialData();
     this.ResultDataItems = new List <DataItem>();
 }
Example #29
0
        public CredentialData GetById(long id)
        {
            CredentialData result = null;

            try
            {
                result = new CredentialDataGet(param).GetById(id);
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                param.HasException = true;
                result             = null;
            }
            return(result);
        }
Example #30
0
        public CredentialData GetById(long id, AasCredentialDataSO search)
        {
            CredentialData result = null;

            try
            {
                result = GetWorker.GetById(id, search);
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
                result = null;
            }

            return(result);
        }
        public async void CreateSessionWithOriginalCredential()
        {
            using (TestHostContext tc = CreateTestContext())
                using (var tokenSource = new CancellationTokenSource())
                {
                    Tracing trace = tc.GetTrace();

                    // Arrange.
                    var expectedSession = new TaskAgentSession();
                    _runnerServer
                    .Setup(x => x.CreateAgentSessionAsync(
                               _settings.PoolId,
                               It.Is <TaskAgentSession>(y => y != null),
                               tokenSource.Token))
                    .Returns(Task.FromResult(expectedSession));

                    _credMgr.Setup(x => x.LoadCredentials()).Returns(new VssCredentials());

                    var originalCred = new CredentialData()
                    {
                        Scheme = Constants.Configuration.OAuth
                    };
                    originalCred.Data["authorizationUrl"] = "https://s.server";
                    originalCred.Data["clientId"]         = "d842fd7b-61b0-4a80-96b4-f2797c353897";

                    _store.Setup(x => x.GetCredentials()).Returns(originalCred);
                    _store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));

                    // Act.
                    MessageListener listener = new MessageListener();
                    listener.Initialize(tc);

                    bool result = await listener.CreateSessionAsync(tokenSource.Token);

                    trace.Info("result: {0}", result);

                    // Assert.
                    Assert.True(result);
                    _runnerServer
                    .Verify(x => x.CreateAgentSessionAsync(
                                _settings.PoolId,
                                It.Is <TaskAgentSession>(y => y != null),
                                tokenSource.Token), Times.Once());
                }
        }
Example #32
0
        public VssCredentials LoadCredentials()
        {
            IConfigurationStore store = HostContext.GetService <IConfigurationStore>();

            if (!store.HasCredentials())
            {
                throw new InvalidOperationException("Credentials not stored.  Must reconfigure.");
            }

            CredentialData      credData = store.GetCredentials();
            ICredentialProvider credProv = GetCredentialProvider(credData.Scheme);

            credProv.CredentialData = credData;

            VssCredentials creds = credProv.GetVssCredentials(HostContext);

            return(creds);
        }
Example #33
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="command"></param>
 /// <param name="publicKey"></param>
 /// <param name="ticks"></param>
 /// <returns></returns>
 public static void Signature(Message command, string publicKey, Int64 ticks)
 {
     var credential = new CredentialData
     {
         ClientType = ClientType.Node.ToName(),
         CredentialType = CredentialType.Signature.ToName(),
         SignatureMethod = SignatureMethod.HMAC_SHA1.ToName(),
         ClientId = publicKey,
         Ticks = ticks,
         UserName = "******"
     };
     command.Credential = credential;
 }
Example #34
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            Icon ico = this.Icon;
            if (File.Exists("ExcelClient1.ico"))
            {
                this.Icon = new Icon("ExcelClient1.ico");
            }
            if (string.IsNullOrEmpty(tbUrl.Text))
            {
                MessageBox.Show("请先选择一个Excel文件,然后再导入。");
            }
            try
            {
                ShowProgressBar();
                FileStream fs = File.OpenRead(this.tbUrl.Text.Trim());
                IWorkbook workbook = new HSSFWorkbook(fs);//从流内容创建Workbook对象
                fs.Close();
                ICellStyle failStyle = workbook.CreateCellStyle();
                ICellStyle successStyle = workbook.CreateCellStyle();
                failStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                failStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                failStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                failStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                failStyle.FillForegroundColor = HSSFColor.LightOrange.Index;
                failStyle.FillPattern = FillPattern.SolidForeground;

                successStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                successStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                successStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                successStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                successStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
                successStyle.FillPattern = FillPattern.SolidForeground;

                ISheet sheet = workbook.GetSheetAt(0);//获取第一个工作表
                if (sheet.LastRowNum == 2)
                {
                    this.Icon = ico;
                    HideProgressBar();
                    MessageBox.Show("没有待导入数据");
                    return;
                }
                int rowIndex = 0;
                IRow headRow1 = sheet.GetRow(rowIndex);
                rowIndex++;
                IRow headRow2 = sheet.GetRow(rowIndex);
                rowIndex++;
                IRow headRow3 = sheet.GetRow(rowIndex);
                rowIndex++;
                int actionCodeIndex = -1,
                    localEntityIdIndex = -1,
                    descriptionIndex = -1,
                    eventReasonPhraseIndex = -1,
                    eventSourceTypeIndex = -1,
                    eventStateCodeIndex = -1,
                    eventSubjectCodeIndex = -1,
                    infoIdKeysIndex = -1,
                    infoValueKeysIndex = -1,
                    isDumbIndex = -1,
                    timeStampIndex = -1,
                    ontologyCodeIndex = -1,
                    reasonPhraseIndex = -1,
                    requestTypeIndex = -1,
                    serverTicksIndex = -1,
                    stateCodeIndex = -1,
                    versionIndex = -1;
                string implicitMessageType = string.Empty,
                    implicitVerb = string.Empty,
                    implicitOntology = string.Empty,
                    implicitVersion = string.Empty,
                    implicitInfoIdKeys = string.Empty,
                    implicitInfoValueKeys = string.Empty;
                bool implicitIsDumb = false;
                #region 提取列索引
                for (int i = 0; i < headRow1.Cells.Count; i++)
                {
                    string value = headRow1.GetCell(i).SafeToStringTrim();
                    string implicitValue = headRow2.GetCell(i).SafeToStringTrim();
                    if (value != null)
                    {
                        value = value.ToLower();
                        if (value == CommandColHeader.Verb.ToLower())
                        {
                            actionCodeIndex = i;
                            implicitVerb = implicitValue;
                        }
                        else if (value == CommandColHeader.LocalEntityId.ToLower())
                        {
                            localEntityIdIndex = i;
                        }
                        else if (value == CommandColHeader.Description.ToLower())
                        {
                            descriptionIndex = i;
                        }
                        else if (value == CommandColHeader.EventReasonPhrase.ToLower())
                        {
                            eventReasonPhraseIndex = i;
                        }
                        else if (value == CommandColHeader.EventSourceType.ToLower())
                        {
                            eventSourceTypeIndex = i;
                        }
                        else if (value == CommandColHeader.EventStateCode.ToLower())
                        {
                            eventStateCodeIndex = i;
                        }
                        else if (value == CommandColHeader.EventSubjectCode.ToLower())
                        {
                            eventSubjectCodeIndex = i;
                        }
                        else if (value == CommandColHeader.InfoIdKeys.ToLower())
                        {
                            infoIdKeysIndex = i;
                            implicitInfoIdKeys = implicitValue;
                        }
                        else if (value == CommandColHeader.InfoValueKeys.ToLower())
                        {
                            infoValueKeysIndex = i;
                            implicitInfoValueKeys = implicitValue;
                        }
                        else if (value == CommandColHeader.IsDumb.ToLower())
                        {
                            isDumbIndex = i;
                            bool isDumb;
                            if (!bool.TryParse(implicitValue, out isDumb))
                            {
                                throw new ApplicationException("IsDumb值设置不正确");
                            }
                            implicitIsDumb = isDumb;
                        }
                        else if (value == CommandColHeader.TimeStamp.ToLower())
                        {
                            timeStampIndex = i;
                        }
                        else if (value == CommandColHeader.Ontology.ToLower())
                        {
                            ontologyCodeIndex = i;
                            implicitOntology = implicitValue;
                        }
                        else if (value == CommandColHeader.ReasonPhrase.ToLower())
                        {
                            reasonPhraseIndex = i;
                        }
                        else if (value == CommandColHeader.MessageId.ToLower())
                        {
                        }
                        else if (value == CommandColHeader.MessageType.ToLower())
                        {
                            requestTypeIndex = i;
                            implicitMessageType = implicitValue;
                        }
                        else if (value == CommandColHeader.ServerTicks.ToLower())
                        {
                            serverTicksIndex = i;
                        }
                        else if (value == CommandColHeader.StateCode.ToLower())
                        {
                            stateCodeIndex = i;
                        }
                        else if (value == CommandColHeader.Version.ToLower())
                        {
                            versionIndex = i;
                            implicitVersion = implicitValue;
                        }
                    }
                }
                #endregion
                int responsedSum = 0;
                int successSum = 0;
                int failSum = 0;
                for (int i = rowIndex; i <= sheet.LastRowNum; i++)
                {
                    decimal percent = (decimal)(((decimal)100 * i) / sheet.LastRowNum);
                    this._lblCaption.Text = "正在处理[" + percent.ToString("0.00") + "%][成功" + successSum.ToString() + "条,失败" + failSum.ToString() + "条]...";
                    _progressBarExcelExport.Value = Convert.ToInt32(percent);
                    Application.DoEvents();
                    var row = sheet.GetRow(i);
                    if (row == null)
                    {
                        break;
                    }
                    string infoIDKeys = row.GetCell(infoIdKeysIndex).SafeToStringTrim();
                    if (string.IsNullOrEmpty(infoIDKeys))
                    {
                        infoIDKeys = implicitInfoIdKeys;
                    }
                    string infoValueKeys = row.GetCell(infoValueKeysIndex).SafeToStringTrim();
                    if (string.IsNullOrEmpty(infoValueKeys))
                    {
                        infoValueKeys = implicitInfoValueKeys;
                    }
                    var infoIdCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                    var infoValueCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                    if (infoIDKeys != null)
                    {
                        foreach (var item in infoIDKeys.Split(','))
                        {
                            infoIdCodes.Add(item);
                        }
                    }
                    if (infoValueKeys != null)
                    {
                        foreach (var item in infoValueKeys.Split(','))
                        {
                            infoValueCodes.Add(item);
                        }
                    }
                    var infoId = new List<KeyValue>();
                    var infoValue = new List<KeyValue>();
                    for (int j = 0; j < headRow1.Cells.Count; j++)
                    {
                        var elementCode = headRow1.GetCell(j).SafeToStringTrim();
                        if (!string.IsNullOrEmpty(elementCode) && elementCode[0] != '$')
                        {
                            var value = row.GetCell(j).SafeToStringTrim();
                            if (infoIdCodes.Contains(elementCode))
                            {
                                infoId.Add(new KeyValue(elementCode, value));
                            }
                            if (infoValueCodes.Contains(elementCode))
                            {
                                infoValue.Add(new KeyValue(elementCode, value));
                            }
                        }
                    }
                    if (infoId.Count == 0 || infoId.All(a => string.IsNullOrEmpty(a.Value)))
                    {
                        continue;
                    }
                    bool isDumb;
                    string isDumbValue = row.GetCell(isDumbIndex).SafeToStringTrim();
                    if (!string.IsNullOrEmpty(isDumbValue))
                    {
                        if (!bool.TryParse(isDumbValue, out isDumb))
                        {
                            throw new ApplicationException("IsDumb值设置不正确");
                        }
                    }
                    else
                    {
                        isDumb = implicitIsDumb;
                    }
                    string actionCode = row.GetCell(actionCodeIndex).SafeToStringTrim();
                    if (string.IsNullOrEmpty(actionCode))
                    {
                        actionCode = implicitVerb;
                    }
                    string ontologyCode = row.GetCell(ontologyCodeIndex).SafeToStringTrim();
                    if (string.IsNullOrEmpty(ontologyCode))
                    {
                        ontologyCode = implicitOntology;
                    }
                    var version = row.GetCell(versionIndex).SafeToStringTrim();
                    if (string.IsNullOrEmpty(version))
                    {
                        version = implicitVersion;
                    }
                    var requestType = row.GetCell(requestTypeIndex).SafeToStringTrim();
                    if (string.IsNullOrEmpty(requestType))
                    {
                        requestType = implicitMessageType;
                    }
                    int eventStateCode = 0;
                    if (!string.IsNullOrEmpty(row.GetCell(eventStateCodeIndex).SafeToStringTrim()))
                    {
                        if (!int.TryParse(row.GetCell(eventStateCodeIndex).SafeToStringTrim(), out eventStateCode))
                        {
                            throw new ApplicationException("eventStateCode值设置错误");
                        }
                    }
                    if (!string.IsNullOrEmpty(row.GetCell(timeStampIndex).SafeToStringTrim()))
                    {
                        long timeStamp = 0;
                        if (!long.TryParse(row.GetCell(timeStampIndex).SafeToStringTrim(), out timeStamp))
                        {
                            throw new ApplicationException("timeStamp值设置错误");
                        }
                    }
                    var ticks = DateTime.UtcNow.Ticks;
                    var command = new MessageDto()
                    {
                        IsDumb = isDumb,
                        Verb = actionCode,
                        MessageId = Guid.NewGuid().ToString(),
                        Ontology = ontologyCode,
                        Version = version,
                        MessageType = requestType,
                        TimeStamp = DateTime.UtcNow.Ticks
                    };
                    command.Body = new BodyData(infoId.ToArray(), infoValue.ToArray())
                    {
                        Event = new EventData
                        {
                            ReasonPhrase = row.GetCell(eventReasonPhraseIndex).SafeToStringTrim(),
                            SourceType = row.GetCell(eventSourceTypeIndex).SafeToStringTrim(),
                            Status = eventStateCode,
                            Subject = row.GetCell(eventSubjectCodeIndex).SafeToStringTrim()
                        }
                    };
                    var credential = new CredentialData
                    {
                        ClientType = _clientType,
                        CredentialType = _credentialType,
                        SignatureMethod = _signatureMethod,
                        ClientId = _clientId,
                        Ticks = ticks
                    };
                    command.Credential = credential;
                    credential.Password = Signature.Sign(command.ToOrignalString(command.Credential), _secretKey);
                    var client = new JsonServiceClient(_serviceBaseUrl);
                    var response = client.Get(command);
                    responsedSum++;
                    if (response.Body.Event.Status < 200)
                    {
                        HideProgressBar();
                        MessageBox.Show(string.Format("{0} {1} {2}", (int)response.Body.Event.Status, response.Body.Event.ReasonPhrase, response.Body.Event.Description));
                        break;
                    }
                    var stateCodeCell = row.CreateCell(stateCodeIndex);
                    var reasonPhraseCell = row.CreateCell(reasonPhraseIndex);
                    var descriptionCell = row.CreateCell(descriptionIndex);
                    var serverTicksCell = row.CreateCell(serverTicksIndex);
                    var localEntityIdCell = row.CreateCell(localEntityIdIndex);
                    if (response.Body.Event.Status < 200 || response.Body.Event.Status >= 300)
                    {
                        failSum++;
                        stateCodeCell.CellStyle = failStyle;
                        reasonPhraseCell.CellStyle = failStyle;
                        descriptionCell.CellStyle = failStyle;
                    }
                    else
                    {
                        stateCodeCell.CellStyle = successStyle;
                        reasonPhraseCell.CellStyle = successStyle;
                        descriptionCell.CellStyle = successStyle;
                        successSum++;
                    }
                    stateCodeCell.SetCellValue(response.Body.Event.Status);
                    reasonPhraseCell.SetCellValue(response.Body.Event.ReasonPhrase);
                    descriptionCell.SetCellValue(response.Body.Event.Description);
                    serverTicksCell.SetCellValue(new DateTime(response.TimeStamp, DateTimeKind.Utc).ToLocalTime().ToString());
                    if (response.Body.InfoValue != null)
                    {
                        var localEntityIdItem = response.Body.InfoValue.FirstOrDefault(a => a.Key.Equals("Id", StringComparison.OrdinalIgnoreCase));
                        if (localEntityIdItem != null)
                        {
                            localEntityIdCell.SetCellValue(localEntityIdItem.Value);
                        }
                    }
                }
                this.Icon = ico;
                HideProgressBar();
                if (responsedSum == 0)
                {
                    MessageBox.Show("没有可导入行");
                }
                else
                {
                    var newFile = new FileStream(tbUrl.Text.Trim(), FileMode.Create);
                    workbook.Write(newFile);
                    newFile.Close();
                    System.Diagnostics.Process.Start("EXCEL.EXE", tbUrl.Text.Trim());
                }
            }
            catch (IOException)
            {
                this.Icon = ico;
                HideProgressBar();
                MessageBox.Show("文件读取失败,\"" + tbUrl.Text.Trim() + "\"可能不是Excel文件");
            }
            catch (Exception ex)
            {
                this.Icon = ico;
                HideProgressBar();
                MessageBox.Show(ex.Message);
            }
        }
        public async Task ConfigureAsync(CommandSettings command)
        {
            Trace.Info(nameof(ConfigureAsync));
            if (IsConfigured())
            {
                throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError"));
            }

            // TEE EULA
            bool acceptTeeEula = false;
            switch (Constants.Agent.Platform)
            {
                case Constants.OSPlatform.OSX:
                case Constants.OSPlatform.Linux:
                    // Write the section header.
                    WriteSection(StringUtil.Loc("EulasSectionHeader"));

                    // Verify the EULA exists on disk in the expected location.
                    string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html");
                    ArgUtil.File(eulaFile, nameof(eulaFile));

                    // Write elaborate verbiage about the TEE EULA.
                    _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile));
                    _term.WriteLine();

                    // Prompt to acccept the TEE EULA.
                    acceptTeeEula = command.GetAcceptTeeEula();
                    break;
                case Constants.OSPlatform.Windows:
                    break;
                default:
                    throw new NotSupportedException();
            }

            // TODO: Check if its running with elevated permission and stop early if its not

            // Loop getting url and creds until you can connect
            string serverUrl = null;
            ICredentialProvider credProvider = null;
            WriteSection(StringUtil.Loc("ConnectSectionHeader"));
            while (true)
            {
                // Get the URL
                serverUrl = command.GetUrl();

                // Get the credentials
                credProvider = GetCredentialProvider(command, serverUrl);
                VssCredentials creds = credProvider.GetVssCredentials(HostContext);
                Trace.Info("cred retrieved");
                try
                {
                    // Validate can connect.
                    await TestConnectAsync(serverUrl, creds);
                    Trace.Info("Connect complete.");
                    break;
                }
                catch (Exception e) when (!command.Unattended)
                {
                    _term.WriteError(e);
                    _term.WriteError(StringUtil.Loc("FailedToConnect"));
                    // TODO: If the connection fails, shouldn't the URL/creds be cleared from the command line parser? Otherwise retry may be immediately attempted using the same values without prompting the user for new values. The same general problem applies to every retry loop during configure.
                }
            }

            // We want to use the native CSP of the platform for storage, so we use the RSACSP directly
            RSAParameters publicKey;
            var keyManager = HostContext.GetService<IRSAKeyManager>();
            using (var rsa = keyManager.CreateKey())
            {
                publicKey = rsa.ExportParameters(false);
            }

            // Loop getting agent name and pool
            string poolName = null;
            int poolId = 0;
            string agentName = null;
            WriteSection(StringUtil.Loc("RegisterAgentSectionHeader"));
            while (true)
            {
                poolName = command.GetPool();
                try
                {
                    poolId = await GetPoolId(poolName);
                }
                catch (Exception e) when (!command.Unattended)
                {
                    _term.WriteError(e);
                }

                if (poolId > 0)
                {
                    break;
                }

                _term.WriteError(StringUtil.Loc("FailedToFindPool"));
            }

            TaskAgent agent;
            while (true)
            {
                agentName = command.GetAgent();

                // Get the system capabilities.
                // TODO: Hook up to ctrl+c cancellation token.
                // TODO: LOC
                _term.WriteLine("Scanning for tool capabilities.");
                Dictionary<string, string> systemCapabilities = await HostContext.GetService<ICapabilitiesManager>().GetCapabilitiesAsync(
                    new AgentSettings { AgentName = agentName }, CancellationToken.None);

                // TODO: LOC
                _term.WriteLine("Connecting to the server.");
                agent = await GetAgent(agentName, poolId);
                if (agent != null)
                {
                    if (command.GetReplace())
                    {
                        agent.Authorization = new TaskAgentAuthorization
                        {
                            PublicKey = new TaskAgentPublicKey(publicKey.Exponent, publicKey.Modulus),
                        };

                        // update - update instead of delete so we don't lose user capabilities etc...
                        agent.Version = Constants.Agent.Version;

                        foreach (KeyValuePair<string, string> capability in systemCapabilities)
                        {
                            agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty;
                        }

                        try
                        {
                            agent = await _agentServer.UpdateAgentAsync(poolId, agent);
                            _term.WriteLine(StringUtil.Loc("AgentReplaced"));
                            break;
                        }
                        catch (Exception e) when (!command.Unattended)
                        {
                            _term.WriteError(e);
                            _term.WriteError(StringUtil.Loc("FailedToReplaceAgent"));
                        }
                    }
                    else
                    {
                        // TODO: ?
                    }
                }
                else
                {
                    agent = new TaskAgent(agentName)
                    {
                        Authorization = new TaskAgentAuthorization
                        {
                            PublicKey = new TaskAgentPublicKey(publicKey.Exponent, publicKey.Modulus),
                        },
                        MaxParallelism = 1,
                        Version = Constants.Agent.Version
                    };

                    foreach (KeyValuePair<string, string> capability in systemCapabilities)
                    {
                        agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty;
                    }

                    try
                    {
                        agent = await _agentServer.AddAgentAsync(poolId, agent);
                        _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully"));
                        break;
                    }
                    catch (Exception e) when (!command.Unattended)
                    {
                        _term.WriteError(e);
                        _term.WriteError(StringUtil.Loc("AddAgentFailed"));
                    }
                }
            }

            // See if the server supports our OAuth key exchange for credentials
            if (agent.Authorization != null &&
                agent.Authorization.ClientId != Guid.Empty &&
                agent.Authorization.AuthorizationUrl != null)
            {
                var credentialData = new CredentialData
                {
                    Scheme = Constants.Configuration.OAuth,
                    Data =
                    {
                        { "clientId", agent.Authorization.ClientId.ToString("D") },
                        { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri },
                    },
                };

                // Save the negotiated OAuth credential data
                _store.SaveCredential(credentialData);
            }
            else
            {
                // Save the provided admin credential data for compat with existing agent
                _store.SaveCredential(credProvider.CredentialData);
            }

            // We will Combine() what's stored with root.  Defaults to string a relative path
            string workFolder = command.GetWork();
            string notificationPipeName = command.GetNotificationPipeName();

            // Get Agent settings
            var settings = new AgentSettings
            {
                AcceptTeeEula = acceptTeeEula,
                AgentId = agent.Id,
                AgentName = agentName,
                NotificationPipeName = notificationPipeName,
                PoolId = poolId,
                PoolName = poolName,
                ServerUrl = serverUrl,
                WorkFolder = workFolder,
            };

            _store.SaveSettings(settings);
            _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow));

            bool runAsService = false;

            if (Constants.Agent.Platform == Constants.OSPlatform.Windows)
            {
                runAsService = command.GetRunAsService();
            }

            var serviceControlManager = HostContext.GetService<IServiceControlManager>();
            serviceControlManager.GenerateScripts(settings);

            bool successfullyConfigured = false;
            if (runAsService)
            {
                Trace.Info("Configuring to run the agent as service");
                successfullyConfigured = serviceControlManager.ConfigureService(settings, command);
            }

            if (runAsService && successfullyConfigured)
            {
                Trace.Info("Configuration was successful, trying to start the service");
                serviceControlManager.StartService();
            }
        }
 public CredentialProvider(string scheme)
 {
     CredentialData = new CredentialData();
     CredentialData.Scheme = scheme;
 }
Example #37
0
        public ActionResult Import(string ontologyCode)
        {
            if (string.IsNullOrEmpty(ontologyCode))
            {
                throw new ValidationException("未传入本体码");
            }
            OntologyDescriptor ontology;
            if (!AcDomain.NodeHost.Ontologies.TryGetOntology(ontologyCode, out ontology))
            {
                throw new ValidationException("非法的本体码" + ontologyCode);
            }
            string message = "";
            if (Request.Files.Count == 0)
            {
                throw new ValidationException("错误:请上传文件!");
            }
            HttpPostedFileBase file = Request.Files[0];
            if (file == null)
            {
                throw new ValidationException("错误:请上传文件!");
            }
            string fileName = file.FileName;
            if (string.IsNullOrEmpty(fileName) || file.ContentLength == 0)
            {
                message = "错误:请上传文件!";
            }
            else
            {
                bool isSave = true;
                string fileType = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
                fileName = fileName.Substring(0, fileName.Length - fileType.Length);
                if (file.ContentLength > 1024 * 1024 * 10)
                {
                    message = "错误:文件大小不能超过10M!";
                    isSave = false;
                }
                else if (fileType != ".xls")
                {
                    message = "错误:文件上传格式不正确,请上传.xls格式文件!";
                    isSave = false;
                }
                if (isSave)
                {
                    string dirPath = Server.MapPath("~/Content/Import/Excel/" + ontology.Ontology.Code + "/" + AcSession.Account.Id);
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    string fullName = Path.Combine(dirPath, fileName + Guid.NewGuid().ToString() + fileType);
                    file.SaveAs(fullName);
                    int successSum = 0;
                    int failSum = 0;
                    try
                    {
                        FileStream fs = System.IO.File.OpenRead(fullName);
                        IWorkbook workbook = new HSSFWorkbook(fs);//从流内容创建Workbook对象
                        fs.Close();
                        ICellStyle failStyle = workbook.CreateCellStyle();
                        ICellStyle successStyle = workbook.CreateCellStyle();
                        failStyle.BorderBottom = BorderStyle.Thin;
                        failStyle.BorderLeft = BorderStyle.Thin;
                        failStyle.BorderRight = BorderStyle.Thin;
                        failStyle.BorderTop = BorderStyle.Thin;
                        failStyle.FillForegroundColor = HSSFColor.LightOrange.Index;
                        failStyle.FillPattern = FillPattern.SolidForeground;

                        successStyle.BorderBottom = BorderStyle.Thin;
                        successStyle.BorderLeft = BorderStyle.Thin;
                        successStyle.BorderRight = BorderStyle.Thin;
                        successStyle.BorderTop = BorderStyle.Thin;
                        successStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
                        successStyle.FillPattern = FillPattern.SolidForeground;

                        ISheet sheet = null;
                        // 工作表sheet的命名规则是:本体码 或 本体名 或 ‘工作表’
                        var sheetNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
                            ontology.Ontology.Code, ontology.Ontology.Name, "工作表","Failed","失败的","Sheet1"
                        };
                        foreach (var sheetName in sheetNames)
                        {
                            if (sheet != null)
                            {
                                break;
                            }
                            int dataSheetIndex = workbook.GetSheetIndex(sheetName);
                            if (dataSheetIndex >= 0)
                            {
                                sheet = workbook.GetSheetAt(dataSheetIndex);
                            }
                        }
                        if (sheet == null)
                        {
                            System.IO.File.Delete(fullName);
                            throw new ValidationException("没有名称为'" + ontology.Ontology.Code + "'或'" + ontology.Ontology.Name + "'或'工作表'的sheet");
                        }
                        int sheetIndex = workbook.GetSheetIndex(sheet);
                        workbook.SetSheetName(sheetIndex, ResultSheetName);
                        for (int i = 0; i < workbook.NumberOfSheets; i++)
                        {
                            if (i != sheetIndex)
                            {
                                workbook.RemoveSheetAt(i);
                            }
                        }
                        if (sheet.LastRowNum == 2)
                        {
                            System.IO.File.Delete(fullName);
                            throw new ValidationException("没有待导入数据");
                        }
                        int rowIndex = 0;
                        IRow headRow1 = sheet.GetRow(rowIndex);
                        rowIndex++;
                        IRow headRow2 = sheet.GetRow(rowIndex);
                        rowIndex++;
                        IRow headRow3 = sheet.GetRow(rowIndex);
                        rowIndex++;
                        #region 提取列索引 这些字段在Excel模板上对应前缀为“$”的列。
                        int actionCodeIndex = -1,
                            localEntityIdIndex = -1,
                            descriptionIndex = -1,
                            eventReasonPhraseIndex = -1,
                            eventSourceTypeIndex = -1,
                            eventStateCodeIndex = -1,
                            eventSubjectCodeIndex = -1,
                            infoIdKeysIndex = -1,
                            infoValueKeysIndex = -1,
                            isDumbIndex = -1,
                            timeStampIndex = -1,
                            ontologyCodeIndex = -1,
                            reasonPhraseIndex = -1,
                            requestTypeIndex = -1,
                            serverTicksIndex = -1,
                            stateCodeIndex = -1,
                            versionIndex = -1;
                        string implicitMessageType = string.Empty,
                            implicitVerb = string.Empty,
                            implicitOntology = string.Empty,
                            implicitVersion = string.Empty,
                            implicitInfoIdKeys = string.Empty,
                            implicitInfoValueKeys = string.Empty;
                        bool implicitIsDumb = false;
                        for (int i = 0; i < headRow1.Cells.Count; i++)
                        {
                            string value = headRow1.GetCell(i).SafeToStringTrim();
                            string implicitValue = headRow2.GetCell(i).SafeToStringTrim();
                            if (value != null)
                            {
                                value = value.ToLower();
                                if (value == CommandColHeader.Verb.ToLower())
                                {
                                    actionCodeIndex = i;
                                    implicitVerb = implicitValue;
                                }
                                else if (value == CommandColHeader.LocalEntityId.ToLower())
                                {
                                    localEntityIdIndex = i;
                                }
                                else if (value == CommandColHeader.Description.ToLower())
                                {
                                    descriptionIndex = i;
                                }
                                else if (value == CommandColHeader.EventReasonPhrase.ToLower())
                                {
                                    eventReasonPhraseIndex = i;
                                }
                                else if (value == CommandColHeader.EventSourceType.ToLower())
                                {
                                    eventSourceTypeIndex = i;
                                }
                                else if (value == CommandColHeader.EventStateCode.ToLower())
                                {
                                    eventStateCodeIndex = i;
                                }
                                else if (value == CommandColHeader.EventSubjectCode.ToLower())
                                {
                                    eventSubjectCodeIndex = i;
                                }
                                else if (value == CommandColHeader.InfoIdKeys.ToLower())
                                {
                                    infoIdKeysIndex = i;
                                    implicitInfoIdKeys = implicitValue;
                                }
                                else if (value == CommandColHeader.InfoValueKeys.ToLower())
                                {
                                    infoValueKeysIndex = i;
                                    implicitInfoValueKeys = implicitValue;
                                }
                                else if (value == CommandColHeader.IsDumb.ToLower())
                                {
                                    isDumbIndex = i;
                                    bool isDumb;
                                    if (!bool.TryParse(implicitValue, out isDumb))
                                    {
                                        System.IO.File.Delete(fullName);
                                        throw new ApplicationException("IsDumb值设置不正确");
                                    }
                                    implicitIsDumb = isDumb;
                                }
                                else if (value == CommandColHeader.TimeStamp.ToLower())
                                {
                                    timeStampIndex = i;
                                }
                                else if (value == CommandColHeader.Ontology.ToLower())
                                {
                                    ontologyCodeIndex = i;
                                    implicitOntology = implicitValue;
                                }
                                else if (value == CommandColHeader.ReasonPhrase.ToLower())
                                {
                                    reasonPhraseIndex = i;
                                }
                                else if (value == CommandColHeader.MessageId.ToLower())
                                {
                                }
                                else if (value == CommandColHeader.MessageType.ToLower())
                                {
                                    requestTypeIndex = i;
                                    implicitMessageType = implicitValue;
                                }
                                else if (value == CommandColHeader.ServerTicks.ToLower())
                                {
                                    serverTicksIndex = i;
                                }
                                else if (value == CommandColHeader.StateCode.ToLower())
                                {
                                    stateCodeIndex = i;
                                }
                                else if (value == CommandColHeader.Version.ToLower())
                                {
                                    versionIndex = i;
                                    implicitVersion = implicitValue;
                                }
                            }
                        }
                        #endregion
                        int responsedSum = 0;
                        var commands = new Dictionary<int, Message>();
                        #region 检测Excel中的每一行是否合法
                        for (int i = rowIndex; i <= sheet.LastRowNum; i++)
                        {
                            // 检测合法性的进度,未展示进度条
                            var percent = (decimal)(((decimal)100 * i) / sheet.LastRowNum);
                            var row = sheet.GetRow(i);
                            if (row != null)
                            {
                                string infoIdKeys = row.GetCell(infoIdKeysIndex).SafeToStringTrim();
                                if (string.IsNullOrEmpty(infoIdKeys))
                                {
                                    infoIdKeys = implicitInfoIdKeys;
                                }
                                string infoValueKeys = row.GetCell(infoValueKeysIndex).SafeToStringTrim();
                                if (string.IsNullOrEmpty(infoValueKeys))
                                {
                                    infoValueKeys = implicitInfoValueKeys;
                                }
                                var infoIdCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                                var infoValueCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                                if (infoIdKeys != null)
                                {
                                    foreach (var item in infoIdKeys.Split(','))
                                    {
                                        infoIdCodes.Add(item);
                                    }
                                }
                                if (infoValueKeys != null)
                                {
                                    foreach (var item in infoValueKeys.Split(','))
                                    {
                                        infoValueCodes.Add(item);
                                    }
                                }
                                var infoId = new List<KeyValue>();
                                var infoValue = new List<KeyValue>();
                                for (int j = 0; j < headRow1.Cells.Count; j++)
                                {
                                    var elementCode = headRow1.GetCell(j).SafeToStringTrim();
                                    if (!string.IsNullOrEmpty(elementCode) && elementCode[0] != '$')
                                    {
                                        var value = row.GetCell(j).SafeToStringTrim();
                                        if (infoIdCodes.Contains(elementCode))
                                        {
                                            infoId.Add(new KeyValue(elementCode, value));
                                        }
                                        if (infoValueCodes.Contains(elementCode))
                                        {
                                            infoValue.Add(new KeyValue(elementCode, value));
                                        }
                                    }
                                }
                                if (infoId.Count == 0 || infoId.All(a => string.IsNullOrEmpty(a.Value)))
                                {
                                    continue;
                                }
                                bool isDumb;
                                string isDumbValue = row.GetCell(isDumbIndex).SafeToStringTrim();
                                if (!string.IsNullOrEmpty(isDumbValue))
                                {
                                    if (!bool.TryParse(isDumbValue, out isDumb))
                                    {
                                        throw new ApplicationException("IsDumb值设置不正确");
                                    }
                                }
                                else
                                {
                                    isDumb = implicitIsDumb;
                                }
                                string actionCode = row.GetCell(actionCodeIndex).SafeToStringTrim();
                                if (string.IsNullOrEmpty(actionCode))
                                {
                                    actionCode = implicitVerb;
                                }
                                ontologyCode = row.GetCell(ontologyCodeIndex).SafeToStringTrim();
                                if (string.IsNullOrEmpty(ontologyCode))
                                {
                                    ontologyCode = implicitOntology;
                                }
                                var version = row.GetCell(versionIndex).SafeToStringTrim();
                                if (string.IsNullOrEmpty(version))
                                {
                                    version = implicitVersion;
                                }
                                var requestType = row.GetCell(requestTypeIndex).SafeToStringTrim();
                                if (string.IsNullOrEmpty(requestType))
                                {
                                    requestType = implicitMessageType;
                                }
                                int eventStateCode = 0;
                                if (!string.IsNullOrEmpty(row.GetCell(eventStateCodeIndex).SafeToStringTrim()))
                                {
                                    if (!int.TryParse(row.GetCell(eventStateCodeIndex).SafeToStringTrim(), out eventStateCode))
                                    {
                                        throw new ApplicationException("eventStateCode值设置错误");
                                    }
                                }
                                if (!string.IsNullOrEmpty(row.GetCell(timeStampIndex).SafeToStringTrim()))
                                {
                                    long timeStamp = 0;
                                    if (!long.TryParse(row.GetCell(timeStampIndex).SafeToStringTrim(), out timeStamp))
                                    {
                                        throw new ApplicationException("timeStamp值设置错误");
                                    }
                                }
                                responsedSum++;
                                var ticks = DateTime.UtcNow.Ticks;
                                var command = new Message()
                                {
                                    IsDumb = isDumb,
                                    Verb = actionCode,
                                    MessageId = Guid.NewGuid().ToString(),
                                    Ontology = ontologyCode,
                                    Version = version,
                                    MessageType = requestType,
                                    TimeStamp = DateTime.UtcNow.Ticks,
                                    Body = new BodyData(infoId.ToArray(), infoValue.ToArray())
                                    {
                                        Event = new EventData
                                        {
                                            ReasonPhrase = row.GetCell(eventReasonPhraseIndex).SafeToStringTrim(),
                                            SourceType = row.GetCell(eventSourceTypeIndex).SafeToStringTrim(),
                                            Status = eventStateCode,
                                            Subject = row.GetCell(eventSubjectCodeIndex).SafeToStringTrim()
                                        }
                                    }
                                };
                                var credential = new CredentialData
                                {
                                    ClientType = ClientType.Node.ToName(),
                                    CredentialType = CredentialType.Token.ToName(),
                                    ClientId = AcDomain.NodeHost.Nodes.ThisNode.Node.Id.ToString(),
                                    Ticks = ticks,
                                    UserName = AcSession.Account.Id.ToString()
                                };
                                command.Credential = credential;
                                commands.Add(i, command);
                            }
                        }
                        if (responsedSum == 0)
                        {
                            throw new ValidationException("没有可导入行");
                        }
                        else
                        {
                            foreach (var command in commands)
                            {
                                // 检测合法性的进度,未展示进度条
                                var percent = (decimal)(((decimal)100 * command.Key) / commands.Count);
                                var result = AnyMessage.Create(HecpRequest.Create(AcDomain, command.Value), AcDomain.NodeHost.Nodes.ThisNode).Response();
                                if (result.Body.Event.Status < 200)
                                {
                                    throw new ValidationException(string.Format("{0} {1} {2}", result.Body.Event.Status, result.Body.Event.ReasonPhrase, result.Body.Event.Description));
                                }
                                var row = sheet.GetRow(command.Key);
                                var stateCodeCell = row.CreateCell(stateCodeIndex);
                                var reasonPhraseCell = row.CreateCell(reasonPhraseIndex);
                                var descriptionCell = row.CreateCell(descriptionIndex);
                                var serverTicksCell = row.CreateCell(serverTicksIndex);
                                var localEntityIdCell = row.CreateCell(localEntityIdIndex);
                                if (result.Body.Event.Status < 200 || result.Body.Event.Status >= 300)
                                {
                                    failSum++;
                                    stateCodeCell.CellStyle = failStyle;
                                    reasonPhraseCell.CellStyle = failStyle;
                                    descriptionCell.CellStyle = failStyle;
                                }
                                else
                                {
                                    stateCodeCell.CellStyle = successStyle;
                                    reasonPhraseCell.CellStyle = successStyle;
                                    descriptionCell.CellStyle = successStyle;
                                    successSum++;
                                }
                                stateCodeCell.SetCellValue(result.Body.Event.Status);
                                reasonPhraseCell.SetCellValue(result.Body.Event.ReasonPhrase);
                                descriptionCell.SetCellValue(result.Body.Event.Description);
                                serverTicksCell.SetCellValue(DateTime.Now.ToString());
                                if (result.Body.InfoValue != null)
                                {
                                    var idItem = result.Body.InfoValue.FirstOrDefault(a => a.Key.Equals("Id", StringComparison.OrdinalIgnoreCase));
                                    if (idItem != null)
                                    {
                                        localEntityIdCell.SetCellValue(idItem.Value);
                                    }
                                }
                            }
                            var newFile = new FileStream(fullName, FileMode.Create);
                            workbook.Write(newFile);
                            newFile.Close();
                        }
                        #endregion
                    }
                    catch (OfficeXmlFileException)
                    {
                        System.IO.File.Delete(fullName);
                        throw new ValidationException("暂不支持Office2007及以上版本的Excel文件");
                    }
                }
            }
            TempData["Message"] = message;
            return this.RedirectToAction("Import", new { ontologyCode });
        }
Example #38
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="result"></param>
 internal void Fill(QueryResult result)
 {
     this.Verb = result.Verb;
     this._credential = ((IMessageDto)result).Credential;
     this._body = ((IMessageDto)result).Body;
     this.IsClosed = result.IsClosed;
     this.IsDumb = result.IsDumb;
     this.Ontology = result.Ontology;
     this.MessageId = result.MessageId;
     this.StackTrace = result.StackTrace;
     this.TimeStamp = result.TimeStamp;
     this.MessageType = result.MessageType;
     this.Version = result.Version;
     this.From = result.From;
     this.SessionId = result.SessionId;
     this.To = result.To;
     this.RelatesTo = result.RelatesTo;
 }
Example #39
0
 /// <summary>
 /// 
 /// </summary>
 private HecpResponse()
 {
     this.MessageType = "Event";
     this._body = new BodyData();
     this._credential = new CredentialData();
 }