Esempio n. 1
0
        /// <summary>
        /// Returns the asteroid belts in the currently open menu
        /// </summary>
        /// <returns>List of menu entries representing the asteroid belts</returns>
        public List <MenuEntry> getBelts()
        {
            List <MenuEntry> belts    = new List <MenuEntry>();
            BooleanResponse  menuOpen = (BooleanResponse)comm.sendCall(FunctionCallFactory.CALLS.ISMENUOPEN, Response.RESPONSES.BOOLEANRESPONSE);

            if (menuOpen == null)
            {
                return(null);
            }

            if (!(Boolean)menuOpen.Data)
            {
                return(null);
            }

            MenuResponse resp = (MenuResponse)comm.sendCall(FunctionCallFactory.CALLS.GETMENUITEMS, Response.RESPONSES.MENURESPONSE);

            if (resp == null)
            {
                Console.WriteLine("couldn't get menu items");
                return(null);
            }

            foreach (MenuEntry entry in (List <MenuEntry>)resp.Data)
            {
                if (entry.Text.ToLower().Contains("belt "))
                {
                    belts.Add(entry);
                }
            }

            return(belts);
        }
Esempio n. 2
0
        public BooleanResponse LogOff(String token)
        {
            BooleanResponse response = new BooleanResponse();

            CacheManager cacheManager = new CacheManager();


            Mercury.Server.Application application = null;

            try {
                application = cacheManager.GetApplication(token);

                if (application == null)
                {
                    throw cacheManager.LastException;
                }

                application.LogOff();

                response.Result = true;
            }

            catch (Exception applicationException) {
                response.Result = false;

                response.SetException(applicationException);
            }

            return(response);
        }
Esempio n. 3
0
        /// <summary>
        /// Check if we are loading something
        /// </summary>
        /// <returns>True if there is a progress dialog open, false otherwise</returns>
        public bool isLoading()
        {
            BooleanResponse bresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISLOADING, Response.RESPONSES.BOOLEANRESPONSE);

            if (bresp == null)
            {
                return(false);
            }
            return((Boolean)bresp.Data);
        }
Esempio n. 4
0
        /// <summary>
        /// Check if the system menu is open
        /// </summary>
        /// <returns>True if it is, false otherwise</returns>
        public bool isSystemMenuOpen()
        {
            BooleanResponse bresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISSYSTEMMENUOPEN, Response.RESPONSES.BOOLEANRESPONSE);

            if (bresp == null)
            {
                return(false);
            }
            return((Boolean)bresp.Data);
        }
        public BooleanResponse GetMuteState()
        {
            var response = new BooleanResponse
            {
                Data = ITunesService.Instance.IsMute,
                Name = nameof(ITunesService.Instance.IsMute)
            };

            return(response);
        }
        public BooleanResponse GetPlayPauseState()
        {
            var response = new BooleanResponse
            {
                Data = ITunesService.Instance.IsPlaying,
                Name = nameof(ITunesService.Instance.IsPlaying)
            };

            return(response);
        }
Esempio n. 7
0
        /// <summary>
        /// Check if we are at the login screen
        /// </summary>
        /// <returns>True if we are, false otherwise</returns>
        public bool atLogin()
        {
            BooleanResponse bresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ATLOGIN, Response.RESPONSES.BOOLEANRESPONSE);

            if (bresp == null)
            {
                return(false);
            }

            return((Boolean)bresp.Data);
        }
Esempio n. 8
0
        /// <summary>
        /// Check if there is a currently open menu
        /// </summary>
        /// <returns>Return true if there is, false otherwise</returns>
        public bool isMenuOpen()
        {
            BooleanResponse menuOpen = (BooleanResponse)comm.sendCall(FunctionCallFactory.CALLS.ISMENUOPEN, Response.RESPONSES.BOOLEANRESPONSE);

            if (menuOpen == null)
            {
                return(false);
            }

            return((Boolean)menuOpen.Data);
        }
Esempio n. 9
0
        /// <summary>
        /// Check if we are at the character selection screen
        /// </summary>
        /// <returns>True if we are, false otherwise</returns>
        public bool atCharSel()
        {
            BooleanResponse bresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISATCHARSEL, Response.RESPONSES.BOOLEANRESPONSE);

            if (bresp == null)
            {
                return(false);
            }

            return((Boolean)bresp.Data);
        }
Esempio n. 10
0
        /// <summary>
        /// Check if the given low slot is active
        /// </summary>
        /// <param name="num">The slot number from 1-9</param>
        /// <returns>True if active, false otherwise</returns>
        public Boolean isLowSlotActive(int num)
        {
            BooleanResponse activeResp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISLOWSLOTACTIVE, "" + num, Response.RESPONSES.BOOLEANRESPONSE);

            if (activeResp == null)
            {
                Console.WriteLine("Can't get activity status");
                return(false);
            }
            return((Boolean)activeResp.Data);
        }
