protected static Post SavePost(Post post)
 {
     string conn = ConfigurationManager.AppSettings["mongolab"];
     PostData postData = new PostData(conn);
     postData.SavePost(post);
     return post;
 }
		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestConfiguration local, IMemoryStreamFactory memoryStreamFactory)
		{
			this.ConnectionSettings = global;
			this.MemoryStreamFactory = memoryStreamFactory;
			this.Method = method;
			this.PostData = data;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, null);

			this.Pipelined = global.HttpPipeliningEnabled || (local?.EnableHttpPipelining).GetValueOrDefault(false);
			this.HttpCompression = global.EnableHttpCompression;
			this.ContentType = local?.ContentType ?? MimeType;
			this.Headers = global.Headers;

			this.RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
			this.PingTimeout = 
				local?.PingTimeout
				?? global?.PingTimeout
				?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

			this.KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
			this.KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);

			this.ProxyAddress = global.ProxyAddress;
			this.ProxyUsername = global.ProxyUsername;
			this.ProxyPassword = global.ProxyPassword;
			this.DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection;
			this.BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
			this.CancellationToken = local?.CancellationToken ?? CancellationToken.None;
			this.AllowedStatusCodes = local?.AllowedStatusCodes ?? Enumerable.Empty<int>();
		}
Esempio n. 3
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     Init();
     RunAnimation();
     data = (PostData)e.Parameter;
     base.OnNavigatedTo(e);
 }
Esempio n. 4
0
		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestParameters local, IMemoryStreamFactory memoryStreamFactory)
#pragma warning disable CS0618 // Type or member is obsolete
			: this(method, path, data, global, (IRequestConfiguration)local?.RequestConfiguration, memoryStreamFactory)
#pragma warning restore CS0618 // Type or member is obsolete
		{
			this.CustomConverter = local?.DeserializationOverride;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, local);
		}
Esempio n. 5
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private void PopulatePage()
        {
            bool isOk = Request.Form["minDepDate"]      != null &&
                        Request.Form["maxDepDate"]      != null &&
                        Request.Form["incPublicTransp"] != null &&
                        Request.Form["maxDriveKm"]      != null &&
                        Request.Form["allowInter"]      != null &&
                        Request.Form["outputUrl"]       != null &&
                        Request.Form["iframeInputUrl"]  != null;

            //incPublicTransp
            if (isOk)
            {
                bool incPublicTransp;
                isOk = bool.TryParse(Request.Form["incPublicTransp"], out incPublicTransp);
            }
            //maxDriveKm
            if (isOk)
            {
                int maxDriveKm;
                isOk = int.TryParse(Request.Form["maxDriveKm"], out maxDriveKm);
            }
            //allowInter
            if (isOk)
            {
                bool allowInter;
                isOk = bool.TryParse(Request.Form["allowInter"], out allowInter);
            }
            //minDepDate
            if (isOk)
            {
                DateTime minDepDate;
                isOk = DateTime.TryParseExact(Request.Form["minDepDate"], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out minDepDate);
            }
            //maxDepDate
            if (isOk)
            {
                DateTime maxDepDate;
                isOk = DateTime.TryParseExact(Request.Form["maxDepDate"], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out maxDepDate);
            }

            // if everything is ok with the request,
            // populate json objet with post data so javascript can know what's going on
            if (isOk)
            {
                PostData p = new PostData();
                p.allowInter = bool.Parse(Request.Form["allowInter"]);
                p.incPublicTransp = bool.Parse(Request.Form["incPublicTransp"]);
                p.maxDepDate = Request.Form["maxDepDate"];
                p.maxDriveKm = int.Parse(Request.Form["maxDriveKm"]);
                p.minDepDate = Request.Form["minDepDate"];
                p.outputUrl = Request.Form["outputUrl"];
                p.iframeInputUrl = Request.Form["iframeInputUrl"];
                string json = JsonConvert.SerializeObject(p);
                litJsonRq.Text = json;
            }
        }
Esempio n. 6
0
 public async Task<IActionResult> Latest(int p = 1)
 {
     if (p <= 0) p = 1;
     var data = new PostData(Db);
     var model = await data.LatestAsync(p);
     if (model == null) Redirect("/");
     ViewBag.PageCount = data.PageCount;
     ViewBag.PageNo = p;
     ViewBag.PagingUrl = "/Latest/{p}";
     return View("Index",model);
 }
Esempio n. 7
0
        static PostData GetEncodedPostData(Dictionary<String, String> values, Dictionary<String, String> files)
        {
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            Stream memStream = new System.IO.MemoryStream();
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
            if (values != null)
                foreach (var v in values)
                {
                    string formitem = string.Format(formdataTemplate, v.Key, v.Value);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }
            memStream.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";

            if (files != null)
                foreach (var v in files)
                {

                    FileStream fileStream = new FileStream(v.Value, FileMode.Open, FileAccess.Read);

                    string header = string.Format(headerTemplate, v.Key, v.Value);
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    memStream.Write(headerbytes, 0, headerbytes.Length);

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

                    memStream.Write(boundarybytes, 0, boundarybytes.Length);
                    fileStream.Close();
                }

            PostData result = new PostData();

            memStream.Position = 0;
            result.data = new byte[memStream.Length];
            memStream.Read(result.data, 0, result.data.Length);
            memStream.Close();

            result.headers = "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n" +
                             "Content-Length: " + result.data.Length + "\r\n" +
                             "\r\n";

            return result;
        }
