Assign extension methods to a variable - c#

I am trying to assign a variable to an extension method, but getting the error when I hover over the line.
cannot assign 'void' to an implicitly-typed local variable
I am checking for empty fields and calling my extension method and wanted to check more than one field and if they were all failing I wanted them to appear in one error box instead of them piling up.
if (drp_SelectGroup.SelectedValue == "0")
{
var message = this.ShowMessage("Select an Ethnic Group", "ERROR", ErrorType.error);
}
Edit*
public static void ShowMessage(this Page page, string message, string title, ErrorType err)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "toastr",
String.Format("toastr.{0}('{1}','{2}');", err, message, title), addScriptTags: true);
}

The problem isn't that it's an extension method - it's that the extension method has a void return type. Presumably that method shows the message, rather than just creating it. You'd get exactly the same error message if you tried to call any other void method and assign the result to a variable.
You probably need to change your extension method to something like this:
public static string GetMessage(this Whatever foo, string message, string type,
ErrorType errorType)

From the error it looks like ShowMessage has a void return type.
That means that it isn't returning anything.
You are trying to assign that nothing type to a variable.
Solution:
Change the signature of ShowMessage to return what you need it to return.

The return type of this method is: void. You can not assign a type void to a variable.

this.ShowMessage("Select an Ethnic Group", "ERROR", ErrorType.error);
appears to have a return type of void. You cannot then assign to a local variable (var message)
You can change the return type of Show.Message() and this should work for you.

Related

How do I get Discord member, mentioned in the message and grant him a role?

That's the code that I came up with
var roleMuted = ctx.Guild.GetRole(role id);
var userId = ctx.Message.MentionedUsers.First().Id;
DiscordMember member = ctx.Guild.GetMemberAsync(user); //exception here
await member.GrantRoleAsync(roleMuted);
It gives me an exception
CS0029 Cannot implicitly convert type "System.Threading.Tasks.Task< DSharpPlus.Entities.DiscordMember>" to "DSharpPlus.Entities.DiscordMember"
As you can see here - my intention in that line is to create a variable of class DiscordMember and set it to the DiscordMember that was returned by ctx.Guild.GetMemberAsync(), but for some reason, Visual Studio tells me that DiscordMember, that was returned by GetMemberAsync() is not the same as DiscordMember I'm trying to create, to later use for .GrantRoleAsync(), which confuses me a lot.
edit1**
And I have to add that if I replace DiscordMember with var for the line to be
var member = ctx.Guild.GetMemberAsync(user);
then instead of giving me an exception, about failed converting, I simply cannot call .GrantRoleAsync() method for the member variable (exception CS1061)
GetMemberAsync is an asynchronous method, you need to await it by putting the await keyword before it like you've done below with GrantRoleAsync. This will then return DiscordMember instead of Task<DiscordMember>.
As for your edit. Your type is now Task<DiscordMember> which means you wont get the methods for DiscordMember and instead get the methods for Task<T>

List<MyClass> from awaitable task

In my application, different canvases are stored as "pages", the contents of each canvas is stored as "cells".
Now when I want to load all cells that occupy / make up one canvas, I retrieve them like this:
public Task<List<Cell>> GetCellsAsync(string uPageGUID)
{
return database.QueryAsync<Cell>("SELECT * FROM cells WHERE cellpageguid = ?", uPageGUID);
}
This works great.
Now I would like to find out the "pageguid" of the page that has the value "pageisstartpage" set to true.
Therefore I'm trying the following:
public Task<string>GetStartPageGUID()
{
nPages<List<Page>>=database.QueryAsync<Page>("SELECT * FROM pages WHERE pageisstartpage=?", true);
return nPages.First.GUID;
}
The compiler tells me:
nPages doesn't exist in the current context.
I don't see where I made a mistake.
nPages doesn't exist in the current context....I don't see where I made a mistake.
The first thing to mention is that the declaration of the List<Page> seems backwards.
nPages<List<Page>>=database....
The type has to be written first followed by the variable name.
List<Page> nPagesTask = database...
Another interpretation could be that you have a generic type variable nPages in which you want to specify the generic type. So the compiler looks whether this variable has already been declared. And apparently it cannot find any.
The second thing If you have an async method that returns a Task<string> you could do the following:
public async Task<string>GetStartPageGUID()
{
Task<List<Page>> nPagesTask = database.QueryAsync<Page>("SELECT * FROM pages WHERE pageisstartpage=?", true);
List<Page> npages = await nPagesTask;
return nPages.First().GUID;
}
Here is the source of the QueryAsync method. this is the signature:
public Task<List<T>> QueryAsync<T> (string query, params object[] args)
so it returns a Task<List<T>>. Since your method specifies a different return type the usual pattern is to await it in a async method as described in the MSDN example and then return the type that you specified in you method.
You have to declare nPages correctly:
List<Page> nPages = database.QueryAsync<Page>("SELECT * FROM pages WHERE pageisstartpage=?", true);