Esempio n. 11
0
        /// <summary>
        /// Check if current system is undergoing an incursion
        /// </summary>
        /// <returns>Returns true if there is an incursion, false otherwise</returns>
        public Boolean isIncursionOngoing()
        {
            BooleanResponse bresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISINCURSIONONGOING, Response.RESPONSES.BOOLEANRESPONSE);

            if (bresp == null)
            {
                return(false);
            }

            return((Boolean)bresp.Data);
        }
Esempio n. 12
0
        /// <summary>
        /// Check if we are fleeted
        /// </summary>
        /// <returns>True if we are fleeted, false otherwise</returns>
        public bool amIFleeted()
        {
            BooleanResponse bresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISFLEETED, Response.RESPONSES.BOOLEANRESPONSE);

            if (bresp == null)
            {
                return(false);
            }

            return((Boolean)bresp.Data);
        }
Esempio n. 13
0
        /// <summary>
        /// Check if the ship has the given med slot
        /// </summary>
        /// <param name="num">The slot number from 1-9</param>
        /// <returns>True if it does, false otherwise</returns>
        public Boolean hasMedSlot(int num)
        {
            BooleanResponse activeResp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.ISMEDSLOTACTIVE, "" + num, Response.RESPONSES.BOOLEANRESPONSE);

            if (activeResp == null)
            {
                Console.WriteLine("Can't get activity status");
                return(false);
            }
            return(true);
        }
        public IEnumerator TestAuthorizationRequestCoro()
        {
            var request          = new AuthorizationRequest(TestUserId, gameVersion);
            var expectedResponse = new BooleanResponse(true);

            _jsonRpcClient.ExpectRequestWithId(request.Id, expectedResponse);
            _jsonRpcClient.ExpectRequestWithMethod(new Requests.System.BulkRequest().Method, new BooleanResponse(true)); // Authorization context

            yield return(CoroutineManager.StartCoroutine(_rDataClient.Send <AuthorizationRequest, BooleanResponse>(request)));

            Assert.AreEqual(request.Response.Result, expectedResponse.Result, "Request returned false");
        }
Esempio n. 15
0
        public async Task <BooleanResponse> DeleteRecord(string TableName, int Id, string DeletedBy)
        {
            MySqlParameter[] parameter =
            {
                new MySqlParameter("@tablename", TableName),
                new MySqlParameter("@id",        Id),
                new MySqlParameter("@deletedby", DeletedBy)
            };
            BooleanResponse BooleanResponse = await _dbContext.Query <BooleanResponse>().AsNoTracking().FromSql("call sp_DeleteRecord(@tablename, @id, @deletedby)", parameter).FirstOrDefaultAsync();

            return(BooleanResponse);
        }
        public IEnumerator TestMockRequestCoro()
        {
            string test             = "test";
            var    request          = new MockRequest(test);
            var    expectedResponse = new BooleanResponse(true);

            _jsonRpcClient.ExpectRequestWithId(request.Id, expectedResponse);
            _jsonRpcClient.ExpectRequestWithMethod(new Requests.System.BulkRequest().Method, new BooleanResponse(true)); // Authorization context

            yield return(CoroutineManager.StartCoroutine(_rDataClient.Send <MockRequest, BooleanResponse>(request)));

            Assert.AreEqual(request.Response.Result, expectedResponse.Result, "Request results don't match");
        }
Esempio n. 17
0
        public async Task <BooleanResponse> UpdatActiveStaus(string TableName, bool IsActive, int Id, string Modifiedby)
        {
            MySqlParameter[] parameter =
            {
                new MySqlParameter("@tablename",  TableName),
                new MySqlParameter("@active",     IsActive),
                new MySqlParameter("@id",         Id),
                new MySqlParameter("@modifiedby", Modifiedby)
            };
            BooleanResponse BooleanResponse = await _dbContext.Query <BooleanResponse>().AsNoTracking().FromSql("call sp_UpdatActiveStaus(@tablename, @active,@id, @modifiedby)", parameter).FirstOrDefaultAsync();

            return(BooleanResponse);
        }
