コード例 #1
0
        public void AddDataPoints(ResponseObject Object)
        {
            try
            {
                CpuMenuItem.Text = "CPU: " + Object.cpu.ToString() + "%";
                Main.ActiveForm.Invoke(new Action(delegate()
                {
                    CpuChart.Series[0].Points.AddXY(IncrementalX, Math.Min(Object.cpu, (float)100));
                }));
            }
            catch { }

            try
            {
                TemperatureMenuItem.Text = "Temperature: " + Object.temp.ToString() + "C";
                Main.ActiveForm.Invoke(new Action(delegate()
                {
                    TemperatureChart.Series[0].Points.AddXY(IncrementalX, Object.temp);
                    IncrementalX++;
                }));
            }
            catch { }

            Main.ActiveForm.Invoke(new Action(delegate()
            {
                if (CpuChart.ChartAreas[0].AxisX.Maximum > CpuChart.ChartAreas[0].AxisX.ScaleView.Size)
                    CpuChart.ChartAreas[0].AxisX.ScaleView.Scroll(CpuChart.ChartAreas[0].AxisX.Maximum);

                if (TemperatureChart.ChartAreas[0].AxisX.Maximum > TemperatureChart.ChartAreas[0].AxisX.ScaleView.Size)
                    TemperatureChart.ChartAreas[0].AxisX.ScaleView.Scroll(TemperatureChart.ChartAreas[0].AxisX.Maximum);
            }));
        }
コード例 #2
0
        public ActionResult Get(PaginationObject pagination, string name)
        {
            var response = Business.Ocorrencia.Instance.GetAllOcorrencias(ref pagination, name);

            var rlResponse = new ResponseObject
            {
                Messages = response.Messages,
                Status = response.Status,
                Pagination = response.Pagination,
                Objects = Mapper.Map<List<OcorrenciaViewModel>>(response.Objects).Select(a=>(object)a).ToList()
            };

            return Json(rlResponse);
        }
コード例 #3
0
        public ActionResult Get(PaginationObject pagination, string name)
        {
            var response = Business.Log.Instance.GetAllLogs(ref pagination, name);

            var rlResponse = new ResponseObject
            {
                Messages = response.Messages,
                Status = response.Status,
                Pagination = response.Pagination,
                Objects = response.Objects
            };

            return Json(rlResponse);
        }
コード例 #4
0
        public ActionResult ForgotPassword(string email)
        {
            var response = new ResponseObject();

            var user = Business.User.Instance.GetByEmail(email);

            if (user != null)
                response = Business.User.Instance.ForgotPassword(user);
            else
            {
                response.Status = false;
                response.Messages.Add("Não foi possível localizar o email informado");
            }

            return Json(response);
        }
コード例 #5
0
    void OnGUI()
    {
        GUILayout.Space(15);

        // An example of an action class with a GUI attached, we are calling the
        // Gui component of the action. No need to worry about the logic part as it is already
        // wired up with the view part by definition
        _radialSpreadAction.OnGUI();

        GUILayout.Space(15);

        // Example of action's which don't have GUI/View's attached
        if (GUILayout.Button("Some Action Class", GUILayout.ExpandWidth(true)))
        {
            SomeActionClass someAction = this.GetInstance<SomeActionClass>(_actionRecorder);

            _actionResult = _actionRecorder.PerformAction(someAction); //Action's supply back an enumerable result?
        }

        if (GUILayout.Button("Fail Undo Action", GUILayout.ExpandWidth(true)))
        {
            FailUndoAction action = this.GetInstance<FailUndoAction>(_actionRecorder);

            _actionResult = _actionRecorder.PerformAction(action);
        }

        if (GUILayout.Button("Fail Redo Action", GUILayout.ExpandWidth(true)))
        {
            FailRedoAction action = this.GetInstance<FailRedoAction>(_actionRecorder);

            _actionResult = _actionRecorder.PerformAction(action);
        }

        // -----------------------
        // Display Built in UndoRedoGUI in the Action Recorder
        _actionRecorder.UndoRedoGUI(this.position);
    }
コード例 #6
0
        private async Task <ResponseObject> ValidateAuthTokenAsync()
        {
            var response = new ResponseObject();

            try
            {
                var authToken = _cookieSvc.Get("access_token");
                var userName  = _cookieSvc.Get("username");

                if (!string.IsNullOrEmpty(authToken))
                {
                    /* Get the user from db */
                    var user = await _userManager.FindByNameAsync(userName);

                    if (user != null)
                    {
                        var userOldToken = await _db.Tokens.Where(x => x.UserId == user.Id).FirstOrDefaultAsync();

                        if (userOldToken != null)
                        {
                            var protectorProvider        = _provider.GetService <IDataProtectionProvider>();
                            var layerOneUnProtector      = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);
                            var unprotectedTokenLayerOne = layerOneUnProtector.Unprotect(authToken);
                            var protectorJwt             = protectorProvider.CreateProtector(userOldToken.EncryptionKeyJwt);
                            unProtectedToken = protectorJwt.Unprotect(unprotectedTokenLayerOne);
                            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);

                            handler = new JwtSecurityTokenHandler();

                            validationParameters = new TokenValidationParameters
                            {
                                ValidateIssuerSigningKey = true,
                                ValidateIssuer           = true,
                                ValidateAudience         = true,
                                ValidIssuer      = _appSettings.Site,
                                ValidAudience    = _appSettings.Audience,
                                IssuerSigningKey = new SymmetricSecurityKey(key),
                                ValidateLifetime = true,
                                ClockSkew        = TimeSpan.Zero
                            };

                            validateToken = handler.ValidateToken(unProtectedToken, validationParameters, out var securityToken);

                            /* This is called pattern matching => is */
                            if (!(securityToken is JwtSecurityToken jwtSecurityToken) ||
                                !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
                                                                    StringComparison.InvariantCultureIgnoreCase))
                            {
                                response.IsValid = false;
                                response.Message = "Token Invalid";
                                return(response);
                            }

                            if (UserRoles.Contains(user.UserRole))
                            {
                                var decryptedUsername = validateToken.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value;

                                if (decryptedUsername == userName)
                                {
                                    response.IsValid = true;
                                    response.Message = "Token Valid";
                                    return(response);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(SecurityTokenExpiredException))
                {
                    if (_appSettings.AllowSiteWideTokenRefresh)
                    {
                        validationParameters.ValidateLifetime = false;
                        validateToken = handler.ValidateToken(unProtectedToken, validationParameters, out var securityToken);

                        /* This is called pattern matching => is */
                        if (!(securityToken is JwtSecurityToken jwtSecurityToken) ||
                            !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
                                                                StringComparison.InvariantCultureIgnoreCase))
                        {
                            response.IsValid = false;
                            response.Message = "Token Invalid";
                            return(response);
                        }

                        response.IsValid = true;
                        response.Message = "Token Expired";
                        return(response);
                    }
                }

                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }
            response.IsValid = false;
            response.Message = "Token Invalid";
            return(response);
        }
コード例 #7
0
        public IActionResult Post([FromBody] BookingPersonRequest bookingPassenger,
                                  [FromServices] IRepository <Person> personRepository,
                                  [FromServices] IRepository <Flight> flightRepository)
        {
            // Check for flight existence.
            Flight flight = flightRepository.GetAll().FirstOrDefault(f => f.Number.Trim() == bookingPassenger.FlightNumber.Trim());

            if (flight.IsNull())
            {
                return(NotFound(ResponseObject.StatusCode(MessageCode.ERROR_VALUE_NOT_FOUND,
                                                          string.Format("No flight found with number: {0}", bookingPassenger.FlightNumber))));
            }

            // Check if a passenger already has the same email, this should not happen as this is supposed to be a new user.
            Person existingPassenger = personRepository.GetAll().FirstOrDefault(
                p => p.Email.Equals(bookingPassenger.Passenger.Email, StringComparison.OrdinalIgnoreCase));

            if (!existingPassenger.IsNull())
            {
                return(BadRequest(ResponseObject.StatusCode(MessageCode.ERROR_DUPLICATE_ENTRY,
                                                            string.Format("Passenger already found with email: {0}", existingPassenger.Email))));
            }


            // ----- Create new passenger.
            // This can be done with a mapping library or if wanted to be done manually, could be done with reflection to be dynamic.
            Person newPassenger = new Person()
            {
                Name      = bookingPassenger.Passenger.Name,
                Email     = bookingPassenger.Passenger.Email,
                Address   = bookingPassenger.Passenger.Address,
                DateBirth = bookingPassenger.Passenger.DateBirth,
                Gender    = bookingPassenger.Passenger.Gender,
                Id        = personRepository.GetAll().Max(b => b.Id) + 1 // Simulating just an auto-increment from DB.
            };

            // - Using an ORM like NHibernate or Entity Framework the saving for the person should be fired in cascade when
            //      the saving for the booking is made.
            personRepository.Save(newPassenger);


            // --- Creates the new booking with the sent flight number and the new passenger.
            int id = repository.GetAll().Max(b => b.Id) + 1; // This depends on how it is being generated, maybe auto-increment in DB.

            // Just adding +1 to the last book number and check if it is unique, this algorithm could be anything.
            // Depending on any number of variables... type of flight, plane, departure, destination, data from passenger, etc.
            // I think this is a propietary algorithm or maybe dictated by an ISO.
            string number = string.Empty;

            do
            {
                int bookNumber = repository.GetAll().Max(b => int.Parse(b.Number.Substring(3))) + 1;
                number = "WO-" + bookNumber;
            }while (repository.GetAll().Any(r => r.Number == number));

            IEnumerable <Person> passengers = new[] { newPassenger }; // As it is a new booking this is the first and only passenger.

            Booking booking = new Booking()
            {
                Id          = id,
                Customer    = newPassenger,
                Flight      = flight,
                Passengers  = passengers,
                Number      = number,
                DateBooking = DateTime.Now
            };

            // Save the new booking.
            repository.Save(booking);

            return(CreatedAtAction("Get", ResponseObject.Ok(booking)));
        }