Esempio n. 8
0
        public async Task<IActionResult> Search(string q = "", int p = 1)
        {
            if (string.IsNullOrWhiteSpace(q)) Redirect("/");
            var data = new PostData(Db);
            var model = await data.SearchAsync(q, p);
            if (model == null) Redirect("/");
            ViewBag.PageCount = data.PageCount;
            ViewBag.PageNo = p;
            ViewBag.PagingUrl = $"/Search?q={q}&p={{p}}";

            return View("Index", model);
        }
 // POST api/rtpplancycle
 public int Post(PostData data)
 {
     var cycle = new PlanCycle() { Name = data.name, Description = data.description };
     try
     {
         return TripsRepository.CreateRtpPlanCycle(cycle, data.rtpYearId);
     }
     catch (Exception ex)
     {
         Logger.WarnException("Could not create RTP Plan Cycle", ex);
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ExpectationFailed) { ReasonPhrase = ex.Message });
     }
 }
Esempio n. 10
0
        public async Task<IActionResult> Index(int id = 0, string slug = "")
        {
            if (id == 0 || string.IsNullOrEmpty(slug))
            {
                return Redirect("/");
            }

            var data = new PostData(Db);
            var model = await data.GetByIdAsync(id);
            if (model == null) Redirect("/");            

            return View(model);
        }
Esempio n. 11
0
        private void SendNotification(string appId, List<string> deviceRegIds, object notificationMessage)
        {
            WebRequest tRequest = null;
            GetWebRequestAndroidCloud(ref tRequest, appId, "application/json");

            PostData postData = new PostData
            {
                data = notificationMessage,
                registration_ids = deviceRegIds
            };

            string postDataJson = new JavaScriptSerializer().Serialize(postData);

            GetResponse(tRequest, postDataJson);
        }
 // POST api/rtpproject
 public int Post(PostData project)
 {
     try
     {
         var id = RtpRepository.CreateProject(project.projectName, project.facilityName, project.plan, project.sponsorOrganizationId, project.cycleId);
         if (id <= 0)
         {
             throw new Exception("Project creation failed.");
         }
         return id;
     }
     catch (Exception ex)
     {
         Logger.WarnException("Could not create RTP Project", ex);
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ExpectationFailed) { ReasonPhrase = "Project creation failed." });
     }
 }
Esempio n. 13
0
        public async Task<IActionResult> Tag(int id = 0, string slug = "", int p = 1)
        {
            if (id == 0 || string.IsNullOrEmpty(slug))
            {
                return Redirect("/");
            }
            if (p <= 0) p = 1;

            var data = new PostData(Db);
            var model = await data.GetByTagAsync(id, p);
            if (model == null) Redirect("/");
            ViewBag.PageCount = data.PageCount;
            ViewBag.PageNo = p;
            ViewBag.PagingUrl = $"/Tag/{id}/{slug}?p={{p}}";

            return View("/Views/Home/Index", model);
        }
Esempio n. 14
0
		private void AddTask(PostData postData)
		{
			if (_queue == null) { 
				_queue = new Queue<PostData>();
				_thread = new System.Threading.Thread(ThreadLoop);
				_manualResetEvent = new System.Threading.ManualResetEvent(true);
				_thread.IsBackground = true;
				_thread.Start();
			}

			if(!_cancel){
				lock (_queue) {
					_queue.Enqueue(postData);
				}

				_manualResetEvent.Set();
			}
		
		}
Esempio n. 15
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         string conn = ConfigurationManager.AppSettings["mongolab"];
         PostData postData = new PostData(conn);
         string sPostId = Request.QueryString["postid"];
         if (!string.IsNullOrWhiteSpace(sPostId))
         {
             // Editing a specific Post.
             ObjectId postId = new ObjectId(sPostId);
             Post post = postData.GetPost(postId);
         }
         else
         {
             // List Posts
             IEnumerable<Post> posts = postData.GetAllPosts();
         }
     }
 }