Esempio n. 18
0
        /// <summary>
        /// Check if there's hostiles in local
        /// </summary>
        /// <returns>Returns true if there is hostiles in local, false otherwise</returns>
        public Boolean isLocalHostile()
        {
            initializeLocal();
            if (getLocalCount() == 1)
            {
                return(false);
            }
            BooleanResponse tresp = (BooleanResponse)com.sendCall(FunctionCallFactory.CALLS.CHECKLOCAL, Response.RESPONSES.BOOLEANRESPONSE);

            if (tresp == null)
            {
                Console.WriteLine("Couldn't retrieve local");
                return(true);
            }
            return((Boolean)tresp.Data);
        }
        public IActionResult PostMuteState()
        {
            if (!ITunesService.Instance.IsActive)
            {
                return(new StatusCodeResult((int)HttpStatusCode.ServiceUnavailable));
            }

            ITunesService.Instance.ToggleMute();

            var response = new BooleanResponse
            {
                Data = ITunesService.Instance.IsMute,
                Name = nameof(ITunesService.Instance.IsMute)
            };

            return(Ok(response));
        }
Esempio n. 20
0
        public BooleanResponse SaveEventCategories(List<EventCategory> eventCategories)
        {
            var response = new BooleanResponse();

            try
            {
                var clnEventCategories = this.StatWinnerDatabase.GetCollection<EventCategoryDBEntity>("NotificationEventCategories");

                var existingList = clnEventCategories.Find(_ => true).ToListAsync().Result;
                var eventCategoriesToSave =
                    eventCategories.Select(EventManagementFactory.ConvertToEventCategoryEntity).ToList();

                var insertList = eventCategoriesToSave.Where(e => e.Id == ObjectId.Empty).ToList();
                insertList.ForEach(i => i.Id = ObjectId.GenerateNewId());

                var deleteList =
                    existingList.Where(l => eventCategories.All(ec => ec.Id != l.Id.ToString())).ToList();
                var deleteFilter = Builders<EventCategoryDBEntity>.Filter.In("_id", deleteList.Select(d => d.Id));
                var deleteResponse = clnEventCategories.DeleteManyAsync(deleteFilter);

                //Iterate over existing elemnts and replace
                foreach (
                    var setting in
                        eventCategoriesToSave.Where(cs => cs.Id != ObjectId.Empty)
                    )
                {
                    var updateFilter = Builders<EventCategoryDBEntity>.Filter.Eq("_id", setting.Id);
                    var replaceResponse = clnEventCategories.ReplaceOneAsync(updateFilter, setting);
                }

                var insertResponse = clnEventCategories.InsertManyAsync(insertList);

                return new BooleanResponse()
                {
                    Result = true
                };
            }
            catch (Exception ex)
            {
                response.SetError(ex);
            }

            return response;
        }
