Example #1
0
        public void GetAgentCode(int AgentID, string username, string password)
        {
            var rs = new ResponseClass();

            if (Login(username, password))
            {
                var agent = AgentController.GetByID(AgentID);
                if (agent != null)
                {
                    rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.SUCCESS);
                    rs.Status = APIUtils.ResponseMessage.Success.ToString();
                    rs.Agent  = agent;
                }
                else
                {
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                    rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                    rs.Message = APIUtils.OBJ_DNTEXIST;
                }
            }
            else
            {
                rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.FAILED);
                rs.Status = APIUtils.ResponseMessage.Fail.ToString();
            }
            Context.Response.ContentType = "application/json";
            Context.Response.Write(JsonConvert.SerializeObject(rs, Formatting.Indented));
            Context.Response.Flush();
            Context.Response.End();
        }
Example #2
0
        public void GetAllCategory(string username, string password)
        {
            var rs = new ResponseClass();

            if (Login(username, password))
            {
                var category = CategoryController.API_GetAllCategory();
                if (category.Count > 0)
                {
                    rs.Code     = APIUtils.GetResponseCode(APIUtils.ResponseCode.SUCCESS);
                    rs.Status   = APIUtils.ResponseMessage.Success.ToString();
                    rs.Category = category;
                }
                else
                {
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                    rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                    rs.Message = APIUtils.OBJ_DNTEXIST;
                }
            }
            else
            {
                rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.FAILED);
                rs.Status = APIUtils.ResponseMessage.Fail.ToString();
            }

            Context.Response.ContentType = "application/json";
            Context.Response.Write(JsonConvert.SerializeObject(rs, Formatting.Indented));
            Context.Response.Flush();
            Context.Response.End();
        }
        public void MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            var splitTopic = e.Topic.Split(new char[] { '/' });

            if (splitTopic.Length < 4)
            {
                return;
            }

            var json = JObject.Parse(System.Text.Encoding.UTF8.GetString(e.Message));

            if (splitTopic[2] == WeightConfig.Key[0])
            {
                json = (JObject)(json[WeightConfig.Key[0]] as JArray)[0];
            }
            else if (splitTopic[2] == ActivitySummaryConfig.Root)
            {
                json = (JObject)json[ActivitySummaryConfig.RootMQTT];
            }

            json.Remove("date");
            APIUtils.Post(MQTTConfig.ControllerUrl + splitTopic[2].Replace("-", "") + "?" +
                          QueryParamsConfig.PatientId + "=" + splitTopic[3] + "&" + QueryParamsConfig.DoctorEmail +
                          "=" + splitTopic[1], json.ToString());
        }
Example #4
0
        public void GetProductVariableValueByProductVariableID(int ProductVariableID, string username, string password)
        {
            var rs = new ResponseClass();

            if (Login(username, password))
            {
                var ProductVariableValue = ProductVariableValueController.GetByProductVariableID(ProductVariableID);
                if (ProductVariableValue.Count > 0)
                {
                    rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.SUCCESS);
                    rs.Status = APIUtils.ResponseMessage.Success.ToString();
                    rs.ProductVariableValue = ProductVariableValue;
                }
                else
                {
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                    rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                    rs.Message = APIUtils.OBJ_DNTEXIST;
                }
            }
            else
            {
                rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.FAILED);
                rs.Status = APIUtils.ResponseMessage.Fail.ToString();
            }

            Context.Response.ContentType = "application/json";
            Context.Response.Write(JsonConvert.SerializeObject(rs, Formatting.Indented));
            Context.Response.Flush();
            Context.Response.End();
        }