Esempio n. 16
0
		private RequestData(
			HttpMethod method,
			string path,
			PostData<object> data,
			IConnectionConfigurationValues global,
			IRequestConfiguration local,
			IMemoryStreamFactory memoryStreamFactory)
		{
			this.ConnectionSettings = global;
			this.MemoryStreamFactory = memoryStreamFactory;
			this.Method = method;
			this.PostData = data;

			if (data != null)
				data.DisableDirectStreaming = local?.DisableDirectStreaming ?? global.DisableDirectStreaming;

			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, null);

			this.Pipelined = local?.EnableHttpPipelining ?? global.HttpPipeliningEnabled;
			this.HttpCompression = global.EnableHttpCompression;
			this.ContentType = local?.ContentType ?? MimeType;
			this.Accept = local?.Accept ?? MimeType;
			this.Headers = global.Headers != null ? new NameValueCollection(global.Headers) : new NameValueCollection();
			this.RunAs = local?.RunAs;

			this.RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
			this.PingTimeout =
				local?.PingTimeout
				?? global?.PingTimeout
				?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

			this.KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
			this.KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);

			this.ProxyAddress = global.ProxyAddress;
			this.ProxyUsername = global.ProxyUsername;
			this.ProxyPassword = global.ProxyPassword;
			this.DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection;
			this.BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
			this.AllowedStatusCodes = local?.AllowedStatusCodes ?? Enumerable.Empty<int>();
		}
Esempio n. 17
0
 private async void NextButtonClicked(object sender, TappedRoutedEventArgs e)
 {
     var color = (ColorItem)colorGrid.SelectedItem;
     var name = nameBox.Text;
     var stick = stickNumBox.Text;
     var gid = gameNumBox.Text;
     if (color == null || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(stick) || string.IsNullOrEmpty(gid))
     {
         var message = new MessageDialog("何か忘れてませんか?", "おや?");
         await message.ShowAsync();
     }
     else
     {
         var data = new PostData();
         data.color = color;
         data.name = name;
         data.stickNum = stick;
         data.gameId = gid;
         this.Frame.Navigate(typeof(InitPage02), data);
     }
 }
Esempio n. 18
0
        public ActionResult AddVideoPost(AddVideoPostInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            var userData = UserManager.GetCurrentUser();

            var post = new PostData
            {
                AuthorId = userData.Id,
                AuthorName = userData.Name,
                Source = VideoManager.GetYoutubeVideoId(model.Source),
                PostType = PostType.VideoPost,
                Title = model.Title,
                TagList = RepositoryManager.TagRepository.GetTagList(model.TagList)
            };

            var id = RepositoryManager.PostRepository.Insert(post);
            return Content(Url.Action("DetailPost", "Post", new {postId = id}));
        }
        protected virtual BaseResponse GetResults(PostData<PlayerRecordViewModel> data)
        {
            try
            {
                var commands = new FoosballCommands();
                var result = commands.GetPlayerRecords().OrderByDescending(r => r.Wins).ToList();

                return new GetResponse<PlayerRecordViewModel>
                {
                    status = ResponseCodes.Success,
                    total = result.Count(),
                    records = result.Select(CreateViewModel).ToList()
                };
            }
            catch (Exception ex)
            {
                return new ErrorResponse
                {
                    status = ResponseCodes.Error,
                    message = ex.Message
                };
            }
        }
Esempio n. 20
0
        bool SaveData()
        {
            DataRow I = DS.invoice.Rows[0];

            PostData.MarkAsTemporaryTable(DS.Tables["pettycashoperationview"], false);
            DS.pettycashoperation.Clear();
            DS.pettycashoperationinvoice.Clear();

            MetaData MetaPettycashoperation = Meta.Dispatcher.Get("pettycashoperation");

            MetaPettycashoperation.SetDefaults(DS.pettycashoperation);

            MetaData MetaPettycashoperationinvoice = Meta.Dispatcher.Get("pettycashoperationinvoice");

            MetaPettycashoperationinvoice.SetDefaults(DS.pettycashoperationinvoice);

            DS.pettycashoperation.Columns["idaccmotive_debit"].DefaultValue = I["idaccmotivedebit"];

            DS.pettycashoperationinvoice.Columns["idinvkind"].DefaultValue = I["idinvkind"];
            DS.pettycashoperationinvoice.Columns["ninv"].DefaultValue      = I["ninv"];
            DS.pettycashoperationinvoice.Columns["yinv"].DefaultValue      = I["yinv"];

            int esercizio = Convert.ToInt32(Meta.GetSys("esercizio"));


            foreach (DataRow R in Tpettycashoperation.Select())
            {
                DataRow NewOp = MetaPettycashoperation.Get_New_Row(null, DS.pettycashoperation);

                NewOp["idpettycash"] = R["idpettycash"];
                NewOp["description"] = R["description"];
                NewOp["idfin"]       = R["idfin"];
                NewOp["idupb"]       = R["idupb"];
                NewOp["idman"]       = R["idman"];
                if (chkDocumentata.Checked)
                {
                    int flag = CfgFn.GetNoNullInt32(DS.pettycashoperation.Columns["flag"].DefaultValue);
                    NewOp["flag"] = flag;
                }
                else
                {
                    int flag = CfgFn.GetNoNullInt32(DS.pettycashoperation.Columns["flag"].DefaultValue);
                    flag          = flag & 0x10; //  Azzero il bit di pos.4 = Spese Documentate
                    flag          = flag & 0x08; //  Azzero il bit di pos.3 = Tipo Operazione 'Spesa'
                    flag          = flag | 0x08; //  Imposto il bit di pos.3 = Tipo Operazione 'Spesa'
                    NewOp["flag"] = flag;
                }

                NewOp["amount"]  = R["amount"];
                NewOp["doc"]     = R["doc"];
                NewOp["docdate"] = R["docdate"];
                NewOp["idexp"]   = R["idexp"];

                DataRow NewOpInvoice = MetaPettycashoperationinvoice.Get_New_Row(NewOp, DS.pettycashoperationinvoice);

                NewOpInvoice["yoperation"]  = Meta.GetSys("esercizio");
                NewOpInvoice["noperation"]  = NewOp["noperation"];
                NewOpInvoice["idpettycash"] = R["idpettycash"];
            }

            PostData Post = Meta.Get_PostData();

            Post.InitClass(DS, Meta.Conn);
            if (!Post.DO_POST())
            {
                MessageBox.Show(this, "Si è verificato un errore o si è deciso di non salvare! L'operazione sarà terminata");
                return(false);
            }
            else
            {
                GeneraScritture();
            }

            //new FrmDettaglioRisultati(DS.pettycashoperation).ShowDialog(this);

            return(true);
        }
		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestParameters local, IMemoryStreamFactory memoryStreamFactory)
			: this(method, path, data, global, (IRequestConfiguration)local?.RequestConfiguration, memoryStreamFactory)
		{
			this.CustomConverter = local?.DeserializationOverride;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, local);
		}
 ///<summary>POST on /_sql/close <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-pagination.html</para></summary>
 ///<param name = "body">Specify the cursor value in the `cursor` element to clean the cursor.</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse ClearCursor <TResponse>(PostData body, ClearSqlCursorRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(POST, "_sql/close", body, RequestParams(requestParameters));