コード例 #8
0
        public ActionResult UploadHB()
        {
            List <ResultUpload> result = new List <ResultUpload>();

            try
            {
                HttpPostedFileBase postedFileBase = Request.Files[0];
                //2.png
                string fileName = postedFileBase.FileName;

                if (IsNetwork)
                {
                    string TepmoraryPath = ConfigurationManager.AppSettings["TepmoraryPath"];
                    if (string.IsNullOrWhiteSpace(TepmoraryPath))
                    {
                        throw new Exception("未配置资源存放路径!");
                    }

                    // 获取指定目录绝对路径,如果不存在,则创建
                    if (!Directory.Exists(TepmoraryPath))
                    {
                        Directory.CreateDirectory(TepmoraryPath);
                    }
                    string pathFile = TepmoraryPath + Guid.NewGuid().ToString() + Path.GetExtension(fileName);
                    postedFileBase.SaveAs(pathFile);

                    string responseContent = UploadFile(pathFile, fileName);
                    if (!string.IsNullOrEmpty(responseContent))
                    {
                        ResultUpload upload = new ResultUpload();
                        //获取文件大小
                        var file = new FileInfo(pathFile);
                        var size = GetLength(file.Length);

                        upload.GuidId      = Guid.NewGuid().ToString();
                        upload.errorCode   = "0";
                        upload.errorString = "";
                        upload.Name        = fileName;
                        upload.Size        = size;
                        upload.UploadName  = UCode;
                        upload.UploadDate  = DateTime.Now;
                        ResponseObject obj = new ResponseObject();
                        obj.FDFS_GROUP        = "";
                        obj.FDFS_NAME         = responseContent;
                        upload.ResponseObject = obj;
                        result.Add(upload);
                    }
                    // 上传成功后, 删除临时文件
                    System.IO.File.Delete(pathFile);
                }
                else
                {
                    string TepmoraryPath = ConfigurationManager.AppSettings["BIMPath"];
                    if (string.IsNullOrWhiteSpace(TepmoraryPath))
                    {
                        throw new Exception("未配置资源存放路径!");
                    }

                    if (!Directory.Exists(TepmoraryPath))
                    {
                        Directory.CreateDirectory(TepmoraryPath);
                    }

                    string pathFile = TepmoraryPath + fileName;
                    postedFileBase.SaveAs(pathFile);

                    //获取文件大小
                    var file = new FileInfo(pathFile);
                    var size = GetLength(file.Length);

                    ResultUpload upload = new ResultUpload();
                    upload.GuidId      = Guid.NewGuid().ToString();
                    upload.errorCode   = "0";
                    upload.errorString = "";
                    upload.Name        = fileName;
                    upload.Size        = size;
                    upload.UploadName  = UCode;
                    upload.UploadDate  = DateTime.Now;
                    ResponseObject obj = new ResponseObject();
                    obj.FDFS_GROUP        = "";
                    obj.FDFS_NAME         = pathFile;
                    upload.ResponseObject = obj;
                    result.Add(upload);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(Json(result));
        }
コード例 #9
0
ファイル: MatchsViewModel.cs プロジェクト: arbaes/SmartchUWP
 private async void RegisterTournamentAsync()
 {
     TournamentsServices tournamentsServices = new TournamentsServices();
     ResponseObject      response            = await tournamentsServices.UpdateAsync(SelectedTournament);
 }
コード例 #10
0
        private async Task <SharepointAPIState> RetrieveNewsFeed(bool doNotify, bool relogin, string host)
        {
            InvokeStateChanged(SharepointAPIState.WORKING);

            if (!IsOnline())
            {
                return(SharepointAPIState.CONNECTION_LOST);
            }                                                               // InvokeStateChanged(SharepointAPIState.CONNECTION_LOST); return; }
            if (string.IsNullOrWhiteSpace(_username))
            {
                return(SharepointAPIState.WRONG_LOGIN);
            }                                                                                    // InvokeStateChanged(SharepointAPIState.WRONG_LOGIN); return; }
            if (string.IsNullOrWhiteSpace(_password))
            {
                return(SharepointAPIState.WRONG_LOGIN);
            }                                                                                    // InvokeStateChanged(SharepointAPIState.WRONG_LOGIN); return; }

            if (!string.IsNullOrWhiteSpace(_spOauth))
            {
                _cookieJar = CreateOAuthCookie();
            }
            else
            {
                _cookieJar = new CookieContainer();
            }

            var listFeed = new List <FeedEntry>();

            string query = host + "_api/SitePages/pages?$select=Id,Title,Modified,CanvasJson1,lastModifiedBy,promotedState,Url&$orderby=Modified%20desc&$expand=lastModifiedBy"; // "_api/web/lists/getbytitle('news_mei')/items?$select=ID,Title,Body,Modified,AttachmentFiles,Author/Name,Author/Title&$orderby=Modified%20desc&$expand=AttachmentFiles,Author/Id";

            try
            {
                HttpWebRequest request = GetRequest(new Uri(_url_endpoint + query));
                request.Headers.Add("X-RequestDigest", _bearer);
                request.Accept = "application/json; odata=verbose";

                ResponseObject response = await GetResponse(request);

                switch (response.StatusCode)
                {
                case ResponseObject.ResponseObjectStatusCode.CONNECTION_LOST:

                    return(SharepointAPIState.CONNECTION_LOST);    //InvokeStateChanged(SharepointAPIState.CONNECTION_LOST); return;

                case ResponseObject.ResponseObjectStatusCode.FORBIDDEN:

                    if (relogin)
                    {
                        var loginState = await CreateLogin();

                        if (loginState == SharepointAPIState.LOGGED_IN)
                        {
                            return(await RetrieveNewsFeed(doNotify, false, host));
                        }
                        return(loginState);    //InvokeStateChanged(loginState); return;
                    }

                    return(SharepointAPIState.WRONG_LOGIN);    // InvokeStateChanged(SharepointAPIState.WRONG_LOGIN); return;

                case ResponseObject.ResponseObjectStatusCode.ERROR:
                case ResponseObject.ResponseObjectStatusCode.UNSET:
                default:

                    return(SharepointAPIState.SERVER_ERROR);    //InvokeStateChanged(SharepointAPIState.SERVER_ERROR); return;

                case ResponseObject.ResponseObjectStatusCode.OK:

                    if (response.Response?.StatusCode == HttpStatusCode.OK)
                    {
                        string responseData = GetResponseData(response.Response); response.Close();

                        JSONObject feedDoc = new JSONObject(responseData);
                        var        results = feedDoc.GetJSONObject("d").GetJSONArray("results");

                        for (int i = 0; i < results.Length(); i++)
                        {
                            var c = results.GetJSONObject(i);

                            const string TITLE    = "Title";
                            const string ID       = "Id";
                            const string MODIFIED = "Modified";
                            const string AUTHOR   = "LastModifiedBy";
                            const string STATE    = "PromotedState";
                            const string CONTENT  = "CanvasJson1";
                            const string PAGEURL  = "Url";

                            if (!c.Has(TITLE) || !c.Has(ID) || !c.Has(MODIFIED) || !c.Has(AUTHOR) || !c.Has(STATE) || !c.Has(PAGEURL))
                            {
                                break;
                            }

                            string title = c.GetString(TITLE);
                            string key   = "#" + c.GetInt(ID).ToString() + "_" + title.Trim(' ').ToLower();

                            if (!DateTime.TryParse(c.GetString(MODIFIED), out DateTime date))
                            {
                                date = DateTime.Now;
                            }

                            string author = _context.GetString(Resource.String.feedentry_unknown);
                            if (c.GetJSONObject(AUTHOR).Has("Name"))
                            {
                                author = c.GetJSONObject(AUTHOR).GetString("Name");
                            }

                            string body = "";
                            //string body = _url_endpoint + "/" + host + c.GetString(PAGEURL);

                            bool isVisible = c.GetInt(STATE) == 2;     //Promoted, sonst ausgeblendet
                            if (isVisible && c.Has(CONTENT))
                            {
                                //Dokument parsen
                                string contentText = c.GetString(CONTENT);
                                var    contentJson = GetJsonArray(contentText);
                                if (contentJson == null)
                                {
                                    break;
                                }

                                var attachmentList = new List <EntryAttachment>();
                                for (int j = 0; j < contentJson.Length(); j++)
                                {
                                    const string WEBPARTS = "webPartData";
                                    if (contentJson.GetJSONObject(j).Has(WEBPARTS))
                                    {
                                        var webPartData = contentJson.GetJSONObject(j).GetJSONObject(WEBPARTS);
                                        if (webPartData != null)
                                        {
                                            string webPartId = webPartData.GetString("id");

                                            switch (webPartId)
                                            {
                                            case "b7dd04e1-19ce-4b24-9132-b60a1c2b910d":

                                                //Eingebettetes Dokument --> Als Anhang speichern
                                                if (!webPartData.Has("properties") || !webPartData.GetJSONObject("properties").Has("file"))
                                                {
                                                    break;
                                                }

                                                string fileUrl  = webPartData.GetJSONObject("properties").GetString("file");
                                                string fileName = Path.GetFileName(fileUrl);
                                                attachmentList.Add(new EntryAttachment(fileName, fileUrl, false));

                                                break;

                                            case "6410b3b6-d440-4663-8744-378976dc041e":

                                                //Link --> Wenn Datei als Anhang, sonst als Hyperlink
                                                if (!webPartData.Has("serverProcessedContent") ||
                                                    !webPartData.GetJSONObject("serverProcessedContent").Has("links") ||
                                                    !webPartData.GetJSONObject("serverProcessedContent").GetJSONObject("links").Has("url"))
                                                {
                                                    break;
                                                }
                                                if (!webPartData.GetJSONObject("serverProcessedContent").Has("searchablePlainTexts") ||
                                                    !webPartData.GetJSONObject("serverProcessedContent").GetJSONObject("searchablePlainTexts").Has("title"))
                                                {
                                                    break;
                                                }

                                                string url        = webPartData.GetJSONObject("serverProcessedContent").GetJSONObject("links").GetString("url");
                                                string link_title = webPartData.GetJSONObject("serverProcessedContent").GetJSONObject("searchablePlainTexts").GetString("title");

                                                if (url.StartsWith("/:"))
                                                {
                                                    url = _url_malteserHost + url;
                                                }

                                                attachmentList.Add(new EntryAttachment(link_title, url, true));

                                                break;

                                            case "d1d91016-032f-456d-98a4-721247c305e8":

                                                //Bild --> Bild als Anhang aufnehmen
                                                if (!webPartData.Has("serverProcessedContent") ||
                                                    !webPartData.GetJSONObject("serverProcessedContent").Has("imageSources") ||
                                                    !webPartData.GetJSONObject("serverProcessedContent").GetJSONObject("imageSources").Has("imageSource"))
                                                {
                                                    break;
                                                }

                                                string pic_url = webPartData.GetJSONObject("serverProcessedContent").GetJSONObject("imageSources").GetString("imageSource");
                                                if (pic_url.StartsWith("/"))
                                                {
                                                    pic_url = _url_malteserHost + pic_url;
                                                }

                                                string pic_filename = Path.GetFileName(pic_url);
                                                if (pic_filename.ToLower().StartsWith("visualtemplateimage"))
                                                {
                                                    break;
                                                }

                                                attachmentList.Add(new EntryAttachment(pic_filename, pic_url, false));

                                                break;

                                            default:

                                                string content = webPartData.ToString();
                                                Console.WriteLine(content);

                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (contentJson.GetJSONObject(j).Has("innerHTML") &&
                                            contentJson.GetJSONObject(j).Has("controlType") && contentJson.GetJSONObject(j).GetInt("controlType") == 4)
                                        {
                                            string bodytext = contentJson.GetJSONObject(j).GetString("innerHTML");
                                            bodytext = Helper.Converter.GetPlainOfHtml(bodytext);
                                            body    += bodytext;
                                        }
                                    }
                                }

                                FeedEntry entry = new FeedEntry(key, title, date, author, body, attachmentList);
                                if (!string.IsNullOrEmpty(body) || attachmentList.Count > 0)
                                {
                                    listFeed.Add(entry);
                                }
                            }
                        }

                        TBL.UpdateEntries(listFeed, doNotify);

                        return(SharepointAPIState.OK);    //InvokeStateChanged(SharepointAPIState.OK); return;
                    }

                    return(SharepointAPIState.SERVER_ERROR);    //InvokeStateChanged(SharepointAPIState.SERVER_ERROR); return;
                }
            }
            catch (Exception)
            {
                return(SharepointAPIState.SERVER_ERROR); //InvokeStateChanged(SharepointAPIState.SERVER_ERROR); return;
            }
        }
コード例 #11
0
        /// <summary>
        /// Fetches all records that matches the query and highlights the full text that it matches
        /// modify the pre tags and post tags to change the html element that renders the highlighted data.
        /// </summary>
        /// <param name="query">search term inputted by the user</param>
        /// <returns>response data</returns>
        public async Task <ResponseObject> GetHighlightedElasticEmployee(string query)
        {
            var response = new ResponseObject(ResponseType.Success, string.Empty);

            try
            {
                var searchResults = await EsClient.SearchAsync <EmployeeElasticDto>(s => s
                                                                                    .From(0)
                                                                                    .Size(10000)
                                                                                    .Index(IndicesConfig.Employee)
                                                                                    .Query(q => q
                                                                                           .Bool(b => b
                                                                                                 .Should(
                                                                                                     bs => bs.Match(p => p.Field(f => f.FullName).Query(query)),
                                                                                                     bs => bs.Match(p => p.Field(f => f.Address).Query(query)),
                                                                                                     bs => bs.Match(p => p.Field(f => f.Notes).Query(query)),
                                                                                                     bs => bs.Match(p => p.Field(f => f.Age).Query(query)),
                                                                                                     bs => bs.Match(p => p.Field(f => f.Department).Query(query)),
                                                                                                     bs => bs.Match(p => p.Field(f => f.Position).Query(query)
                                                                                                                    ))))
                                                                                    .Highlight(x =>
                                                                                               x.PreTags("<b>")
                                                                                               .PostTags("</b>")
                                                                                               .Fields(
                                                                                                   fs =>
                                                                                                   fs.Field(y => y.Address)
                                                                                                   .Type("plain")
                                                                                                   .FragmentSize(150)
                                                                                                   .ForceSource()
                                                                                                   .NumberOfFragments(3)
                                                                                                   .Fragmenter(HighlighterFragmenter.Span)
                                                                                                   .NoMatchSize(150)
                                                                                                   .HighlightQuery(m => m
                                                                                                                   .Match(b => b
                                                                                                                          .Field(k => k.Address)
                                                                                                                          .Query(query))),
                                                                                                   fs =>
                                                                                                   fs.Field(y => y.Age)
                                                                                                   .Type("plain")
                                                                                                   .FragmentSize(150)
                                                                                                   .ForceSource()
                                                                                                   .NumberOfFragments(3)
                                                                                                   .Fragmenter(HighlighterFragmenter.Span)
                                                                                                   .NoMatchSize(150)
                                                                                                   .HighlightQuery(m => m
                                                                                                                   .Match(b => b
                                                                                                                          .Field(k => k.Age)
                                                                                                                          .Query(query))),
                                                                                                   fs =>
                                                                                                   fs.Field(y => y.Department)
                                                                                                   .Type("plain")
                                                                                                   .FragmentSize(150)
                                                                                                   .ForceSource()
                                                                                                   .NumberOfFragments(3)
                                                                                                   .Fragmenter(HighlighterFragmenter.Span)
                                                                                                   .NoMatchSize(150)
                                                                                                   .HighlightQuery(m => m
                                                                                                                   .Match(b => b
                                                                                                                          .Field(k => k.Department)
                                                                                                                          .Query(query))),
                                                                                                   fs =>
                                                                                                   fs.Field(y => y.FullName)
                                                                                                   .Type("plain")
                                                                                                   .FragmentSize(150)
                                                                                                   .ForceSource()
                                                                                                   .NumberOfFragments(3)
                                                                                                   .Fragmenter(HighlighterFragmenter.Span)
                                                                                                   .NoMatchSize(150)
                                                                                                   .HighlightQuery(m => m
                                                                                                                   .Match(b => b
                                                                                                                          .Field(k => k.FullName)
                                                                                                                          .Query(query))),
                                                                                                   fs =>
                                                                                                   fs.Field(y => y.Position)
                                                                                                   .Type("plain")
                                                                                                   .FragmentSize(150)
                                                                                                   .ForceSource()
                                                                                                   .NumberOfFragments(3)
                                                                                                   .Fragmenter(HighlighterFragmenter.Span)
                                                                                                   .NoMatchSize(150)
                                                                                                   .HighlightQuery(m => m
                                                                                                                   .Match(b => b
                                                                                                                          .Field(k => k.Position)
                                                                                                                          .Query(query)))
                                                                                                   )));

                response.Data = TransmuteAndHighlightEmployeeElasticResults(searchResults).Data;
            }
            catch (Exception e)
            {
                response = ErrorHandling.LogError(e);
            }
            return(response);
        }
コード例 #12
0
        /// <summary>
        /// Maps the key value into a view model from the search response. the highlighted characters are with the html tags <b></b>
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResponseObject TransmuteAndHighlightEmployeeElasticResults(ISearchResponse <EmployeeElasticDto> model)
        {
            var response = new ResponseObject(ResponseType.Success, string.Empty);

            try
            {
                var results = new ElasticSearchResultsSummary();
                if (model.Hits.Any())
                {
                    List <ElasticSearchResults> elasticConsolidatedResults = new List <ElasticSearchResults>();
                    results.SearchDuration = model.Took.ToString();
                    results.Hits           = model.Documents.Count();
                    foreach (var item in model.Hits)
                    {
                        ElasticSearchResults modelToAppend = new ElasticSearchResults();
                        modelToAppend.Id    = item.Id;
                        modelToAppend.Index = item.Index;
                        modelToAppend.Score = item.Score.ToString();
                        var mappedHighlightedData = new EmployeeElasticDto();
                        if (item.Highlight.Any())
                        {
                            foreach (var x in item.Highlight)
                            {
                                if (x.Key.Equals("address"))
                                {
                                    mappedHighlightedData.Address = x.Value.FirstOrDefault();
                                }
                                else if (x.Key.Equals("notes"))
                                {
                                    mappedHighlightedData.Notes = x.Value.FirstOrDefault();
                                }
                                else if (x.Key.Equals("fullName"))
                                {
                                    mappedHighlightedData.FullName = x.Value.FirstOrDefault();
                                }
                                else if (x.Key.Equals("position"))
                                {
                                    mappedHighlightedData.Position = x.Value.FirstOrDefault();
                                }
                                else if (x.Key.Equals("department"))
                                {
                                    mappedHighlightedData.Department = x.Value.FirstOrDefault();
                                }
                                else if (x.Key.Equals("age"))
                                {
                                    mappedHighlightedData.Age = x.Value.FirstOrDefault();
                                }
                            }
                            modelToAppend.StringSearchResults = mappedHighlightedData;
                        }
                        elasticConsolidatedResults.Add(modelToAppend);
                    }
                    results.SearchOutPut = elasticConsolidatedResults;
                    response.Data        = results;
                }
                else
                {
                    response.Data = results;
                }
            }
            catch (Exception e)
            {
                response = ErrorHandling.LogError(e);
            }
            return(response);
        }
コード例 #13
0
        /// <summary>
        /// Search the employee index (employee table if sql)
        /// </summary>
        /// <param name="model">filters</param>
        /// <returns>response object</returns>
        public async Task <ResponseObject> EmployeeElasticQueries(ElasticSearchConfigDto model)
        {
            var response = new ResponseObject(ResponseType.Success, string.Empty);

            try
            {
                EsConfig.DefaultIndex(IndicesConfig.Employee);
                EsClient = new ElasticClient(EsConfig);
                var query = model.SearchTerm.ToLower();

                if (model.FilterTypeId == 0) //all
                {
                    var searchResults = await GetAllElasticEmployee(query);

                    if (searchResults.IsSuccess)
                    {
                        response.Data = searchResults.Data;
                    }
                }
                else if (model.FilterTypeId == 2) //smart search
                {
                    var searchResults = await GetSmartSearchElasticEmployee(query);

                    if (searchResults.IsSuccess)
                    {
                        response.Data = searchResults.Data;
                    }
                }
                else if (model.FilterTypeId == 3) //highlight
                {
                    var searchResults = await GetHighlightedElasticEmployee(query);

                    if (searchResults.IsSuccess)
                    {
                        response.Data = searchResults.Data;
                    }
                }
                else if (model.FilterTypeId == 4) //must not match
                {
                    var searchResults = await GetMustNotMatchElasticEmployee(query);

                    if (searchResults.IsSuccess)
                    {
                        response.Data = searchResults.Data;
                    }
                }
                //else if (model.FilterTypeId == 5)
                //{
                //    var searchResults = await GetLanguageSearchElasticEmployee(query);
                //    if (searchResults.IsSuccess)
                //    {
                //        response.Data = searchResults.Data;
                //    }
                //}
            }
            catch (Exception e)
            {
                response = ErrorHandling.LogError(e);
            }
            return(response);
        }
コード例 #14
0
 public IActionResult PutErrorUnknown(int code)
 {
     return(NotFound(ResponseObject.StatusCode(MessageCode.ERROR_UNKNOWN, "Unknown error, we're working to find out what happened!")));
 }
コード例 #15
0
 public IActionResult PutError404(int code)
 {
     return(NotFound(ResponseObject.StatusCode(MessageCode.ERROR_404, "The page you're looking for does not exist! Sorry, this should be a nice page.")));
 }
コード例 #16
0
 public CartController(AppDbContext context)
 {
     response     = new ResponseObject();
     this.context = context;
 }
コード例 #17
0
 public bool Expired(ResponseObject responseObject)
 {
     return(ExpiredValue);
 }
        public static void SetCustomError(this OAuthGrantResourceOwnerCredentialsContext context, ResponseObject errorMessage)
        {
            var json = errorMessage.ToJsonString();



            context.Response.ContentType = "application/json";
            context.Response.Write(json);
        }
コード例 #19
0
        /// <inheritdoc />
        public override ResponseObject <OrderUpdate> PlaceStoplossOrder(TradingPair pair, OrderSide side, decimal quantity, decimal price, long tradeId)
        {
            var     client = _communications.Client;
            decimal limitPrice;

            if (side == OrderSide.Sell)
            {
                // Set the limit price extremely low -> sell immediately for the best price.
                // 5% is an arbitrary number that is probably more than the spread, but is not
                // rejected by Binance for deviating too much from the current price.
                limitPrice = price * 0.95M;
            }
            else
            {
                // Skew the quantity and the price -> buy immediately for the best price.
                // Quantity must scale inverse because (quantity * price) is the amount that needs to
                // be locked. You cannot lock more assets than you have.
                // 2% is hardcoded on purpose because it is unlikely to change.
                limitPrice = price * 1.02M;
                quantity  /= 1.02M;
            }

            var realQuantity   = pair.RoundToTradable(quantity);
            var realLimitPrice = pair.RoundToPriceable(limitPrice);
            var realStopPrice  = pair.RoundToPriceable(price);

            lock (_orderCache)
            {
                var query = client.PlaceOrder(
                    symbol: pair.ToString(),
                    side: BinanceUtilities.ToExternal(side),
                    type: OrderType.StopLossLimit,
                    quantity: realQuantity,
                    newClientOrderId: null,
                    price: realLimitPrice,
                    timeInForce: TimeInForce.GoodTillCancel,
                    stopPrice: realStopPrice,
                    icebergQty: null,
                    orderResponseType: null,
                    receiveWindow: (int)_communications.ReceiveWindow);

                if (query.Success)
                {
                    var order = new OrderUpdate(
                        query.Data.OrderId,
                        tradeId,
                        OrderUpdate.OrderStatus.New,
                        OrderUpdate.OrderTypes.StopLoss,
                        DateTimeOffset.Now.ToUnixTimeMilliseconds(),
                        realLimitPrice,
                        side,
                        pair,
                        realQuantity)
                    {
                        StopPrice = realStopPrice,
                    };

                    // Enter middleware instance to make sure this order is
                    // also converted to a stoploss order when the exchange reports updates.
                    _transformMiddleWare.Add(order.OrderId, x => x.OrderType = OrderUpdate.OrderTypes.StopLoss);

                    return(new ResponseObject <OrderUpdate>(order));
                }

                return(ResponseObject.OrderPlacementFailed(BinanceUtilities.ToInternalError(query.Error.Code), query.Error.Message));
            }
        }
コード例 #20
0
        public Response GenerarDocumento(RequestExternalReport requestExternalReport)
        {
            Response resul = new Response {
                State = ResponseType.Success
            };

            try
            {
                var resulBDDocumento = repositoryMySql.SimpleSelect <Paramdocumento>(x => x.NombrePlantilla == requestExternalReport.NombrePlantilla);
                if (resulBDDocumento.Count == 0 || string.IsNullOrEmpty(resulBDDocumento.First().Method))
                {
                    resul.State   = ResponseType.Warning;
                    resul.Message = "Plantilla  no implmentada";
                    return(resul);
                }
                string pathPlantilla    = Path.Combine(Global.PATH_PLANTILLAS, resulBDDocumento.First().Area, resulBDDocumento.First().Path);
                string pathOutPlantilla = Path.Combine(Global.PATH_PLANTILLAS, resulBDDocumento.First().Area, "salidas");
                string fileNameGenerado = string.Empty;

                WordHelper generadorWord = new WordHelper(pathPlantilla);

                if (requestExternalReport.SoloGenerar)
                {
                    List <WordHelper.ItemValues> itemValues = new List <WordHelper.ItemValues>();
                    requestExternalReport.ListItemReporte.ForEach(x =>
                    {
                        itemValues.Add(new WordHelper.ItemValues {
                            key = x.Key, values = x.Value
                        });
                    });

                    //generamos el documento en word
                    fileNameGenerado = generadorWord.GenerarDocumento(itemValues, null, pathOutPlantilla);
                    resul.Message    = fileNameGenerado;
                }

                ///TDO rescatamos el id del ciclo
                var ciclo = repositoryMySql.GetDataByProcedure <Praciclosprogauditorium>("spGetCilcloByIdServicioAnio", requestExternalReport.IdServicio, requestExternalReport.Anio);
                if (ciclo.Count == 0)
                {
                    resul.State   = ResponseType.Warning;
                    resul.Message = $"No se tiene programas y/o auditorias con el Id Servicio: {requestExternalReport.IdServicio} y anio {requestExternalReport.Anio}";
                    return(resul);
                }


                ElaboracionAuditoriaManager elaboracionAuditoriaManager = new ElaboracionAuditoriaManager();


                string            methodPlantilla   = resulBDDocumento.First().Method;
                RequestDataReport requestDataReport = new RequestDataReport {
                    IdCiclo = (int)ciclo.First().IdPrAcicloProgAuditoria
                };
                //llamamos el metodo para recuperar data
                var      myMethod   = elaboracionAuditoriaManager.GetType().GetMethod(methodPlantilla);
                object[] parameters = new object[] { requestDataReport };
                ResponseObject <GlobalDataReport> resulMethod = myMethod.Invoke(elaboracionAuditoriaManager, parameters) as ResponseObject <GlobalDataReport>;
                if (resulMethod.State != ResponseType.Success)
                {
                    return(resulMethod);
                }

                ///TDO completamos la informacion con los parametros de entrada
                requestExternalReport.ListItemReporte?.ForEach(x =>
                {
                    resulMethod.Object.data.GetType().GetProperty(x.Key)?.SetValue(resulMethod.Object.data, x.Value);
                });


                //generamos el documento en word
                fileNameGenerado = generadorWord.GenerarDocumento(resulMethod.Object.data, resulMethod.Object.HeadersTables, pathOutPlantilla);
                resul.Message    = fileNameGenerado;
            }
            catch (Exception ex)
            {
                ProcessError(ex, resul);
            }
            return(resul);
        }
コード例 #21
0
    /// <summary>
    /// Creates and sends a request to the <paramref name="requestUri"/> using the HTTP verb
    ///  from <paramref name="httpMethod"/> and the request body from <paramref name="requestBody"/>.
    /// If IdentityServerOptions are set (using the <see cref="SetIdentityServerOptions{TOptions}(TOptions)"/> or one of the overloads),
    /// then a valid access token will be fetched by the <see cref="IIdentityServerService"/> and attached to this request.
    /// </summary>
    /// <typeparam name="TResponseBody">
    ///     The type of the property <see cref="ResponseObject{TResponseBody}.BodyAsType"/> of the <see cref="ResponseObject{TResponseBody}"/> object,
    ///     that will contain the body of the response deserialized or casted to type <typeparamref name="TResponseBody"/>.
    ///     The type used can be one of the following:
    ///     <list type="bullet">
    ///         <item>
    ///             <term><see cref="StringContent"/></term>
    ///             <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description>
    ///         </item>
    ///         <item>
    ///             <term><see cref="StreamContent"/></term>
    ///             <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description>
    ///         </item>
    ///         <item>
    ///             <term>A serializable complex type</term>
    ///             <description>Any serializable object to attempt to deserialize the body of the response to it.</description>
    ///         </item>
    ///         <item>
    ///             <term>A simple type</term>
    ///             <description>Any other simple type to try convert the body of the response to it.</description>
    ///         </item>
    ///     </list>
    /// </typeparam>
    /// <typeparam name="TRequestBody">
    ///     The type of the request body. The type used can be one of the following:
    ///     <list type="bullet">
    ///         <item>
    ///             <term><see cref="StringContent"/></term>
    ///             <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description>
    ///         </item>
    ///         <item>
    ///             <term><see cref="StreamContent"/></term>
    ///             <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description>
    ///         </item>
    ///         <item>
    ///             <term>A serializable complex type</term>
    ///             <description>Any serializable object that will be serialized and sent in the body of the request.</description>
    ///         </item>
    ///         <item>
    ///             <term>A simple type</term>
    ///             <description>Any other simple type that will be sent in the body of the request.</description>
    ///         </item>
    ///     </list>
    /// </typeparam>
    /// <param name="requestUri">The <see cref="Uri"/> of the request.</param>
    /// <param name="httpMethod">The <see cref="HttpMethod"/> of the request.</param>
    /// <param name="requestBody">The body of the request (available only in POST, PUT and PATCH).</param>
    /// <returns>
    /// A <see cref="ResponseObject{TResponseBody}"/> containing the body of the response
    /// as <c>String</c> in the <see cref="ResponseObject{TResponseBody}.BodyAsString"/> property,
    /// as <typeparamref name="TResponseBody"/> in the <see cref="ResponseObject{TBody}.BodyAsType"/> and,
    /// as <c>Stream</c> in the <see cref="ResponseObject{TResponseBody}.BodyAsStream"/> property.
    /// The <typeparamref name="TResponseBody"/> can be of the following:
    ///     <list type="bullet">
    ///         <item>
    ///             <term><see cref="StringContent"/></term>
    ///             <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description>
    ///         </item>
    ///         <item>
    ///             <term><see cref="StreamContent"/></term>
    ///             <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description>
    ///         </item>
    ///         <item>
    ///             <term>A serializable complex type</term>
    ///             <description>Any serializable object to attempt to deserialize the body of the response to it.</description>
    ///         </item>
    ///         <item>
    ///             <term>A simple type</term>
    ///             <description>Any other simple type to try convert the body of the response to it.</description>
    ///         </item>
    ///     </list>
    /// </returns>
    public async Task <ResponseObject <TResponseBody> > SendAsync <TRequestBody, TResponseBody>(Uri requestUri, HttpMethod httpMethod, TRequestBody?requestBody)
    {
        var httpRequestMessage = _requestMessageFactory.CreateRequestMessage();

        httpRequestMessage.Method     = httpMethod;
        httpRequestMessage.RequestUri = requestUri;

        //todo: unit test that
        if ((httpMethod == HttpMethod.Get || httpMethod == HttpMethod.Head || httpMethod == HttpMethod.Delete) && requestBody != null)
        {
            throw new ArgumentException("HTTP method " + httpMethod.Method + " does not support a request body.", nameof(requestBody));
        }

        //headers
        foreach (var kv in Headers)
        {
            httpRequestMessage.Headers.Add(kv.Key, kv.Value);
        }

        //handle request body
        if (requestBody is not null)
        {
            //HttpContent types
            if (requestBody as HttpContent is not null)
            {
                httpRequestMessage.Content = requestBody as HttpContent;
            }
            //no HttpContent types, wrap in an HttpContent type with default encoding and content-type
            else
            {
                //utf-8, text/plain
                httpRequestMessage.Content = IsSimpleType(typeof(TRequestBody))
                    ? new StringContent(requestBody.ToString() ?? string.Empty)
                    : new TypeContent <TRequestBody>(requestBody);
            }
        }

        //handle authentication
        if (identityServerOptions != null)
        {
            var tokenResponse = await _accessTokenService.GetTokenResponseAsync(identityServerOptions);

            if (tokenResponse.IsError)
            {
                return(new ResponseObject <TResponseBody>
                {
                    StatusCode = tokenResponse.HttpStatusCode,
                    HttpResponseMessage = tokenResponse.HttpResponse,
                    HttpRequestMessge = null,
                    HasError = true,
                    Error = tokenResponse.Error + Environment.NewLine + tokenResponse.ErrorDescription,
                    BodyAsString = await tokenResponse.HttpResponse.Content.ReadAsStringAsync()
                });
            }

            httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken);
        }

        //set timeout
        if (Timeout != TimeSpan.Zero)
        {
            _coreHttpClient.SetTimeout(Timeout);
        }

        //make the call
        var response = await _coreHttpClient.SendAsync(httpRequestMessage);

        var apiResponse = new ResponseObject <TResponseBody>
        {
            Headers             = response.Headers,
            StatusCode          = response.StatusCode,
            HttpResponseMessage = response,
            HttpRequestMessge   = httpRequestMessage
        };

        //handle response body
        if (response.IsSuccessStatusCode)
        {
            if (!typeof(TResponseBody).IsAssignableFrom(typeof(Stream)))
            {
                apiResponse.BodyAsString = await response.Content.ReadAsStringAsync();

                //try to convert to the requested type
                apiResponse.BodyAsType = IsSimpleType(typeof(TResponseBody))
                    ? (TResponseBody)Convert.ChangeType(apiResponse.BodyAsString, typeof(TResponseBody))
                    : JsonConvert.DeserializeObject <TResponseBody>(apiResponse.BodyAsString);
            }
            else
            {
                apiResponse.BodyAsStream = await response.Content.ReadAsStreamAsync();
            }
        }
        else
        {
            apiResponse.HasError     = true;
            apiResponse.Error        = response.ReasonPhrase;
            apiResponse.BodyAsString = await response.Content.ReadAsStringAsync();
        }

        return(apiResponse);
    }
コード例 #22
0
ファイル: UserSvc.cs プロジェクト: techhowdy/CMS_CORE_NG
        public async Task <ResponseObject> RegisterUserAsync(RegisterViewModel model)
        {
            // Will hold all the errors related to registration
            var errorList = new List <string>();

            ResponseObject responseObject = new ResponseObject();

            try
            {
                var defaultProfilePicPath = _env.WebRootPath + $"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}default{Path.DirectorySeparatorChar}profile.jpeg";


                // Create the Profile Image Path
                var profPicPath = _env.WebRootPath + $"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}";

                var extension   = ".jpeg";
                var filename    = DateTime.Now.ToString("yymmssfff");
                var path        = Path.Combine(profPicPath, filename) + extension;
                var dbImagePath = Path.Combine($"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}", filename) + extension;

                File.Copy(defaultProfilePicPath, path);

                var user = new ApplicationUser
                {
                    Email             = model.Email,
                    UserName          = model.Username,
                    UserRole          = "Customer",
                    PhoneNumber       = model.Phone,
                    Firstname         = model.Firstname,
                    Lastname          = model.Lastname,
                    Gender            = model.Gender,
                    Terms             = model.Terms,
                    IsProfileComplete = false,
                    Birthday          = model.Dob,
                    ProfilePic        = dbImagePath,
                    SecurityStamp     = Guid.NewGuid().ToString(),
                    UserAddresses     = new List <AddressModel>
                    {
                        new AddressModel {
                            Country = model.Country, Type = "Billing"
                        },
                        new AddressModel {
                            Country = model.Country, Type = "Shipping"
                        }
                    }
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Customer");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var dynamicProperties = new Dictionary <string, object> {
                        ["Code"] = code, ["User"] = user
                    };

                    responseObject.IsValid = true;
                    responseObject.Message = "Success";

                    responseObject.Data = dynamicProperties;
                    return(responseObject);
                }

                foreach (var error in result.Errors)
                {
                    errorList.Add(error.Description);
                }
                responseObject.IsValid = false;
                responseObject.Message = "Failed";
                responseObject.Data    = errorList;
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while registering new user  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }
            return(responseObject);
        }
コード例 #23
0
            private async Task initializeWebsocketAsync()
            {
                // If we happen to have one laying around, clean it up first
                if (this.websocket != null)
                {
                    try
                    {
                        this.websocket.Dispose();
                    }
                    catch
                    {
                        // Ignore
                    }
                }

                this.websocket = new WebsocketClient(new Uri($"ws://{this.Device.Hostname}:{this.Device.Port}/sony/{Utilities.GetApiLibName(this.Lib)}"));
                this.websocket.ReconnectTimeout = TimeSpan.FromSeconds(30);

                // Send an empty switchNotifications to get the available notification types
                NotificationRequest subscriptionsRequest = null;

                Action initialSubscribe = () =>
                {
                    subscriptionsRequest = new NotificationRequest(
                        enabled: new NotificationSubscription[0],
                        disabled: new NotificationSubscription[0]
                        );

                    this.websocket.Send(subscriptionsRequest.Serialized);
                };

                this.websocket.ReconnectionHappened.Subscribe((message) =>
                {
                    Debug.WriteLine($"NOTIFY ({this.Lib}): subscription reconnected ({message})");
                    //initialSubscribe();
                });

                this.websocket.MessageReceived.Subscribe(async(message) =>
                {
                    await Task.Run(() =>
                    {
                        Debug.WriteLine($"NOTIFY ({this.Lib}): message received ({message})");

                        SlimResponseObject basicResponse = JsonSerializer.Deserialize <SlimResponseObject>(message.Text);
                        if (basicResponse.Id == subscriptionsRequest?.Id)
                        {
                            // This is the response to a notification subscription
                            ResponseObject <NotificationParms> response = JsonSerializer.Deserialize <ResponseObject <NotificationParms> >(message.Text);

                            // Let's find out if any subscriptions are missing
                            bool anySubscriptionsMissing = this.subscriptions.Any((subscription) =>
                            {
                                bool subscribed = response.Result.Enabled.Contains(subscription);
                                bool available  = !subscribed && response.Result.Disabled.Contains(subscription);
                                return(!subscribed && available);
                            });
                            if (anySubscriptionsMissing)
                            {
                                HashSet <NotificationSubscription> availableSubscriptions = new HashSet <NotificationSubscription>();
                                availableSubscriptions.UnionWith(response.Result.Disabled);
                                availableSubscriptions.UnionWith(response.Result.Enabled);

                                List <NotificationSubscription> enabled  = new List <NotificationSubscription>();
                                List <NotificationSubscription> disabled = new List <NotificationSubscription>();
                                foreach (NotificationSubscription available in availableSubscriptions)
                                {
                                    if (this.subscriptions.Contains(available))
                                    {
                                        enabled.Add(available);
                                    }
                                    else
                                    {
                                        disabled.Add(available);
                                    }
                                }

                                // Subscribe to everything - we don't expect too much traffic
                                // This may need to change later
                                subscriptionsRequest = new NotificationRequest(
                                    enabled: enabled.ToArray(),
                                    disabled: disabled.ToArray()
                                    );

                                this.websocket.Send(subscriptionsRequest.Serialized);
                            }
                            else
                            {
                                bool newInitialization = !this.IsInitialized;
                                this.IsInitialized     = true;
                                if (newInitialization)
                                {
                                    try
                                    {
                                        this.OnInitialized?.Invoke(this);
                                    }
                                    catch
                                    {
                                        // Swallow handler errors
                                    }
                                }
                            }
                        }
                        else
                        {
                            // This is a notification
                            NotificationObject notification = JsonSerializer.Deserialize <NotificationObject>(message.Text);
                            try
                            {
                                this.OnNotification?.Invoke(this, notification.Method, notification.Version, JsonSerializer.Serialize(notification.Params));
                            }
                            catch
                            {
                                // Swallow handler errors
                            }
                        }
                    });
                });

                await this.websocket.Start();

                initialSubscribe();
            }
コード例 #24
0
        public IHttpActionResult Wechat(string code)
        {
            //定义返回对象
            var response = new ResponseObject <WechatTokenModel>();

            try
            {
                #region 微信认证
                string url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", _wechatAppId, _wechatSecret, code);

                var httpReq = WebRequest.Create(url);
                httpReq.Method = "Get";

                var httpResponse = httpReq.GetResponse() as HttpWebResponse;
                var responseTxt  = string.Empty;
                using (StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                {
                    responseTxt = sr.ReadToEnd();
                }
                #endregion

                if (string.IsNullOrEmpty(responseTxt))
                {
                    response = new ResponseObject <WechatTokenModel> {
                        Code = "500", Message = "微信登录失败"
                    }
                }
                ;
                var wechatLoginViewModel = Newtonsoft.Json.JsonConvert.DeserializeObject <WechatLoginEventModel>(responseTxt);

                if (wechatLoginViewModel.Errcode == 0)
                {
                    #region 记录登录状态
                    var wechatLoginEvent = _wechatLoginEventService.GetWechatLoginEventByOpenId(wechatLoginViewModel.OpenId);
                    if (wechatLoginEvent == null)
                    {
                        wechatLoginEvent       = wechatLoginViewModel.ToEntity();
                        wechatLoginEvent.Token = Guid.NewGuid().ToString();
                        _wechatLoginEventService.InsertWechatLoginEvent(wechatLoginEvent);
                    }
                    else
                    {
                        _wechatLoginEventService.UpdateWechatLoginEvent(wechatLoginEvent);
                    }

                    #endregion

                    response = new ResponseObject <WechatTokenModel> {
                        Code = "200", Data = new WechatTokenModel {
                            Token = wechatLoginEvent.Token, Days = 1
                        }
                    };
                }
                else
                {
                    response = new ResponseObject <WechatTokenModel> {
                        Code = wechatLoginViewModel.Errcode.ToString(), Message = wechatLoginViewModel.Errmsg
                    };
                }
            }
            catch (Exception ex)
            {
                response = new ResponseObject <WechatTokenModel> {
                    Code = "500", Message = ex.Message
                };
                //_logger.Error(string.Format("微信登录失败,错误原因:{0}", ex.GetOriginalException().Message));
            }

            return(Ok(response));
        }
コード例 #25
0
        /// <summary>
        /// Main add shell/host To GUI routine
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnAddShell_Click(object sender, EventArgs e)
        {
            string shellURL = txtBoxShellUrl.Text;

            if (string.IsNullOrEmpty(shellURL))
            {
                return;
            }

            if (checkBoxEncryptRequest.Checked)
            {
                string encryptionKey = textBoxEncrpytionKey.Text;

                if (encryptionKey.Length != 32)
                {
                    labelDynAddHostsStatus.Text = "Encryption key length must be 32 chars... Try again.";
                    return;
                }

                if (!checkBoxSendIVInRequest.Checked)
                {
                    string encryptionIV = textBoxEncrpytionIV.Text;

                    if (string.IsNullOrEmpty(encryptionIV) || encryptionIV.Length != 16)
                    {
                        labelDynAddHostsStatus.Text = "Encryption IV length must be 16 chars... Try again.";
                        return;
                    }
                }
            }

            //Remove Shell
            if (BantamMain.Shells.ContainsKey(shellURL))
            {
                BantamMain.Instance.GuiCallbackRemoveShellURL(shellURL);

                if (!BantamMain.Shells.TryRemove(shellURL, out ShellInfo shellInfoOut))
                {
                    LogHelper.AddGlobalLog("Unable to remove (" + shellURL + ") from shells", "AddShell failure", LogHelper.LOG_LEVEL.ERROR);
                    return;
                }
            }

            //Add Shell
            if (!BantamMain.Shells.TryAdd(shellURL, new ShellInfo()))
            {
                LogHelper.AddGlobalLog("Unable to add (" + shellURL + ") to shells", "AddShell failure", LogHelper.LOG_LEVEL.ERROR);
                return;
            }

            BantamMain.Shells[shellURL].RequestArgName = txtBoxArgName.Text;

            if (comboBoxVarType.Text == "cookie")
            {
                BantamMain.Shells[shellURL].SendDataViaCookie = true;
            }

            if (checkBoxResponseEncryption.Checked == false)
            {
                BantamMain.Shells[shellURL].ResponseEncryption = false;
            }
            else
            {
                BantamMain.Shells[shellURL].ResponseEncryption     = true;
                BantamMain.Shells[shellURL].ResponseEncryptionMode = comboBoxEncryptionMode.SelectedIndex;
            }

            if (checkBoxGZipRequest.Checked)
            {
                BantamMain.Shells[shellURL].GzipRequestData = true;
            }
            else
            {
                BantamMain.Shells[shellURL].GzipRequestData = false;
            }

            bool encryptResponse        = BantamMain.Shells[shellURL].ResponseEncryption;
            int  ResponseEncryptionMode = BantamMain.Shells[shellURL].ResponseEncryptionMode;

            if (checkBoxEncryptRequest.Checked)
            {
                BantamMain.Shells[shellURL].RequestEncryption    = true;
                BantamMain.Shells[shellURL].RequestEncryptionKey = textBoxEncrpytionKey.Text;

                if (checkBoxSendIVInRequest.Checked)
                {
                    BantamMain.Shells[shellURL].SendRequestEncryptionIV           = true;
                    BantamMain.Shells[shellURL].RequestEncryptionIV               = string.Empty;
                    BantamMain.Shells[shellURL].RequestEncryptionIVRequestVarName = textBoxIVVarName.Text;
                }
                else
                {
                    BantamMain.Shells[shellURL].RequestEncryptionIV = textBoxEncrpytionIV.Text;
                    BantamMain.Shells[shellURL].RequestEncryptionIVRequestVarName = string.Empty;
                }
            }
            else
            {
                BantamMain.Shells[shellURL].RequestEncryption = false;
                BantamMain.Shells[shellURL].RequestEncryptionIVRequestVarName = string.Empty;
                BantamMain.Shells[shellURL].RequestEncryptionIV  = string.Empty;
                BantamMain.Shells[shellURL].RequestEncryptionKey = string.Empty;
            }

            string         phpCode  = PhpBuilder.PhpTestExecutionWithEcho1(encryptResponse);
            ResponseObject response = await WebRequestHelper.ExecuteRemotePHP(shellURL, phpCode);

            if (string.IsNullOrEmpty(response.Result))
            {
                labelDynAddHostsStatus.Text = "Unable to connect, check your settings and try again.";
                BantamMain.Shells.TryRemove(shellURL, out ShellInfo shellInfoOut);
                return;
            }

            string result = response.Result;

            if (encryptResponse)
            {
                result = CryptoHelper.DecryptShellResponse(response.Result, response.EncryptionKey, response.EncryptionIV, ResponseEncryptionMode);
            }

            if (string.IsNullOrEmpty(result) || result != "1")
            {
                labelDynAddHostsStatus.Text = "Unable to connect, check your settings and try again.";
                BantamMain.Shells.TryRemove(shellURL, out ShellInfo shellInfoOut);
                return;
            }

            BantamMain.Instance.InitializeShellData(shellURL);

            this.Close();
        }
コード例 #26
0
        public ActionResult Save(DocumentViewModel model, HttpPostedFileBase FileUpload)
        {
            var response = new ResponseObject();

            byte[] bytes;
            if (FileUpload.ContentLength > 0)
            {
                bytes = FileUpload.InputStream.ReadAllBinary();
            }
            else
            {
                bytes = null;
            }

            var rlModel = new Model.Models._Document.Document();
            rlModel.FileStream = bytes;
            rlModel.IsRemoved = model.IsRemoved;
            rlModel.Id = model.Id;
            rlModel.LastUpdated = model.LastUpdated;
            rlModel.CreatedBy = model.CreatedBy;
            rlModel.UpdatedBy = model.UpdatedBy;
            rlModel.CreatedDate = model.CreatedDate;
            rlModel.ExpirationDate = model.ExpirationDate;
            rlModel.Name = FileUpload.FileName;
            rlModel.Path = "form";
            rlModel.DocumentExtension = FileUpload.FileName.Split('.').Last();
            rlModel.DocumentType = FileUpload.ContentType;

            if (model.ReferenceId != null)
                response = BO.Document.Instance.SaveDocument(rlModel, model.Reference, model.ReferenceId.Value);
            else
            {
                response.Status = false;
                response.Messages.Add("Dados incorretos.");
            }

            return Json(response);
        }
コード例 #27
0
        public async Task <ResponseObject> Post()
        {
            FileUploadManager fileUploadManager = new FileUploadManager();
            ResponseObject    responseObject    = new ResponseObject();

            try
            {
                string email         = WebConfigurationManager.AppSettings["pdfixEmail"];
                string password      = WebConfigurationManager.AppSettings["pdfixPassword"];
                string fileSize      = WebConfigurationManager.AppSettings["fileSize"];
                string fileExtension = WebConfigurationManager.AppSettings["fileExtension"];

                var resourcesDir = HttpContext.Current.Server.MapPath("~/UploadedFiles/");
                var outputDir    = HttpContext.Current.Server.MapPath("~/JSON/");

                if (!Directory.Exists(resourcesDir))
                {
                    Directory.CreateDirectory(resourcesDir);
                }

                if (!Directory.Exists(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }


                string fileName = string.Empty;

                System.Web.HttpFileCollection httpFileCollection = System.Web.HttpContext.Current.Request.Files;

                for (int count = 0; count <= httpFileCollection.Count - 1; count++)
                {
                    System.Web.HttpPostedFile postedFile = httpFileCollection[count];
                    bool result = Convert.ToBoolean(fileSize.CompareTo(Convert.ToString(postedFile.ContentLength)));

                    if (postedFile.ContentLength > 0)
                    {
                        if (!result)
                        {
                            responseObject.flag    = false;
                            responseObject.message = "Document size cannot be more than 8MB";
                        }
                        if (postedFile.ContentType != fileExtension)
                        {
                            responseObject.flag    = false;
                            responseObject.message = "File type is not supported";
                            return(responseObject);
                        }

                        fileName = postedFile.FileName;
                        var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + postedFile.FileName);
                        postedFile.SaveAs(filePath);
                    }
                    else
                    {
                        responseObject.flag    = false;
                        responseObject.message = "Please upload file";
                        return(responseObject);
                    }
                }


                responseObject = await fileUploadManager.TemplateFileUpload(email, password, outputDir, resourcesDir, fileName);
            }
            catch (Exception ex)
            {
                responseObject.flag         = false;
                responseObject.message      = "Document import failed";
                responseObject.exceptionMsg = ex.Message;
            }

            return(responseObject);
        }
コード例 #28
0
        public ActionResult UploadHB()
        {
            List <ResultUpload> result = new List <ResultUpload>();

            try
            {
                HttpPostedFileBase postedFileBase = Request.Files[0];
                //2.png
                string fileName = postedFileBase.FileName;

                // 获取指定目录绝对路径,如果不存在,则创建
                if (!Directory.Exists(TepmoraryPath))
                {
                    Directory.CreateDirectory(TepmoraryPath);
                }

                string pathFile = TepmoraryPath + Guid.NewGuid().ToString() + Path.GetExtension(fileName);
                postedFileBase.SaveAs(pathFile);

                string guid = Guid.NewGuid().ToString();

                if (IsOpenHbUpload == "1")
                {
                    string responseContent = UploadFile(pathFile, fileName);
                    if (!string.IsNullOrEmpty(responseContent))
                    {
                        ResultUpload upload = JsonConvert.DeserializeObject <ResultUpload>(responseContent);//将文件信息json字符

                        //获取文件大小
                        var file = new FileInfo(pathFile);
                        var size = GetLength(file.Length);

                        upload.GuidId      = guid;
                        upload.errorCode   = "0";
                        upload.errorString = "";
                        upload.Name        = fileName;
                        upload.Size        = size;
                        upload.UploadName  = UCode;
                        upload.UploadDate  = DateTime.Now;
                        ResponseObject obj = new ResponseObject();
                        obj.FDFS_GROUP        = upload.ResponseObject.responseObject[0];
                        obj.FDFS_NAME         = upload.ResponseObject.responseObject[1];
                        upload.ResponseObject = obj;
                        result.Add(upload);
                    }
                }
                else
                {
                    //获取文件大小
                    var file = new FileInfo(pathFile);
                    var size = GetLength(file.Length);

                    ResultUpload upload = new ResultUpload();
                    upload.GuidId      = guid;
                    upload.errorCode   = "0";
                    upload.errorString = "";
                    upload.Name        = fileName;
                    upload.Size        = size;
                    upload.UploadName  = UCode;
                    upload.UploadDate  = DateTime.Now;
                    ResponseObject obj = new ResponseObject();
                    obj.FDFS_GROUP        = string.Empty;
                    obj.FDFS_NAME         = pathFile;
                    upload.ResponseObject = obj;
                    result.Add(upload);
                }

                #region 生成缩略图
                if (MakeThumbnail == "1" && ImageHelper.IsImage(Path.GetExtension(fileName)))
                {
                    string thumbnailPath = ConfigurationManager.AppSettings["ThumbnailPath"];
                    if (!string.IsNullOrWhiteSpace(thumbnailPath))
                    {
                        if (!thumbnailPath.EndsWith("\\"))
                        {
                            thumbnailPath += "\\";
                        }

                        //拼接相对路径
                        string RelativePath = thumbnailPath.Substring(0, thumbnailPath.Length - 1);
                        RelativePath = string.Format("{0}\\{1}\\{2}\\", RelativePath.Substring(RelativePath.LastIndexOf("\\") + 1), DateTime.Today.Year, DateTime.Today.Month);

                        // 缩略图存储文件夹按年月格式生成
                        thumbnailPath = string.Format("{0}{1}\\{2}\\", thumbnailPath, DateTime.Today.Year, DateTime.Today.Month);
                        if (!Directory.Exists(thumbnailPath))
                        {
                            Directory.CreateDirectory(thumbnailPath);
                        }

                        string smallReName = string.Format("{0}{1}", Small, Guid.NewGuid() + fileName);

                        //ImageHelper.MakeThumbnailImage(pathFile, thumbnailPath + smallReName, 300, 300, ImageHelper.ImageCutMode.Cut);
                        ImageHelper.CompressImage(pathFile, thumbnailPath + smallReName);

                        //获取文件大小
                        var file = new FileInfo(thumbnailPath.Replace("\\", "/") + smallReName);
                        var size = GetLength(file.Length);

                        ResultUpload upload = new ResultUpload();
                        upload.errorCode   = "0";
                        upload.errorString = "";
                        upload.GuidId      = guid;
                        upload.Name        = smallReName;
                        upload.Size        = size;
                        upload.UploadName  = UCode;
                        upload.UploadDate  = DateTime.Now;
                        upload.ImageType   = Small;
                        ResponseObject obj = new ResponseObject();
                        obj.FDFS_GROUP        = "";
                        obj.FDFS_NAME         = RelativePath.Replace("\\", "/") + smallReName;
                        upload.ResponseObject = obj;
                        result.Add(upload);

                        #region 内网上传图片,缩略图发送给DMZ区服务器
                        if (IsOpenHbUpload == "1" && !IsNetwork)
                        {
                            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UploadUrlThumbnail + "?fileName=" + string.Format("{0}\\{1}\\{2}", DateTime.Today.Year, DateTime.Today.Month, smallReName));
                            // 边界符
                            var boundary      = "---------------" + DateTime.Now.Ticks.ToString("x");
                            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

                            // 设置属性
                            webRequest.Method      = "POST";
                            webRequest.Timeout     = 600000;
                            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

                            // Header
                            const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
                            var          header         = string.Format(filePartHeader, "filepath", thumbnailPath + smallReName);
                            var          headerbytes    = Encoding.UTF8.GetBytes(header);

                            // 写入文件
                            var fileStream = new FileStream(thumbnailPath + smallReName, FileMode.Open, FileAccess.Read);

                            var memStream = new MemoryStream();
                            memStream.Write(beginBoundary, 0, beginBoundary.Length);
                            memStream.Write(headerbytes, 0, headerbytes.Length);

                            var buffer = new byte[fileStream.Length];
                            int bytesRead;
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                memStream.Write(buffer, 0, bytesRead);
                            }

                            // 写入字符串的Key
                            Dictionary <string, string> dicr = new Dictionary <string, string>();
                            dicr.Add("status", "1");
                            var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n";
                            foreach (byte[] formitembytes in from string key in dicr.Keys select string.Format(stringKeyHeader, key, dicr[key]) into formitem select Encoding.UTF8.GetBytes(formitem))
                            {
                                memStream.Write(formitembytes, 0, formitembytes.Length);
                            }

                            // 最后的结束符
                            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
                            memStream.Write(endBoundary, 0, endBoundary.Length);
                            memStream.Position = 0;

                            webRequest.ContentLength = memStream.Length;
                            var requestStream = webRequest.GetRequestStream();

                            var tempBuffer = new byte[memStream.Length];

                            memStream.Read(tempBuffer, 0, tempBuffer.Length);
                            memStream.Close();

                            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                            requestStream.Close();
                            fileStream.Close();
                            webRequest.Abort();
                        }
                        #endregion
                    }
                }
                #endregion

                if (IsOpenHbUpload == "1")
                {
                    // 上传成功后, 删除临时文件
                    System.IO.File.Delete(pathFile);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(Json(result));
        }
コード例 #29
0
 public CommentsController(AppDbContext appDbContext)
 {
     this.context    = appDbContext;
     response        = new ResponseObject();
     response.Status = false;
 }
コード例 #30
0
    public override void ValidateBeforeRedo(ref ResponseObject response)
    {
        if (Prefab == null)
        {
            response.StringResponse = "Original Prefab is missing!";
            response.Result=ResponseEnums.Failed;

        }
    }
コード例 #31
0
ファイル: BuddyHelper.cs プロジェクト: santhign/Grid
        public async Task <int> AddRemoveBuddyHandler(int orderID, int customerID)
        {
            try
            {
                OrderDataAccess _orderAccess = new OrderDataAccess(_iconfiguration);

                // call remove buddy handler here

                int isRemoved = await RemoveBuddyHandler(orderID, customerID);

                DatabaseResponse checkAdditionalBuddyResponse = await _orderAccess.CheckAdditionalBuddy(orderID);

                // check additional Buddy

                if (checkAdditionalBuddyResponse.ResponseCode == (int)DbReturnValue.RecordExists && checkAdditionalBuddyResponse.Results != null)
                {
                    List <AdditionalBuddy> additionalBuddies = (List <AdditionalBuddy>)checkAdditionalBuddyResponse.Results;

                    foreach (AdditionalBuddy buddy in additionalBuddies)
                    {
                        if (buddy.OrderAdditionalBuddyID > 0 && buddy.IsProcessed == 0)
                        {
                            BSSAPIHelper bsshelper = new BSSAPIHelper();

                            DatabaseResponse configResponse = await _orderAccess.GetConfiguration(ConfiType.BSS.ToString());

                            GridBSSConfi config = bsshelper.GetGridConfig((List <Dictionary <string, string> >)configResponse.Results);

                            DatabaseResponse serviceCAF = await _orderAccess.GetBSSServiceCategoryAndFee(ServiceTypes.Free.ToString());

                            DatabaseResponse requestIdToGetAdditionalBuddy = await _orderAccess.GetBssApiRequestId(GridMicroservices.Order.ToString(), BSSApis.GetAssets.ToString(), customerID, (int)BSSCalls.NewSession, "");

                            ResponseObject res = new ResponseObject();

                            BSSNumbers numbers = new BSSNumbers();
                            //get a free number for additional buddy
                            try
                            {
                                res = await bsshelper.GetAssetInventory(config, (((List <ServiceFees>)serviceCAF.Results)).FirstOrDefault().ServiceCode, (BSSAssetRequest)requestIdToGetAdditionalBuddy.Results);
                            }

                            catch (Exception ex)
                            {
                                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical) + EnumExtensions.GetDescription(CommonErrors.BSSConnectionFailed));
                                // need to unblock all subscribers for the order and roll back the order  and return
                                int buddyRollback = await HandleRollbackOnAdditionalBuddyProcessingFailure(customerID, orderID, additionalBuddies);

                                // rollback on bss failure
                                return(3);
                            }

                            if (res != null && res.Response != null && res.Response.asset_details != null && (int.Parse(res.Response.asset_details.total_record_count) > 0))
                            {
                                numbers.FreeNumbers = bsshelper.GetFreeNumbers(res);

                                //insert these number into database
                                string json = bsshelper.GetJsonString(numbers.FreeNumbers); // json insert

                                DatabaseResponse updateBssCallFeeNumbers = await _orderAccess.UpdateBSSCallNumbers(json, ((BSSAssetRequest)requestIdToGetAdditionalBuddy.Results).userid, ((BSSAssetRequest)requestIdToGetAdditionalBuddy.Results).BSSCallLogID);

                                DatabaseResponse requestIdToUpdateAdditionalBuddyRes = await _orderAccess.GetBssApiRequestId(GridMicroservices.Order.ToString(), BSSApis.UpdateAssetStatus.ToString(), customerID, (int)BSSCalls.ExistingSession, numbers.FreeNumbers[0].MobileNumber);

                                BSSUpdateResponseObject bssUpdateAdditionalBuddyResponse = new BSSUpdateResponseObject();
                                // block the number for additional buddy
                                try
                                {
                                    bssUpdateAdditionalBuddyResponse = await bsshelper.UpdateAssetBlockNumber(config, (BSSAssetRequest)requestIdToUpdateAdditionalBuddyRes.Results, numbers.FreeNumbers[0].MobileNumber, false);

                                    // create buddy subscriber with blocked number and the existing main line

                                    if (bsshelper.GetResponseCode(bssUpdateAdditionalBuddyResponse) == "0")
                                    {
                                        CreateBuddySubscriber additinalBuddySubscriberToCreate = new CreateBuddySubscriber {
                                            OrderID = orderID, MobileNumber = numbers.FreeNumbers[0].MobileNumber, MainLineMobileNumber = buddy.MobileNumber, UserId = ((BSSAssetRequest)requestIdToUpdateAdditionalBuddyRes.Results).userid
                                        };

                                        DatabaseResponse createAdditionalBuddySubscriberResponse = await _orderAccess.CreateBuddySubscriber(additinalBuddySubscriberToCreate);

                                        // update
                                        if (createAdditionalBuddySubscriberResponse.ResponseCode == (int)DbReturnValue.CreateSuccess)
                                        {
                                            DatabaseResponse updateBuddyProcessedResponse = await _orderAccess.UpdateAdditionalBuddyProcessing(buddy.OrderAdditionalBuddyID);
                                        }
                                    }
                                }

                                catch (Exception ex)
                                {
                                    LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical) + EnumExtensions.GetDescription(CommonErrors.BuddyRemovalFailed) + " for Order : " + orderID);
                                }
                            }
                            else
                            {     // rollback on no assets retunred
                                int buddyRollback = await HandleRollbackOnAdditionalBuddyProcessingFailure(customerID, orderID, additionalBuddies);

                                return(2);
                            }
                        }
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(0);
            }
        }
コード例 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InstrumentationLib.ResponseObject"/> class with an
 /// existing object of type ResponseObject.
 /// </summary>
 /// <param name="R">An object of type ResponseObject.</param>
 public ResponseObject(ResponseObject R)
 {
     Response = R.Response;
     Type = (int)R.Type;
 }
コード例 #33
0
        public async Task <SharepointAPIState> CreateLogin()
        {
            InvokeStateChanged(SharepointAPIState.WORKING);

            if (!IsOnline())
            {
                return(SharepointAPIState.CONNECTION_LOST);
            }
            if (string.IsNullOrWhiteSpace(_username))
            {
                return(SharepointAPIState.WRONG_LOGIN);
            }
            if (string.IsNullOrWhiteSpace(_password))
            {
                return(SharepointAPIState.WRONG_LOGIN);
            }

            //Init
            _bearer    = string.Empty;
            _spOauth   = string.Empty;
            _cookieJar = new CookieContainer();

            try
            {
                //Anmeldung ###########################################################################################################################################
                //Federate-Login der Malteser abrufen

                string realmRequest = string.Format("login={0}&xml=1", _username.Replace("@", "%40"));

                HttpWebRequest request = await GetRequest_POSTAsync(GetRequest(new Uri(_url_getAdfs)), RequestContentType.WWW_FORM, RequestContentType.XML, realmRequest);

                if (request == null)
                {
                    return(SharepointAPIState.CONNECTION_LOST);
                }

                ResponseObject response = await GetResponse(request);

                switch (response.StatusCode)
                {
                case ResponseObject.ResponseObjectStatusCode.CONNECTION_LOST:

                    return(SharepointAPIState.CONNECTION_LOST);

                case ResponseObject.ResponseObjectStatusCode.FORBIDDEN:

                    return(SharepointAPIState.WRONG_LOGIN);

                case ResponseObject.ResponseObjectStatusCode.ERROR:
                case ResponseObject.ResponseObjectStatusCode.UNSET:
                default:

                    return(SharepointAPIState.SERVER_ERROR);

                case ResponseObject.ResponseObjectStatusCode.OK:

                    if (response.Response?.StatusCode == HttpStatusCode.OK)
                    {
                        string responseData = GetResponseData(response.Response); response.Close();

                        XElement x             = XElement.Parse(responseData);
                        string   NameSpaceType = x.Descendants().Where(xg => xg.Name.LocalName == "NameSpaceType").First().Value;
                        if (NameSpaceType != "Federated")
                        {
                            return(SharepointAPIState.WRONG_LOGIN);
                        }

                        string sts = x.Descendants().Where(xg => xg.Name.LocalName == "STSAuthURL").First().Value;
                        string auth_certificate = x.Descendants().Where(xg => xg.Name.LocalName == "Certificate").First().Value;

                        //#####################################################################################################################
                        //ADFS beantragen

                        string msgID       = Guid.NewGuid().ToString("D");
                        string r_created   = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fff0000Z");
                        string r_expired   = DateTime.Now.AddMinutes(10).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fff0000Z");
                        string adfsRequest = @"<?xml version='1.0' encoding='UTF-8'?><s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' xmlns:wsa='http://www.w3.org/2005/08/addressing' xmlns:wssc='http://schemas.xmlsoap.org/ws/2005/02/sc' xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust'><s:Header><wsa:Action s:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action><wsa:To s:mustUnderstand='1'>{0}</wsa:To><wsa:MessageID>{1}</wsa:MessageID><ps:AuthInfo xmlns:ps='http://schemas.microsoft.com/Passport/SoapServices/PPCRL' Id='PPAuthInfo'><ps:HostingApp>Managed IDCRL</ps:HostingApp><ps:BinaryVersion>6</ps:BinaryVersion><ps:UIVersion>1</ps:UIVersion><ps:Cookies></ps:Cookies><ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams></ps:AuthInfo><wsse:Security><wsse:UsernameToken wsu:Id='user'><wsse:Username>{2}</wsse:Username><wsse:Password>{3}</wsse:Password></wsse:UsernameToken><wsu:Timestamp Id='Timestamp'><wsu:Created>{4}</wsu:Created><wsu:Expires>{5}</wsu:Expires></wsu:Timestamp></wsse:Security></s:Header><s:Body><wst:RequestSecurityToken Id='RST0'><wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType><wsp:AppliesTo><wsa:EndpointReference><wsa:Address>urn:federation:MicrosoftOnline</wsa:Address></wsa:EndpointReference></wsp:AppliesTo><wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType></wst:RequestSecurityToken></s:Body></s:Envelope>";

                        request = await GetRequest_POSTAsync(GetRequest(new Uri(sts)), RequestContentType.SOAP, RequestContentType.ALL, string.Format(adfsRequest, sts, msgID, _username, _password, r_created, r_expired));

                        if (request == null)
                        {
                            return(SharepointAPIState.CONNECTION_LOST);
                        }

                        response = await GetResponse(request);

                        switch (response.StatusCode)
                        {
                        case ResponseObject.ResponseObjectStatusCode.CONNECTION_LOST:

                            return(SharepointAPIState.CONNECTION_LOST);

                        case ResponseObject.ResponseObjectStatusCode.FORBIDDEN:

                            return(SharepointAPIState.WRONG_LOGIN);

                        case ResponseObject.ResponseObjectStatusCode.ERROR:
                        case ResponseObject.ResponseObjectStatusCode.UNSET:
                        default:

                            return(SharepointAPIState.SERVER_ERROR);

                        case ResponseObject.ResponseObjectStatusCode.OK:

                            if (response.Response?.StatusCode == HttpStatusCode.OK)
                            {
                                responseData = GetResponseData(response.Response); response.Close();

                                x = XElement.Parse(responseData);
                                string auth_SignatureValue  = x.Descendants().Where(xg => xg.Name.LocalName == "SignatureValue").First().Value;
                                string auth_X509Certificate = x.Descendants().Where(xg => xg.Name.LocalName == "X509Certificate").First().Value;
                                string auth_DigestValue     = x.Descendants().Where(xg => xg.Name.LocalName == "DigestValue").First().Value;
                                string auth_NameIdentifier  = x.Descendants().Where(xg => xg.Name.LocalName == "NameIdentifier").First().Value;
                                string auth_AssertionID     = x.Descendants().Where(xg => xg.Name.LocalName == "Assertion").First().Attributes("AssertionID").First().Value;
                                string auth_Issuer          = x.Descendants().Where(xg => xg.Name.LocalName == "Assertion").First().Attributes("Issuer").First().Value;

                                string auth_AssertionFullXml = x.Descendants().Where(xg => xg.Name.LocalName == "Assertion").First().ToString(SaveOptions.DisableFormatting);

                                //################################################################################################################
                                //Sharepoint-Token beantragen

                                string spTokenRequest = @"<S:Envelope xmlns:S='http://www.w3.org/2003/05/soap-envelope' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' xmlns:wsa='http://www.w3.org/2005/08/addressing' xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust'><S:Header><wsa:Action S:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action><wsa:To S:mustUnderstand='1'>https://login.microsoftonline.com/rst2.srf</wsa:To><ps:AuthInfo xmlns:ps='http://schemas.microsoft.com/LiveID/SoapServices/v1' Id='PPAuthInfo'><ps:BinaryVersion>5</ps:BinaryVersion><ps:HostingApp>Managed IDCRL</ps:HostingApp></ps:AuthInfo><wsse:Security>{0}</wsse:Security></S:Header><S:Body><wst:RequestSecurityToken xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust' Id='RST0'><wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType><wsp:AppliesTo><wsa:EndpointReference><wsa:Address>sharepoint.com</wsa:Address></wsa:EndpointReference></wsp:AppliesTo><wsp:PolicyReference URI='MBI'/></wst:RequestSecurityToken></S:Body></S:Envelope>";

                                request = await GetRequest_POSTAsync(GetRequest(new Uri(_url_getSpToken)), RequestContentType.SOAP, RequestContentType.ALL, string.Format(spTokenRequest, auth_AssertionFullXml));

                                if (request == null)
                                {
                                    return(SharepointAPIState.CONNECTION_LOST);
                                }

                                response = await GetResponse(request);

                                switch (response.StatusCode)
                                {
                                case ResponseObject.ResponseObjectStatusCode.CONNECTION_LOST:

                                    return(SharepointAPIState.CONNECTION_LOST);

                                case ResponseObject.ResponseObjectStatusCode.FORBIDDEN:

                                    return(SharepointAPIState.WRONG_LOGIN);

                                case ResponseObject.ResponseObjectStatusCode.ERROR:
                                case ResponseObject.ResponseObjectStatusCode.UNSET:
                                default:

                                    return(SharepointAPIState.SERVER_ERROR);

                                case ResponseObject.ResponseObjectStatusCode.OK:

                                    if (response.Response?.StatusCode == HttpStatusCode.OK)
                                    {
                                        responseData = GetResponseData(response.Response); response.Close();

                                        x = XElement.Parse(responseData);
                                        string auth_BinarySecurityToken = x.Descendants().Where(xg => xg.Name.LocalName == "BinarySecurityToken").First().Value;

                                        //###################################################################################################################
                                        //Cookies laden

                                        Uri idcrlUri = new Uri(_url_malteserHost + "/_vti_bin/idcrl.svc/");

                                        request = GetRequest(idcrlUri);
                                        request.Headers.Set("Authorization", "BPOSIDCRL " + auth_BinarySecurityToken);
                                        request.Headers.Add("X-IDCRL_ACCEPTED", "t");

                                        response = await GetResponse(request);

                                        switch (response.StatusCode)
                                        {
                                        case ResponseObject.ResponseObjectStatusCode.CONNECTION_LOST:

                                            return(SharepointAPIState.CONNECTION_LOST);

                                        case ResponseObject.ResponseObjectStatusCode.FORBIDDEN:

                                            return(SharepointAPIState.WRONG_LOGIN);

                                        case ResponseObject.ResponseObjectStatusCode.ERROR:
                                        case ResponseObject.ResponseObjectStatusCode.UNSET:
                                        default:

                                            return(SharepointAPIState.SERVER_ERROR);

                                        case ResponseObject.ResponseObjectStatusCode.OK:

                                            if (response.Response?.StatusCode == HttpStatusCode.OK)
                                            {
                                                //#############################################################################################################################
                                                //Digest beantragen

                                                Uri    digestUri     = new Uri(_url_malteserHost + "/_vti_bin/sites.asmx");
                                                string digestRequest = @"<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><GetUpdatedFormDigestInformation xmlns='http://schemas.microsoft.com/sharepoint/soap/' /></soap:Body></soap:Envelope>";

                                                request = await GetRequest_POSTAsync(GetRequest(digestUri), RequestContentType.XML, RequestContentType.ALL, digestRequest);

                                                if (request == null)
                                                {
                                                    return(SharepointAPIState.CONNECTION_LOST);
                                                }

                                                request.Headers.Add("X-RequestForceAuthentication", "true");
                                                request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                                                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                                                request.Headers.Add("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetUpdatedFormDigestInformation");

                                                response = await GetResponse(request);

                                                switch (response.StatusCode)
                                                {
                                                case ResponseObject.ResponseObjectStatusCode.CONNECTION_LOST:

                                                    return(SharepointAPIState.CONNECTION_LOST);

                                                case ResponseObject.ResponseObjectStatusCode.FORBIDDEN:

                                                    return(SharepointAPIState.WRONG_LOGIN);

                                                case ResponseObject.ResponseObjectStatusCode.ERROR:
                                                case ResponseObject.ResponseObjectStatusCode.UNSET:
                                                default:

                                                    return(SharepointAPIState.SERVER_ERROR);

                                                case ResponseObject.ResponseObjectStatusCode.OK:

                                                    if (response.Response?.StatusCode == HttpStatusCode.OK)
                                                    {
                                                        responseData = GetResponseData(response.Response); response.Close();
                                                        x            = XElement.Parse(responseData);

                                                        _bearer  = x.Descendants().Where(xg => xg.Name.LocalName == "DigestValue").First().Value;
                                                        _spOauth = _cookieJar.GetCookies(new Uri(_url_malteserHost))["SPOIDCRL"].Value;

                                                        TBL.UpdateTokens(_bearer, _spOauth);

                                                        return(SharepointAPIState.LOGGED_IN);
                                                    }
                                                    return(SharepointAPIState.SERVER_ERROR);
                                                }
                                            }
                                            return(SharepointAPIState.SERVER_ERROR);
                                        }
                                    }
                                    return(SharepointAPIState.SERVER_ERROR);
                                }
                            }
                            return(SharepointAPIState.SERVER_ERROR);
                        }
                    }
                    return(SharepointAPIState.SERVER_ERROR);
                }
            }
            catch (Exception)
            {
                return(SharepointAPIState.SERVER_ERROR);
            }
        }
コード例 #34
0
 public override void ValidateBeforeRedo(ref ResponseObject response)
 {
     response.Result = ResponseEnums.Failed;
 }
コード例 #35
0
ファイル: ErrorHandling.cs プロジェクト: ArcMarky/arcelastic
        public static ResponseObject LogCustomError(string errorMessage)
        {
            ResponseObject response = new ResponseObject(ResponseType.Error, errorMessage);

            return(response);
        }
コード例 #36
0
 public override void ValidateBeforeUndo(ref ResponseObject response)
 {
     response.Result = ResponseEnums.Failed;
 }
コード例 #37
-1
        public ActionResult Save(EmailConfigurationViewModel model)
        {
            var response = new ResponseObject();
            response.Messages.Add("");

            if (ModelState.IsValid)
            {
                var md = Mapper.Map<Model.Models._Email.EmailConfiguration>(model);
                md.ConfigurationType = (Model.Models._Email.ConfigurationType)Enum.Parse(typeof(ConfigurationType), model.ConfigurationType);

                response = EmailConfiguration.Instance.SaveEmailConfiguration(md);
            }

            return Json(response);
        }
コード例 #38
-1
    public override void ValidateBeforeDo(ref ResponseObject response)
    {
        if (Prefab == null)
        {
            response.StringResponse = "Need an object to copy";
            response.Result=ResponseEnums.Failed;
            return;
        }

        if (NumOfCopies <= 0)
        {
            response.StringResponse = "Num of copies can't be equal/less than 0";
            response.Result = ResponseEnums.Failed;
            return;
        }

        if (RadialDistance < 0)
        {
            response.StringResponse = "Radial distance can't be less than 0";
            response.Result = ResponseEnums.Failed;
            return;
        }
    }