Пример #1
0
        public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
        {
            string requestString = "";

            if (request is OracleQuery)
            {
                requestString = ((OracleQuery)request).Command.CommandText + buildParametersString(((OracleQuery)request).Command.Parameters);
            }
            else
            {
                throw new ArgumentException("Only supporting OracleQuery request types. Need to implement others...");
            }

            SQLiteCommand cmd = new SQLiteCommand("SELECT ASSEMBLY_NAME, DOMAIN_OBJECT_SIZE, DOMAIN_OBJECT, QUERY_STRING FROM SITE_" + _src.SiteId.Id +
                                                  " WHERE QUERY_STRING_HASH = '" + StringUtils.getMD5Hash(requestString) + "';", _cxn);

            connect();
            SQLiteDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                string fullAssemblyName = rdr.GetString(0); // gives us the object type
                Int32  objectSize       = rdr.GetInt32(1);  // gives us the object size in bytes - should have saved this info to database when mocking data
                byte[] buffer           = new byte[objectSize];
                rdr.GetBytes(2, 0, buffer, 0, objectSize);

                return(deserializeObject(buffer));
            }
            else
            {
                throw new exceptions.MdoException("Record not found in mock site " + _src.SiteId.Id);
            }
        }
Пример #2
0
        public virtual object query(SqlDataAdapter adapter, AbstractPermission permission = null)
        {
            Impersonator imp = null;

            try
            {
                if (_impersonationUser != null)
                {
                    imp = new Impersonator(_impersonationUser);
                }
                using (SqlConnection newCxn = new SqlConnection(this.DataSource.ConnectionString))
                {
                    newCxn.Open();

                    if (adapter.SelectCommand != null)
                    {
                        adapter.SelectCommand.Connection = newCxn;
                        //DataSet results = new DataSet();
                        //adapter.Fill(results);
                        //return results;
                        SqlDataReader rdr = adapter.SelectCommand.ExecuteReader();
                        // the SqlDataReader will be closed at the exit of this using block so we copy everything over to our MockDataReader where it will be cached in a DataTable
                        MockDataReader mock     = new MockDataReader();
                        DataTable      newTable = new DataTable();
                        newTable.Load(rdr);
                        mock.Table = newTable; // the previous couple lines are broken out so the setter on MockDataReader.Table can properly map the column names - IMPORTANT!!

                        return(mock);
                    }
                    else if (adapter.DeleteCommand != null)
                    {
                        adapter.DeleteCommand.Connection = newCxn;
                        return(adapter.DeleteCommand.ExecuteNonQuery());
                    }
                    else if (adapter.UpdateCommand != null)
                    {
                        adapter.UpdateCommand.Connection = newCxn;
                        return(adapter.UpdateCommand.ExecuteNonQuery());
                    }
                    else if (adapter.InsertCommand != null)
                    {
                        adapter.InsertCommand.Connection = newCxn;
                        return(adapter.InsertCommand.ExecuteNonQuery());
                    }

                    throw new ArgumentException("Must supply a SQL command");
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (imp != null)
                {
                    imp.stopImpersonation();
                }
            }
        }
Пример #3
0
        //=========================================================================================
        // Permissions: security keys
        //=========================================================================================
        public AbstractPermission addSecurityKey(string duz, AbstractPermission p)
        {
            // No empty args
            if (p == null || String.IsNullOrEmpty(p.Name) || String.IsNullOrEmpty(duz))
            {
                throw new ArgumentNullException("Missing arguments");
            }

            // No bogus security keys
            p.PermissionId = getSecurityKeyIen(p.Name);
            if (!StringUtils.isNumeric(p.PermissionId))
            {
                throw new ArgumentException("No such security key");
            }

            // No bogus users
            if (!isUser(duz))
            {
                throw new ArgumentException("No such user");
            }

            // Make sure user does not already have this key
            if (hasSecurityKey(duz, p))
            {
                throw new ArgumentException("User already has key");
            }

            p.RecordId = addSecurityKeyByName(p.Name, duz);
            return p;
        }
Пример #4
0
        public override object query(string request, AbstractPermission permission = null)
        {
            // add prefix and suffix to message as expected by Vista
            request = HL7Constants.LLP_PREFIX + request + HL7Constants.LLP_SUFFIX;

            byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(request);
            int    sent         = _socket.Send(requestBytes);

            _socket.ReceiveTimeout = 120;

            int bufferLength = 1024;

            byte[] buffer        = new byte[bufferLength];
            int    bytesReceived = _socket.Receive(buffer, _socket.Available > bufferLength ? bufferLength : _socket.Available, SocketFlags.None);

            string        batch = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesReceived);
            StringBuilder sb    = new StringBuilder(batch);

            while (!batch.Contains(hl7.HL7Constants.LLP_SUFFIX))
            {
                bytesReceived   = _socket.Receive(buffer, _socket.Available > bufferLength ? bufferLength : _socket.Available, SocketFlags.None);
                sb.Append(batch = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesReceived));
            }

            return(gov.va.medora.utils.StringUtils.stripInvalidXmlCharacters(sb.ToString()));
        }