Esempio n. 23
0
 ///<summary>POST on /_snapshot/{repository}/{snapshot}/_mount <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/searchable-snapshots-api-mount-snapshot.html</para></summary>
 ///<param name = "repository">The name of the repository containing the snapshot of the index to mount</param>
 ///<param name = "snapshot">The name of the snapshot of the index to mount</param>
 ///<param name = "body">The restore configuration for mounting the snapshot as searchable</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 ///<remarks>Note: Experimental within the Elasticsearch server, this functionality is Experimental and may be changed or removed completely in a future release. Elastic will take a best effort approach to fix any issues, but experimental features are not subject to the support SLA of official GA features. This functionality is subject to potential breaking changes within a minor version, meaning that your referencing code may break when this library is upgraded.</remarks>
 public TResponse Mount <TResponse>(string repository, string snapshot, PostData body, MountRequestParameters requestParameters = null)
     where TResponse : class, IElasticsearchResponse, new() => DoRequest <TResponse>(POST, Url($"_snapshot/{repository:repository}/{snapshot:snapshot}/_mount"), body, RequestParams(requestParameters));
 public Task <TResponse> SimulatePipelineAsync <TResponse>(string id, PostData body, SimulatePipelineRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, ITransportResponse, new() => DoRequestAsync <TResponse>(POST, Url($"_ingest/pipeline/{id:id}/_simulate"), ctx, body, RequestParams(requestParameters));
 public Task <TResponse> ClearCursorAsync <TResponse>(PostData body, ClearSqlCursorRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, ITransportResponse, new() => DoRequestAsync <TResponse>(POST, "_sql/close", ctx, body, RequestParams(requestParameters));
        private async Task Store(object data)
        {
            try
            {
                var json = JsonConvert.SerializeObject(data);

                var result = await this.client.IndexAsync <StringResponse>("metrics", "metric", Guid.NewGuid().ToString(), PostData.String(json));

                result.TryGetServerError(out var error);

                if (error != default(ServerError))
                {
                    throw new Exception(error.ToString());
                }

                this.Logger.Debug($"Stored metric: {json}");
            }
            catch (Exception ex)
            {
                this.Logger.Error(ex);
            }
        }
Esempio n. 27
0
 public void FilterThreadByPostAuthorAsync(PostData post, Action<ThreadData> action)
 {
     throw new NotImplementedException();
 }
Esempio n. 28
0
 ///<summary>PUT on /_snapshot/{repository} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html</para></summary>
 ///<param name = "repository">A repository name</param>
 ///<param name = "body">The repository definition</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse CreateRepository <TResponse>(string repository, PostData body, CreateRepositoryRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(PUT, Url($"_snapshot/{repository:repository}"), body, RequestParams(requestParameters));
        public bool InsertItem <T>(string indexName, T data)
        {
            BytesResponse res = conn.LowLevel.Index <BytesResponse>(indexName, PostData.Serializable <T>(data));

            return(res.Success);
        }
Esempio n. 30
0
 public Task <TResponse> SnapshotAsync <TResponse>(string repository, string snapshot, PostData body, SnapshotRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, ITransportResponse, new() => DoRequestAsync <TResponse>(PUT, Url($"_snapshot/{repository:repository}/{snapshot:snapshot}"), ctx, body, RequestParams(requestParameters));
Esempio n. 31
0
 ///<summary>PUT on /_snapshot/{repository}/{snapshot} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html</para></summary>
 ///<param name = "repository">A repository name</param>
 ///<param name = "snapshot">A snapshot name</param>
 ///<param name = "body">The snapshot definition</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse Snapshot <TResponse>(string repository, string snapshot, PostData body, SnapshotRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(PUT, Url($"_snapshot/{repository:repository}/{snapshot:snapshot}"), body, RequestParams(requestParameters));
Esempio n. 32
0
        private bool TryPutPipeline(ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(Options.PipelineName))
            {
                return(true);
            }

            var getPipelineResponse = Client.Ingest.GetPipeline <VoidResponse>(Options.PipelineName);

            if (getPipelineResponse.Success)
            {
                return(true);
            }

            var rounding = GetIndexRounding();

            var pipeline = new
            {
                description = "Enriches the benchmark exports from BenchmarkDotNet",
                processors  = new[]
                {
                    new
                    {
                        date_index_name = new
                        {
                            field             = "@timestamp",
                            index_name_prefix = $"{Options.IndexName}-",
                            // 2020-01-08T20:48:18.1548182+00:00
                            date_formats  = new[] { "ISO8601", "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ" },
                            date_rounding = rounding
                        }
                    }
                }
            };

            var putPipeline = Client.Ingest.PutPipeline <VoidResponse>(Options.PipelineName, PostData.Serializable(pipeline));

            if (putPipeline.Success)
            {
                return(true);
            }

            logger.WriteLine(putPipeline.DebugInformation);
            return(false);
        }
Esempio n. 33
0
 public async Task <ActionResult> BlockChapter(PostData data) => await BlockContent <Chapter>(data);
Esempio n. 34
0
        public static async Task <ConcurrentBag <ProductModel> > GetEsSearchableProducts()
        {
            EsClient       client         = new EsClient();
            StringResponse searchResponse = new StringResponse();

            try
            {
                searchResponse = await client.Client.SearchAsync <StringResponse>("product_search", PostData.Serializable(
                                                                                      new
                {
                    from = 0,
                    size = 10000,

                    query = new
                    {
                        match = new
                        {
                            type = "product"
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
                Debug.WriteLine(ex.InnerException.ToString());
            }

            string responseJson = searchResponse.Body;

            using JsonDocument document = JsonDocument.Parse(responseJson);
            JsonElement root          = document.RootElement;
            JsonElement sourceElement = root.GetProperty("hits").GetProperty("hits");

            ConcurrentBag <ProductModel> products = new ConcurrentBag <ProductModel>();

            Parallel.ForEach(sourceElement.EnumerateArray().AsParallel(), source =>
            {
                if (source.TryGetProperty("_source", out JsonElement rec))
                {
                    ProductModel product = new ProductModel
                    {
                        Type        = rec.GetProperty("type").GetString(),
                        Sku         = rec.GetProperty("sku").GetString(),
                        Image       = rec.GetProperty("image").GetString(),
                        Url         = rec.GetProperty("url").GetString(),
                        Price       = rec.GetProperty("price").GetDecimal(),
                        Name        = rec.GetProperty("name").GetString(),
                        Description = rec.GetProperty("description").GetString()
                    };

                    products.Add(product);
                }
            });
            return(products);
        }
Esempio n. 35
0
 public Task <TResponse> FindStructureAsync <TResponse>(PostData body, FindStructureRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, ITransportResponse, new() => DoRequestAsync <TResponse>(POST, "_text_structure/find_structure", ctx, body, RequestParams(requestParameters));
Esempio n. 36
0
 private string SendFanficRequest(object body)
 {
     return(_elasticClient.Search <StringResponse>("fullinfofanfic", "fullinfofanfic", PostData.Serializable(body)).Body);
 }
Esempio n. 37
0
		private PostData<object> ImplicitlyConvertsFrom(PostData<object> postData) => postData;
Esempio n. 38
0
        public void AddPost(PostData post)
        {

        }
 ///<summary>POST on /_sql <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest-overview.html</para></summary>
 ///<param name = "body">Use the `query` element to start a query. Use the `cursor` element to continue a query.</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse Query <TResponse>(PostData body, QuerySqlRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(POST, "_sql", body, RequestParams(requestParameters));
Esempio n. 40
0
 public Task <TResponse> SubmitAsync <TResponse>(string index, PostData body, AsyncSearchSubmitRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync <TResponse>(POST, Url($"{index:index}/_async_search"), ctx, body, RequestParams(requestParameters));
Esempio n. 41
0
 public static IEnumerable<Post> GetPosts(int page=1, int pageSize=int.MaxValue)
 {
     string conn = ConfigurationManager.AppSettings["mongolab"];
     PostData postData = new PostData(conn);
     return postData.GetAllPosts();
 }
        /**
         * The client will serialize each item seperately and join items up using the `\n` character as required by the Bulk API. Refer to the
         * Elasticsearch Bulk API documentation for further details and supported operations.
         *
         * [float]
         * === Searching
         *
         * Now that we have indexed some documents we can begin to search for them.
         *
         * The Elasticsearch Query DSL can be expressed using an anonymous type within the request
         */
        public void SearchingWithAnonymousTypes()
        {
            var searchResponse = lowlevelClient.Search <StringResponse>("people", "person", PostData.Serializable(new
            {
                from  = 0,
                size  = 10,
                query = new
                {
                    match = new
                    {
                        field = "firstName",
                        query = "Martijn"
                    }
                }
            }));

            var successful   = searchResponse.Success;
            var responseJson = searchResponse.Body;
        }
Esempio n. 43
0
 public Task <TResponse> MountAsync <TResponse>(string repository, string snapshot, PostData body, MountRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync <TResponse>(POST, Url($"_snapshot/{repository:repository}/{snapshot:snapshot}/_mount"), ctx, body, RequestParams(requestParameters));
Esempio n. 44
0
 ///<summary>POST on /{index}/_async_search <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/async-search.html</para></summary>
 ///<param name = "index">A comma-separated list of index names to search; use the special string `_all` or Indices.All to perform the operation on all indices</param>
 ///<param name = "body">The search definition using the Query DSL</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse Submit <TResponse>(string index, PostData body, AsyncSearchSubmitRequestParameters requestParameters = null)
     where TResponse : class, IElasticsearchResponse, new() => DoRequest <TResponse>(POST, Url($"{index:index}/_async_search"), body, RequestParams(requestParameters));
Esempio n. 45
0
        void GeneraScritture()
        {
            if (DS.pettycashoperation.Rows.Count == 0)
            {
                return;                                        //It was an insert-cancel
            }
            DataRow rPettycashoperation = DS.pettycashoperation.Rows[0];
            // Prendo la Rows[0] perchè alcune info sono in comune alle n-pettycashoperation, quindi evito di mostrare i messaggi all'utente n volte.
            object idpettycash = rPettycashoperation["idpettycash"];
            string filterpcash = "(idpettycash=" + QueryCreator.quotedstrvalue(idpettycash, false) + ")";

            DataRow[] PettyCash = DS.pettycashsetup.Select(filterpcash);
            if (PettyCash.Length == 0)
            {
                MessageBox.Show("Non è stata inserita la configuraz. del fondo economale per quest'anno");
                return;
            }
            DataRow rPettyCash      = PettyCash[0];
            object  idacc_pettycash = rPettyCash["idacc"];

            object idreg          = rPettycashoperation["idreg"];
            object idpettycashreg = rPettyCash["registrymanager"];

            EP_functions EP = new EP_functions(Meta.Dispatcher);

            if (!EP.attivo)
            {
                return;
            }

            object idaccmot_debit = rPettycashoperation["idaccmotive_debit"];
            object idacc_registry = EP.GetSupplierAccountForRegistry(null, idreg);

            if (idacc_registry == null || idacc_registry.ToString() == "")
            {
                MessageBox.Show("Non è stato configurato il conto di debito/credito opportuno");
                return;
            }

            if (idaccmot_debit == DBNull.Value)
            {
                MessageBox.Show("Non è stata impostata la causale di debito. Sarà usata una causale di debito standard.");
            }

            foreach (DataRow Curr in DS.pettycashoperation.Rows)
            {
                EP.GetEntryForDocument(Curr);

                object doc = "Op. Fondo Econ. " +
                             Curr["idpettycash"].ToString() + "/" +
                             Curr["yoperation"].ToString().Substring(2, 2) + "/" +
                             Curr["noperation"].ToString().PadLeft(6, '0');

                EP.SetEntry(Curr["description"], Curr["adate"],
                            doc, Curr["adate"], EP_functions.GetIdForDocument(Curr));

                EP.ClearDetails();

                string  idepcontext_debito = "PSPESED";
                decimal importo            = CfgFn.GetNoNullDecimal(Curr["amount"]);

                //Scrittura :  DEBITO	A	F.ECONOMALE	contesto PSPESED (P.SPESE DEBITO)
                object idacc_debit = idacc_registry;
                if (idaccmot_debit != DBNull.Value)
                {
                    DataRow[] ContiDebito = EP.GetAccMotiveDetails(idaccmot_debit.ToString());
                    if (ContiDebito.Length > 0)
                    {
                        idacc_debit = ContiDebito[0]["idacc"];
                    }
                }
                EP.EffettuaScrittura(idepcontext_debito, importo,
                                     idacc_debit.ToString(),
                                     idreg, Curr["idupb"], Curr["start"], Curr["stop"], Curr, idaccmot_debit);
                EP.EffettuaScrittura(idepcontext_debito, importo,
                                     idacc_pettycash.ToString(),
                                     idpettycashreg, Curr["idupb"], Curr["start"], Curr["stop"], Curr, idaccmot_debit);

                EP.RemoveEmptyDetails();

                MetaData MetaEntry = MetaData.GetMetaData(this, "entry");
                PostData Post      = MetaEntry.Get_PostData();

                Post.InitClass(EP.D, Meta.Conn);
                if (Post.DO_POST())
                {
                    EditEntry(Curr);
                }
                else
                {
                    EP.viewDetails(Meta);
                }
            }
        }
Esempio n. 46
0
 ///<summary>POST on /_async_search <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/async-search.html</para></summary>
 ///<param name = "body">The search definition using the Query DSL</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse Submit <TResponse>(PostData body, AsyncSearchSubmitRequestParameters requestParameters = null)
     where TResponse : class, IElasticsearchResponse, new() => DoRequest <TResponse>(POST, "_async_search", body, RequestParams(requestParameters));
		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IMemoryStreamFactory memoryStreamFactory)
			: this(method, path, data, global, (IRequestConfiguration)null, memoryStreamFactory)
		{ }
 public Task <TResponse> TranslateAsync <TResponse>(PostData body, TranslateSqlRequestParameters requestParameters = null, CancellationToken ctx = default)
     where TResponse : class, ITransportResponse, new() => DoRequestAsync <TResponse>(POST, "_sql/translate", ctx, body, RequestParams(requestParameters));
Esempio n. 49
0
 public async Task <ActionResult> BlockBlogpost(PostData data) => await BlockContent <Blogpost>(data);
 ///<summary>POST on /_sql/translate <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-translate.html</para></summary>
 ///<param name = "body">Specify the query in the `query` element.</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse Translate <TResponse>(PostData body, TranslateSqlRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(POST, "_sql/translate", body, RequestParams(requestParameters));
Esempio n. 51
0
 public async Task <ActionResult> BlockStory(PostData data) => await BlockContent <Story>(data);
Esempio n. 52
0
		/// <summary>
		/// Asynchronously edits an existing post.
		/// </summary>
		/// <remarks>
		/// See: http://www.tumblr.com/docs/en/api/v2#editing
		/// </remarks>
		/// <param name="blogName">
		/// The name of the blog where the post to edit is (must be one of the current user's blogs).
		/// </param>
		/// <param name="postId">
		/// The identifier of the post to edit.
		/// </param>
		/// <param name="postData">
		/// The data that represents the updated information for the post. See <see cref="PostData"/> for how
		/// to create various post types.
		/// </param>
		/// <returns>
		/// A <see cref="Task{T}"/> that can be used to track the operation. If the task succeeds, the <see cref="Task{T}.Result"/> will
		/// carry a <see cref="PostCreationInfo"/> instance. Otherwise <see cref="Task.Exception"/> will carry a <see cref="TumblrException"/>
		/// representing the error occurred during the call.
		/// </returns>
		/// <exception cref="ArgumentNullException">
		/// <list type="bullet">
		/// <item>
		///		<description>
		///			<paramref name="blogName"/> is <b>null</b>.
		///		</description>
		///	</item>
		///	<item>
		///		<description>
		///			<paramref name="postData"/> is <b>null</b>.
		///		</description>
		///	</item>
		/// </list>
		/// </exception>
		/// <exception cref="ArgumentException">
		/// <list type="bullet">
		/// <item>
		///		<description>
		///			<paramref name="blogName"/> is empty.
		///		</description>
		///	</item>
		///	<item>
		///		<description>
		///			<paramref name="postId"/> is less than 0.
		///		</description>
		///	</item>
		/// </list>
		/// </exception>
		/// <exception cref="InvalidOperationException">
		/// This <see cref="TumblrClient"/> instance does not have an OAuth token specified.
		/// </exception>
		public Task<PostCreationInfo> EditPostAsync(string blogName, long postId, PostData postData)
		{
			return EditPostAsync(blogName, postId, postData, CancellationToken.None);
		}
Esempio n. 53
0
 ///<summary>POST on /_text_structure/find_structure <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/find-structure.html</para></summary>
 ///<param name = "body">The contents of the file to be analyzed</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse FindStructure <TResponse>(PostData body, FindStructureRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(POST, "_text_structure/find_structure", body, RequestParams(requestParameters));
Esempio n. 54
0
		/// <summary>
		/// Asynchronously edits an existing post.
		/// </summary>
		/// <remarks>
		/// See: http://www.tumblr.com/docs/en/api/v2#editing
		/// </remarks>
		/// <param name="blogName">
		/// The name of the blog where the post to edit is (must be one of the current user's blogs).
		/// </param>
		/// <param name="postId">
		/// The identifier of the post to edit.
		/// </param>
		/// <param name="postData">
		/// The data that represents the updated information for the post. See <see cref="PostData"/> for how
		/// to create various post types.
		/// </param>
		/// <param name="cancellationToken">
		/// A <see cref="CancellationToken"/> that can be used to cancel the operation.
		/// </param>
		/// <returns>
		/// A <see cref="Task{T}"/> that can be used to track the operation. If the task succeeds, the <see cref="Task{T}.Result"/> will
		/// carry a <see cref="PostCreationInfo"/> instance. Otherwise <see cref="Task.Exception"/> will carry a <see cref="TumblrException"/>
		/// representing the error occurred during the call.
		/// </returns>
		/// <exception cref="ObjectDisposedException">
		/// The object has been disposed.
		/// </exception>
		/// <exception cref="ArgumentNullException">
		/// <list type="bullet">
		/// <item>
		///		<description>
		///			<paramref name="blogName"/> is <b>null</b>.
		///		</description>
		///	</item>
		///	<item>
		///		<description>
		///			<paramref name="postData"/> is <b>null</b>.
		///		</description>
		///	</item>
		/// </list>
		/// </exception>
		/// <exception cref="ArgumentException">
		/// <list type="bullet">
		/// <item>
		///		<description>
		///			<paramref name="blogName"/> is empty.
		///		</description>
		///	</item>
		///	<item>
		///		<description>
		///			<paramref name="postId"/> is less than 0.
		///		</description>
		///	</item>
		/// </list>
		/// </exception>
		/// <exception cref="InvalidOperationException">
		/// This <see cref="TumblrClient"/> instance does not have an OAuth token specified.
		/// </exception>
		public Task<PostCreationInfo> EditPostAsync(string blogName, long postId, PostData postData, CancellationToken cancellationToken)
		{
			if (disposed)
				throw new ObjectDisposedException("TumblrClient");

			if (blogName == null)
				throw new ArgumentNullException("blogName");

			if (blogName.Length == 0)
				throw new ArgumentException("Blog name cannot be empty.", "blogName");

			if (postId < 0)
				throw new ArgumentOutOfRangeException("postId", "Post ID must be greater or equal to zero.");

			if (postData == null)
				throw new ArgumentNullException("postData");

			if (OAuthToken == null)
				throw new InvalidOperationException("EditPostAsync method requires an OAuth token to be specified.");

			var parameters = postData.ToMethodParameterSet();
			parameters.Add("id", postId);

			return CallApiMethodAsync<PostCreationInfo>(
				new BlogMethod(blogName, "post/edit", OAuthToken, HttpMethod.Post, parameters),
				CancellationToken.None);
		}
Esempio n. 55
0
		private static async Task PostAssertAsync(PostData<object> postData, byte[] writes, bool storesBytes, IConnectionConfigurationValues settings)
		{
			using (var ms = new MemoryStream())
			{
				await postData.WriteAsync(ms, settings);
				var sentBytes = ms.ToArray();
				sentBytes.Should().Equal(writes);
				if (storesBytes)
					postData.WrittenBytes.Should().NotBeNull();
				else 
					postData.WrittenBytes.Should().BeNull();
			}
		}
Esempio n. 56
0
 public void MarkPostAsReadAsync(PostData post)
 {
     throw new NotImplementedException();
 }
        /**
         * Indexing a single instance of this POCO, either synchronously or asynchronously, is as simple as
         */
        public async Task Indexing()
        {
            var person = new Person
            {
                FirstName = "Martijn",
                LastName  = "Laarman"
            };

            var indexResponse = lowlevelClient.Index <BytesResponse>("people", "person", "1", PostData.Serializable(person)); //<1> synchronous method that returns an `IIndexResponse`

            byte[] responseBytes = indexResponse.Body;

            var asyncIndexResponse = await lowlevelClient.IndexAsync <StringResponse>("people", "person", "1", PostData.Serializable(person)); //<2> asynchronous method that returns a `Task<IIndexResponse>` that can be awaited

            string responseString = asyncIndexResponse.Body;
        }
 ///<summary>POST on /_ingest/pipeline/{id}/_simulate <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/simulate-pipeline-api.html</para></summary>
 ///<param name = "id">Pipeline ID</param>
 ///<param name = "body">The simulate definition</param>
 ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param>
 public TResponse SimulatePipeline <TResponse>(string id, PostData body, SimulatePipelineRequestParameters requestParameters = null)
     where TResponse : class, ITransportResponse, new() => DoRequest <TResponse>(POST, Url($"_ingest/pipeline/{id:id}/_simulate"), body, RequestParams(requestParameters));
Esempio n. 59
0
 public void BuildPost(PostData post) { _page.AddPost(post); }
        /**
         * NOTE: All available methods within Elasticsearch.Net are exposed as both synchronous and asynchronous versions,
         * with the latter using the idiomatic *Async suffix for the method name.
         *
         * Both index requests will index the document to the endpoint `/people/person/1`.
         *
         * An https://msdn.microsoft.com/en-us/library/bb397696.aspx[anonymous type] can also be used to represent the document to index
         */
        public async Task IndexingWithAnonymousType()
        {
            var person = new
            {
                FirstName = "Martijn",
                LastName  = "Laarman"
            };

            var indexResponse = await lowlevelClient.IndexAsync <BytesResponse>("people", "person", "1", PostData.Serializable(person));

            byte[] responseStream = indexResponse.Body;
        }