How can I see the passed parameter to the method?

I have this method:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
//some logic
return results.ToArray();
}
I need to see contextKey variable.
So I tried to use this rows inside the method above:
Response.Write(contextKey);
Response.End();
When I try to use row above, I get this error:
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Response.get'
The problem is that my method is static and I can't use Response class.
Any idea if there is some alternative way to see the prefixText value?
The project doesn't have a solution. I open it in notepad++.

Rename existing method returning void with input arguments

Maybe this is silly, but I'm trying to shorten the calling of the method StreamWriter.WriteLine becasue I have to call it many times throughout my code. So, instead of calling myFile.WriteLine() I would like to write just myFile.WL().
Is this possible?
After searching for a solution I wrote this:
private static void WL(this StreamWriter myFile, params string myString)
{
return (void)myFile.WriteLine(myString);
}
but I get the error
Cannot convert type 'void' to 'void'
Any ideas?
There is no need for the extension method, but just for the sake of completeness...
Remove the return statement from your method, as it doesn't have to return anything.
private static void WL(this StreamWriter myFile, params string myString)
{
myFile.WriteLine(myString);
}
BUT, Reconsider what you are trying to do. There is no point in shortening WriteLine to WL, it doesn't serve any purpose, it will make the code less readable, also you will not be able to cover up all the overloads.
Your Extension method should only be
private static void WL(this StreamWriter myFile, params string myString)
{
myFile.WriteLine(myString);
}
Reasons:
WriteLinemethod of StreamWriter does not return anything i.e. void. It only and I quote Writes a string followed by a line terminator to the text string or stream. So you should remove return keyword from the method. Read here.
BTW, Extension method should probably be public if you want to use it outside of the class you define it in.

How to get method results with AsyncCallback?

I hope you can help me with the following:
I have a WebService method which is supposed to return an array of CompensationPlanReturnReturn objects.
The method is called like this:
//This is the object I need to instanciate because it contains the method I wanna call
CompensationPlan_Out_SyncService test = new CompensationPlan_Out_SyncService();
//This is the method that is supposed to return me an array of CompensationPlanReturnReturn objects
//The data.ToArray() is the parameter the method need, then I pass the method that I wanna run when the method finishes and I dont know what to pass as the final parameter
test.BeginCompensationPlan_Out_Sync(data.ToArray(), new AsyncCallback(complete), null)
//The method description is:
public System.IAsyncResult BeginCompensationPlan_Out_Sync(CompensationPlanDataCompensationPlan[] CompensationPlanRequest, System.AsyncCallback callback, object asyncState)
//On this method I'd like to access to the resuls (the array of CompensationPlanReturnReturn) but I dont know how
private void complete(IAsyncResult result)
{
lblStatus.Text = "Complete";
}
You need to call test.EndCompensationPlan_Out_Sync(result), which will return the result of the asynchronous operation, or throw an exception if an error occurred.
Async methods breakdown into two submethods - Begin and End.
You need to call EndCompensationPlan_Out_Sync to get the actual result returned by method -
private void complete(IAsyncResult result)
{
var actualResult = test.EndCompensationPlan_Out_Sync(result);
lblStatus.Text = "Complete";
}
Try to use the AsyncState-Property and cast it the the given Type.
Like this:
cSACommand = (SACommand)Result.AsyncState;

Categories