what is the difference between System.Net.Cookie and System.Web.HttpCookie? - asp.net

I obtain a HTTPCookie, but need a Net.Cookie. Are they just something you can recast, or how would i go about it?

Actually you have two questions:
Difference between System.Web.HttpCookie and System.Net.Cookie
How to convert from HTTPCookie to a Cookie.
Part 1)
This question is really interesting ,I'm still thinking why there are two classes which looks pretty same ,My initial thought was System.Web.HttpCookie inherits System.Net.Cookie but this isn't true both directly inherit from Object so they are distinct classes ,but the properties matches a lot ,so this gives a hope for the solution of part 2.
Part 2)
I think its possible to convert one into another theoretically since both are just objects if you populate them the right way it will work , here a little analysis when I compared the two classes.
Click to open in new tab to enlarge
Update:
The System.Web is made to be used in server-based apps and System.Net can be used for client based apps.
Some Thoughts:
Write a method or a static class which can convert one object into another, I haven't check all of them but properties whose names match, there signature also matches.
Properties which don't exists in the another object you can stuff some constant or a value which you know matches the scenario like Port number.
Good luck ,let me know how you came up with the final solution ,post the code or link.
Some Links
this post has some related code

Related

How to convert byte[] to ObjectParameter in ASP.net

I have a byte[] and wanna convert it to object parameter in asp.net.
byte[] version =98471574580;
and I have One method that wants "ObjectParametere version".I must convert byte[] version to
ObjectParametere.
The way to do this has a few steps that if you follow in future shoudl save you needing to ask this sort of question again.
1) Look at the documentation for the class you want to use. It is found here: http://msdn.microsoft.com/en-us/library/system.data.objects.objectparameter(v=vs.110).aspx googleing for "ObjectParameter" returns it as top hit for me. Google might have noticed me doing a lot of MSDN searches though and bumping them to the top so if in doubt try adding MSDN or c# to the search.
2) Look for how to create an instance of the object. This would usually be through constructors. Sometimes you may use static methods but constructors are usual and in fact there are two here we can consider.
3) Decide which constructor to use. One takes a name and a type. One takes a name and a value. Since we have a value this seems like the one to choose.
4) Call the constructor you have decided to use and assign it to a variable (or use it directly in your code). In this case the syntax would be var objParam = new ObjectParameter("version", version);.
Some of these steps might be short circuited. For example if you are programming in Visual Studio then typing new ObjectParameter( should then offer intellisense help on what constructors are available, saving the need to look the documentation up online.

Understanding some code

I have an application which was built a few years ago. I came across a section of code that baffled me as the functionality this provides throughout the ASP .Net application is great but i just dont understand it. Perhaps its the [] throwing me off but i think it could be some C# code converted to VB .Net.... Not sure but wondered if anyone understands this and if so could they share what its doing
The code in an NotInheritable class
Public Overloads Function [Get](Of B)() As B
Dim myType = GetType(B)
Return DirectCast([Get](myType), B)
End Function
I understand it overloads a function but
Why are the [] there for and what do they mean? When would you use them? If i remove them i have a compiler error.
Get in VB .Net is used in properties so is this some shortcut access to a property somewhere? Or
where could i view which method its overloading?
I've used code similar to List(Of Customer), IQueryable(of Customer) but how has (Of B) allowed in this manner?
I have read up on MSDN and researched around. The only thing that comes to mind is either some C# syntax conversion or some old VB6 syntax which the original developer must have used whilst creating the application.
Appreciate any clarification on this.
Because Get is part of Visual Basic Language Keywords. You need the bracket to indicate you want to use them as a method/property name.
Here is an excerpt from Microsoft on Keywords as Element Names in Code (Visual Basic):
Any program element — such as a variable, class, or member — can have
the same name as a restricted keyword. For example, you can create a
variable named Loop. However, to refer to your version of it — which
has the same name as the restricted Loop keyword — you must either
precede it with a full qualification string or enclose it in square
brackets ([ ]), as the following example shows.
1) Brackets allow you to use reserved words as identifiers (like the ampersand in c#).
2) It appears to be a bad naming decision. If they wanted to hide an existing member they could have used the Shadows keyword.
3) You'll need to examine the inheritance hierarchy. Start with the most recent parent.
4) It is calling a different overload of Get in the implementation but the Of B is trying to contrain it to B for some reason.

How to change multiple connection string value using one method