Esempio n. 21
0
        public Response OnRequest(Message r)
        {
            var response = new BooleanResponse {
                Ok = false
            };                                                 // Figure out exception mechanics

            switch (r.Type)
            {
            case MessageTypes.ServiceHostRequest:
                var m = r as ServiceHostRequest;
                ConcurrentBag <string> existing = new ConcurrentBag <string> {
                    m.Address
                };

                var list = Services.GetOrAdd(m.ServiceType, existing);
                if (list != existing)
                {
                    list.Add(m.Address);
                }
                response.Ok = true;
                return(response);

            case MessageTypes.ServiceProvederRequest:
                var req  = r as ServiceProvideRequest;
                var resp = new ServiceProvederResponse();
                ConcurrentBag <string> providers = null;
                if (Services.TryGetValue(req.ServiceType, out providers))
                {
                    string s = "";
                    providers.TryPeek(out s);     // TODO: Take a random item
                    if (!string.IsNullOrEmpty(s))
                    {
                        resp.Address = s;
                        return(resp);
                    }
                }
                return(response);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 22
0
        public BaseResponse <BooleanResponse> Remove(VMRemoveUserRequest vmRequest)
        {
            if (vmRequest == null)
            {
                return(BaseResponse <BooleanResponse> .SetError("Request body is empty"));
            }

            try
            {
                bool            result         = _userService.Remove(vmRequest);
                BooleanResponse responseObject = new BooleanResponse(result);
                var             response       = BaseResponse <BooleanResponse> .SetResponse(responseObject);

                return(response);
            }
            catch (Exception exc)
            {
                return(BaseResponse <BooleanResponse> .SetError(exc));
            }
        }
Esempio n. 23
0
        public HttpResponseMessage IsBirthDateMatchReaderId()
        {
            string JSONRequest = Request.Content.ReadAsStringAsync().Result;
            BirthDateMatchReaderId request;

            try
            {
                request = JsonConvert.DeserializeObject <BirthDateMatchReaderId>(JSONRequest, ALISSettings.ALISDateFormatJSONSettings);
            }
            catch
            {
                return(ALISErrorFactory.CreateError("G001", Request));
            }

            ReaderInfo reader;

            try
            {
                reader = ReaderInfo.GetReader(request.ReaderId);
            }
            catch (Exception ex)
            {
                return(ALISErrorFactory.CreateError("R004", Request));
            }
            BooleanResponse result = new BooleanResponse();

            try
            {
                result.Result = reader.IsBirthDateMatchReaderId(request);
            }
            catch (Exception ex)
            {
                return(ALISErrorFactory.CreateError(ex.Message, Request));
            }

            return(ALISResponseFactory.CreateResponse(result, Request));
        }
Esempio n. 24
0
        public void Serve(HttpListenerRequest request, HttpListenerResponse response, Url url)
        {
            var queueCreateRequest =
                (QueueCreateRequest) new DataContractJsonSerializer(typeof(QueueCreateRequest)).ReadObject(
                    request.InputStream);

            var jsonResponse = new BooleanResponse {
                Success = false
            };


            if (!UserEngine.LoginBySessionId(queueCreateRequest.Id, queueCreateRequest.NodeId, queueCreateRequest.SessionKey))
            {
                jsonResponse.Message = "Login Failed";
            }
            else
            {
                try
                {
                    QueueEngine.CreateQueue(queueCreateRequest.Id, queueCreateRequest.NodeId, queueCreateRequest.QueueName, queueCreateRequest.Readers);

                    PartnersEngine.PartnersUpdateRequest(new PartnerSyncQueueCreate {
                        NodeId = queueCreateRequest.NodeId, UID = queueCreateRequest.Id, QueueName = queueCreateRequest.QueueName, Readers = queueCreateRequest.Readers
                    });

                    jsonResponse.Success = true;
                }
                catch (Exception e)
                {
                    jsonResponse.Message = e.Message;
                }
            }

            new DataContractJsonSerializer(typeof(BooleanResponse)).WriteObject(response.OutputStream,
                                                                                jsonResponse);
        }
Esempio n. 25
0
        public BrokerResult AuthUser(List <string> tableNames, string userToken)
        {
            try
            {
                //bool busy = true;
                string data = RTStringBuilder.MakeAuthString(tableNames, userToken);

                var    AuthUrl = Properties.Settings.Default.RTFAuthURL;
                string result  = MessageConnect.SendRequest(AuthUrl, data);
                Debug.Print(result);
                BooleanResponse response = JsonConvert.DeserializeObject <BooleanResponse>(result);
                if (response.data)
                {
                    return(BrokerResult.newSuccess());
                }
                throw new Exception("RTF returned error " + response.error.message);
            }
            catch (WebException e)
            {
                return(new BrokerResult {
                    type = ResultType.authError, Message = e.Message
                });
            }
        }
Esempio n. 26
0
        public void Serve(HttpListenerRequest request, HttpListenerResponse response, Url url)
        {
            var partnerSyncRequest = JSONSerializer <PartnerSyncMessage> .Deserialize(request.InputStream);

            var jsonResponse = new BooleanResponse {
                Success = false
            };

            /* Validate incoming certificate */
            try
            {
                if (!CryptoEngine.GetInstance().verifyCertificate(partnerSyncRequest.key, partnerSyncRequest.certId, partnerSyncRequest.cert)
                    .VerifyData(partnerSyncRequest.data, partnerSyncRequest.signature, HashAlgorithmName.SHA256))
                {
                    throw new CryptographicException("Data verification failed");
                }

                /* Parse action */
                var partnerSyncRequestData = JSONSerializer <PartnerSyncMessageData> .Deserialize(partnerSyncRequest.data);

                /* Figure out which message type need to be handled */
                switch (partnerSyncRequestData.MessageType)
                {
                case PartnerSyncMessageType.PARTNER_JOIN:
                {
                    /* Parse join request */
                    var partnerJoinRequest = JSONSerializer <PartnerSyncRequestJoin> .Deserialize(partnerSyncRequestData.Data);

                    /* Add to partners */
                    PartnersEngine.AddPartner(partnerJoinRequest.Address);

                    /* Create a DB Dump object */
                    var partnerDBDump = new PartnerSyncResponseDBDump {
                        Partners = PartnersEngine.Partners.ToArray()
                    };

                    /* Dump te DB */
                    var dbFile = File.Open(Config <string> .GetInstance()["DB_Filename"], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    using (var reader = new BinaryReader(dbFile))
                    {
                        /* Hopefully DB will not be larger than 2GB */
                        partnerDBDump.DBDump = reader.ReadBytes((int)dbFile.Length);
                    }

                    JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(partnerDBDump), response.OutputStream);

                    break;
                }

                case PartnerSyncMessageType.USER_CREATE:
                {
                    /* Parse register request */
                    var userRegisterRequest = JSONSerializer <PartnerSyncUserCreate> .Deserialize(partnerSyncRequestData.Data);

                    /* Update here */
                    UserEngine.RegisterUser(partnerSyncRequest.certId, userRegisterRequest.Id, Encoding.ASCII.GetBytes(userRegisterRequest.Key));

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Success";

                    JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream);

                    break;
                }

                case PartnerSyncMessageType.QUEUE_CREATE:
                {
                    /* Parse queue create request */
                    var queueCreateRequest = JSONSerializer <PartnerSyncQueueCreate> .Deserialize(partnerSyncRequestData.Data);

                    QueueEngine.CreateQueue(queueCreateRequest.UID, queueCreateRequest.NodeId, queueCreateRequest.QueueName, queueCreateRequest.Readers);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Success";

                    JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream);

                    break;
                }

                case PartnerSyncMessageType.QUEUE_WRITE:
                {
                    /* Parse queue write request */
                    var queueWriteRequest = JSONSerializer <PartnerSyncQueueWrite> .Deserialize(partnerSyncRequestData.Data);

                    /* Try to correct timezone issues */
                    Config <long> .GetInstance()["TIMEZONE_CORRECTION"] = queueWriteRequest.Timestamp.ToFileTimeUtc() - DateTime.UtcNow.ToFileTimeUtc();

                    /* Add to buffered queue */
                    if (QueueEngine.WriteBufferedQueue(queueWriteRequest.UID, queueWriteRequest.NodeId, queueWriteRequest.QueueName, queueWriteRequest.Data, queueWriteRequest.Timestamp))
                    {
                        jsonResponse.Success = true;
                        jsonResponse.Message = "Success";
                    }
                    else
                    {
                        jsonResponse.Success = false;
                        jsonResponse.Message = "Not enough space in queue";
                    }

                    JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream);

                    break;
                }

                case PartnerSyncMessageType.QUEUE_COMMIT:
                {
                    /* Parse queue commit request */
                    var queueCommitRequest = JSONSerializer <PartnerSyncRequestCommit> .Deserialize(partnerSyncRequestData.Data);

                    QueueEngine.CommitQueue(queueCommitRequest.UID, queueCommitRequest.NodeId, queueCommitRequest.ReaderId, queueCommitRequest.ReaderNodeId, queueCommitRequest.QueueName);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Success";

                    JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream);

                    break;
                }

                default:
                {
                    jsonResponse.Message = "Invalid Message ID";

                    break;
                }
                }
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e);

                jsonResponse.Message = e.Message;

                JSONSerializer <PartnerSyncMessage> .Serialize(PartnersEngine.PrepareSignedMessage(jsonResponse), response.OutputStream);
            }
        }
