예제 #1
0
        public WebServiceResult AddAutoRequest(Auto client)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            using (ClientRepository rep = new ClientRepository(new DiplomnaRabotaEntities()))
            {
                string path = @"D:\recourse\auto\" + client.LeaderFullName.Split(' ')[0] + client.PolicyNumber + ".jpg";
                if (File.Exists(path))
                {
                    retVal.Message = "Error";
                    retVal.Result  = "Този файл вече съществува!";
                }
                else
                {
                    File.WriteAllBytes(path, Convert.FromBase64String(client.AttachFile.ToString()));
                    File.Copy(path, @"C:\inetpub\wwwroot\front\images\Auto\" + client.LeaderFullName.Split(' ')[0] + client.PolicyNumber + ".jpg");
                    client.AttachFile = path;

                    retVal = rep.AddAutoRequest(client);
                }
            }
            return(retVal);
        }
예제 #2
0
        public WebServiceResult ProcessRequest(string function, string[] parameters, string postData)
        {
            try
            {
                switch (function)
                {
                case "addTarget":
                    return(AddTarget(postData));

                case "deleteTarget":
                    return(DeleteTarget(parameters));

                case "getMetricGroupSettings":
                    return(MetricGroupTable());

                case "getServiceAccount":
                    return(GetServiceAccount());

                case "updateMetricGroupSettings":
                    return(UpdateMetricGroups(postData));

                case "updateMetricGroupScript":
                    return(UpdateMetricGroupScript(postData));

                default:
                    return(WebServiceResult.ReturnError(String.Format("Unknown method: [{0}].", function)));
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                _logger.Error(e.StackTrace);
                return(WebServiceResult.ReturnError(e.Message));
            }
        }
예제 #3
0
        public WebServiceResult AddEstateRequest(Estate client)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            Estate newClient = new Estate();
            Guid   guid      = Guid.NewGuid();

            newClient.Id              = guid;
            newClient.FullName        = client.FullName;
            newClient.EGN             = client.EGN;
            newClient.MobilePhone     = client.MobilePhone;
            newClient.Email           = client.Email;
            newClient.Address         = client.Address;
            newClient.AttachFile      = client.AttachFile;
            newClient.CreatedAt       = DateTime.Now;
            newClient.Company         = client.Company;
            newClient.Area            = client.Area;
            newClient.Kind            = client.Kind;
            newClient.InsuranceAmount = client.InsuranceAmount;

            context.Estates.Add(newClient);
            context.SaveChanges();

            retVal.Result = "Клиент  " + newClient.FullName + " е добавен";

            return(retVal);
        }
예제 #4
0
        public WebServiceResult AddHealthRequest(Health client)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            Health newClient = new Health();
            Guid   guid      = Guid.NewGuid();

            newClient.Id             = guid;
            newClient.FullName       = client.FullName;
            newClient.EGN            = client.EGN;
            newClient.UserId         = client.UserId;
            newClient.MobilePhone    = client.MobilePhone;
            newClient.Email          = client.Email;
            newClient.Address        = client.Address;
            newClient.DocumentNumber = client.DocumentNumber;
            newClient.IBAN           = client.IBAN;
            newClient.AttachFile     = client.AttachFile;
            newClient.CreatedAt      = DateTime.Now;
            newClient.Company        = client.Company;

            context.Healths.Add(newClient);
            context.SaveChanges();

            retVal.Result = "Клиент  " + newClient.FullName + " е добавен";

            return(retVal);
        }