Example #5
0
        public async Task <Models.Patient> Read(int id)
        {
            JObject patientsJson = await APIUtils.GetAsync(IPConfig.GetTotalUrl() + JsonDataConfig.Url + "/" + id);

            return((patientsJson == null) ? null :
                   ((JObject)patientsJson[JsonDataConfig.Root]).GetObject <Models.Patient>());
        }
        public void AllDogBreeds_Test()
        {
            var currentTest = Core.ExtentReport.CreateTest(
                MethodBase.GetCurrentMethod().ToString().Replace("Void", "").Replace("()", ""),
                "This is a demo test for Locating a value in the Json response."
                );

            APIUtils apiInstance = new APIUtils("https://dog.ceo");

            //Sets the headers
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Cookie", "__cfduid=df3050b40e97ce8431938fa8864b5a07b1593608688");

            //Retrieves the whole list of Dog breeds
            var response = apiInstance.GetRequest(
                "/api/breeds/list/all"
                , headers
                , currentTest
                );

            //Verifys that 200 response
            response.ValidateResponseIs(HttpStatusCode.OK, currentTest);
            response.ValidateResponseIsJson(response.responseData, currentTest);

            //Verify a breed is present
            string breedToSearchFor = "retriever";

            response.ValidateResponseContains(breedToSearchFor, currentTest);

            //logs that the value was found
            Core.ExtentReport.StepPassed(currentTest, "Successfully located the value '" + breedToSearchFor + "' in the Json response.");
        }
        public void RandomImage_Test()
        {
            var currentTest = Core.ExtentReport.CreateTest(
                MethodBase.GetCurrentMethod().ToString().Replace("Void", "").Replace("()", ""),
                "This is a demo test for injecting a parameter into the URL of a API request."
                );

            APIUtils apiInstance = new APIUtils("https://dog.ceo");

            //Sets the headers
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Cookie", "__cfduid=df3050b40e97ce8431938fa8864b5a07b1593608688");

            //Retrieves the whole list of Dog breeds
            var response = apiInstance.GetRequest(
                "/api/breeds/image/random"
                , headers
                , currentTest
                );

            //Verifys that 200 response
            response.ValidateResponseIs(HttpStatusCode.OK, currentTest);
            response.ValidateResponseIsJson(response.responseData, currentTest);

            //Locating the image url
            JObject json          = JObject.Parse(response.responseData.ToString());
            var     imageLocation = json["message"];

            //Rendering the image in the report
            Core.ExtentReport.InjectPictureFrom(currentTest, imageLocation.ToString());
        }
Example #8
0
        public IHttpActionResult GetForUser()
        {
            var user_id   = APIUtils.GetUserFromClaim(ClaimsPrincipal.Current);
            var curr_user = UserHelper.GetById(user_id);

            using (var dc = new ArmsContext())
            {
                dc.Configuration.LazyLoadingEnabled = false;
                if (curr_user.Type == "student")
                {
                    var participations = dc.Participants.Include(x => x.Course).Include(x => x.Course.Creator)
                                         .Include(x => x.User)
                                         .Where(x => x.UserID == curr_user.UserID);
                    return(Ok(participations.ToList()));
                }

                if (curr_user.Type == "teacher")
                {
                    var supervisions = dc.Supervisors.Include(x => x.Course).Include(x => x.Course.Creator)
                                       .Include(x => x.User)
                                       .Where(x => x.UserID == curr_user.UserID);
                    return(Ok(supervisions.ToList()));
                }
            }

            return(Ok());
        }
        public async Task <object> Update(int id, string day, [FromBody] MealKendo item)
        {
            JObject jsonMeal = JObject.Parse(JsonConvert.SerializeObject
                                                 (Meal.CreateFromOptionKendoList(item), serializerSettings));

            var jsonMealDay = new JObject
            {
                { JsonDataConfig.Key[0], day },
                { JsonDataConfig.Key[1], new JArray()
                  {
                      jsonMeal
                  } }
            };
            var jsonMealDays = new JArray
            {
                jsonMealDay
            };
            var jsonDiet = new JObject
            {
                { JsonDataConfig.Root, jsonMealDays }
            };

            await APIUtils.PostAsync(IPConfig.GetTotalUrlUser() + id + JsonDataConfig.Url, jsonDiet.ToString());

            return(Empty);
        }