Пример #5
0
        //internal void setVisitorContext(AbstractPermission requestedContext, string DUZ)
        //{
        //    try
        //    {
        //        setContext(requestedContext);
        //        return;
        //    }
        //    catch (UnauthorizedAccessException uae)
        //    {
        //        addContextInVista(DUZ, requestedContext);
        //        setContext(requestedContext);
        //    }
        //    catch (Exception e)
        //    {
        //        throw;
        //    }
        //}

        // This is how the visitor gets the requested context - typically
        // OR CPRS GUI CHART. The visitor comes back from VistA with CAPRI
        // context only.
        internal void addContextInVista(string duz, AbstractPermission requestedContext)
        {
            if (Permissions.ContainsKey(requestedContext.Name))
            {
                return;
            }
            VistaUserDao dao = new VistaUserDao(Cxn);

            // try/catch should fix: http://trac.medora.va.gov/web/ticket/2288
            try
            {
                setContext(requestedContext);
            }
            catch (Exception)
            {
                try
                {
                    // will get CONTEXT HAS NOT BEEN CREATED if we don't set this again after failed attempt
                    setContext(new MenuOption(VistaConstants.DDR_CONTEXT));
                    dao.addPermission(duz, requestedContext);
                    setContext(requestedContext);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #6
0
 public virtual object query(SqlDataAdapter adapter, AbstractPermission permission = null)
 {
     if (!IsConnected)
     {
         connect();
     }
     if (adapter.SelectCommand != null)
     {
         adapter.SelectCommand.Connection = _cxn;
         //DataSet results = new DataSet();
         //adapter.Fill(results);
         //return results;
         return(adapter.SelectCommand.ExecuteReader());
     }
     else if (adapter.DeleteCommand != null)
     {
         adapter.DeleteCommand.Connection = _cxn;
         return(adapter.DeleteCommand.ExecuteNonQuery());
     }
     else if (adapter.UpdateCommand != null)
     {
         adapter.UpdateCommand.Connection = _cxn;
         return(adapter.UpdateCommand.ExecuteNonQuery());
     }
     else if (adapter.InsertCommand != null)
     {
         adapter.InsertCommand.Connection = _cxn;
         return(adapter.InsertCommand.ExecuteNonQuery());
     }
     throw new ArgumentException("Must supply a SQL command");
 }
Пример #7
0
 internal void doTheAuthorize(AbstractCredentials credentials, AbstractPermission permission)
 {
     //// if we are requesting CPRS context with a visit and user does not have it - add it to their account
     if (permission.Name == VistaConstants.CPRS_CONTEXT &&
         !Cxn.Account.Permissions.ContainsKey(VistaConstants.CPRS_CONTEXT) &&
         !Cxn.Account.AuthenticationMethod.Equals(VistaConstants.LOGIN_CREDENTIALS))
     {
         addContextInVista(Cxn.Uid, permission);
     }
     else
     {
         setContext(permission);
     }
     if (String.IsNullOrEmpty(Cxn.Uid))
     {
         if (String.IsNullOrEmpty(credentials.FederatedUid))
         {
             throw new MdoException("Missing federated UID, cannot get local UID");
         }
         VistaUserDao dao = new VistaUserDao(Cxn);
         Cxn.Uid = dao.getUserIdBySsn(credentials.FederatedUid);
         if (String.IsNullOrEmpty(Cxn.Uid))
         {
             throw new MdoException("Unable to get local UID for federated ID " + credentials.FederatedUid);
         }
     }
     if (!credentials.Complete)
     {
         VistaUserDao dao = new VistaUserDao(Cxn);
         dao.addVisitorInfo(credentials);
     }
 }
Пример #8
0
        internal void setContext(AbstractPermission permission)
        {
            if (permission == null || string.IsNullOrEmpty(permission.Name))
            {
                throw new ArgumentNullException("permission");
            }

            MdoQuery request  = buildSetContextRequest(permission.Name);
            string   response = "";

            try
            {
                response = (string)Cxn.query(request);
            }
            catch (MdoException e)
            {
                response = e.Message;
            }
            if (response != "1")
            {
                throw getException(response);
            }
            if (!Cxn.Account.Permissions.ContainsKey(permission.Name))
            {
                Cxn.Account.Permissions.Add(permission.Name, permission);
            }
            isAuthorized = isAuthorized || permission.IsPrimary;
        }
Пример #9
0
        public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
        {
            string requestString = "";

            if (request is OracleQuery)
            {
                requestString = ((OracleQuery)request).Command.CommandText + buildParametersString(((OracleQuery)request).Command.Parameters);
            }
            else
            {
                throw new ArgumentException("Only supporting OracleQuery request types. Need to implement others...");
            }

            string sql = "SELECT OBJECT_TYPE, DOMAIN_OBJECT_SIZE, DOMAIN_OBJECT, QUERY_STRING FROM " +
                         _src.SiteId.Id + " WHERE QUERY_STRING_HASH = '" + StringUtils.getMD5Hash(requestString) + "';";

            SQLiteCommand    cmd = new SQLiteCommand(sql, _cxn);
            SQLiteDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                string fullAssemblyName = rdr.GetString(0); // gives us the object type
                Int32  objectSize       = rdr.GetInt32(1);  // gives us the object size in bytes - should have saved this info to database when mocking data
                byte[] buffer           = new byte[objectSize];
                rdr.GetBytes(2, 0, buffer, 0, objectSize);

                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                return(deserializer.Deserialize(new MemoryStream(buffer)));
            }
            else
            {
                throw new exceptions.MdoException(exceptions.MdoExceptionCode.DATA_NO_RECORD_FOR_ID);
            }
        }
Пример #10
0
        public override object query(string statement, AbstractPermission permission = null)
        {
            OleDbCommand cmd = cxn.CreateCommand();

            cmd.CommandText = statement;
            return(cmd.ExecuteReader());
        }
Пример #11
0
        //internal void setVisitorContext(AbstractPermission requestedContext, string DUZ)
        //{
        //    try
        //    {
        //        setContext(requestedContext);
        //        return;
        //    }
        //    catch (UnauthorizedAccessException uae)
        //    {
        //        addContextInVista(DUZ, requestedContext);
        //        setContext(requestedContext);
        //    }
        //    catch (Exception e)
        //    {
        //        throw;
        //    }
        //}

        // This is how the visitor gets the requested context - typically
        // OR CPRS GUI CHART. The visitor comes back from VistA with CAPRI
        // context only.
        internal void addContextInVista(string duz, AbstractPermission requestedContext)
        {
            //if (!Permissions.ContainsKey(VistaConstants.MDWS_CONTEXT) && !Permissions.ContainsKey(VistaConstants.DDR_CONTEXT))
            //{
            //    throw new ArgumentException("User does not have correct menu options to add new context");
            //}
            if (hasPermission(this.Cxn.Account.Permissions, requestedContext))
            {
                return;
            }
            //setContext(Permissions[VistaConstants.DDR_CONTEXT]); // tbd - needed? i think this is superfluous
            VistaUserDao dao = new VistaUserDao(Cxn);

            // try/catch should fix: http://trac.medora.va.gov/web/ticket/2288
            try
            {
                setContext(requestedContext);
            }
            catch (Exception)
            {
                try
                {
                    // will get CONTEXT HAS NOT BEEN CREATED if we don't set this again after failed attempt
                    setContext(new MenuOption(VistaConstants.DDR_CONTEXT));
                    dao.addPermission(duz, requestedContext);
                    setContext(requestedContext);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
 public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
 {
     object result = base.authorizedConnect(credentials, permission, validationDataSource);
     //_eventArgs.ConnectionEventType = ConnectionPoolEventArgs.ConnectionChangeEventType.ConnectionAvailable;
     //OnChanged(_eventArgs);
     return result;
 }
Пример #13
0
 object query(bool resetTimer, string request, AbstractPermission context = null)
 {
     if (resetTimer)
     {
         base.resetTimer();
     }
     return(base.query(request, context));
 }
Пример #14
0
 // the disconnect message was resetting the timeout timer!!! so, to get around this, this class
 // implements its own disconnect that signals these methods to not reset the timer
 object query(bool resetTimer, MdoQuery vq, AbstractPermission context = null)
 {
     if (resetTimer)
     {
         base.resetTimer();
     }
     return(base.query(vq, context));
 }
Пример #15
0
        public override object query(string request, AbstractPermission context = null)
        {
            object result = base.query(request, context);

            _eventArgs.ConnectionEventType = ConnectionPoolEventArgs.ConnectionChangeEventType.ConnectionAvailable;
            OnChanged(_eventArgs); // query complete event
            return(result);
        }
Пример #16
0
        public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
        {
            object result = base.authorizedConnect(credentials, permission, validationDataSource);

            //_eventArgs.ConnectionEventType = ConnectionPoolEventArgs.ConnectionChangeEventType.ConnectionAvailable;
            //OnChanged(_eventArgs);
            return(result);
        }
Пример #17
0
 public UserSecurityKeyTO(AbstractPermission p)
 {
     if (p.Type != PermissionType.SecurityKey)
     {
         fault = new FaultTO(p.Name + " is not a Security Key");
         return;
     }
     this.id   = p.PermissionId;
     this.name = p.Name;
 }
Пример #18
0
        public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
        {
            if (_authenticate)
            {
                return(base.authorize(credentials, permission));
            }

            isAuthorized = isAuthenticated = true;
            return(new User());
        }
Пример #19
0
 public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
 {
     if (_creds == null)
     {
         throw new MdoException("Invalid RDW credenetials. Must authenticate first");
     }
     return(new User()
     {
         UserName = _creds.AccountName, Pwd = _creds.AccountPassword
     });
 }
Пример #20
0
 public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
 {
     if (permission == null)
     {
         throw new ArgumentNullException("permission");
     }
     checkAuthorizeReadiness();
     checkPermissionString(permission.Name);
     doTheAuthorize(credentials, permission);
     return(toUser(credentials));
 }
Пример #21
0
 // Needs to return object so it can be either User or Exception on multi-site connections.
 public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
 {
     try
     {
         connect();
         return(Account.authenticateAndAuthorize(credentials, permission, validationDataSource));
     }
     catch (Exception ex)
     {
         return(ex);
     }
 }
Пример #22
0
        public override object query(MdoQuery vq, AbstractPermission context = null)
        {
            // see http://trac.medora.va.gov/web/ticket/2716
            if (Rpcs == null)
            {
                Rpcs = new List <string>();
            }
            Rpcs.Add(vq.RpcName);

            string request = vq.buildMessage();

            return(query(request, context));
        }
Пример #23
0
        public override object query(string request, AbstractPermission permission = null)
        {
            if (!IsConnected)
            {
                connect();
            }
            SqlCommand cmd = new SqlCommand();

            cmd.Connection  = _cxn;
            cmd.CommandText = request;
            SqlDataReader rdr = cmd.ExecuteReader();

            return(rdr);
        }
Пример #24
0
        public override object query(MdoQuery mq, AbstractPermission permission = null)
        {
            string request = mq.buildMessage();

            string response = (string)base.query(mq, permission);

            if (displayRPCList)
            {
                Console.WriteLine(request);
            }

            if (saveAuthConnect || (Account.IsAuthorized && !isCreateContextRequest(request) && !isDisconnectRequest(request)))
            {
                requests.Add(request);
                responses.Add(response);

                if (saveResults)
                {
                    // lazily create tables if they don't exist
                    if (!_sqliteDao.hasTable(_mockSiteId))
                    {
                        _sqliteDao.createTableForSite(_mockSiteId);
                    }

                    // see if this query has already been saved
                    object dbObj = _sqliteDao.getObject(_mockSiteId, gov.va.medora.utils.StringUtils.getMD5Hash(request));
                    if (dbObj == null)
                    {
                        _sqliteDao.saveObject(_mockSiteId, request, response);
                    }
                    else if (updateResults)
                    {
                        _sqliteDao.updateObject(_mockSiteId, gov.va.medora.utils.StringUtils.getMD5Hash(request), response);
                    }

                    //if (updateResults)
                    //{
                    //    _sqliteDao.saveOrUpdateObject(_mockSiteId, request, response);
                    //}
                    //else
                    //{
                    //    _sqliteDao.saveObject(_mockSiteId, request, response);
                    //}
                    //xmlSource.addRequest(mq, response, UpdateResults);
                }
            }

            return(response);
        }
Пример #25
0
        public override object query(string request, AbstractPermission permission = null)
        {
            if (this.DataSource == null || String.IsNullOrEmpty(this.DataSource.Provider))
            {
                throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Invalid domain");
            }
            DirectoryEntry de = new DirectoryEntry(this.DataSource.Provider);

            de.AuthenticationType = AuthenticationTypes.Secure;
            DirectorySearcher search = new DirectorySearcher();

            search.SearchRoot = de;
            search.Filter     = request;
            return(search.FindAll());
        }
Пример #26
0
 /// <summary>
 /// Execute a SqlQuery function on the connection. SqlQuery should be of type OracleQuery
 /// </summary>
 /// <param name="request">SqlQuery with SqlCommand already built</param>
 /// <param name="functionToExecute">The SqlCommand.function to execute - should take no parameters</param>
 /// <param name="permission"></param>
 /// <returns>Returns the type returned by SqlCommand.function</returns>
 public override object query(SqlQuery request, Delegate functionToExecute, AbstractPermission permission = null)
 {
     if (!IsConnected)
     {
         connect();
     }
     if (!(request is OracleQuery))
     {
         throw new ArgumentException("request must be of type OracleQuery");
     }
     ((OracleQuery)request).Command.Connection = this._cxn;
     if (_currentTx != null)
     {
         ((OracleQuery)request).Command.Transaction = _currentTx;
     }
     return(functionToExecute.DynamicInvoke(null));
 }
Пример #27
0
 //=========================================================================================
 // Permissions
 //=========================================================================================
 public AbstractPermission addPermission(string duz, AbstractPermission p)
 {
     if (p.Type == PermissionType.MenuOption)
     {
         p.RecordId = addMenuOption(duz, p);
         return p;
     }
     if (p.Type == PermissionType.DelegatedOption)
     {
         p.RecordId = addDelegatedOption(duz, p);
         return p;
     }
     if (p.Type == PermissionType.SecurityKey)
     {
         return addSecurityKey(duz, p);
     }
     throw new ArgumentException("Invalide permission type");
 }
Пример #28
0
        /// <summary>
        /// Execute a query
        /// </summary>
        /// <param name="request">SQL request</param>
        /// <param name="permission"></param>
        /// <returns>OracleDataReader</returns>
        public override object query(string request, AbstractPermission permission = null)
        {
            if (!IsConnected)
            {
                connect();
            }
            OracleCommand cmd = new OracleCommand();

            cmd.Connection  = _cxn;
            cmd.CommandText = request;
            if (_currentTx != null)
            {
                cmd.Transaction = _currentTx;
            }
            OracleDataReader rdr = cmd.ExecuteReader();

            return(rdr);
        }
Пример #29
0
        public override object query(MdoQuery vq, AbstractPermission context = null)
        {
            // see http://trac.medora.va.gov/web/ticket/2716
            //if (Rpcs == null)
            //{
            //    Rpcs = new List<string>();
            //}
            //Rpcs.Add(vq.RpcName);

            //if (String.Equals(vq.RpcName, "DDR LISTER"))
            //{
            //    return query(vq, context, true);
            //}

            string request = vq.buildMessage();

            return(query(request, context));
        }
Пример #30
0
        public override object query(string request, AbstractPermission permission = null)
        {
            connect();
            string msg   = "HELO " + DataSource.SiteId.Id + "\r\n";
            string reply = sendReceive(msg, "\r\n");

            if (!reply.StartsWith("220"))
            {
                disconnect();
                throw new Exception("ERROR sending HELO: " + reply);
            }
            string datamsg = "DATA PARAM=MPI\r\n";
            string hl7msg  = "";

            string[] segments = StringUtils.split(request, "\r");
            segments = StringUtils.trimArray(segments);
            for (int i = 0; i < segments.Length; i++)
            {
                segments[i] += '\r';    //Gotta put the terminator back after splitting on it
                hl7msg      += StringUtils.strPack(segments[i], 3);
            }
            hl7msg += StringUtils.strPack(END_MESSAGE, 3);

            send(datamsg);
            reply = sendReceive(hl7msg, "\r\n");
            if (!reply.StartsWith("220"))
            {
                disconnect();
                throw new Exception("ERROR sending DATA PARAM=MPI: " + reply);
            }
            msg   = "TURN\r\n";
            reply = sendReceive(msg, "\r\n");
            if (!reply.StartsWith("220"))
            {
                disconnect();
                throw new Exception("ERROR sending HL7: " + reply);
            }
            reply = receive(END_MESSAGE);
            msg   = "QUIT\r\n";
            send(msg);
            disconnect();
            return(reply);
        }
Пример #31
0
        // This is the core visit method the others are using. The permission must have been set before
        // getting here.
        internal User doTheVisit(string sitecode, AbstractCredentials credentials, AbstractPermission permission)
        {
            Site       site = mySession.SiteTable.getSite(sitecode);
            DataSource src  = site.getDataSourceByModality("HIS");

            if (src == null)
            {
                throw new Exception("No HIS data source at site " + sitecode);
            }

            AbstractDaoFactory factory = AbstractDaoFactory.getDaoFactory(AbstractDaoFactory.getConstant(src.Protocol));

            myCxn = factory.getConnection(src);
            myCxn.Account.AuthenticationMethod = mySession.DefaultVisitMethod;

            if (!MdwsUtils.isValidCredentials(myCxn.Account.AuthenticationMethod, credentials, permission))
            {
                throw new Exception("Invalid credentials");
            }

            object result = null;

            if (myCxn.Account.AuthenticationMethod == VistaConstants.BSE_CREDENTIALS_V2WEB)
            {
                result = myCxn.authorizedConnect(credentials, permission,
                                                 new DataSource()
                {
                    ConnectionString = mySession.MdwsConfiguration.BseValidatorConnectionString
                });
            }
            else
            {
                result = myCxn.authorizedConnect(credentials, permission, null);
            }
            if (result.GetType().Name.EndsWith("Exception"))
            {
                throw (Exception)result;
            }
            else
            {
                return((User)result);
            }
        }
Пример #32
0
        public override object query(string request, AbstractPermission permission = null)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Connection  = _myCxn;
            cmd.CommandText = request;
            if (_params != null && _params.Count > 0)
            {
                int count = _params.Count;
                for (int i = 0; i < count; i++)
                {
                    SqlParameter temp = _params[0];
                    _params.RemoveAt(0);
                    cmd.Parameters.Add(temp);
                }
            }
            SqlDataReader rdr = cmd.ExecuteReader();

            return(rdr);
        }
Пример #33
0
        public override object query(string request, AbstractPermission permission = null)
        {
            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);
            int    sent         = _socket.Send(requestBytes);

            _socket.ReceiveTimeout = 120;

            byte[] buffer        = new byte[1024];
            int    bytesReceived = _socket.Receive(buffer, _socket.Available, SocketFlags.None);

            string        batch = System.Text.Encoding.UTF8.GetString(buffer);
            StringBuilder sb    = new StringBuilder(batch);

            while (!batch.Contains(EndOfMessage))
            {
                bytesReceived   = _socket.Receive(buffer, _socket.Available, SocketFlags.None);
                sb.Append(batch = System.Text.Encoding.UTF8.GetString(buffer));
            }

            return(sb.ToString());
        }
Пример #34
0
        public override object query(SqlDataAdapter adapter, AbstractPermission permission = null)
        {
            string request = adapter.SelectCommand.CommandText;
            IDataReader rdr = (IDataReader)base.query(request);

            // copy to datatable
            DataTable table = new DataTable();

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                table.Columns.Add(rdr.GetName(i), rdr.GetFieldType(i));
            }
            while (rdr.Read())
            {
                object[] destination = new object[rdr.FieldCount];
                rdr.GetValues(destination);
                table.Rows.Add(destination);
            }

            if (!String.Equals(System.Reflection.Assembly.GetExecutingAssembly().FullName, "gov.va.medora.mdo-x"))
            {
                throw new ApplicationException("You should only use XCdwConnection from mdo-x dummy");
            }
            // save to file is set
            if (SaveToFile && !String.IsNullOrEmpty(FileName))
            {
                Stream stream = new FileStream("./../../../mdo/resources/data/" + FileName, FileMode.Create);
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, table);
            }

            MockDataReader newRdr = new MockDataReader();
            newRdr.Table = table;

            return newRdr;
        }
Пример #35
0
 public virtual object query(SqlDataAdapter adapter, AbstractPermission permission = null)
 {
     if (!IsConnected)
     {
         connect();
     }
     if (adapter.SelectCommand != null)
     {
         adapter.SelectCommand.Connection = _cxn;
         //DataSet results = new DataSet();
         //adapter.Fill(results);
         //return results;
         return adapter.SelectCommand.ExecuteReader();
     }
     else if (adapter.DeleteCommand != null)
     {
         adapter.DeleteCommand.Connection = _cxn;
         return adapter.DeleteCommand.ExecuteNonQuery();
     }
     else if (adapter.UpdateCommand != null)
     {
         adapter.UpdateCommand.Connection = _cxn;
         return adapter.UpdateCommand.ExecuteNonQuery();
     }
     else if (adapter.InsertCommand != null)
     {
         adapter.InsertCommand.Connection = _cxn;
         return adapter.InsertCommand.ExecuteNonQuery();
     }
     throw new ArgumentException("Must supply a SQL command");
 }
Пример #36
0
 public override object query(MdoQuery request, AbstractPermission permission = null)
 {
     throw new NotImplementedException();
 }
Пример #37
0
 public override object query(string request, AbstractPermission permission = null)
 {
     if (!IsConnected)
     {
         connect();
     }
     SqlCommand cmd = new SqlCommand();
     cmd.Connection = _cxn;
     cmd.CommandText = request;
     SqlDataReader rdr = cmd.ExecuteReader();
     return rdr;
 }
Пример #38
0
        public override object query(string request, AbstractPermission permission = null)
        {
            connect();
            string msg = "HELO " + DataSource.SiteId.Id + "\r\n";
            string reply = sendReceive(msg, "\r\n");
            if (!reply.StartsWith("220"))
            {
                disconnect();
                throw new Exception("ERROR sending HELO: " + reply);
            }
            string datamsg = "DATA PARAM=MPI\r\n";
            string hl7msg = "";
            string[] segments = StringUtils.split(request, "\r");
            segments = StringUtils.trimArray(segments);
            for (int i = 0; i < segments.Length; i++)
            {
                segments[i] += '\r';    //Gotta put the terminator back after splitting on it
                hl7msg += StringUtils.strPack(segments[i], 3);
            }
            hl7msg += StringUtils.strPack(END_MESSAGE, 3);

            send(datamsg);
            reply = sendReceive(hl7msg, "\r\n");
            if (!reply.StartsWith("220"))
            {
                disconnect();
                throw new Exception("ERROR sending DATA PARAM=MPI: " + reply);
            }
            msg = "TURN\r\n";
            reply = sendReceive(msg, "\r\n");
            if (!reply.StartsWith("220"))
            {
                disconnect();
                throw new Exception("ERROR sending HL7: " + reply);
            }
            reply = receive(END_MESSAGE);
            msg = "QUIT\r\n";
            send(msg);
            disconnect();
            return reply;
        }
Пример #39
0
 public override User authenticateAndAuthorize(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
 {
     string msg = authenticate(credentials, validationDataSource);
     User u = authorize(credentials, permission);
     u.Greeting = msg;
     return u;
 }
Пример #40
0
 public bool hasPermission(string uid, AbstractPermission permission)
 {
     throw new NotImplementedException();
 }
Пример #41
0
 internal void doTheAuthorize(AbstractCredentials credentials, AbstractPermission permission)
 {
     //// if we are requesting CPRS context with a visit and user does not have it - add it to their account
     if (permission.Name == VistaConstants.CPRS_CONTEXT &&
         !Cxn.Account.Permissions.ContainsKey(VistaConstants.CPRS_CONTEXT) &&
         !Cxn.Account.AuthenticationMethod.Equals(VistaConstants.LOGIN_CREDENTIALS))
     {
         addContextInVista(Cxn.Uid, permission);
     }
     else
     {
         setContext(permission);
     }
     if (String.IsNullOrEmpty(Cxn.Uid))
     {
         if (String.IsNullOrEmpty(credentials.FederatedUid))
         {
             throw new MdoException("Missing federated UID, cannot get local UID");
         }
         VistaUserDao dao = new VistaUserDao(Cxn);
         Cxn.Uid = dao.getUserIdBySsn(credentials.FederatedUid);
         if (String.IsNullOrEmpty(Cxn.Uid))
         {
             throw new MdoException("Unable to get local UID for federated ID " + credentials.FederatedUid);
         }
     }
     if (!credentials.Complete)
     {
         VistaUserDao dao = new VistaUserDao(Cxn);
         dao.addVisitorInfo(credentials);
     }
 }
Пример #42
0
 //// Needs to return object so it can be either User or Exception on multi-site connections.
 //public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission)
 //{
 //    try
 //    {
 //        connect();
 //        return Account.authenticateAndAuthorize(credentials, permission);
 //    }
 //    catch (Exception ex)
 //    {
 //        return ex;
 //    }
 //}
 // Needs to return object so it can be either User or Exception on multi-site connections.
 public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
 {
     try
     {
         connect();
         return Account.authenticateAndAuthorize(credentials, permission, validationDataSource);
     }
     catch (Exception ex)
     {
         return ex;
     }
 }
Пример #43
0
        //internal void setVisitorContext(AbstractPermission requestedContext, string DUZ)
        //{
        //    try
        //    {
        //        setContext(requestedContext);
        //        return;
        //    }
        //    catch (UnauthorizedAccessException uae)
        //    {
        //        addContextInVista(DUZ, requestedContext);
        //        setContext(requestedContext);
        //    }
        //    catch (Exception e)
        //    {
        //        throw;
        //    }
        //}
        // This is how the visitor gets the requested context - typically
        // OR CPRS GUI CHART. The visitor comes back from VistA with CAPRI
        // context only.
        internal void addContextInVista(string duz, AbstractPermission requestedContext)
        {
            if (Permissions.ContainsKey(requestedContext.Name))
            {
                return;
            }
            VistaUserDao dao = new VistaUserDao(Cxn);

            // try/catch should fix: http://trac.medora.va.gov/web/ticket/2288
            try
            {
                setContext(requestedContext);
            }
            catch (Exception)
            {
                try
                {
                    // will get CONTEXT HAS NOT BEEN CREATED if we don't set this again after failed attempt
                    setContext(new MenuOption(VistaConstants.DDR_CONTEXT));
                    dao.addPermission(duz, requestedContext);
                    setContext(requestedContext);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #44
0
        public override object query(string request, AbstractPermission permission = null)
        {
            // add prefix and suffix to message as expected by Vista
            request = HL7Constants.LLP_PREFIX + request + HL7Constants.LLP_SUFFIX;

            byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(request);
            int sent = _socket.Send(requestBytes);
            _socket.ReceiveTimeout = 120;

            int bufferLength = 1024;
            byte[] buffer = new byte[bufferLength];
            int bytesReceived = _socket.Receive(buffer, _socket.Available > bufferLength ? bufferLength : _socket.Available, SocketFlags.None);

            string batch = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesReceived);
            StringBuilder sb = new StringBuilder(batch);

            while (!batch.Contains(hl7.HL7Constants.LLP_SUFFIX))
            {
                bytesReceived = _socket.Receive(buffer, _socket.Available > bufferLength ? bufferLength : _socket.Available, SocketFlags.None);
                sb.Append(batch = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesReceived));
            }

            return gov.va.medora.utils.StringUtils.stripInvalidXmlCharacters(sb.ToString());
        }
Пример #45
0
        public override object query(MdoQuery vq, AbstractPermission context = null)
        {
            // see http://trac.medora.va.gov/web/ticket/2716
            if (Rpcs == null)
            {
                Rpcs = new List<string>();
            }
            Rpcs.Add(vq.RpcName);

            string request = vq.buildMessage();
            return query(request, context);
        }
Пример #46
0
 public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
 {
     this.isAuthorized = true;
     this.isAuthenticated = true;
     return new User();
 }
 public override object query(string request, AbstractPermission context = null)
 {
     object result = base.query(request, context);
     _eventArgs.ConnectionEventType = ConnectionPoolEventArgs.ConnectionChangeEventType.ConnectionAvailable;
     OnChanged(_eventArgs); // query complete event
     return result;
 }
Пример #48
0
 //public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission)
 //{
 //    return null;
 //}
 public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
 {
     return null;
 }
Пример #49
0
 public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
 {
     throw new NotImplementedException();
 }
Пример #50
0
 public override object query(MdoQuery vq, AbstractPermission context = null)
 {
     return this.query(true, vq, context);
 }
Пример #51
0
 public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
 {
     throw new NotImplementedException();
 }
Пример #52
0
 public override User authenticateAndAuthorize(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
 {
     this.isAuthorized = true;
     this.isAuthenticated = true;
     return new User();
 }
Пример #53
0
        internal void setContext(AbstractPermission permission)
        {
            if (permission == null || string.IsNullOrEmpty(permission.Name))
            {
                throw new ArgumentNullException("permission");
            }

            MdoQuery request = buildSetContextRequest(permission.Name);
            string response = "";
            try
            {
                response = (string)Cxn.query(request);
            }
            catch (MdoException e)
            {
                response = e.Message;
            }
            if (response != "1")
            {
                throw getException(response);
            }
            if (!Cxn.Account.Permissions.ContainsKey(permission.Name))
            {
                Cxn.Account.Permissions.Add(permission.Name, permission);
            }
            isAuthorized = isAuthorized || permission.IsPrimary;
        }
Пример #54
0
        public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
        {
            string requestString = "";
            if (request is OracleQuery)
            {
                requestString = ((OracleQuery)request).Command.CommandText + buildParametersString(((OracleQuery)request).Command.Parameters);
            }
            else
            {
                throw new ArgumentException("Only supporting OracleQuery request types. Need to implement others...");
            }

            string sql = "SELECT OBJECT_TYPE, DOMAIN_OBJECT_SIZE, DOMAIN_OBJECT, QUERY_STRING FROM " +
                _src.SiteId.Id + " WHERE QUERY_STRING_HASH = '" + StringUtils.getMD5Hash(requestString) + "';";

            SQLiteCommand cmd = new SQLiteCommand(sql, _cxn);
            SQLiteDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                string fullAssemblyName = rdr.GetString(0); // gives us the object type
                Int32 objectSize = rdr.GetInt32(1); // gives us the object size in bytes - should have saved this info to database when mocking data
                byte[] buffer = new byte[objectSize];
                rdr.GetBytes(2, 0, buffer, 0, objectSize);

                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                return deserializer.Deserialize(new MemoryStream(buffer));
            }
            else
            {
                throw new exceptions.MdoException(exceptions.MdoExceptionCode.DATA_NO_RECORD_FOR_ID);
            }
        }
Пример #55
0
 public override object query(string request, AbstractPermission context = null)
 {
     return this.query(true, request, context);
 }
Пример #56
0
        public override object query(string request, AbstractPermission context = null)
        {
            // see http://trac.medora.va.gov/web/ticket/2716
            if (Rpcs == null)
            {
                Rpcs = new List<string>();
            }
            try
            {
                // TBD - do we want to just not log calls if not passed through query(MdoQuery)??? it seems excessive to use reflection on every query
                // to determine if the calling function was query(MdoQuery) and thus has already been logged.

                // don't want to duplicate calls being logged by query(MdoQuery) so make sure that was NOT the calling function
                if (!String.Equals(new System.Diagnostics.StackFrame(1).GetMethod().Name, "query", StringComparison.CurrentCultureIgnoreCase))
                {
                    // we can't get RPC since we just received message but that information is human readable so save anyways
                    Rpcs.Add(request);
                }
            }
            catch (Exception) { /* don't want to blow everything up - just hide this */ }

            if (!IsConnecting && !IsConnected)
            {
                throw new NotConnectedException();
            }
            AbstractPermission currentContext = null;
            if (context != null && context.Name != this.Account.PrimaryPermission.Name)
            {
                currentContext = this.Account.PrimaryPermission;
                ((VistaAccount)this.Account).setContext(context);
            }

            Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
            Byte[] bytesReceived = new Byte[256];

            socket.Send(bytesSent, bytesSent.Length, 0);

            int bytes = 0;
            string reply = "";
            StringBuilder sb = new StringBuilder();
            string thisBatch = "";
            bool isErrorMsg = false;
            int endIdx = -1;

            // first read from socket so we don't need to use isHdr any more
            bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
            if (bytes == 0)
            {
                throw new ConnectionException("Timeout waiting for response from VistA");
            }
            thisBatch = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
            endIdx = thisBatch.IndexOf('\x04');
            if (endIdx != -1)
            {
                thisBatch = thisBatch.Substring(0, endIdx);
            }
            if (bytesReceived[0] != 0)
            {
                thisBatch = thisBatch.Substring(1, bytesReceived[0]);
                isErrorMsg = true;
            }
            else if (bytesReceived[1] != 0)
            {
                thisBatch = thisBatch.Substring(2);
                isErrorMsg = true;
            }
            else
            {
                thisBatch = thisBatch.Substring(2);
            }
            sb.Append(thisBatch);

            // now we can start reading from socket in a loop
            MemoryStream ms = new MemoryStream();
            while (endIdx == -1)
            {
                bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
                if (bytes == 0)
                {
                    throw new ConnectionException("Timeout waiting for response from VistA");
                }
                for (int i = 0; i < bytes; i++)
                {
                    if (bytesReceived[i] == '\x04')
                    {
                        endIdx = i;
                        break;
                    }
                    else
                    {
                        ms.WriteByte(bytesReceived[i]);
                    }
                }
            }
            sb.Append(Encoding.ASCII.GetString(ms.ToArray()));

            reply = sb.ToString();

            if (currentContext != null)
            {
                ((VistaAccount)this.Account).setContext(currentContext);
            }

            if (isErrorMsg || reply.Contains("M  ERROR"))
            {
                throw new MdoException(MdoExceptionCode.VISTA_FAULT, reply);
            }
            return reply;
        }
Пример #57
0
 // the disconnect message was resetting the timeout timer!!! so, to get around this, this class
 // implements its own disconnect that signals these methods to not reset the timer
 object query(bool resetTimer, MdoQuery vq, AbstractPermission context = null)
 {
     if (resetTimer)
     {
         base.resetTimer();
     }
     return base.query(vq, context);
 }
Пример #58
0
 object query(bool resetTimer, string request, AbstractPermission context = null)
 {
     if (resetTimer)
     {
         base.resetTimer();
     }
     return base.query(request, context);
 }
Пример #59
0
 public void removePermission(string uid, AbstractPermission permission)
 {
     throw new NotImplementedException();
 }
Пример #60
0
 public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
 {
     if (permission == null)
     {
         throw new ArgumentNullException("permission");
     }
     checkAuthorizeReadiness();
     checkPermissionString(permission.Name);
     doTheAuthorize(credentials, permission);
     return toUser(credentials);
 }