What other options are there in IClientProxy.SendAsync string method parameter? - c#

I'm studying azure signal R management sdk and based on the sample it only passes Target to the method's string parameter. I wonder what other option's there are?
private const string Target = "Target";
switch (command)
{
case "broadcast":
return _hubContext.Clients.All.SendAsync(Target, message);
case "user":
var userId = receiver;
return _hubContext.Clients.User(userId).SendAsync(Target, message);
case "users":
var userIds = receiver.Split(',');
return _hubContext.Clients.Users(userIds).SendAsync(Target, message);
case "group":
var groupName = receiver;
return _hubContext.Clients.Group(groupName).SendAsync(Target, message);
case "groups":
var groupNames = receiver.Split(',');
return _hubContext.Clients.Groups(groupNames).SendAsync(Target, message);
default:
Console.WriteLine($"Can't recognize command {command}");
return Task.CompletedTask;
}

Related

Creating a magic 8 ball program c#

I need help with a homework I have in school. These are the requirements from my teacher.
Program requirements:
Accept user input of a question.
Output a result based upon a real "magic 8-ball" (do not add any of your own)
use a switch statement
Create a Method with the following signature:
public static string responses ()
All user input and output should be done in your main method.
This is my code and I have a problem with returning the value and Visual Studio highlights the command break and reports an CS0162 Unreachable code detected.
using System;
public class Magic8Ball
{
public static void Main(string[] args)
{
Console.WriteLine("Ask you question to the Magic 8 Ball: ");
Console.ReadLine();
string response;
response = responses(response);
Console.WriteLine(response);
}
public static string responses(string response)
{
string affirmativeResponse1 = "It is certain.";
string affirmativeResponse2 = "It is decidedly so.";
string affirmativeResponse3 = "Without a doubt.";
string affirmativeResponse4 = "Yes definitely.";
string affirmativeResponse5 = "You may rely on it.";
string affirmativeResponse6 = "As I see it, yes.";
string affirmativeResponse7 = "Most likely.";
string affirmativeResponse8 = "Outlook good.";
string affirmativeResponse9 = "Yes.";
string affirmativeResponse10 = "Signs point to yes.";
string nonCommittalResponse1 = "Reply hazy, try again.";
string nonCommittalResponse2 = "Ask again later.";
string nonCommittalResponse3 = "Better not tell you now.";
string nonCommittalResponse4 = "Cannot predict now.";
string nonCommittalResponse5 = "Concentrate and ask again.";
string negativeResponse1 = "Don't count on it.";
string negativeResponse2 = "My reply is no.";
string negativeResponse3 = "My sources say no.";
string negativeResponse4 = "Outlook not so good.";
string negativeResponse5 = "Very doubtful.";
int numberOfResponse;
Random var = new Random();
numberOfResponse = var.Next(20);
switch (numberOfResponse)
{
case 0:
response = affirmativeResponse1;
return response;
break;
case 1:
response = affirmativeResponse2;
return response;
break;
case 2:
response = affirmativeResponse3;
return response;
break;
case 3:
response = affirmativeResponse4;
return response;
break;
case 4:
response = affirmativeResponse5;
return response;
break;
case 5:
response = affirmativeResponse6;
return response;
break;
case 6:
response = affirmativeResponse7;
return response;
break;
case 7:
response = affirmativeResponse8;
return response;
break;
case 8:
response = affirmativeResponse9;
return response;
break;
case 9:
response = affirmativeResponse10;
return response;
break;
case 10:
response = nonCommittalResponse1;
return response;
break;
case 11:
response = nonCommittalResponse2;
return response;
break;
case 12:
response = nonCommittalResponse3;
return response;
break;
case 13:
response = nonCommittalResponse4;
return response;
break;
case 14:
response = nonCommittalResponse5;
return response;
break;
case 15:
response = negativeResponse1;
return response;
break;
case 16:
response = negativeResponse2;
return response;
break;
case 17:
response = negativeResponse3;
return response;
break;
case 18:
response = negativeResponse4;
return response;
break;
case 19:
response = negativeResponse5;
return response;
break;
}
}
}
the "return" keyword pretty much ends the method so you don't really need to add the "break;" in this instance. Also you need to a default condition when using switch statements and lastly your string response needs to be set to the console.readline.
{
public static void Main(string[] args)
{
Console.WriteLine("Ask you question to the Magic 8 Ball: ");
string response = Console.ReadLine();
response = Responses(response);
Console.WriteLine(response);
}
public static string Responses(string response)
{
string affirmativeResponse1 = "It is certain.";
string affirmativeResponse2 = "It is decidedly so.";
string affirmativeResponse3 = "Without a doubt.";
string affirmativeResponse4 = "Yes definitely.";
string affirmativeResponse5 = "You may rely on it.";
string affirmativeResponse6 = "As I see it, yes.";
string affirmativeResponse7 = "Most likely.";
string affirmativeResponse8 = "Outlook good.";
string affirmativeResponse9 = "Yes.";
string affirmativeResponse10 = "Signs point to yes.";
string nonCommittalResponse1 = "Reply hazy, try again.";
string nonCommittalResponse2 = "Ask again later.";
string nonCommittalResponse3 = "Better not tell you now.";
string nonCommittalResponse4 = "Cannot predict now.";
string nonCommittalResponse5 = "Concentrate and ask again.";
string negativeResponse1 = "Don't count on it.";
string negativeResponse2 = "My reply is no.";
string negativeResponse3 = "My sources say no.";
string negativeResponse4 = "Outlook not so good.";
string negativeResponse5 = "Very doubtful.";
int numberOfResponse;
Random var = new Random();
numberOfResponse = var.Next(20);
switch (numberOfResponse)
{
case 0:
response = affirmativeResponse1;
return response;
case 1:
response = affirmativeResponse2;
return response;
case 2:
response = affirmativeResponse3;
return response;
case 3:
response = affirmativeResponse4;
return response;
case 4:
response = affirmativeResponse5;
return response;
case 5:
response = affirmativeResponse6;
return response;
case 6:
response = affirmativeResponse7;
return response;
case 7:
response = affirmativeResponse8;
return response;
case 8:
response = affirmativeResponse9;
return response;
case 9:
response = affirmativeResponse10;
return response;
case 10:
response = nonCommittalResponse1;
return response;
case 11:
response = nonCommittalResponse2;
return response;
case 12:
response = nonCommittalResponse3;
return response;
case 13:
response = nonCommittalResponse4;
return response;
case 14:
response = nonCommittalResponse5;
return response;
case 15:
response = negativeResponse1;
return response;
case 16:
response = negativeResponse2;
return response;
case 17:
response = negativeResponse3;
return response;
case 18:
response = negativeResponse4;
return response;
case 19:
response = negativeResponse5;
return response;
default:
response = affirmativeResponse1;
return response;
}
}
} ```
When you return a value from a function, nothing after that return can be ran - you're leaving the function. Therefore the breaks will never be reached because there is always a return right before them.
You also don't need to assign the return value to the response variable, you can just write
return affirmativeResponseX;
This is because when you return, you exit the function. It will never reach the break because you return right before it. The fix is simple. Just remove the breaks.

Bad Request: Shopify pagination

I would like to ask about shopify pagination version 2020-01
First request query:
URL: https://klevarange.myshopify.com/admin/api/2020-01/orders.json?fulfillment_status=unfulfilled&limit=250&financial_status=paid&created_at_min=2019-08-27T16:15:47-04:00
Return Header:
"<https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzIxNzM2NTIsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjA5OjUyIiwiZGlyZWN0aW9uIjoibmV4dCJ9>; rel=\"next\""
2nd Request Query:
"https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9>; rel=\"next\""
Result: Bad Request
What should I put in page_info? Do I need to include the rel=\"next\"" in the page_info?
Thank you.
Remove > from your page_info variable
var page_info = "eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9"
and Make your request URL like below.
https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info={page_info}
Digging Deeper
You need to iterate your while loop until there is no Link Parameter in the response header and this parameter is not a static value it is the address of last object you get and saying next will give you next 250 objects.
you need to update your pageInfo parameter in every request with newly generated next reference ( pageInfo )
When you do not get this parameter that means there is no next or previous page .
Have a look in this below code...( written in php )
How to create pagination in shopify rest api using php
You should use only this part: https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9 i.e. without rel="next"
In the 2nd and all next requests, you can only pass up to 3 query parameters:
page_info
limit
fields
So if you want to get results from the next page you need to extract page_info value from the first response headers.
The idea is that you can move only forward or backwards while requesting the results and you can get the link (page_info token) to the next (or previous) page only after retrieving the current page results.
Maybe in the last 2 years, Shopify has made some modifications to their API, then I use GetNextPageFilter method. This is my approach.
public async Task<IEnumerable<Product>> ProductsGetList(string shopUrl, string accessToken)
{
var products = new List<Product>();
var service = new ProductService(shopUrl, accessToken);
var filter = GetFilters(shopUrl);
var productList = await service.ListAsync(filter);
if (productList != null && productList.Items.Any())
{
products.AddRange(productList.Items);
bool hasMorePages = productList.HasNextPage;
if (hasMorePages)
{
do
{
var filterList = productList.GetNextPageFilter(filter.Limit, filter.Fields);
productList = await service.ListAsync(filterList);
if (productList != null && productList.Items.Any())
{
products.AddRange(productList.Items);
hasMorePages = productList.HasNextPage;
}
} while (hasMorePages);
}
}
return products;
}
private ProductListFilter GetFilters(string url)
{
ProductListFilter filters = new ProductListFilter();
string queryString = new System.Uri(url).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
foreach (var parameter in queryDictionary)
{
var key = (string)parameter;
var value = queryDictionary.Get(key);
switch (key)
{
case "published_status":
filters.PublishedStatus = value;
break;
case "published_at_max":
filters.PublishedAtMax = DateTimeOffset.Parse(value);
break;
case "published_at_min":
filters.PublishedAtMin = DateTimeOffset.Parse(value);
break;
case "updated_at_max":
filters.UpdatedAtMax = DateTimeOffset.Parse(value);
break;
case "updated_at_min":
filters.UpdatedAtMin = DateTimeOffset.Parse(value);
break;
case "created_at_max":
filters.CreatedAtMax = DateTimeOffset.Parse(value);
break;
case "presentment_currencies":
filters.PresentmentCurrencies = value.Split(',').AsEnumerable();
break;
case "created_at_min":
filters.CreatedAtMin = DateTimeOffset.Parse(value);
break;
case "status":
filters.Status = value;
break;
case "product_type":
filters.ProductType = value;
break;
case "handle":
filters.Handle = value;
break;
case "vendor":
filters.Vendor = value;
break;
case "title":
filters.Title = value;
break;
case "since_id":
filters.SinceId = long.Parse(value);
break;
case "collection_id":
filters.CollectionId = long.Parse(value);
break;
case "ids":
filters.Ids = value.Split(',').AsEnumerable().Cast<long>();
break;
case "limit":
filters.Limit = int.Parse(value);
break;
}
}
return filters;
}
Where shopUrl is the entire URL (https://{apiKey}:{password}#{hostname}/admin/api/{version}/{resource}.json) and accessToken is the URL {password} atribute

Why c# switch going in to a different case

I have an enumeration like (a,b,c,d).
public enum BeatSession
{
on_ended,
on_new,
on_hold,
on_paused,
on_accepted,
on_answered,
on_timed_out,
on_hanged_up,
on_initiated,
unknown
}
and a method to do a switch on the enumeration.
public static string GetStatusMessage(BeatSession status, string custom_message="")
{
string msg = "";
try
{
switch (status)
{
case BeatSession.on_answered:
// msg will be here
break;
case BeatSession.on_ended:
// msg will be here
break;
case BeatSession .on_hanged_up:
// msg will be here
break;
case BeatSession.on_hold:
// msg will be here
break;
case BeatSession.on_new:
break;
case BeatSession.on_paused:
// msg will be here
break;
case BeatSession.on_timed_out:
// msg will be here
break;
case BeatSession.on_accepted:
// msg will be here
break;
default:
msg = "Unknown";
break;
}
}
catch (Exception ex)
{
throw ex;
}
// Override message
if (!String.IsNullOrEmpty(custom_message))
{
msg = custom_message;
}
return msg;
}
Updated
However, every time I call my method GetStatusMessage(BeatSession.on_ended).
Even if I pass "on_ended" it goes to "on_answered".
I tried re-arranging "public enum BeatSession". When I passed "on_ended" it now goes to "on_accepted".
Screenshot
Notice the watch for session_status varriable.
I have some code where i do something like this
public enum Letters
{
A = 1,
B = 2,
...
}
public void someFunction(int value)
{
switch(value)
{
case (int)Letters.A: {/* Code */ break;}
case (int)Letters.B: {/* Code */ break;}
...
}
}
And it works, but i think what you are trying to do is send the enum and use it in the switch in the switch, maybe something like this will work
public void someFunction(Letters l)
{
switch(l)
{
case Letters.A: {/* Code */ break;}
case Letters.B: {/* Code */ break;}
...
}
}
Your current code shouldn't compile, following are the main problems.
First, the method definition contains a parameter enum status, you can't do that, It seems you need a parameter of type BeatSession, you should modify the function to:
public static string GetStatusMessage(BeatSession status, string custom_message="")
{
...
}
Next thing in your case statement, you are using enum.on_answered, this should be BeatSession.on_answered. So your complete function should be:
public static string GetStatusMessage(BeatSession status, string custom_message = "")
{
string msg = "";
try
{
switch (status)
{
case BeatSession.on_answered:
// msg will be here
break;
case BeatSession.on_ended:
// msg will be here
break;
case BeatSession.on_hanged_up:
// msg will be here
break;
case BeatSession.on_hold:
// msg will be here
break;
case BeatSession.on_new:
break;
case BeatSession.on_paused:
// msg will be here
break;
case BeatSession.on_timed_out:
// msg will be here
break;
case BeatSession.on_accepted:
// msg will be here
break;
default:
msg = "Unknown";
break;
}
}
catch (Exception ex)
{
throw ex;
}
// Override message
if (!String.IsNullOrEmpty(custom_message))
{
msg = custom_message;
}
return msg;
}
EDIT: Since you edited your question with the answer code, you should have any problem with your switch statement, take a look at the following screen shot.
If enum was actually an enum case a: would not pass a compile.
This works for me
enum myEnum {A, B, C};
public MainWindow()
{
InitializeComponent();
myEnum thisEnum = myEnum.B;
switch(thisEnum)
{
case myEnum.A:
// do something
break;
case myEnum.B:
// do something
break;
default:
break;
}
}
Fixed the problem. Here is what I did. I modified my Enum to be like this.
public enum BeatSession
{
on_ended=0,
on_new=1,
on_hold=2,
on_paused=3,
on_accepted=4,
on_answered=5,
on_timed_out=6,
on_hanged_up=7,
on_initiated=8,
unknown=9
}
So I think what happened was at some point during runtime or compile time the values on my Enum get's scrambled. So I tried setting the value manually and that did the trick.
Thanks Everyone for your reply.
maybe your code is like :
public static string GetStatusMessage(BeatSession status, string custom_message = "")
{
string msg = "";
try
{
switch (status)
{
case BeatSession.on_answered:
// msg will be here
case BeatSession.on_ended:
// msg will be here
break;
.....
if you pass BeatSession.on_answered then in swith (think you missed "break;") goes to BeatSession.on_ended.

Use string.Contains() with switch()

I'm doing an C# app where I use
if ((message.Contains("test")))
{
Console.WriteLine("yes");
} else if ((message.Contains("test2"))) {
Console.WriteLine("yes for test2");
}
There would be any way to change to switch() the if() statements?
Correct final syntax for [Mr. C]s answer.
With the release of VS2017RC and its C#7 support it works this way:
switch(message)
{
case string a when a.Contains("test2"): return "no";
case string b when b.Contains("test"): return "yes";
}
You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.
Nope, switch statement requires compile time constants. The statement message.Contains("test") can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.
If you just want to use switch/case, you can do something like this, pseudo-code:
string message = "test of mine";
string[] keys = new string[] {"test2", "test" };
string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s));
switch (sKeyResult)
{
case "test":
Console.WriteLine("yes for test");
break;
case "test2":
Console.WriteLine("yes for test2");
break;
}
But if the quantity of keys is a big, you can just replace it with dictionary, like this:
static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
string message = "test of mine";
// this happens only once, during initialization, this is just sample code
dict.Add("test", "yes");
dict.Add("test2", "yes2");
string sKeyResult = dict.Keys.FirstOrDefault<string>(s=>message.Contains(s));
Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`...
}
This will work in C# 8 using a switch expresion
var message = "Some test message";
message = message switch
{
string a when a.Contains("test") => "yes",
string b when b.Contains("test2") => "yes for test2",
_ => "nothing to say"
};
For further references
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
Simple yet efficient with c#
string sri = "Naveen";
switch (sri)
{
case var s when sri.Contains("ee"):
Console.WriteLine("oops! worked...");
break;
case var s when sri.Contains("same"):
Console.WriteLine("oops! Not found...");
break;
}
string message = "This is test1";
string[] switchStrings = { "TEST1", "TEST2" };
switch (switchStrings.FirstOrDefault<string>(s => message.ToUpper().Contains(s)))
{
case "TEST1":
//Do work
break;
case "TEST2":
//Do work
break;
default:
//Do work
break;
}
You can do the check at first and then use the switch as you like.
For example:
string str = "parameter"; // test1..test2..test3....
if (!message.Contains(str)) return ;
Then
switch(str)
{
case "test1" : {} break;
case "test2" : {} break;
default : {} break;
}
Faced with this issue when determining an environment, I came up with the following one-liner:
string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));
That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null. This could easily be amended to return a different value.
It's not strictly a switch, more a cascading if statement but it's neat and it worked.
Some custom swtich can be created like this. Allows multiple case execution as well
public class ContainsSwitch
{
List<ContainsSwitch> actionList = new List<ContainsSwitch>();
public string Value { get; set; }
public Action Action { get; set; }
public bool SingleCaseExecution { get; set; }
public void Perform( string target)
{
foreach (ContainsSwitch act in actionList)
{
if (target.Contains(act.Value))
{
act.Action();
if(SingleCaseExecution)
break;
}
}
}
public void AddCase(string value, Action act)
{
actionList.Add(new ContainsSwitch() { Action = act, Value = value });
}
}
Call like this
string m = "abc";
ContainsSwitch switchAction = new ContainsSwitch();
switchAction.SingleCaseExecution = true;
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.Perform(m);
Stegmenn nalied it for me, but I had one change for when you have an IEnumerable instead of a string = message like in his example.
private static string GetRoles(IEnumerable<External.Role> roles)
{
string[] switchStrings = { "Staff", "Board Member" };
switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
{
case "Staff":
roleNameValues += "Staff,";
break;
case "Board Member":
roleNameValues += "Director,";
break;
default:
break;
}
}
This will work in C# 7. As of this writing, it has yet to be released. But if I understand this correctly, this code will work.
switch(message)
{
case Contains("test"):
Console.WriteLine("yes");
break;
case Contains("test2"):
Console.WriteLine("yes for test2");
break;
default:
Console.WriteLine("No matches found!");
}
Source: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
switch(message)
{
case "test":
Console.WriteLine("yes");
break;
default:
if (Contains("test2")) {
Console.WriteLine("yes for test2");
}
break;
}