예제 #5
0
        public static void Register()
        {
            Logger.Debug("Method called.");
            string baseUri            = WebConfigurationManager.AppSettings["WebServiceBaseURI"];
            string webServiceProvider = WebConfigurationManager.AppSettings["WebServiceProvider"];
            string ipsUsername        = WebConfigurationManager.AppSettings["IPSUsername"];
            string ipsPassword        = WebConfigurationManager.AppSettings["IPSPassword"];

            WebServiceProxyBase.BaseUri = baseUri;

            var loginService = new LoginService();
            var res          = new WebServiceResult();

            try
            {
                res = loginService.ServiceLogin(webServiceProvider, ipsUsername, ipsPassword, ref Ticket);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }

            if (!res.IsSuccess)
            {
                var message = string.Format("Unable to get Infor Ticket from WebService. Received the following error: {0}", res.Message);
                Logger.Error(message);
                throw new Exception(message);
            }
        }
 public static TaskResult FromResult(WebServiceResult res)
 {
     return(new TaskResult()
     {
         Data = null, Result = res
     });
 }
예제 #7
0
        public WebServiceResult ForgivPassword(string userName, string email)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };
            ClientRepository rep = new ClientRepository(new DiplomnaRabotaEntities());

            var user = context.Users.Where(x => x.Name == userName && x.Email == email).FirstOrDefault();

            if (user == null)
            {
                retVal.Message = "Error";
                retVal.Result  = "Username and email are not found";
            }
            else
            {
                user.PassHash = "c6001d5b2ac3df314204a8f9d7a00e1503c9aba0fd4538645de4bf4cc7e2555cfe9ff9d0236bf327ed3e907849a98df4d330c4bea551017d465b4c1d9b80bcb0"; //0000
                context.SaveChanges();

                retVal.Result = rep.SendMail(email, "reset password", "Новата ви парола в системата за регистрация на авариини ситуации е 0000. Можете да е смените след като влезнете в системата!");
            }


            return(retVal);
        }
예제 #8
0
        public WebServiceResult Login(string name, string pass)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            using (UserRepository rep = new UserRepository(new DiplomnaRabotaEntities()))
            {
                retVal = rep.Login(name, pass);
            }

            if (retVal.Result.ToString() != "Username not found")
            {
                int?   userId    = Convert.ToInt32(Utils.GetPropertyValueFromAnonymousObject(retVal.Result, "userId"));
                Guid?  sessionId = new Guid(Utils.GetPropertyValueFromAnonymousObject(retVal.Result, "sessionId").ToString());
                string userName  = Utils.GetPropertyValueFromAnonymousObject(retVal.Result, "userName").ToString();
                string fullName  = Utils.GetPropertyValueFromAnonymousObject(retVal.Result, "fullName").ToString();
                string address   = Utils.GetPropertyValueFromAnonymousObject(retVal.Result, "address").ToString();
                string email     = Utils.GetPropertyValueFromAnonymousObject(retVal.Result, "email").ToString();

                retVal.Result = new
                {
                    userId    = userId,
                    sessionId = sessionId,
                    userName  = userName,
                    firstName = fullName.Split(' ')[0],
                    lastName  = fullName.Split(' ')[1],
                    address   = address,
                    email     = email
                };
            }

            return(retVal);
        }
예제 #9
0
        public HttpResponseMessage UpdateUser(HttpRequestMessage requestUpdate)
        {
            if (Request.Method == HttpMethod.Options)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };
            UserBusinessLayer bl = new UserBusinessLayer();

            try
            {
                if (!bl.CheckSession(new Guid(Utils.GetSessionId())))
                {
                    retVal.Message = "Session error";
                    retVal.Result  = "Invalid session";
                }
                else
                {
                    string[] json = requestUpdate.Content.ReadAsStringAsync().Result.Split('=');

                    Dictionary <string, string> result = new Dictionary <string, string>();
                    if (json[0] != null && json[0] == "data")
                    {
                        result = JsonConvert.DeserializeObject <Dictionary <string, string> >(HttpUtility.UrlDecode(json[1]));
                        retVal = bl.UpdateUser(result);
                    }
                    else
                    {
                        retVal = new WebServiceResult()
                        {
                            Message = "POST request parameters error!", Result = "No 'data' parameter"
                        };
                    }
                }
            }

            catch (Exception ex)
            {
                retVal = new WebServiceResult()
                {
                    Message = "POST request parameters error!", Result = String.Format("Message: {0}, StackTrace: {1}", ex.Message, ex.StackTrace)
                };
            };

            HttpStatusCode status = HttpStatusCode.OK;

            if (retVal.Message != "OK")
            {
                status = HttpStatusCode.InternalServerError;
            }
            return(Request.CreateResponse(status, retVal));
        }
