Else is not working in my payment check program C# - c#

There are only 3 situations for result.
1- Paid
2- waiting for payment
3- blocked
(Think like this is a bank program)
So when I run the code, always says true. Never false. I want it work normally. Need help.
[HttpPut(Name = "OdemeYapildiSosyalOdeme")]
public ActionResult<bool> Put(string tckn, int odemeNo)
{
try
{
DbOperations dbOperations = new DbOperations();
var parameters = new List<SqlParameter>();
var param1 = new SqlParameter("TCKN", tckn);
parameters.Add(param1);
var param2 = new SqlParameter("ODEMENO", odemeNo);
parameters.Add(param2);
if (odemeKd == 0)
{
dbOperations.ExecuteNonQuery("ODEME_YAP", parameters);
return Ok(true);
}
else return Ok(false);
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SosyalYardimApi.Operations;
using System.Data.SqlClient;
using System.Data;
namespace SosyalYardimApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SosyalOdemeController : ControllerBase
{
private int odemeKd;
private object sosyalOdemeleri;
public bool Boolean { get; private set; }
[HttpGet(Name = "SorgulaSosyalOdeme ")]
public ActionResult<List<SosyalOdeme>> Get(string tckn)
{
try
{
//Yapılacak: Tckn 11 karakterli mi kontrolü yapılacak değilse dönüş olacak,
//return Ok("TCKN Hatalı");
if (tckn.Length == 11)
{
List<SosyalOdeme> sosyalOdemeleri = new List<SosyalOdeme>();
DbOperations dbOperations = new DbOperations();
var parameters = new List<SqlParameter>();
var param = new SqlParameter("TCKN", tckn);
parameters.Add(param);
DataTable dtSonuc = dbOperations.GetData("MUSTERI_SELECT", parameters);
for (int i = 0; i < dtSonuc.Rows.Count; i++)
{
SosyalOdeme sosyalOdeme = new SosyalOdeme();
sosyalOdeme.OdemeNo = Convert.ToInt32(dtSonuc.Rows[i]["ODEMENO"]);
sosyalOdeme.Tckn = Convert.ToString(dtSonuc.Rows[i]["TCKIMLIKNO"]);
sosyalOdeme.Adi = dtSonuc.Rows[i]["MUSTERIAD"].ToString();
sosyalOdeme.SoyAdi = dtSonuc.Rows[i]["MUSTERISOYAD"].ToString();
sosyalOdeme.OdemeKd = Convert.ToInt32(dtSonuc.Rows[i]["ODEME_KD"]);
sosyalOdeme.OdenecekTtr = Convert.ToDecimal(dtSonuc.Rows[i]["ODENECEK_TTR"]);
if (dtSonuc.Rows[i]["ODEME_TR"] != DBNull.Value)
sosyalOdeme.OdenecekDt = Convert.ToDateTime(dtSonuc.Rows[i]["ODEME_TR"]);
sosyalOdemeleri.Add(sosyalOdeme);
}
return Ok(sosyalOdemeleri);
}
else return Ok("hatalı tckn girdiniz");
}
catch (Exception)
{
throw;
}
}
[HttpPut(Name = "OdemeYapildiSosyalOdeme")]
public ActionResult<bool> Put(string tckn, int odemeNo)
{
try
{
//Yapılacak: Odeme no ve tckn e ait ödemeyi bul
//Ödemenin durum kontrolü yap =0 ise
//eğer kontrolden başarılı geçmez ise false dön işlemi kes
DbOperations dbOperations = new DbOperations();
var parameters = new List<SqlParameter>();
var param1 = new SqlParameter("TCKN", tckn);
parameters.Add(param1);
var param2 = new SqlParameter("ODEMENO", odemeNo);
parameters.Add(param2);
if (odemeKd == 0)
{
dbOperations.ExecuteNonQuery("ODEME_YAP", parameters);
return Ok(true);
}
else return Ok(false);
}
catch (Exception)
{
throw;
}
}
}
}
So that's the whole code for odemeKd.
We have one more big code but there is no definition in the other one.
So i hope you can find the answer of this code.
Thank you so much.

Related

C# System.IndexOutOfRangeException: Index was outside the bounds of the array. But when I check it manualy it is within bounds of the array

My problem is probably stupid, but I can't figure out the solution by myself, so I hope someone here can help me.
I am trying to make a dll file for hosting a server on the localhost. I thought I did everything right, but I receive this error:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at minihttpc.Requests.HttpRequest.ParseHeaders(String[] requestLine) in C:\Users\deqnb\OneDrive\minihttpc\minihttpc\Requests\HttpRequest.cs:line 87
at minihttpc.Requests.HttpRequest.ParseRequest(String requestString) in C:\Users\deqnb\OneDrive\minihttpc\minihttpc\Requests\HttpRequest.cs:line 44
at minihttpc.Requests.HttpRequest..ctor(String requestString) in C:\Users\deqnb\OneDrive\minihttpc\minihttpc\Requests\HttpRequest.cs:line 21
at MiniServerHTTP.WebServer.ConnectionHandler.ReadRequest() in C:\Users\deqnb\OneDrive\minihttpc\MiniServerHTTP.WebServer\ConnectionHandler.cs:line 80
at MiniServerHTTP.WebServer.ConnectionHandler.ProcessRequest() in C:\Users\deqnb\OneDrive\minihttpc\MiniServerHTTP.WebServer\ConnectionHandler.cs:line 28
Here is my code - HttpRequest.cs:
using minihttpc.Common.CoreValidator;
using minihttpc.Common.GlobalConstants;
using minihttpc.Headers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace minihttpc.Requests
{
public class HttpRequest:IHttpRequest
{
public HttpRequest(string requestString)
{
CoreValidator.ThrowIfNullOrEmpty(requestString, nameof(requestString));
this.FormData = new Dictionary<string, object>();
this.QueryData = new Dictionary<string, object>();
this.Headers = new HttpHeaderCollection();
this.ParseRequest(requestString);
}
public string Path { get; private set; }
public string Url { get; private set; }
public Dictionary<string,object>FormData { get; }
public Dictionary<string, object> QueryData { get; }
public IHttpHeaderCollection Headers { get; private set; }
public HttpRequestMethod RequestMethod { get; private set; }
public void ParseRequest(string requestString)
{
string[] splitRequestContent = requestString.Split(new[] {
GlobalConstants.HttpNewLine }, StringSplitOptions.None);
string[] requestLine = splitRequestContent[0].Trim().Split(new[]
{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (!this.IsValidReqiestLine(requestLine))
{
throw new BadRequestException();
}
this.ParseRequestMethod(requestLine);
this.ParseRequestUrl(requestLine);
this.ParseRequestPath();
this.ParseHeaders(splitRequestContent.Skip(1).ToArray());
//this.ParseRequestQueryParameters();
this.ParseRequestParameters(splitRequestContent[splitRequestContent.Length - 1]);
}
bool IsValidRequestLine(string[] requestLine)
{
if (requestLine.Count() != 3 && requestLine[2] != "HTTP/1.1")
{
return false;
}
else
{
return true;
}
}
void ParseRequestMethod(string[] requestLine)
{
switch (requestLine[0])
{
case "GET": RequestMethod = HttpRequestMethod.Get; break;
case "POST": RequestMethod = HttpRequestMethod.Post; break;
case "PUT": RequestMethod = HttpRequestMethod.Put; break;
case "DELETE": RequestMethod = HttpRequestMethod.Delete; break;
}
}
void ParseRequestUrl(string [] requestLine)
{
this.Url = requestLine[1];
}
void ParseRequestPath()
{
this.Path = this.Url.Split("?").Take(1).First().ToString();
}
void ParseHeaders(string [] requestLine)
{
foreach(var line in requestLine)
{
Console.WriteLine(line); //a lot of info about the req
if (line == GlobalConstants.HttpNewLine) break;
string[] header = line.Split(' ').ToArray();
//Console.WriteLine(header[1]);
Headers.AddHeader(new HttpHeader(header[0],
header[1]));//seems fine //line 87
}
if (Headers.ContainsHeader("host"))
{
throw new BadRequestException();
}
}
void ParseRequestQueryParameters()
{
if (!(this.Url.Split('?').Length > 1)) return;
this.Url.Split('?', '#')[1].Split('&').Select(plainQueryParameter =>
plainQueryParameter.Split());//not finished !!!!
}
void ParseFormDataParameters(string formData)
{
if (!string.IsNullOrEmpty(formData))
{
formData.Split('&').Select(plainQueryParameter =>
plainQueryParameter.Split('=')).ToList().ForEach(queryParameterKeyValue =>
this.FormData.Add(queryParameterKeyValue[0],
queryParameterKeyValue[1]));
}
}
void ParseRequestParameters(string formData)//not being called
{
ParseRequestQueryParameters();
ParseFormDataParameters(formData);
}
}
}
ConnectionHandler.cs:
using minihttpc.Common.CoreValidator;
using minihttpc.Requests;
using MiniServerHTTP.WebServer.Results;
using MiniServerHTTP.WebServer.Routing;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MiniServerHTTP.WebServer
{
public class ConnectionHandler
{
private readonly Socket client;
private readonly IServerRoutingTable table;
public ConnectionHandler(Socket client, IServerRoutingTable table)
{
CoreValidator.ThrowIfNull(client, nameof(client));
CoreValidator.ThrowIfNull(client, nameof(client));
this.client = client;
this.table = table;
}
public async Task ProcessRequest()
{
try
{
var httpRequest = await this.ReadRequest();
if (httpRequest != null)
{
Console.WriteLine($"Processing: {httpRequest.RequestMethod} {httpRequest.Path}...");
var httpResponse = this.HandleRequest((IHttpRequest)httpRequest);
this.ProcessResponse(httpResponse);
}
}
catch (BadRequestException e)//400
{
this.ProcessResponse(new TextResult(e.ToString(),
HttpResponseStatusCode.BadRequest));
}
catch (Exception e)//500
{
this.ProcessResponse(new TextResult(e.ToString(),
HttpResponseStatusCode.InternalServerError));
}
this.client.Shutdown(SocketShutdown.Both);
}
private async Task ProcessResponse(IHttpResponse httpResponse)
{
byte[] byteSegments = httpResponse.GetBytes();
await this.client.SendAsync(byteSegments, SocketFlags.None);
}
private IHttpResponse HandleRequest(IHttpRequest httpRequest)
{
if(!this.table.Contains(httpRequest.RequestMethod,
httpRequest.Path))
{
return new TextResult($"Route with method {httpRequest.RequestMethod} and path \"{httpRequest.Path}\"not found.",
HttpResponseStatusCode.NotFound);
}
return this.table.Get(httpRequest.RequestMethod,
httpRequest.Path).Invoke(httpRequest);
}
private async Task<HttpRequest> ReadRequest()
{
var result = new StringBuilder();
var data = new ArraySegment<byte>(new byte[1024]);
while (true)
{
int numberOfBytes = await this.client.ReceiveAsync(data.Array, SocketFlags.None);
if (numberOfBytes == 0) break;
var bytesAsString = Encoding.UTF8.GetString(data.Array, 0,
numberOfBytes);
result.Append(bytesAsString);
if (numberOfBytes < 1023) break;
}
if (result.Length == 0)
{
return null;
}
return new HttpRequest(result.ToString());
}
}
}
When I check the parameters manually and variables in minihttpc.Requests.HttpRequest.ParseHeaders(), everything seems fine. I can't get where the problem is.
string[] header = line.Split(' ').ToArray();
Headers.AddHeader(new HttpHeader(header[0], header[1]));
I can pretty much guarantee you're running into a line that doesn't have a space in it. Maybe there's a line that's empty, for example. That wouldn't be obvious from the Console.WriteLine() that you're doing, because empty lines are kind of invisible.

How I can start multiple download async in c#

my problem is the following: I just want to run x requests at the same time depending on the user.
Well, it seems to work fine when the MaxConcurrentDownloads variable is equal to 1, but when I increase it, say 10: I have to wait for the 10taches to finish for it to execute so that Console.WriteLine as to write, when it's supposed to run asynchronously, right?
Can you help me? Here is a minimalist version of my "problem" (Also I want to specify that I have no compiler or syntax errors)
main.c
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace test_client
{
class Program
{
private static client cli = new client();
private static readonly string PATH = #Directory.GetCurrentDirectory();
private static int concurrency = 100;
private static async Task<bool> MakeJOB(int pos)
{
return await cli.NewRequest<bool>((HttpClient client)=>
{
try
{
HttpClientHandler handler = null;
if (cli.handler != null)
handler = cli.GethandlerIndexed(pos);
client = new HttpClient(handler);
cli.AssignDefaultHeaders(client);
using (HttpResponseMessage response = client.GetAsync("https://api.my-ip.io/ip.txt").Result)
using (HttpContent content = response.Content)
Console.WriteLine(content.ReadAsStringAsync().Result + " / " + Task.CurrentId);
return true;
}
catch { /* exception .. */ return false; }
});
}
static void Main(string[] args)
{
ServicePointManager.DefaultConnectionLimit = 100;
MainAsync(args).GetAwaiter().GetResult();
Console.ReadLine();
}
static async Task MainAsync(string[] args)
{
cli.SetConcurrentDownloads(concurrency);
var t = new Task[concurrency];
int pos = 0;
for (int i = 0; i < t.Length; i++, pos++)
t[i] = MakeJOB(pos++);
await Task.WhenAll(t);
}
}
}
client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Collections.Concurrent;
using System.Threading;
namespace test_client
{
public class client
{
private readonly ConcurrentDictionary<string, HttpClient> Clients;
public SemaphoreSlim Locker;
private CancellationTokenSource TokenSource = new CancellationTokenSource();
public HttpClientHandler[] handler { get; set; }
public string[] address { get; set; }
public string[] port { get; set; }
public string[] username { get; set; }
public string[] password { get; set; }
public int MaxConcurrentDownloads { get; set; }
private void initializeHandler(string address = "", string port = "", string user = "", string pass = "")
{
initializeHandler(new string[] { string.Concat(address, ":", port, ":", user, ":", pass) });
}
private void initializeHandler(string[] proxies_client)
{
if (proxies_client == null || proxies_client.Length == 0)
return;
this.address = new string[proxies_client.Length];
this.port = new string[proxies_client.Length];
this.username = new string[proxies_client.Length];
this.password = new string[proxies_client.Length];
for (int i = 0; i < proxies_client.Length; i++)
{
var split = proxies_client[i].Split(new char[] { ':' });
this.address[i] = split[0] != "" ? split[0] : "";
this.port[i] = split[1] != "" ? split[1] : "";
this.username[i] = split[2] != "" ? split[2] : "";
this.password[i] = split[3] != "" ? split[3] : "";
}
var proxies = new WebProxy[proxies_client.Length];
NetworkCredential[] credential = new NetworkCredential[proxies_client.Length];
for (int i = 0; i < proxies_client.Length; i++)
{
if (this.username[i] != "")
credential[i] = new NetworkCredential(this.username[i], this.password[i]);
else
credential[i] = CredentialCache.DefaultNetworkCredentials;
}
const string protocol = "http://";
for (int i = 0; i < proxies.Length; i++)
{
if (this.address[i] != "")
{
var uri = proxies_client[i].Split(new char[] { ':' });
if (!uri[0].Contains(protocol))
uri[0] = string.Concat(protocol, uri[0]);
proxies[i] = new WebProxy()
{
Address = new Uri(string.Concat(uri[0], ":", uri[1])),
Credentials = credential[i],
};
}
};
this.handler = new HttpClientHandler[proxies.Length];
for (int i = 0; i < proxies.Length; i++)
{
if (proxies[i].Address.AbsoluteUri != "")
this.handler[i] = new HttpClientHandler() { Proxy = proxies[i] };
else
this.handler[i] = new HttpClientHandler();
}
}
public HttpClientHandler GethandlerIndexed(int index)
{
return (this.handler[index % this.handler.Length]);
}
public void SetConcurrentDownloads(int nb = 1)
{
Locker = new SemaphoreSlim(nb, nb);
}
public client(string[] proxies = null)
{
Clients = new ConcurrentDictionary<string, HttpClient>();
if (Locker is null)
Locker = new SemaphoreSlim(1, 1);
if (proxies != null)
initializeHandler(proxies);
}
private async Task<HttpClient> CreateClient(string Name, bool persistent, CancellationToken token)
{
if (Clients.ContainsKey(Name))
return Clients[Name];
HttpClient newClient = new HttpClient();
if (persistent)
{
while (Clients.TryAdd(Name, newClient) is false)
{
token.ThrowIfCancellationRequested();
await Task.Delay(1, token);
}
}
return newClient;
}
public async Task<T> NewRequest<T>(Func<HttpClient, T> Expression, int? MaxTimeout = 2000, string Id = null)
{
await Locker.WaitAsync(MaxTimeout ?? 2000, TokenSource.Token);
bool persistent = true;
if (Id is null)
{
persistent = false;
Id = string.Empty;
}
try
{
HttpClient client = await CreateClient(Id, persistent, TokenSource.Token);
T result = await Task.Run<T>(() => Expression(client), TokenSource.Token);
if (persistent is false)
client?.Dispose();
return result;
}
finally
{
Locker.Release();
}
}
public void AssignDefaultHeaders(HttpClient client)
{
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
//client.Timeout = TimeSpan.FromSeconds(3);
}
public async Task Cancel(string Name)
{
if (Clients.ContainsKey(Name))
{
CancellationToken token = TokenSource.Token;
HttpClient foundClient;
while (Clients.TryGetValue(Name, out foundClient) is false)
{
token.ThrowIfCancellationRequested();
await Task.Delay(1, token);
}
if (foundClient != null)
{
foundClient?.Dispose();
}
}
}
public void ForceCancelAll()
{
TokenSource?.Cancel();
TokenSource?.Dispose();
TokenSource = new CancellationTokenSource();
foreach (var item in Clients)
{
item.Value?.Dispose();
}
Clients.Clear();
}
}
}
One thing I spotted in a quick skim: Your line in main.cs::Program.MakeJOB:
using (HttpResponseMessage response = client.GetAsync("https://api.my-ip.io/ip.txt").Result)
should instead read
using (HttpResponseMessage response = await client.GetAsync("https://api.my-ip.io/ip.txt"))
This may not be your only issue, but by not awaiting the GetAsync method, you are effectively blocking on the request rather than yielding control back to the caller so that it can, for instance, context switch between tasks or queue up other tasks.
Same goes for
Console.WriteLine(content.ReadAsStringAsync().Result + " / " + Task.CurrentId);
which should be
Console.WriteLine((await content.ReadAsStringAsync()) + " / " + Task.CurrentId);
Although that one is not likely to block for a significant amount of time.

Try to call Clients.Caller but it's not working

Hello I am trying to catch messages from database and transfer to caller but when I used Clients.Caller method then it pass me error like
Using a Hub instance not created by the HubPipeline is unsupported
If I am using
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.receiver(respose);
then it replying nothing. So please help me to solve out this question.
and I am using below code:
public async Task GetAllMessages(int roomid, int fromuserId, int touserId, int index, int pageSize, int broadcastid = 0)
{
ResponseModel respose = new ResponseModel();
try
{
var model = new MessageDetailModel
{
Index = index,
PageSize = pageSize,
FromUserId = fromuserId,
ToUserId = touserId,
ChatRoomId = roomid,
BroadCastId = broadcastid
};
MesaageModel totalmessages = new MesaageModel();
List<RecentMessage> messages = new List<RecentMessage>();
var usermessages = await _userService.GetAllMessages(model);
messages.AddRange(usermessages);
foreach (var message in messages)
{
model.BroadCastMessageId = model.BroadCastId == 0 ? 0 : message.BroadCastMessageId;
model.ChatRoomMessageId = model.BroadCastId == 0 ? message.ChatRoomMessageId : 0;
List<UserDetail> userofseenby = new List<UserDetail>();
var users = await _userService.GetMessageSeenBy(model);
userofseenby.AddRange(users);
message.SeenBy = userofseenby;
}
//totalmessages.Messages.AddRange(messages);
totalmessages.Messages = messages;
totalmessages.UnseenMessageCount = await _userService.GetUnSeenCount(messages.FirstOrDefault().ChatRoomId, fromuserId);
if (messages.FirstOrDefault().IsBroadCast == true)
totalmessages.Users = (List<UserDetail>)await _userService.GetUsersByBroadCastId(messages.FirstOrDefault().BroadCastId);
else if (messages.FirstOrDefault().IsGroup == true)
totalmessages.Users = (List<UserDetail>)await _userService.GetUsersByChatRoomId((int)messages.FirstOrDefault().ChatRoomId);
respose = ResponseHelper.SuccessResponse("onAllMessagesReceived", totalmessages);
Clients.Caller.receiver(respose); // Error catch here
}
catch (Exception ex)
{
respose.ActionCommand = "onAllMessagesReceived";
respose = ResponseHelper.ErrorResponse(respose.ActionCommand, ex.ToString());
Clients.Caller.receiver(respose);
}
}
And Constructors of class is below :
public ChatHub()
{
_userService = new UserBusinessLogic();
_chatterService = new ChatterBusinessLogic();
}
public ChatHub(IChatterBusinessLogic chatterService, IUserBusinessLogic userService)
{
_chatterService = chatterService;
_userService = userService;
}
And Controller constructor are like this :
public ChatterController()
{
_userService = new UserBusinessLogic();
_chatterService = new ChatterBusinessLogic();
}
public ChatterController(IChatterBusinessLogic chatterService, IUserBusinessLogic userService)
{
_chatterService = chatterService;
_userService = userService;
}

Converting Query Expression into Linq C#

I'm having trouble converting a Query Expression found here: http://www.oak3.org/crm/workflow-activity-checking-duplicate-instances/
into a linq query. To put it simply, the goal is if two workflows get triggered at the same time, only let one go through sorted by most recent. Currently my linq version will sometimes cancel a workflow even if it is the only one running. I know I need to utilize the input parameter somehow (to tell it what workflow to compare to), and I'm sure there could be more issues. Any help is greatly appreciated.
[Input("Current workflow")]
[ReferenceTarget("workflow")]
public InArgument<EntityReference> workflowReferenceInput { get; set; }
[Output("Is first workflow")]
public OutArgument<Boolean> isFirstWorkflow { get; set; }
protected override void Execute(CodeActivityContext executionContext)
{
ITracingService tracer = executionContext.GetExtension<ITracingService>();
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
Entity entity = (Entity)context.InputParameters["Target"];
isFirstWorkflow.Set(executionContext, false);
var wfReference = workflowReferenceInput.Get(executionContext);
var wfEntity = service.Retrieve("workflow", wfReference.Id, new ColumnSet ( "name" ));
ConditionExpression ce1 = new ConditionExpression();
ce1.AttributeName = "statuscode";
ce1.Operator = ConditionOperator.In;
ce1.Values.Add(0);
ce1.Values.Add(10);
ce1.Values.Add(20);
ce1.Values.Add(21);
ce1.Values.Add(22);
FilterExpression fe1 = new FilterExpression();
fe1.Conditions.Add(ce1);
QueryExpression qe = new QueryExpression();
qe.EntityName = AsyncOperation.EntityLogicalName;
qe.ColumnSet = new ColumnSet();
qe.Criteria = new FilterExpression();
qe.Criteria.AddFilter(fe1);
var childFilter = qe.Criteria.AddFilter(LogicalOperator.And);
childFilter.AddCondition("operationtype", ConditionOperator.Equal, 10);
childFilter.AddCondition("name", ConditionOperator.Equal, wfEntity["name"]);
LinkEntity link = new LinkEntity
{
LinkFromEntityName = AsyncOperation.EntityLogicalName,
LinkToEntityName = Quote.EntityLogicalName,
LinkFromAttributeName = "regardingobjectid",
LinkToAttributeName = "quoteid"
};
link.LinkCriteria.AddCondition("quoteid", ConditionOperator.Equal, context.PrimaryEntityId.ToString());
DataCollection<Entity> result = service.RetrieveMultiple(qe).Entities;
var list = result.ToList().OrderBy(c => c.Id);
for (var i = 0; i < list.Count(); i++)
{
var item = list.ElementAt(i);
if(item.Id == context.OperationId && i == 0)
{
isFirstWorkflow.Set(executionContext, true);
}
}
}
catch (Exception e)
{
throw new InvalidPluginExecutionException(e.Message);
}
}
into this:
public class WorkflowChecker: CodeActivity
{
[Input("Current workflow")]
[ReferenceTarget("workflow")]
public InArgument<EntityReference> workflowReferenceInput { get; set; }
[Output("Is first workflow")] public OutArgument<Boolean> isFirstWorkflow { get; set; }
protected override void Execute(CodeActivityContext executionContext)
{
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
try
{
var ok = WorkflowChecker(context.PrimaryEntityId, context.OperationId);
isFirstWorkflow.Set(executionContext, ok);
}
catch (Exception e)
{
throw new InvalidPluginExecutionException(e.Message);
}
}
}
which calls:
public static bool WorkflowChecker(Guid workflowContextId,
Guid asyncOperationId)
{
var someReturnValue = false;
var listOfWorkflowIds = new List<Guid>();
try
{
var query = from async in AsyncOperationSet
join b in BSet on async.RegardingObjectId.Id equals b.Id
where b.Id.Equals(workflowContextId)
&& (async.StateCode.Equals(0)
|| async.StateCode.Equals(1)
|| async.StateCode.Equals(2))
select new {async.AsyncOperationId};
foreach (var x in query)
{
if (x.AsyncOperationId != Guid.Empty)
{
listOfWorkflowIds.Add(x.AsyncOperationId.Value);
}
}
listOfWorkflowIds.Sort();
if (listOfWorkflowIds.First() == asyncOperationId)
{
someReturnValue = true;
}
}
catch (Exception e)
{
Console.WriteLine("Error in Workflow Checker: " + e);
}
return someReturnValue;
}
I've added the following lines to the workflow library then passed the parameter into the call to compare by name and so far it appears to be working successfully:
var wfReference = workflowReferenceInput.Get(executionContext);
var wfEntity = service.Retrieve("workflow", wfReference.Id, new ColumnSet("name"));
var test = wfEntity["name"];

How to make a request asynchronously in c# (xamarin)?

I used to work with browser-based applications. for example Angular simple repository.
function getSomeData(params) {
...
return $http({
url: conf.urlDev + 'some/rest-url',
method: "GET",
params: params,
cache: true
}).then(getDataComplete);
function getDataComplete(response) {
return response.data;
}
}
How it will look the same in c# (XAMARIN for example)?
i try :
public class BaseClient
{
protected Http _client = null;
protected string _urlObj;
protected string _basePath;
public BaseClient ()
{
_client = new Http(new HttpClientHandler());
}
public string Path
{
set
{
_urlObj = value;
}
}
public async Task<Result<IList<T>>>getList<T>(Dictionary<string,object> parametrs = null)
{
if (parametrs != null)
{
foreach(KeyValuePair<string, object> keyValue in parametrs)
{
_urlObj = _urlObj.SetQueryParam(keyValue.Key, keyValue.Value);
}
}
var response = await _client.GetAsync(_urlObj.ToString());
if (response.IsSuccessStatusCode)
{
return new Result<IList<T>>()
{
Success = true,
Value = JsonConvert.DeserializeObject<IList<T>>(await response.Content.ReadAsStringAsync())
};
}
else
{
var error = new Result<IList<T>>()
{
Error = response.StatusCode.ToString(),
Message = response.ReasonPhrase,
Success = false
};
return error;
}
}
in my service:
public async Task<IList<News>> GetAllNewsByParams(DateTime from,
string orderBy = "-published",
DateTime to = new DateTime(),
int page = 1, int category = 0)
{
_client.Path = _config.NewsPath;
var dict = new Dictionary<string, object> {
{"from", from.ToString("s")},
{"order_by", orderBy.ToString()},
{"to", to.ToString("s")},
{"page", page.ToString()}
};
if (category != 0)
{
dict.Add("category", category.ToString());
}
var res = await _client.getList<News>(dict);
return res.Value;
}
and im ny viewmodel
foreach (var item in await _newsService.GetAllNewsByParams(
_To,
_OrderBy,
_From, _Page,
selectedTag == null ? _SeletedNewsTagId : selectedTag.Id))
{
NewsList.Add(item);
}
Is his query executed synchronously ?
How do I make it an asynchronous?
First of all I would really encourage you to use RestSharp, it really simplifies making HTTP requests and deserialise them. Add a RestSharp nuget package to your project. Here is how your code will look like using RestSharp.
public class BaseClient
{
protected IRestClient _client = null;
protected string _urlObj;
protected string _basePath;
public BaseClient()
{
_client = new RestClient();
}
public async Task<Result<IList<T>>> GetList<T>(string path, Dictionary<string, object> parametrs = null)
{
var request = new RestRequest(path, Method.GET);
if (parametrs != null)
{
foreach (var keyValue in parametrs)
{
request.AddQueryParameter(keyValue.Key, keyValue.Value);
}
}
var response = await _client.Execute<List<T>>(request);
if (response.IsSuccess)
{
return new Result<IList<T>>()
{
Success = true,
Value = response.Data
};
}
else
{
var error = new Result<IList<T>>()
{
Error = response.StatusCode.ToString(),
Message = response.StatusDescription,
Success = false
};
return error;
}
}
}
In your service
public async Task<IList<News>> GetAllNewsByParams(DateTime from,
string orderBy = "-published",
DateTime to = new DateTime(),
int page = 1, int category = 0)
{
var dict = new Dictionary<string, object> {
{"from", from.ToString("s")},
{"order_by", orderBy.ToString()},
{"to", to.ToString("s")},
{"page", page.ToString()}
};
if (category != 0)
{
dict.Add("category", category.ToString());
}
var res = await _client.GetList<News>(_config.NewsPath, dict);
return res.Value;
}
And in your viewmodel
var news = await _newsService.GetAllNewsByParams(
_To,
_OrderBy,
_From, _Page,
selectedTag == null ? _SeletedNewsTagId : selectedTag.Id);
foreach (var item in news)
{
NewsList.Add(item);
}
This will be 100% asynchronous.

Categories

Resources