what is the use of first argument of createAsyncThunk? - redux

I'm new in redux toolkit and I've managed state with redux toolkit lately. But the thing I don't know, what is usage of first argument of CreateAsyncThunk. I've read this article: https://redux-toolkit.js.org/api/createAsyncThunk and according to this, CreateAsyncThunk has two argument and first argument is named type :
A string that will be used to generate additional Redux action type constants, representing the lifecycle of an async request
Ok. But we never need to call or use this argument again, so why is important to name this argument? I tried adsfds insted of requestStatus after / and my project worked perfectly! I also understand it also works even without slash.
It seems it doesn't matter what you write as first argument, It always works! So what is the usage of the first argument?

In Redux, every action is identified by a unique type string. So createAsyncThunk creates three actions for you - in your case with the type strings "adsfds/pending", "adsfds/fulfilled" and "adsfds/rejected".
If you do not use "asdfds" in any other createAsyncThunk, that's a perfectly fine thing to do, but if you look at the Redux Devtools browser extension to see what is happening in your application, a string like that might make it very difficult to read.

Related

Request versus Request.QueryString

What is the difference between these two in VBScript:
Request("startDate")
Request.QueryString["startDate"]
And where is Request("startDate") documented? I don't see this usage here:
http://www.w3schools.com/asp/asp_ref_request.asp
The official documentation for the Request object in ASP classic is here: http://msdn.microsoft.com/en-us/library/ms524948%28VS.90%29.aspx
Quoting the relevant part for this question:
All variables can be accessed directly by calling Request(variable)
without the collection name. In this case, the Web server searches the
collections in the following order:
QueryString
Form
Cookies
ClientCertificate
ServerVariables
If a variable with the same name exists in more than one collection,
the Request object returns the first instance that the object
encounters.
EDIT: AnthonyWJones made a great comment on the question: Avoid using the Request("name") syntax. In fact, this is mentioned in the documentation link above:
It is strongly recommended that when referring to members of a
collection the full name be used. For example, rather than
Request.("AUTH_USER") use Request.ServerVariables("AUTH_USER"). This
allows the server to locate the item more quickly.
See Request() vs Request.QueryString()
From what I understand when you use Request on it's own it will return the first matched item in the request collection. well explained in the attached solution.
Sorry to dredge up this question, but given the warnings against using Request("param"), I had to add my two cents. In this particular case there's a good reason to use Request("param") instead of Request.QueryString("param"): It allows you to write code that will accept parameters as part of a query string or when submitted through a form. I regularly run into situations where that is not only handy, but desirable.

Optional Invalid Query String Variables

This is a somewhat philosophical issue. I have a .net (but could be any platform) based helper library that parses query string values. Take for example a variable that returns an Int32: my framework has an option that specifies whether this value is required or optional. If it is required but not provided, the framework throws an exception. If it is optional and not specified, it returns a null.
Now an edge case has come up based on users hacking (in a good way) our urls. If they specify a variable with either an invalidly formatted Int32 ("&ID=abc") or provide the variable but not specify a value ("&id="), should the framework throw an exception or should it return a null?
Part of me feels that invalid variables or formats should return a null. It might be valid to argue that even if the parameter is optional, an invalidly formatted query string or value should still throw an exception.
Thoughts?
Since this is philophical ...
On something like an ID, I would agree with Shawn that it is a 404, especially if you are thinking in terms of state. There is no object, so not found. But, ID may not tie directly to a resource in all cases.
If the item is truly optional, a null is okay. But optional should mean "if present it makes the call more specific" in this case and there should always be a fallback. I don't see this in ID, unless the ID is keyed to an optional part of the page.
In the long run, I think you should look at the business reason for the page and what each variable means.
I believe that if a variable is optionaly, providing the variable but not specifying the value is equivalent to ommitting the variable itself. In this case, returning null seems OK.
However, providing an invalidly formatted value ought to cause an Exception, since the intent was to provide a value. In this case the user ought to be notified through some sort of validation mechanism.
A HttpException of 404 (Not Found). Your web application framework should know how to catch these errors and redirect to the proper page.
This is actually a not found error because the resources that the ID is pointing to does not exist.
I suspect there's no "right" answer to your question. If I were a developer using your library, I would expect/hope that the public API would include in its code comments, a description of how the function behaves when the URL param includes bad (wrong type) data.
You might also be able to craft your public API to get the best of both worlds: .NET seems to have adopted the "Parse" / "TryParse" approach in many places. If I'm the caller and I want the function to throw if given invalid data, I call Parse(). If I don't want it to throw, I call TryParse(). In my opinion, that is a nice pattern to follow with your API as well.