예제 #10
0
        protected virtual WebServiceResult GetData(CommandType cmdType, string sqlQuery, SqlParameters sqlParameters)
        {
            string data;

            try
            {
                using (SqlConnection reposConnection = new SqlConnection(Configuration.GetReposConnectionString("WebService")))
                {
                    reposConnection.Open();

                    using (SqlCommand reposCommand = reposConnection.CreateCommand())
                    {
                        reposCommand.CommandText = sqlQuery;
                        reposCommand.CommandType = cmdType;

                        for (int i = 0; i < sqlParameters.Count; i++)
                        {
                            reposCommand.Parameters.Add(sqlParameters[i].Item1, SqlDbType.VarChar, sqlParameters[i].Item2.Length);
                            reposCommand.Parameters[sqlParameters[i].Item1].Value = sqlParameters[i].Item2;
                        }

                        // prepare the statement if there is at least one parameter
                        if (sqlParameters.Count > 0)
                        {
                            reposCommand.Prepare();
                        }

                        SqlDataReader dataReader = reposCommand.ExecuteReader();
                        data = "[";
                        while (dataReader.Read())
                        {
                            if (data.Length > 1)
                            {
                                data += ",";
                            }

                            if (!DBNull.Value.Equals(dataReader[0]))
                            {
                                data += (string)dataReader[0];
                            }
                        }

                        data += "]";
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error("GetData: " + e.Message);
                _logger.Debug(e.StackTrace);
                return(WebServiceResult.ReturnError(e.Message));
            }

            return(WebServiceResult.ReturnSuccess(data));
        }
예제 #11
0
            public async Task ShouldNotUpdateStatusIfSetFanModeFails()
            {
                var errorResult = new WebServiceResult(WebServiceError.Unknown, new Exception());

                _nestWebService.Setup(n => n.SetFanModeAsync(It.IsAny <Thermostat>(), It.IsAny <FanMode>())).Returns(Task.FromResult(errorResult));
                await _viewModel.LoginAsync();

                _viewModel.FanMode = FanMode.Auto;

                _statusUpdaterService.Verify(s => s.UpdateStatusAsync(), Times.Never());
            }
예제 #12
0
        public HttpResponseMessage NewUser(HttpRequestMessage request)
        {
            if (Request.Method == HttpMethod.Options)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };
            UserBusinessLayer bl = new UserBusinessLayer();

            try
            {
                string[] json = request.Content.ReadAsStringAsync().Result.Split('=');

                Dictionary <string, string> result = new Dictionary <string, string>();
                if (json[0] != null && json[0] == "data")
                {
                    result = JsonConvert.DeserializeObject <Dictionary <string, string> >(HttpUtility.UrlDecode(json[1]));



                    User user = new User()
                    {
                        Name     = Convert.ToString(result["Name"]),
                        FullName = Convert.ToString(result["FullName"]),
                        Address  = Convert.ToString(result["Address"]),
                        PassHash = Convert.ToString(result["PassHash"]),
                        Email    = Convert.ToString(result["Email"])
                    };
                    retVal = bl.AddUser(user);
                }


                var status = HttpStatusCode.OK;
                if (retVal.Message != "OK")
                {
                    status = HttpStatusCode.InternalServerError;
                }
                return(new HttpResponseMessage(status)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(retVal), Encoding.UTF8, "application/json")
                });
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(ex), Encoding.UTF8, "application/json")
                });
            }
        }