Example #10
0
File: Main.cs Project: tuga1975/SSK
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Turn off all LED(s)
            if (LEDStatusLightingUtil.Instance.IsPortOpen)
            {
                //LEDStatusLightingUtil.Instance.TurnOffAllLEDs();
                LEDStatusLightingUtil.Instance.ClosePort();
            }

            //if (DocumentScannerUtil.Instance.EnableFeeder)
            //{
            //    DocumentScannerUtil.Instance.StopScanning();
            //}

            if (DocumentScannerUtil.Instance.Scanner_Connected)
            {
                DocumentScannerUtil.Instance.Disconnect();
            }

            BarcodeScannerUtil.Instance.Disconnect();
            FacialRecognition.Instance.Dispose();

            Application.ExitThread();
            APIUtils.Dispose();
        }
Example #11
0
        public IHttpActionResult GetParticipantAttendance(int course_id)
        {
            var user_id    = APIUtils.GetUserFromClaim(ClaimsPrincipal.Current);
            var attendance = ParticipantHelper.GetParticipantAttendance(user_id, course_id);

            return(Ok(new ApiCallbackMessage(attendance.ToString(), true)));
        }
        public void SetValue(object target, object value)
        {
            object currentModel = target;

            if (DependentAttribute.DependentOn != null)
            {
                var targetPath = DependentAttribute.DependentOn.Trim().Split('.');
                foreach (var path in targetPath)
                {
                    if (currentModel == null)
                    {
                        break;
                    }

                    currentModel = currentModel.GetType().GetProperty(path).GetValue(currentModel);
                }
            }

            var resolvedValue = APIUtils.InvokeMethod(DependentAttribute.Resolver,
                                                      "Resolve",
                                                      new object[] {
                DB,
                engineService,
                RequesterId,
                currentModel,
                DependentAttribute.DependentOn
            });

            this.ValueProvider.SetValue(target, resolvedValue);
        }
Example #13
0
        public async Task <TModel> Read(int id, string date)
        {
            JObject json = await APIUtils.GetAsync(IPConfig.GetTotalUrlUser() + id + JsonDataConfig.Url +
                                                   EndUrl(Request, date));

            return((json == null) ? null : (json[JsonDataConfig.Root] as JObject)?.GetObject <TModel>());
        }
Example #14
0
        public string Get()
        {
            return(APIUtils.GetRandomWord());

            //alla vain APIn testaukseen käytettävä metodi (kovakoodatut promptisanat)
            //return APIUtils.GetRandomWordHardcoded();
        }
        public void SubBreeds_Test()
        {
            var currentTest = Core.ExtentReport.CreateTest(
                MethodBase.GetCurrentMethod().ToString().Replace("Void", "").Replace("()", ""),
                "This is a demo test for injecting a parameter into the URL of a API request."
                );

            APIUtils apiInstance = new APIUtils("https://dog.ceo");

            //Value of breed to search for
            string breedToSearchFor = "retriever";

            //Sets the headers
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Cookie", "__cfduid=df3050b40e97ce8431938fa8864b5a07b1593608688");

            //Retrieves the sub breeds of the above <breedToSearchFor> value
            var response = apiInstance.GetRequest(
                "/api/breed/" + breedToSearchFor + "/list"
                , headers
                , currentTest
                );

            //Verifys that 200 response
            response.ValidateResponseIs(HttpStatusCode.OK, currentTest);
            response.ValidateResponseIsJson(response.responseData, currentTest);
        }