I'm currently handling a .Net system that was developed in Linq for its data retrieval structure. This system was developed by other developers last time and I'm dealing a big problem now.
One of the bad practice (or i just not sure why must the developer do that) i found from this system is that, inside /AppData/DataContext/, there are alot of .dbml files and in the .designer.vb, for example Product.designer.vb file, consists of this piece of code:
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource
Public Sub New()
MyBase.New(Global.System.Configuration.ConfigurationManager.ConnectionStrings("DBconstr").ConnectionString, mappingSource)
OnCreated
End Sub
My current major challenge is, I need to change to a new connection string name for all DBconstr and point to another database while keeping the current "Dbconstr" setting in web.config. There are over 400 lines in the entire system I need to find and replace if i have to do it manually. So I need advice if there is any way i can change all hard-coded connection string using one or few direct methods instead of changing all 400 plus lines manually?
I had thought about calling certain method in .Master page and override the value of .ConnectionString for all the child pages but not sure if this is possible.
Please advice. Thanks
You should have a look at this: http://blogs.msdn.com/b/webdev/archive/2009/05/04/web-deployment-web-config-transformation.aspx. It explains how to use web.config transformation. It basically allows modifying the value of a setting (ie. connection strings) depending on your solution/build configuration.
Modifying the configuration file "on the fly" is much easier than trying to modify it in the code.
You should also check these two answers I provided on the same topic:
How to have different web.config settings for my local machine? -
https://stackoverflow.com/a/19294499/375304
Applying web.config transformations locally - https://stackoverflow.com/a/19301084/375304

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 =)

What is the best alternative for QueryString

We heard a lot about the vulnerabilities of using QueryStrings and the possible attacks.
Aside from that, yesterday, an error irritated me so much that i just decide to stop using QueryStrings, i was passing something like:
Dim url As String = "pageName.aspx?type=3&st=34&am=87&m=9"
I tried to
Response.Write(url)
in the redirecting page, it printed the "type" as 3, then i tried it in the target page, it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0 in the next page's load to take my action accordingly???
So what should we use? what is the safest way to pass variables, parameters...etc to the next page?
You could use Cross-Page Postbacks.
Check also this article:
How to: Pass Values Between ASP.NET Web Pages
There are many options you can use, most of them requires you to build a strategy to pass variables between pages.
In most projects I use this strategy, I create a formVariables class to hold currently active items. it has properties which you will need to pass by querystring. and I store this class at session. and in my base page I read it from session. so in every page I get values over this object. the only negative thing about this method is to clean up items when you finished your work on it..
hope this helps.
I would sugest you avoid using Session to pass variables between pages as this breaks the stateless model of the web.
if you have just stored some values in session that relate to a certain page then the user uses their browsers back button to go back to the same page whcih should have a different state then you are not going to know about it.
It leads to the possibility of reading session values that are not relevant to the page the user is currently viewing - Which is potentially very confusing for the end user.
You will also run into issues with session expiration if you rely on it too much.
I personally try to avoid using session where possible in preference of hidden form values + query strings that can be read on postback + navigation.
The best / most secure way to pass info between pages is to use the session.
// On page 1:
this.Session["type"] = 3;
// On Page 2:
int type = (int)this.Session["type"];
You can store any kind of object in the session and it is stored on the server side, so the user can't manipulate it like a query string, viewstate, or hidden field
You said:
it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0
There's a difference between "3,0" (three comma oh) and "3.0" (three point oh). You also said that you were "passing something like".
In a query string, if you pass multiple values in the same key, they will be seperated with commas.
As all values are passed as strings there's no way that an int "3" is going to magically become decimal "3.0" unless you parse it as such when you request it.
I'd go back and double check what you are passing into your URL, if it ends up as something like:
pageName.aspx?type=3&st=34&am=87&m=9&type=0
Then when you read back
Request.QueryString["type"]
You'll get "3,0" back as the comma seperated list of values in that key.
First, in asp .net you can use several strategys to pass values between pages. You have viewstate too, however the viewstate store the value and the use is in different scenarios , you can use it too. Sessions instead, and of course by post in a form.
If your problem is the security, I recommended you to create 2 users for accesing the data. One user with read only access, this for accessing the pages ( Sql Inyection prevent ) and validate the data throw the querystring. And One with write access for your private zone.
Sorry, for my unreadeable English.
I like to use query string as I like users to be able to bookmark things like common searches and the like. E.g. if a page can work stand-alone then I like to it to be able to work stand-alone.
Using session/cross-page postbacks is cool if you needed to come from another page for the page you're on to make sense, but otherwise I generally find querystrings to be the better solution.
Just remember that query strings are unvalidated input and treat them with the caution you would treat any unvalidated input.
If you do proper security checks on each page load then the querystring is fine and most flexible IMHO.
They provide the most flexibility as the entry poitn to a page is not dependant on the sender as in some other options. You can call a page from any point within your own app or externally if needed via querystrings. They can also be bookmarked and manually modified for testing or direct manipulation.
Again the key is adding proper security and validation to the querystring, and not processing it blindly. Keep in mind that the seucirty goes beyond having edit or read access, depending on the data and user, they may not have access to the data with thos paranters at all, in cases where data is owned and private to specific users.
We have tried various methods, in an attempt to hide the querystring but in the end have gone back to it, as it is easier to do, debug, and manage.

Resources