예제 #13
0
            public async Task ShouldNotUpdateStatusIfChangeTemperatureFails()
            {
                var result = new WebServiceResult(WebServiceError.Unknown, new Exception());

                _nestWebService.Setup(n => n.ChangeTemperatureAsync(It.IsAny <Thermostat>(), It.IsAny <double>(), It.IsAny <TemperatureMode>()))
                .Returns(Task.FromResult(result));
                await _viewModel.LoginAsync();

                await _viewModel.RaiseTemperatureAsync();

                _statusUpdaterService.Verify(s => s.UpdateStatusAsync(), Times.Never());
            }
예제 #14
0
        public WebServiceResult AddUser(User user)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            using (UserRepository rep = new UserRepository(new DiplomnaRabotaEntities()))
            {
                retVal = rep.NewUser(user);
            }
            return(retVal);
        }
예제 #15
0
        public WebServiceResult SendMail(string to, string subject, string body)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            using (ClientRepository rep = new ClientRepository(new DiplomnaRabotaEntities()))
            {
                retVal = rep.SendMail(to, subject, body);
            }
            return(retVal);
        }
 public WebServiceResult ProcessRequest(string function, string[] parameters, string postData)
 {
     try
     {
         return(StatusTable());
     }
     catch (Exception e)
     {
         _logger.Error(e.Message);
         _logger.Error(e.StackTrace);
         return(WebServiceResult.ReturnError(e.Message));
     }
 }
예제 #17
0
        private IHttpActionResult FormatResult(WebServiceResult result)
        {
            switch (result.ErrorType)
            {
            case "None":
                return(Ok(result.Content));

            case "BadRequest":
                return(BadRequest(result.Content));

            default:
                return(InternalServerError(new Exception($"{result.ErrorType}: {result.Content}")));
            }
        }
예제 #18
0
        public WebServiceResult ForgivPassword(string userName, string email)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            using (UserRepository rep = new UserRepository(new DiplomnaRabotaEntities()))
            {
                retVal = rep.ForgivPassword(userName, email);
            }

            return(retVal);
        }
예제 #19
0
 public static WebServiceResult FromException(this WebServiceResult webServiceResult, Exception e)
 {
     return(new WebServiceResult
     {
         Code = 0,
         Date = DateTime.Now,
         HasFailed = true,
         IsSuccess = false,
         Message = e.Message,
         IsNoDataFound = false,
         Reference = "",
         Severity = ResultSeverity.Fault,
         Stack = e.StackTrace
     });
 }
예제 #20
0
        private WebServiceResult UpdateMetricGroupScript(string postDataRaw)
        {
            int    metricGroupId;
            string scriptBase64;
            string script;
            string errorMsg;

            if (string.IsNullOrEmpty(postDataRaw))
            {
                return(WebServiceResult.ReturnError("POST data cannot be NULL or empty"));
            }

            string postData = DecodeUriCharacters(postDataRaw);

            _logger.Debug(postData);

            try
            {
                // Extract metricGroupId and script (Base64 encoded)
                foreach (Match itemsMatch in Regex.Matches(postData, @"id=([0-9]*)&script=([0-9a-zA-Z+/=]*)"))
                {
                    if (itemsMatch.Groups.Count != 3)
                    {
                        return(WebServiceResult.ReturnError(@"Data is not in ([0-9]*)\[interval*\]=(\-?[0-9]*)&[0-9]*\[retention\]=(\-?[0-9]*) format"));
                    }

                    metricGroupId = Int32.Parse(itemsMatch.Groups[1].Value);
                    scriptBase64  = itemsMatch.Groups[2].Value;
                    _logger.Debug(scriptBase64);

                    script = Base64.Decode(scriptBase64);

                    _logger.Debug(script);

                    if (!_cfg.UpdateMetricGroupScript(metricGroupId, script, out errorMsg))
                    {
                        return(WebServiceResult.ReturnError(errorMsg));
                    }
                }

                return(WebServiceResult.ReturnSuccess());
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                return(WebServiceResult.ReturnError(e.Message));
            }
        }