Example #16
0
        public static void PopulateResourceLinks()
        {
            int i      = 0;
            var animes = RepoFactory.AniDB_Anime.GetAll().ToList();

            foreach (var anime in animes)
            {
                if (i % 10 == 0)
                {
                    ServerState.Instance.CurrentSetupStatus = string.Format(
                        Commons.Properties.Resources.Database_Validating, "Populating Resource Links from Cache",
                        $" {i}/{animes.Count}");
                }
                i++;
                try
                {
                    var xmlDocument = APIUtils.LoadAnimeHTTPFromFile(anime.AnimeID);
                    if (xmlDocument == null)
                    {
                        continue;
                    }
                    var resourceLinks = AniDBHTTPHelper.ProcessResources(xmlDocument, anime.AnimeID);
                    anime.CreateResources(resourceLinks);
                }
                catch (Exception e)
                {
                    logger.Error(
                        $"There was an error Populating Resource Links for AniDB_Anime {anime.AnimeID}, Update the Series' AniDB Info for a full stack: {e.Message}");
                }
            }


            using (var session = DatabaseFactory.SessionFactory.OpenStatelessSession())
            {
                i = 0;
                var batches = animes.Batch(50).ToList();
                foreach (var animeBatch in batches)
                {
                    i++;
                    ServerState.Instance.CurrentSetupStatus = string.Format(Commons.Properties.Resources.Database_Validating,
                                                                            "Saving AniDB_Anime batch ", $"{i}/{batches.Count}");
                    try
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            foreach (var anime in animeBatch)
                            {
                                RepoFactory.AniDB_Anime.SaveWithOpenTransaction(session.Wrap(), anime);
                            }
                            transaction.Commit();
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error($"There was an error saving anime while Populating Resource Links: {e}");
                    }
                }
            }
        }
Example #17
0
        internal StudioSequence(byte *buffer, Native *nativeMemory)
        {
            Data = nativeMemory;

            Label = Marshal.PtrToStringUTF8(new IntPtr(Data->label));

            Events = APIUtils.AllocateListWrapper(buffer, Data->numevents, Data->eventindex, n => new StudioEvent((StudioEvent.Native *)n.ToPointer()));
        }
Example #18
0
        public async Task <List <Models.Patient> > Read()
        {
            var patientConfig = JsonDataConfig as Patient;

            JObject patientsJson = await APIUtils.GetAsync(IPConfig.GetTotalUrl() + patientConfig.Url);

            return((patientsJson == null) ? new List <Models.Patient>() :
                   ((JArray)patientsJson[patientConfig.RootPatients]).GetList <Models.Patient>());
        }