Set HttpContext.Current.Request.Browser.Type in ASP.NET

Is there a way to set HttpContext.Current.Request.Browser.Type in ASP.NET. That is a read-only, string property. So you cannot really just assign a string to it. Tried initializing Browser property which is of type HttpBrowserCapabilities, but it has only one constructor and does not take any parameters and browser Type is still null. The reason why I want to be able to set Type for browser is that my unit test is failing as Type property is null.
Edit per null check comments:
I could definitely modify code to check for null, but that will be just for my unit test as when the requests come from browsers, that value is never null. Hence not quite excited about doing that. But it can be my last resort.
You can define your own browser definition files which ASP.net will then use. Check out http://forums.asp.net/p/955969/1176101.aspx.
So if you know what browser it's failing on you could setup a browser file for it. However, I agree that checking for null values makes more sense as it accounts for a lot more possiblities that way.
You might want to think about refactoring your code to use HttpContextBase instead of relying directly on the concrete type.
By doing so you could simply create a stub object that provides the behavior you want. Eventually implementing your own HttpBrowserCapabilitiesBase object.
You would then have full control to use your mock types during unit testing. Indeed that is what they were created for.

Looking for a good technique for storing email templates

I am building a site in which we are making moderate use of email templates. As in, HTML templates which we pass tokens into like {UserName}, {Email}, {NameFirst}, etc.
I am struggling with where to store these, as far as best practice goes. I'll first show the approach I took, and I'd be really excited to hear some expert perspective as a far as alternate approaches.
I created HTML templates in a folder called /Templates/.
I call a static method in my service layer, which takes in the following arguments:
UserName
UserID
Email
TemplatePath ("~/Templates")
Email Subject
Within the service layer I have my static method SendUserEmail() which makes use of a Template class - which takes a path, loads it as a string, and has a AddToken() Method.
Within my static SendUserEmail(), I build the token list off of the method signature, and send the email.
This makes for a quite long method call in my actual usage, especially since I am calling from the web.config the "TemplatePath", and "Email Subject". I could create a utility that has a shorter method call than the ConfigurationManager.AppSettings, but my concern is more that I don't usually see method signatures this long and I feel like it's because I'm doing something wrong.
This technique works great for the emails I have now, which at the most are using the first 3 tokens. However in the future I will have more tokens to pass in, and I'm just wondering what approach to take.
Do I create methods specific to the email needing to be sent? ie. SendNewUserRegistration(), SendMarketingMaterial(), and each has a different signature for the parameters?
I am using ASP.NET Membership, which contains probably the extend of all the fields I'll ever need. There are three main objects, aspnet_User, aspnet_Mebership and aspnet_profile. If it was all contained in one object, I would have just passed that in. Is there performance concerns with passing in all 3, to get all the fields I need? That is versus just passing in aspnet_User.UserID, aspnet_User.Email, etc?
I could see passing in a dictionary with the token entries, but I'm just wondering if that is too much to ask the calling page?
Is there a way to stick these in a config file of it's own called Templates.config, which has tags like -
<Templates>
<EmailTemplate Name="New User Registration">
<Tokens>
<UserName>
<UserID>
<Email>
</Tokens>
<Message Subject="Hi welcome...">
Hi {UserName}...
</Message>
</EmailTemplate>
</Templates>
I guess the main reason I'm asking, is because I'm having a hard time determining where the responsibility should be as far as determining what template to use, and how to pass in parameters. Is it OK if the calling page has to build the dictionary of TokenName, TokenValue? Or should the method take each in as a defined parameter? This looks out of place in the web.config, because I have 2 entries for and , and it feels like it should look more nested.
Thank you. Any techniques or suggestions of an objective approach I can use to ask whether my approach is OK.
First of all I would like to suggest you to use NVelocity as a template engine. As for main problem I think you can create an abstract class MailMessage and derive each one for every needed message (with unique template). So you will use this like following:
MailMessage message = new UserRegistrationMessage(tokens);
//some code that sends this message
Going this way you force each concrete XXXMessage class to be responsible for storing a template and filling it with the given tokens. How to deal with tokens? The simpliest way is to create a dictionary before passing it to the message, so each concrete message class will know how to deal with passed dictionary and what tokens it should contain, but you also need to remember what tokens it should contain. Another way (I like it more) is to create a general abstract type TokenSet and a derived one for every needed unique set of tokens. For example you can create a UserMessageTokenSet : TokenSet and several properties in it:
UserNameToken
SomeUserProfileDataToken
etc. So using this way you will always know, what data you should set for each token set and
UserRegistrationMessage will know what to take from this tokenSet.
There are a lot of ways to go. If you will describe you task better I think I will try suggest you something more concrete. But general idea is listed above. Hope it helps =)