예제 #21
0
        public HttpResponseMessage Login(string user, string pass)
        {
            if (Request.Method == HttpMethod.Options)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            try
            {
                UserBusinessLayer bl = new UserBusinessLayer();
                retVal = bl.Login(user, pass);

                var status = HttpStatusCode.OK;
                if (retVal.Message != "OK")
                {
                    status = HttpStatusCode.InternalServerError;
                }
                if (retVal.Message != "OK")
                {
                    return new HttpResponseMessage(status)
                           {
                               Content = new StringContent(JsonConvert.SerializeObject(retVal), Encoding.UTF8, "application/json")
                           }
                }
                ;
                else
                {
                    return new HttpResponseMessage(status)
                           {
                               Content = new StringContent(JsonConvert.SerializeObject(retVal.Result), Encoding.UTF8, "application/json")
                           }
                };
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(ex), Encoding.UTF8, "application/json")
                });
            }
        }
예제 #22
0
        public WebServiceResult Logout(int userId)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };

            using (UserRepository rep = new UserRepository(new DiplomnaRabotaEntities()))
            {
                if (!rep.Logout(userId))
                {
                    retVal.Message = "Logout error";
                    retVal.Result  = "Logout error";
                }
            }
            return(retVal);
        }
예제 #23
0
        public WebServiceResult AddAutoRequest(Auto client)
        {
            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };
            Random rand      = new Random();
            Auto   newClient = new Auto();
            Guid   guid      = Guid.NewGuid();

            newClient.Id                       = guid;
            newClient.OwnerFullName            = client.OwnerFullName;
            newClient.OwnerAddress             = client.OwnerAddress;
            newClient.OwnerPhone               = client.OwnerPhone;
            newClient.MPSModel                 = client.MPSModel;
            newClient.MPSNumber                = client.MPSNumber;
            newClient.TrailerNumber            = client.TrailerNumber;
            newClient.InsurerCompany           = client.InsurerCompany;
            newClient.InsurerPolicyNumber      = client.InsurerPolicyNumber;
            newClient.InsurerGreenCardNumber   = client.InsurerGreenCardNumber;
            newClient.ValidFrom                = client.ValidFrom;
            newClient.ValidTo                  = client.ValidTo;
            newClient.InsurerAgency            = client.InsurerAgency;
            newClient.InsurerAddress           = client.InsurerAddress;
            newClient.InsurerPhone             = client.InsurerPhone;
            newClient.LeaderFullName           = client.LeaderFullName;
            newClient.LeaderBornDate           = client.LeaderBornDate;
            newClient.LeaderAddress            = client.LeaderAddress;
            newClient.LeaderPhone              = client.LeaderPhone;
            newClient.LeaderCertificate        = client.LeaderCertificate;
            newClient.LeaderCategory           = client.LeaderCategory;
            newClient.LeaderCertificateValidTo = client.LeaderCertificateValidTo;
            newClient.PolicyNumber             = client.PolicyNumber;
            newClient.VisibleDamage            = client.VisibleDamage;
            newClient.AttachFile               = client.AttachFile;
            newClient.Circumstances            = client.Circumstances;
            newClient.CreateDate               = DateTime.Now;
            newClient.IsGuilty                 = client.IsGuilty;

            context.Autoes.Add(newClient);
            context.SaveChanges();

            retVal.Result = "Клиент  " + newClient.LeaderFullName + " е добавен";

            return(retVal);
        }
        public static TaskResult Failure(string message, string stackTrace)
        {
            var res = new WebServiceResult()
            {
                Date          = DateTime.Now,
                HasFailed     = true,
                IsNoDataFound = false,
                IsSuccess     = false,
                Message       = message,
                Severity      = ResultSeverity.Error,
                Stack         = stackTrace
            };

            return(new TaskResult()
            {
                Data = null, Result = res
            });
        }
        public static TaskResult Warning(object data, string message)
        {
            var res = new WebServiceResult()
            {
                Date          = DateTime.Now,
                HasFailed     = false,
                IsNoDataFound = false,
                IsSuccess     = false,
                Message       = message,
                Severity      = ResultSeverity.Warning,
                Stack         = ""
            };

            return(new TaskResult()
            {
                Data = data, Result = res
            });
        }
        public static TaskResult Success(object data)
        {
            var res = new WebServiceResult()
            {
                Date          = DateTime.Now,
                HasFailed     = false,
                IsNoDataFound = false,
                IsSuccess     = true,
                Message       = "",
                Severity      = ResultSeverity.Success,
                Stack         = ""
            };

            return(new TaskResult()
            {
                Data = data, Result = res
            });
        }
        // returns a set of datetime-value tuples in a JSON string
        // param0: MetricGroupName - MetricGroup->Name
        // param1: MetricName - MetricGroup->Metrics->Name
        // param2: TargetId - Targets->Id
        // param3: StartDateTime - YYYYMMDDHHMM
        // param4: EndDateTime - YYYYMMDDHHMM
        // param5: Interval - M in minutes
        // test string ok http://localhost:3128/ws/fastsingle/Range/SQL%20Server%20Activity/CPU%20mils/0/201305201800/201305201900/5
        // test string not ok http://localhost:3128/ws/fastsingle/Range/SQL%20Server%20Activity/CPU%20mils/0/201305201800/201305M900/5
        private WebServiceResult Range(string[] parameters)
        {
            if (parameters.Count() < 6)
            {
                return(WebServiceResult.ReturnError(GetType().Name + ".Range(): not enough parameters. Format is MetricGroupName/MetricName/TargetId/StartDateTime/EndDateTime/IntervalInMinutes"));
            }

            Regex r = new Regex("^[0-9]*$");

            // check that supplied target id is valid
            if (!r.IsMatch(parameters[2]) || !Configuration.targets.ContainsId(Convert.ToInt32(parameters[2])))
            {
                return(WebServiceResult.ReturnError(GetType().Name + ".Range(): TargetId is either not numeric or doesn't exist"));
            }

            if (!r.IsMatch(parameters[3]) || !r.IsMatch(parameters[4]) || !r.IsMatch(parameters[5]))
            {
                return(WebServiceResult.ReturnError(GetType().Name + ".Range(): at least one of the parameters is not numeric. Format is TargetId/StartDateTime/EndDateTime/IntervalInMinutes"));
            }

            if (parameters[3].Length != 12 || parameters[4].Length != 12)
            {
                return(WebServiceResult.ReturnError(GetType().Name + ".Range(): StartDateTime and EndDateTime must be in YYYYMMDDHHMM format"));
            }

            // look up metric group by name
            int metricGroupId = Configuration.metricGroups[parameters[0]].id;

            // look up metric by name
            string columnName = parameters[1].Replace(' ', '_');

            // prepare parameters
            SqlParameters sqlParameters = new SqlParameters
            {
                { "@tablename", SqlServerProbe.DataTableName(Convert.ToInt32(parameters[2]), Configuration.metricGroups[metricGroupId]) },
                { "@columnname", columnName },
                { "@start_dt", SqlServerProbe.FormatDate(parameters[3]) },
                { "@end_dt", SqlServerProbe.FormatDate(parameters[4]) },
                { "@interval", parameters[5] }
            };

            // execute procedure and return results
            return(GetData(System.Data.CommandType.StoredProcedure, "dbo.GetRangeSingleRowFastCumulative", sqlParameters));
        }