Esempio n. 27
0
        public static void Register(HttpConfiguration config)
        {
            //// Uncomment the following to use the documentation from XML documentation file.
            config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/Documentation/documentation.xml")));

            //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
            //// formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});

            // Extend the following to provide factories for types not handled automatically (those lacking parameterless
            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
            // since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif

            // Extend the following to use a preset object directly as the sample for all actions that support a media
            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
            config.SetSampleForMediaType(
                new TextSample("Binary JSON content. See http://bsonspec.org for details."),
                new MediaTypeHeaderValue("application/bson"));

            //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
            //// and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));

            //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
            //// and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");

            //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
            //// on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");

            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");

            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");


            ReaderInfo reader = ReaderInfo.GetReader(189245);
            //Readers.Get
            ReaderSimpleView rsv  = ReaderViewFactory.GetReaderSimpleView(reader);
            string           json = JsonConvert.SerializeObject(rsv, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Readers", "Get");


            //Readers.GetByOauthToken
            AccessToken token = new AccessToken();
            token.TokenValue = "jhgfjfg*%&$*FKGfkfKfI^(*&^5&^TGVfjtgfdtre$E65r86T87t)(*7goYGV986T98^&Go8yg";
            json             = JsonConvert.SerializeObject(token, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "GetByOauthToken");

            json = JsonConvert.SerializeObject(rsv, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Readers", "GetByOauthToken");

            ////Readers.ChangePasswordLocalReader
            //ChangePasswordLocalReader password = new ChangePasswordLocalReader();
            //password.DateBirth = "1984-02-14";// new DateTime(1984, 2, 14);
            //password.NewPassword = "******";
            //password.NumberReader = 189245;
            //json = JsonConvert.SerializeObject(password, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            //config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "ChangePasswordLocalReader");

            //Readers.GetLoginType
            LoginType ltype = new LoginType();
            ltype.LoginTypeValue = "Email";
            json = JsonConvert.SerializeObject(ltype, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Readers", "GetLoginType");
            UserLogin ul = new UserLogin();
            ul.Login = "******";
            json     = JsonConvert.SerializeObject(ul, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "GetLoginType");


            //Readers.ByEmail
            UserEmail ue = new UserEmail();
            ue.Email = "*****@*****.**";
            json     = JsonConvert.SerializeObject(ue, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "ByEmail");
            json = JsonConvert.SerializeObject(rsv, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Readers", "ByEmail");



            //Readers.Authorize
            AuthorizeInfo aut = new AuthorizeInfo();
            aut.login    = "******";
            aut.password = "******";
            json         = JsonConvert.SerializeObject(aut, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "Authorize");
            config.SetSampleForType(aut, new MediaTypeHeaderValue("application/json"), typeof(AuthorizeInfo));
            config.SetActualRequestType(typeof(AuthorizeInfo), "Readers", "Authorize");
            json = JsonConvert.SerializeObject(rsv, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Readers", "Authorize");

            //Readers / IsBirthDateMatchReaderId
            BirthDateMatchReaderId match = new BirthDateMatchReaderId();
            match.DateBirth = "1984-02-14";
            match.ReaderId  = 189245;
            BooleanResponse br = new BooleanResponse();
            br.Result = true;
            json      = JsonConvert.SerializeObject(match, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "IsBirthDateMatchReaderId");
            json = JsonConvert.SerializeObject(br, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Readers", "IsBirthDateMatchReaderId");

            //Readers/SetPasswordLocalReader
            SetPasswordLocalReader spwd = new SetPasswordLocalReader();
            spwd.NewPassword = "******";
            spwd.ReaderId    = 189245;
            json             = JsonConvert.SerializeObject(spwd, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "SetPasswordLocalReader");


            //Books.Get
            BookSimpleView book;
            book = ViewFactory.GetBookSimpleView("BJVVV_1411951");
            json = JsonConvert.SerializeObject(book, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Books", "Get");

            //Circulation.InsertIntoUserBasket
            ImpersonalBasket basket = new ImpersonalBasket();
            basket.BookIdArray = new List <string>();
            basket.BookIdArray.AddRange(new string[] { "BJVVV_1299121", "BJVVV_1304618", "REDKOSTJ_31866", "REDKOSTJ_43090" });
            basket.ReaderId = 189245;
            json            = JsonConvert.SerializeObject(basket, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Circulation", "InsertIntoUserBasket");

            //Circulation.Basket
            CirculationInfo   circ       = new CirculationInfo();
            List <BasketInfo> UserBasket = circ.GetBasket(888);
            json = JsonConvert.SerializeObject(UserBasket, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Circulation", "Basket");

            //Circulation.Order
            circ = new CirculationInfo();
            MakeOrder mo = new MakeOrder();
            mo.BookId      = "BJVVV_1078762";
            mo.ReaderId    = 100000;
            mo.OrderTypeId = 2;
            json           = JsonConvert.SerializeObject(mo, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Circulation", "Order");


            //Circulation.Orders
            List <OrderInfo> UserOrders = circ.GetOrders(155);
            json = JsonConvert.SerializeObject(UserOrders, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Circulation", "Orders");
            //Circulation.Basket    Delete
            BasketDelete bd = new BasketDelete();
            bd.BooksToDelete.Add("BJVVV_1299121");
            bd.BooksToDelete.Add("BJVVV_1491232");
            bd.ReaderId = 200500;
            json        = JsonConvert.SerializeObject(bd, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Circulation", "DeleteFromBasket");

            //Circulation.OrdersHistory
            List <OrderHistoryInfo> UserOrdersHistory = circ.GetOrdersHistory(100000);
            json = JsonConvert.SerializeObject(UserOrdersHistory, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Circulation", "OrdersHistory");


            //Readers.PreRegisterRemoteReader
            PreRegisterRemoteReader re = new PreRegisterRemoteReader();
            re.BirthDate   = "1975-05-05";//new DateTime(1975, 05, 05);
            re.CountryId   = 137;
            re.Email       = "*****@*****.**";
            re.FamilyName  = "Иванов";
            re.FatherName  = "Иванович";
            re.MobilePhone = "89551234567";
            re.Name        = "Иван";
            re.Password    = "******";
            json           = JsonConvert.SerializeObject(re, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "PreRegisterRemoteReader");

            //Readers.ConfirmRegistrationRemoteReader
            ConfirmRegistrationRemoteReader c = new ConfirmRegistrationRemoteReader();
            c.Url = "https://oauth.libfl.ru/activate/<activation code>";
            json  = JsonConvert.SerializeObject(c, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "ConfirmRegistrationRemoteReader");

            //Readers.ChangePasswordByEmail
            ChangePasswordByEmail em = new ChangePasswordByEmail();
            em.Email = "*****@*****.**";
            json     = JsonConvert.SerializeObject(em, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "ChangePasswordByEmail");

            //Readers.SetPasswordRemoteReader
            SetPasswordRemoteReader set = new SetPasswordRemoteReader();
            set.Url      = "https://oauth.libfl.ru/recovery/<recovery code>";
            set.Password = "******";
            json         = JsonConvert.SerializeObject(set, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "SetPasswordRemoteReader");

            //Readers.CheckPasswordUrl
            CheckPasswordUrl check = new CheckPasswordUrl();
            check.Url = "https://oauth.libfl.ru/recovery/<recovery code>";
            json      = JsonConvert.SerializeObject(check, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleRequest(json, new MediaTypeHeaderValue("application/json"), "Readers", "CheckPasswordUrl");

            //GET Litres/Account/{ReaderId}
            LitresInfo li = new LitresInfo();
            li.Login    = "******";
            li.Password = "******";
            json        = JsonConvert.SerializeObject(li, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Litres", "LitresAccount");
            //POST Litres/AssignAccount/{ReaderId}
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Litres", "AssignLitresAccount");


            //Circulation / Orders / ById /{ OrderId}
            OrderInfo oi = circ.GetOrder(22);
            json = JsonConvert.SerializeObject(oi, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Circulation", "OrdersById");

            //Books/ElectronicCopy/{id}
            ElectronicCopyFullView ec = ViewFactory.GetElectronicCopyFullView("BJVVV_138023");
            json = JsonConvert.SerializeObject(ec, Formatting.Indented, ALISSettings.ALISDateFormatJSONSettings);
            config.SetSampleResponse(json, new MediaTypeHeaderValue("application/json"), "Books", "GetElectronicCopyFullView");
        }
Esempio n. 28
0
        /// <summary>
        /// Select the given string in the currently open menu
        /// </summary>
        /// <param name="menuItem">The text in the menu to select</param>
        /// <returns>True if success, false otherwise</returns>
        public bool select(string menuItem)
        {
            Thread.Sleep(300);

            if (!comm.connect())
            {
                return(false);
            }

            BooleanResponse menuOpen = (BooleanResponse)comm.sendCall(FunctionCallFactory.CALLS.ISMENUOPEN, Response.RESPONSES.BOOLEANRESPONSE);

            if (menuOpen == null)
            {
                return(false);
            }

            if (!(Boolean)menuOpen.Data)
            {
                InterfaceResponse inflight = (InterfaceResponse)comm.sendCall(FunctionCallFactory.CALLS.GETINFLIGHTINTERFACE, Response.RESPONSES.INTERFACERESPONSE);
                if (inflight == null)
                {
                    return(false);
                }

                Point pt = getOpenSpace();
                if (pt.X == -1 || pt.Y == -1)
                {
                    return(false);
                }

                m.move(pt);
                pm.x = m.x;
                pm.y = m.y;

                Thread.Sleep(300);
                m.click(false);
                Thread.Sleep(600);
            }

            InterfaceResponse resp = (InterfaceResponse)comm.sendCall(FunctionCallFactory.CALLS.FINDBYTEXTMENU, menuItem, Response.RESPONSES.INTERFACERESPONSE);

            if (resp == null)
            {
                if (isMenuOpen())
                {
                    kb.sendChar((char)KeyBoard.VKeys.VK_ESCAPE);
                }
                return(false);
            }

            pm.MissChance = 100;
            pm.Speed      = 5;

            pm.move(10, resp.X + 5, pm.getY(), 0, 0, 0);
            pm.move(10, resp.Width / 2 + resp.X, resp.Y + 5, 0, 0, 0);

            //Synchronize both mouse devices
            m.synchronize(pm);

            return(true);
        }
Esempio n. 29
0
        /// <summary>
        /// Save Notification Event
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<BooleanResponse> SaveNotificationEvent(EventEntity entity)
        {
            var response = new BooleanResponse();

            try
            {
                var dbEntity = EventManagementFactory.ConvertToEventDbEntity(entity);

                ApplicationUser appUser = null;

                if (HttpContext.Current.User != null)
                {
                    appUser = await UserManager.FindByNameAsync(HttpContext.Current.User.Identity.Name);
                }

                if (dbEntity.Id == ObjectId.Empty)
                {
                    if (appUser != null)
                    {
                        dbEntity.CreatedBy = new EventUserDbEntity()
                        {
                            UserId = appUser.Id.ToString(),
                            EmailAddress = appUser.Email,
                            FullName = String.Format("{0} {1}", appUser.FirstName, appUser.LastName)
                        };
                    }

                    dbEntity.CreatedDate = DateTime.Now;
                }

                if (appUser != null)
                {
                    dbEntity.ModifiedBy = new EventUserDbEntity()
                    {
                        UserId = appUser.Id.ToString(),
                        EmailAddress = appUser.Email,
                        FullName = String.Format("{0} {1}", appUser.FirstName, appUser.LastName)
                    };
                }

                dbEntity.ModifiedDate = DateTime.Now;

                var clnEvents = this.StatWinnerDatabase.GetCollection<EventDbEntity>("NotificationEvents");
                if (dbEntity.Id == ObjectId.Empty)
                {
                    dbEntity.Id = ObjectId.GenerateNewId();
                    await clnEvents.InsertOneAsync(dbEntity);
                }
                else
                {
                    var updateFilter = Builders<EventDbEntity>.Filter.Eq("_id", dbEntity.Id);
                    await clnEvents.ReplaceOneAsync(updateFilter, dbEntity);
                }
            }
            catch (Exception ex)
            {
                response.SetError(ex);
            }

            return response;
        }
Esempio n. 30
0
        private async Task <BooleanResponse> PostForBoolean(Uri url, string content)
        {
            BooleanResponse resp = null;

            try
            {
                using (var client = new HttpClient(
                           new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip
                                             | DecompressionMethods.Deflate
                }))
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");

                    var credentials = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("json", content)
                    });

                    var res = await client.PostAsync(url, credentials);

                    var respo = await res.Content.ReadAsStringAsync();

                    if (respo == "true")
                    {
                        resp = new BooleanResponse()
                        {
                            Response = true
                        }
                    }
                    ;
                    else
                    {
                        if (respo == "false")
                        {
                            resp = new BooleanResponse()
                            {
                                Response = false
                            }
                        }
                        ;
                        else
                        {
                            resp = new BooleanResponse()
                            {
                                ErrorMessage = respo
                            };
                            LogHelper.Instance.Log(LogLevel.Error, "Post failed for url " + url + " with json " + content + " Reponse recieved: " + respo, this);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.LogException(ex, this);
                resp = new BooleanResponse()
                {
                    ErrorMessage = "Post failed for url " + url
                };
            }
            return(resp);
        }
        /// <summary>
        /// Registers user in the system
        /// </summary>
        /// <param name="registerUser"></param>
        /// <returns></returns>
        public async Task<BooleanResponse> UserRegistration(RegisterUser registerUser)
        {
            var response = new BooleanResponse();
            try
            {
                
                var user = new ApplicationUser()
                {
                    City = registerUser.City,
                    CountryId = registerUser.CountryId,
                    Email = registerUser.Email,
                    FirstName = registerUser.FirstName,
                    LastName = registerUser.LastName,

                    State = registerUser.State,
                    UserName = registerUser.Email
                };

                var result = await UserManager.CreateAsync(user, registerUser.Password);

                if (result.Succeeded)
                {
                    user = UserManager.FindByName(registerUser.Email);
                    var identity = await user.GenerateUserIdentityAsync(UserManager);
                    AuthManager.SignIn(new AuthenticationProperties {IsPersistent = true}, identity);
                    response.Result = true;
                }
                else
                {
                    response.Errors.AddRange(result.Errors.Select(s => new Error() { Message = s}));
                }
            }
            catch (Exception ex)
            {
                response.SetError(ex);
            }

            return response;
        }
        /// <summary>
        /// Signs user in the system
        /// </summary>
        /// <param name="signInUser"></param>
        /// <returns></returns>
        public async Task<BooleanResponse> SignInUser(SignInRequest signInUser)
        {
            var response = new BooleanResponse();
            
            try
            {

                const string errorMessage = "Invalid Email or Password";

                var user = await UserManager.FindByNameAsync(signInUser.Email);
                if (user == null)
                {
                    response.SetError(errorMessage);
                }

                var isValidUser = await UserManager.CheckPasswordAsync(user, signInUser.Password);

                if (isValidUser)
                {
                    AuthManager.SignOut();
                    var identity = await user.GenerateUserIdentityAsync(UserManager);

                    if (signInUser.RememberMe)
                    {
                        var rememberBrowserIdentity = AuthManager.CreateTwoFactorRememberBrowserIdentity(user.Id);
                        AuthManager.SignIn(new AuthenticationProperties { IsPersistent = true }, identity, rememberBrowserIdentity);
                    }
                    else
                    {
                        AuthManager.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);
                    }

                    response.Result = true;
                }
                else
                {
                    response.SetError("");
                }
            }
            catch (Exception ex)
            {
                response.SetError(ex);
            }

            return response;
        }
Esempio n. 33
0
 public static void CheckBooleanResponseForFalse(BooleanResponse resp)
 {
     Assert.IsNull(resp.ErrorMessage, "Error message not null: " + resp.ErrorMessage);
     Assert.IsFalse(resp.Response, "Boolean Result not false as expected: " + resp.Response);
 }
Esempio n. 34
0
 public static void CheckBooleanResponse(BooleanResponse resp)
 {
     Assert.IsTrue(resp.IsSuccessfull,
                   "Boolean Result failed with response: " + resp.Response + " and Error Message: " + resp.ErrorMessage);
 }