How can I preserve the QueryString semantics when converting an MFC CHttpServer based web server to ASP.Net?

In a legacy MFC CHttpServer based web server, we have a command parsing map something like this:
BEGIN_PARSE_MAP(MyHttpServer, CHttpServer)
ON_PARSE_COMMAND(MyPage, MyHttpServer, ITS_I4 ITS_I4 ITS_I4 ITS_I4 ITS_PSTR ITS_PSTR ITS_PSTR ITS_I4)
ON_PARSE_COMMAND_PARAMS("intParam1=11 intParam2=12 intParam3=13 intParam4=14 strParam5=s5 strParam6=s6 strParam7=s7 intParam8=18")
END_PARSE_MAP(MyHttpServer)
This defines a page accessible at http://host/path/dllname.dll?MyPage that accepts up to 8 parameters named intParam1, intParam2, intParam3, intParam4, strParam5, strParam6, strParam7, and intParam8.
The calling applications can invoke the page with the parameters in a named fashion like this:
http://host/path/dllname.dll?MyPage?intParam4=32&strParam7=somestring
But the way MFC command parsing maps work, they can also call it with unnamed parameters as long as they are provided in the order defined by the map:
http://host/path/dllname.dll?MyPage?21&22&23&24&string5&string6&string7&28
I would like to replace this old code with an ASP.Net page, but we have existing calling applications that will not be changed that invoke the page using both styles of parameter passing, named and unnamed.
I can easily manage the necessary URL rewriting to allow an ASP.Net page to respond to the URL as given above, replacing the path/dllname.dll? MyPage portion with the path to an .aspx page or .ashx handler.
The problem comes in when trying to handle the unnamed parameters in an equivalent fashion to the old MFC parameter parser. Request.QueryString treats all the unnamed parameters as being named with null and Request.QueryString[null] returns a comma-separated list of the values. This is pretty close to workable, but should one of the parameters actually contain a comma, this encoding falls apart because the extra comma is not escaped and splitting the string on the commas will end up with too many parameters.
In classic ASP, I believe Request.QueryString(...) returned a collection of all the parameters that were identically named. There seems to be no equivalent to that in ASP.Net that I can find.
As a secondary issue, the MFC command parsing map had some pretty convoluted logic for dealing with a mixture of named and unnamed parameters. Although the callers of the page in question will not be mixing their usage in this way, I am interested in perhaps duplicating the logic for completeness sake. Can anyone confirm that MFC's behavior was essentially the following?
Process all parameters in the URL from left to right, using & as separator.
If named (has an equal sign), apply the value to the parameter with the corresponding name, regardless of its position. If that parameter already assigned a value, error.
If unnamed, apply the value to the parameter at the nth position in the command parsing map, where n is the number of already processed unnamed parameters plus 1. If that parameter was already assigned a value, error.
Apply default values from command parsing map to any parameters not assigned above
If any parameters from command parsing map have not been assigned a value, error.
One more interesting note, it appears that Request.QueryString.ToString() will nearly reconstitute the original parameters on the URL, but it always moves the parameters with identical names to be together, including the unnamed parameters I am concerned with here.
Not sure if solves your problem, but you could try using Request.PathInfo. This will give you everything entered after the page, which you could then parse manually using something like a regex.
For example, if you had the URL:
http://host/path/dllname.dll?MyPage?21&22&23&24&string5&string6&string7&28
The Request.PathInfo property would return:
?MyPage?21&22&23&24&string5&string6&string7&28
Processing this into a set of values that you can work with could also be problematic as you've got both named and un-named parameters, but this should be achievable using regular expressions and/or splitting the string.
I found that Request.QueryString has a GetValues() method. This returns an array of strings and solves the problem of a comma being embedded within one of the values. It'll be even easier to use than having to split the results of Request.QueryString[null].
I still have a bit of work to use this to implement an MFC-like mapping of URL parameters that handles both named and unnamed parameters.

Resources