Example #19
0
        public Main()
        {
            InitializeComponent();

            // Check if another instance of ALK is running
            if (CommonUtil.CheckIfAnotherInstanceIsRunning("ALK"))
            {
                MessageBox.Show("An instance of ALK is already running.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
            APIUtils.Start();
            //Notification
            Trinity.SignalR.Client signalrClient = Trinity.SignalR.Client.Instance;
            // setup variables
            _smartCardFailed          = 0;
            _fingerprintFailed        = 0;
            _displayLoginButtonStatus = false;
            _popupModel = new Trinity.BE.PopupModel();

            #region Initialize and register events
            double _sessionTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["session_timeout"]);
            if (_sessionTimeout > 0)
            {
                this._timerCheckLogout           = new System.Timers.Timer();
                this._timerCheckLogout.AutoReset = true;
                this._timerCheckLogout.Interval  = _sessionTimeout * 1000;
                this._timerCheckLogout.Elapsed  += TimeCheckLogout_EventHandler;
            }
            // _jsCallCS
            _jsCallCS = new JSCallCS(this.LayerWeb, this);
            _jsCallCS.OnNRICFailed      += JSCallCS_OnNRICFailed;
            _jsCallCS.OnShowMessage     += JSCallCS_ShowMessage;
            _jsCallCS.OnLogOutCompleted += JSCallCS_OnLogOutCompleted;

            // SmartCard
            SmartCard.Instance.GetCardInfoSucceeded += GetCardInfoSucceeded;
            // Fingerprint
            Fingerprint.Instance.OnIdentificationCompleted += Fingerprint_OnIdentificationCompleted;
            Fingerprint.Instance.OnDeviceDisconnected      += Fingerprint_OnDeviceDisconnected;

            // NRIC
            _nric = CodeBehind.Authentication.NRIC.GetInstance(LayerWeb);
            _nric.OnNRICSucceeded += NRIC_OnNRICSucceeded;
            _nric.OnShowMessage   += OnShowMessage;

            // Supervisee
            _superviseeParticulars = new CodeBehind.SuperviseeParticulars(LayerWeb, _jsCallCS, this);

            _eventCenter             = EventCenter.Default;
            _eventCenter.OnNewEvent += EventCenter_OnNewEvent;
            #endregion


            Lib.LayerWeb = LayerWeb;
            LayerWeb.Url = new Uri(String.Format("file:///{0}/View/html/Layout.html", CSCallJS.curDir));
            LayerWeb.ObjectForScripting = _jsCallCS;
        }
Example #20
0
        public async Task <List <Models.Doctor> > Read()
        {
            var doctorConfig = JsonDataConfig as Doctor;

            JObject doctorsJson = await APIUtils.GetAsync(IPConfig.GetTotalUrl() + doctorConfig.Url);

            return((doctorsJson == null) ? new List <Models.Doctor>() :
                   ((JArray)doctorsJson[doctorConfig.RootDoctors]).GetList <Models.Doctor>());
        }
Example #21
0
        public async Task <List <Models.Patient> > Read(string email)
        {
            var doctorConfig = JsonDataConfig as Doctor;

            JObject patientsJson = await APIUtils.GetAsync(IPConfig.GetTotalUrl() + doctorConfig.UrlPatients +
                                                           "?" + QueryParamsConfig.DoctorId + "=" + email);

            return((patientsJson == null) ? new List <Models.Patient>() :
                   ((JArray)patientsJson[doctorConfig.RootPatients]).GetList <Models.Patient>());
        }
Example #22
0
        public IHttpActionResult UpdateCourse([FromBody] Course courseToUpdate)
        {
            if (!APIUtils.CanChangeCourse(courseToUpdate.CourseID, ClaimsPrincipal.Current))
            {
                return(Unauthorized());
            }

            var success = courseToUpdate.Update();

            return(Ok(new ApiCallbackMessage(success ? "Success" : "Failed", success)));
        }
Example #23
0
        public async Task <object> Create([FromBody] Models.Doctor item)
        {
            var doctorJson = new JObject
            {
                { JsonDataConfig.Root, JObject.Parse(JsonConvert.SerializeObject(item, serializerSettings)) }
            };

            await APIUtils.PostAsync(IPConfig.GetTotalUrl() + JsonDataConfig.Url, doctorJson.ToString());

            return(Empty);
        }
Example #24
0
        public async Task <object> Update(int id, [FromBody] Models.PatientData.GoalCaloriesOut item)
        {
            var goalCaloriesJson = new JObject
            {
                { JsonDataConfig.Root, JObject.Parse(JsonConvert.SerializeObject(item, serializerSettings)) }
            };

            await APIUtils.PostAsync(IPConfig.GetTotalUrlUser() + id + JsonDataConfig.Url, goalCaloriesJson.ToString());

            return(Empty);
        }
Example #25
0
        public async Task <IEnumerable <TrainingKendo> > Read(int id)
        {
            JObject jsonTraining = await APIUtils.GetAsync(IPConfig.GetTotalUrlUser() + id + JsonDataConfig.Url);

            List <Models.Training> trainings = ((JArray)jsonTraining[JsonDataConfig.Root]).GetList <Models.Training>();

            List <TrainingKendo> trainingsKendo = new List <TrainingKendo>();

            trainings.ForEach(x => trainingsKendo.Add(TrainingKendo.CreateFromOptionList(x)));

            return(trainingsKendo);
        }
Example #26
0
        public IHttpActionResult ApplyParticipant(int course_id)
        {
            var user_id = APIUtils.GetUserFromClaim(ClaimsPrincipal.Current);

            using (var dc = new ArmsContext())
            {
                //TODO: Add check if exists
                Participant part = new Participant(user_id, course_id, "pending");
                part.Insert();
                return(Ok(new ApiCallbackMessage("Success", true)));
            }
        }
        public async Task <IEnumerable <MealKendo> > Read(int id, string day)
        {
            JObject jsonDiet = await APIUtils.GetAsync(IPConfig.GetTotalUrlUser() + id + JsonDataConfig.Url);

            JObject     jsonDietDay = (JObject)jsonDiet[JsonDataConfig.Root].FirstOrDefault(x => x[JsonDataConfig.Key[0]].ToString() == day);
            List <Meal> meals       = ((JArray)jsonDietDay[JsonDataConfig.Key[1]]).GetList <Meal>();

            List <MealKendo> mealsKendo = new List <MealKendo>();

            meals.ForEach(x => mealsKendo.Add(MealKendo.CreateFromOptionList(x)));

            return(mealsKendo);
        }
        public async Task <object> Update(int id, [FromBody] GoalStepsDaily item)
        {
            var GoalsStepsDailyConfig = JsonDataConfig as GoalsStepsDaily;
            var goalStepsJson         = new JObject
            {
                { GoalsStepsDailyConfig.RootUpdate, JObject.Parse(JsonConvert.SerializeObject(item, serializerSettings)) }
            };

            await APIUtils.PostAsync(IPConfig.GetTotalUrlUser() + id + GoalsStepsDailyConfig.UrlUpdate + "?"
                                     + QueryParamsConfig.Period + "=" + GoalsStepsDailyConfig.Period, goalStepsJson.ToString());

            return(Empty);
        }
Example #29
0
        public IHttpActionResult DeleteCourse([FromBody] Course courseToDelete)
        {
            bool success = false;

            APIUtils.CanChangeCourse(courseToDelete.CourseID, ClaimsPrincipal.Current);
            success = courseToDelete.Delete();
            if (success)
            {
                return(Ok(new ApiCallbackMessage("", success)));
            }

            return(BadRequest());
        }
Example #30
0
        public void GetProductByCategory(int CategoryID, int limit, string username, string password, int showHomePage, int minQuantity, int changeProductName)
        {
            var rs = new ResponseClass();

            if (Login(username, password))
            {
                var Product = ProductController.GetProductAPI(CategoryID, limit, showHomePage, minQuantity, changeProductName);

                if (Product.Count > 0)
                {
                    rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.SUCCESS);
                    rs.Status = APIUtils.ResponseMessage.Success.ToString();

                    foreach (var item in Product)
                    {
                        if (!string.IsNullOrEmpty(item.ProductImage))
                        {
                            item.ProductContent += String.Format("<p><img src='/wp-content/uploads/{0}' alt='{1}'/></p>", item.ProductImage.Split('/')[3], item.ProductTitle);
                        }

                        var productImage = ProductImageController.GetByProductID(item.ID);

                        if (productImage.Count() > 0)
                        {
                            foreach (var image in productImage)
                            {
                                item.ProductImage   += "|" + image.ProductImage;
                                item.ProductContent += String.Format("<p><img src='/wp-content/uploads/{0}' alt='{1}'/></p>", image.ProductImage.Split('/')[3], item.ProductTitle);
                            }
                        }
                    }
                    rs.Product = Product;
                }
                else
                {
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                    rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                    rs.Message = APIUtils.OBJ_DNTEXIST;
                }
            }
            else
            {
                rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.FAILED);
                rs.Status = APIUtils.ResponseMessage.Fail.ToString();
            }

            Context.Response.ContentType = "application/json";
            Context.Response.Write(JsonConvert.SerializeObject(rs, Formatting.Indented));
            Context.Response.Flush();
            Context.Response.End();
        }