예제 #28
0
        public HttpResponseMessage Logout(int userId)
        {
            if (Request.Method == HttpMethod.Options)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };
            UserBusinessLayer bl = new UserBusinessLayer();

            try
            {
                if (!bl.CheckSession(new Guid(Utils.GetSessionId())))
                {
                    retVal.Message = "Session error";
                    retVal.Result  = "Invalid session";
                }
                else
                {
                    retVal = bl.Logout(userId);
                }

                var status = HttpStatusCode.OK;
                if (retVal.Message != "OK")
                {
                    status = HttpStatusCode.InternalServerError;
                }
                return(new HttpResponseMessage(status)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(retVal), Encoding.UTF8, "application/json")
                });
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(ex), Encoding.UTF8, "application/json")
                });
            }
        }
예제 #29
0
        public HttpResponseMessage GetHealthDocumentsCount(string fullName = "", string company = "")
        {
            if (Request.Method == HttpMethod.Options)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            WebServiceResult retVal = new WebServiceResult()
            {
                Message = "OK", Result = ""
            };
            ClientBusinessLayer bl = new ClientBusinessLayer();

            try
            {
                if (!bl.CheckSession(new Guid(Utils.GetSessionId())))
                {
                    retVal.Message = "Session error";
                    retVal.Result  = "Invalid session";
                }
                else
                {
                    retVal.Result = bl.GetHealthDocumentsCount(fullName, company);
                }

                var status = HttpStatusCode.OK;
                if (retVal.Message != "OK")
                {
                    status = HttpStatusCode.InternalServerError;
                }
                return(new HttpResponseMessage(status)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(retVal), Encoding.UTF8, "application/json")
                });
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(ex), Encoding.UTF8, "application/json")
                });
            }
        }
        public WebServiceResult ProcessRequest(string function, string[] parameters, string postData)
        {
            try
            {
                switch (function)
                {
                case "Range":
                    return(Range(parameters));

                default:
                    return(WebServiceResult.ReturnError(GetType().Name + ".ProcessRequest(): function " + function + " could not be found"));
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                _logger.Debug(e.StackTrace);
                return(WebServiceResult.ReturnError(e.Message));
            }
        }
        public override Guid InitiateGet(string url, WebServiceResult result, IDictionary<string, string> parameters, object userState)
        {
            var data = CreateGetRequestData(url, result, parameters, userState);

            lock (ApiLockSync)
            {
                _queuedRequest.Enqueue(data);
                Monitor.Pulse(ApiLockSync);
            }

            return data.ApiGuidToken;
        }
예제 #32
0
			public virtual void Dispose()
			{
				if (_disposed)
					throw new ObjectDisposedException("PrivateRequestData", "Cannot dispose a disposed request");

				GC.SuppressFinalize(this);

				Debug.WriteLine("====> WEB PRE-GC: PrivateRequestData GUID: {0} disposed!", _apiGuidToken);

				_userState = null;
				_result = null;
				_requestUri = null;
				_parameters = null;
				_disposed = true;
				IsHandled = true;

				GC.ReRegisterForFinalize(this);
				GC.Collect();
			}
예제 #33
0
		/// <summary>
		/// Initiate a GET request, returns result string in the WebServiceResult callback
		/// </summary>
		/// <param name="url">Get URL</param>
		/// <param name="result">Response delegate</param>
		/// <param name="parameters">Get parameters (if any)</param>
		/// <param name="userState">User state (if any) </param>
		/// <returns>Guid of the request</returns>
		public abstract Guid InitiateGet(string url, WebServiceResult result, IDictionary<string, string> parameters, object userState);
예제 #34
0
		/// <summary>
		/// Initiate a POST request with an string to upload, returns the result string in the WebServiceResult callback
		/// </summary>
		/// <param name="url">Get URL</param>
		/// <param name="result">Response delegate</param>
		/// <param name="writableString">String to upload</param>
		/// <param name="userState">User state (if any)</param>
		/// <returns>Guid of the Request</returns>
		public abstract Guid InitiatePost(string url, WebServiceResult result, string writableString, object userState);
예제 #35
0
		protected static PrivateRequestData CreatePostRequestDataFromString(string url, WebServiceResult result, string args, object userState = null, bool onUi = false)
		{
			return PrivateRequestData.CreateRequest(RequestType.Post, url, args, userState, result, onUi);
		}
예제 #36
0
			public DoubleQueueRequestData(Guid apiGuidToken, RequestType requestType, string requestUri, string parameters, object userState, WebServiceResult result, CurrentlyUsedWorker currentWorker, bool returnOnUi = false)
				: base(apiGuidToken, requestType, requestUri, parameters, userState, result, returnOnUi)
			{

				_currentWorker = currentWorker;

			}
예제 #37
0
		public override Guid InitiatePost(string url, WebServiceResult result, string writableString, object userState)
		{
			var guid = Guid.NewGuid();

			var requestItem = new DoubleQueueRequestData(guid, RequestType.Post, url, writableString, userState, result, _currentWorker);

			switch (_currentWorker)
			{
				case CurrentlyUsedWorker.Primary:
					_primaryWorker.EnqueueOperation(requestItem);
					_currentWorker = CurrentlyUsedWorker.Secondary;
					break;
				case CurrentlyUsedWorker.Secondary:
					_secondaryWorker.EnqueueOperation(requestItem);
					_currentWorker = CurrentlyUsedWorker.Primary;
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}

			return guid;
		}
예제 #38
0
			protected PrivateRequestData(Guid apiGuidToken, RequestType requestType, string requestUri, string parameters, object userState, WebServiceResult result, bool returnOnUi = false)
			{
				_apiGuidToken = apiGuidToken;
				_result = result;
				_returnOnUi = returnOnUi;
				_userState = userState;
				_parameters = parameters;
				_requestUri = requestUri;
				_requestType = requestType;
			}
예제 #39
0
			public static PrivateRequestData CreateRequest(RequestType requestType, string requestUri, string args, object userState, WebServiceResult result, bool returnOnUi = false)
			{
				return new PrivateRequestData(Guid.NewGuid(), requestType, requestUri, args, userState, result, returnOnUi);
			}
        public override Guid InitiatePost(string url, WebServiceResult result, string writableString, object userState)
        {
            var data = CreatePostRequestDataFromString(url, result, writableString, userState);

            lock (ApiLockSync)
            {
                _queuedRequest.Enqueue(data);
                Monitor.Pulse(ApiLockSync);
            }

            return data.ApiGuidToken;
        }
예제 #41
0
		public override Guid InitiateGet(string url, WebServiceResult result, IDictionary<string, string> parameters, object userState)
		{
			var guid = Guid.NewGuid();

			var pars = Utils.ProcessArguments(parameters);
			var requestItem = new DoubleQueueRequestData(guid, RequestType.Get, url, pars, userState, result, _currentWorker);

			ThreadPool.QueueUserWorkItem(state =>
											 {
												 var item = (DoubleQueueRequestData)state;

												 switch (_currentWorker)
												 {
													 case CurrentlyUsedWorker.Primary:
														 _primaryWorker.EnqueueOperation(item);
														 _currentWorker = CurrentlyUsedWorker.Secondary;
														 break;
													 case CurrentlyUsedWorker.Secondary:
														 _secondaryWorker.EnqueueOperation(item);
														 _currentWorker = CurrentlyUsedWorker.Primary;
														 break;
													 default:
														 throw new ArgumentOutOfRangeException();
												 }
											 }, requestItem);
			return guid;
		}
예제 #42
0
		protected static PrivateRequestData CreatePostRequestData(string url, WebServiceResult result, IDictionary<string, string> args, object userState = null, bool onUi = false)
		{
			return PrivateRequestData.CreateRequest(RequestType.Post, url, ArgumentsProcessor(args), userState, result, onUi);
		}
예제 #43
0
		/// <summary>
		/// Initiate a POST request with parameters to upload, return the result string in the WebServiceResult callback
		/// </summary>
		/// <param name="url">Get URL</param>
		/// <param name="result">Response delegate</param>
		/// <param name="parameters">Parameters to upload</param>
		/// <param name="userState">User state object (if any)</param>
		/// <returns>Guid of the Request</returns>
		public Guid InitiatePost(string url, WebServiceResult result, IDictionary<string, string> parameters, object userState)
		{
			return InitiatePost(url, result, ArgumentsProcessor(parameters), userState);
		}