DotNetOpenId - Open Id get some data

I'm using OpenId on a new website and am trying to get some basic information about the user, see the code below. Why is the following allways null?
var myData = response.GetExtension<ClaimsResponse>();
And the main code
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)]
public ActionResult LogOn()
{
var openid = new OpenIdRelyingParty();
IAuthenticationResponse response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
FormsAuthentication.RedirectFromLoginPage(
response.ClaimedIdentifier, false);
var myData = response.GetExtension<ClaimsResponse>();
break;
case AuthenticationStatus.Canceled:
ModelState.AddModelError("loginIdentifier",
"Login was cancelled at the provider");
break;
case AuthenticationStatus.Failed:
ModelState.AddModelError("loginIdentifier",
"Login failed using the provided OpenID identifier");
break;
}
}
return View("Register");
}
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string loginIdentifier)
{
if (!Identifier.IsValid(loginIdentifier))
{
ModelState.AddModelError("loginIdentifier",
"The specified login identifier is invalid");
return View();
}
else
{
var openid = new OpenIdRelyingParty();
IAuthenticationRequest request = openid.CreateRequest(
Identifier.Parse(loginIdentifier));
// Require some additional data
request.AddExtension(new ClaimsRequest
{
Email = DemandLevel.Request,
FullName = DemandLevel.Request
});
return request.RedirectingResponse.AsActionResult();
}
}
http://www.dotnetopenauth.net/developers/help/the-axfetchassregtransform-behavior/

Categories

Resources