How to persist a control property without using PostBack

February 16, 2008 10:24 by Admin

For whom program in ASP.Net, since the first version you probably start to appreciate and contemporary hate the page’s StateBag, otherwise called ViewState. Without going through the particulars, to avoid loosing the article path, in few words the ViewState take care to serialize the content of the page variables into a string that is passed back to the next page request through a mechanism called PostBack.
The drama is that not all controls need ViewState, and often this persisting process is turned off to reserve memory and avoid unuseful server roundtrip.

Things changed when ASP.Net 2.0 framework has been released: a new method called ControlState was introduced for persistance. This method basically works as the ViewState, but first of all cannot be deactivated by the web page programmer, and it memorize only what is really needed (according to the override you will do in your code). Again, you can also decide for which control activate this repository and for which not.
Immediately should jumps in mind that you can even completely deactivate the ViewState and continue to be supported by the Control’s variable persistance without any matter.

That’s all true, but only in part!

 

So you are probably asking why I’m writing this if this isn’t the truth. As I said, it’s not true only in part. To correctly work, both ViewState and ControlState needs to embrace the PostBack technique. For whom don’t know what PostBack is, it's a small javascript function automatically added by the framework to the rendered HTML page that take care to collect every input control’s value and to submit them to the same page through a server call. This let you restore value on the next page load for following elaboration.

Now, suppose just for a moment - as it was in my case - while I was developing a control to have a limit where you cannot use Javascript (without worrying why). What happen in this case? No javavascript = no PostBack. And then?

To avoid this kind of problem I had to use an alternative way to persist my control’s value, based always on the serialization, but persisting values in the Session object.

 

The serialization is the process of saving an object into a storage medium (such as a file or a memory buffer) and to transmit it across a network request.

In this way, with a couple of if inside the code, and using the same execution path used by the ControlState, I finally successfull persisted my control’s value without using PostBack.

Below an abstract of the code I used.

 

First of all I created a serializable class that you need both you want to persist values in a traditional way and with Session method.

[Serializable]
internal struct PersistedData
{
 
public int test;
}

You then add a condition if you want to use the ControlState mechanism or not. This can be done in the OnInit method of our control.

 if (PagingMode == PagingModeEnum.Postback)

  Page.RegisterRequiresControlState(this);
else
 
LoadControlStateInSession();

It's now necessary to add the alternative storage path in the PreRender override. You shouldn't do anything for the ControlState since you are obliged to override the SaveControlState method.

if (PagingMode != PagingModeEnum.Postback)
 
this.SaveControlStateInSession();

Finally paste the code that will perform the persistance above used.

///
/// Saves state the specified storage mechanism by
/// first serializing to a string with the LosFormatter
///

private void SaveControlStateInSession()
{
 
LosFormatter output = new LosFormatter();
 
using (StringWriter writer = new StringWriter())
  {
   
output.Serialize(writer, this.SaveControlState());
   
HttpContext.Current.Session["__" + this.UniqueID] = writer.ToString();
  }
}


///
/// Retrieves the serialized data from the Storage medium
/// as string using LosFormatter formatting.
///

private void LoadControlStateInSession()
{
 
string RawBuffer = HttpContext.Current.Session["__" + this.UniqueID] as string;
  if (RawBuffer == null)
   
return;

  LosFormatter input = new LosFormatter();

  this.LoadControlState(input.Deserialize(RawBuffer));
}

The above function use the LosFormatter class that is an hidden class of the System.Web.UI namespace, used by the framework for the serialization process of the page ViewState and of the famous hidden form field __VIESTATE.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

ASP.Net My Web Page Starter Kit Static Section

January 18, 2008 21:14 by Admin

Finding an open source CMS (hence free) written in C # 2.0, which does not need a database to store data is not easy. On ASP.Net platform, there aren't so much solutions like per Linux platform, and Microsoft guy did a great job when they released the MWPSK.

This time what I find as missing is the possibility to share a particular content among different pages, i.e. a disclaimer.

So with a bit of code, also using the newest LINQ to XML functionality provided by the .net framework 3.5, I developed the Static Content section.

The usage is pretty simple, just add the section, create the content and save it. Automatically the new XML file generated will be linked to the section. If you need the same section into another page, add the Web-MA Static Section, choose the previously created file and save.

Changes made to a specific section file, anywhere, obviously will be reflected on all pages.

Enjoy the code and feel free to report bugs and comment.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

ASP.Net My Web Page Starter Kit Seo Extension

January 5, 2008 18:01 by Admin

Finding an open source CMS (hence free) written in C # 2.0, which does not need a database to store data is not easy. On ASP.Net platform, there aren't so much solutions like per Linux platform, and Microsoft guy did a great job when they released the MWPSK.

But like for everything, also in this case something was missing, at least looking into this CMS the personalization of the Meta Tag Description and Keywords is strictly at global level.
And everybody who works in SEO agency knows how important are these meta tag for the search engine optimization.

So, after a bit of code, I released the My Web Page Starter Kit SEO Extension. Enjoy the code and feel free to report bugs and comment.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Is Sql Server Management Studio missing?

December 20, 2007 19:49 by Blog Author

The other day I installed SQL Server 2005, but I didn't used because I was preparing the PC formatted to work again. Just today I realized that the installation has not installed Management Studio, but I was sure to have asked setup to install it.

So I opened the setup again to verify the configuration, and really the Management Studio wasn't there. The Tools directory too was empty.

I then inserted the SQL Server disk into the DVD bay and asked for a reinstall, but I got strange error saying Management Studio was there. Where I really don't know.

So the solution is (and I didn't install SP2 yet, in order to rule out problems like different version)

  1. Run the installer and ask to remove workstation components
  2. Rename the tools folder in C:\Program Files\Microsoft SQL Server\90
  3. Go to into the Microsoft SQL Server DVD (i.e. D:\ENGLISH\SQL2005\DEVELOPER\SQL Server x86\Tools) and run the setup.exe, select the component you need and proceed with the installation.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Delete all appointments and contacts from Windows Mobile

December 12, 2007 11:07 by Admin

Having a PDA and Windows Mobile is not always synonymous of "ease of use". To cancel all appointments and all contacts previously synchronized with Active Sync is not simple. There isn't a button, an hidden key, a native tool, perhaps with 200 password, that will clean up your listing without drive your pencil to the hard reset (meaning the PDA back to the roots, when you pulled out out of the box, and then without a bit of software that is not the OS preinstalled).

The alternative, the most simple, I've found is to synchronize your PDA with a false Outlook profile.

Of course, even here things aren't immediately, while creating a new profile on Outlook, the database of contacts and calendar, PDA realize that the source and destination aren't the same. Nor replace the file with a new file with a blank work. The solution (not immediate but effective):

    1. Restart the PC you use for the sync process (so no file is pending or in memory)
    2. Create a new file Outlook (pst) completely empty
    3. Copy the old file (for backup purpose)
    4. Open Outlook, canceled all appointments, and all contacts
    5. Synchronize again PDA (at this stage the profile match and Active Sync did not complain)

This will cleanse the PDA. Obviously at the end of the process, after the handheld detached and closed the Mobile Device Center, we must restore the backup copy made in paragraph 3 to get all the data back.

If someone knows a shortest way, a welcome comment.

Technorati Tags: ,


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Solving the SPAM problem with the Grey list

November 4, 2007 18:31 by Admin

The problem of SPAM is becoming something unbearable. Levels of garbage (Viagra, Drugs, pirated software, watches etc) sent from users seems to have become a job for these people that I won't ever understand, but that everyone - including myself - makes a huge annoyance.

On most e-mail systems actually in use there are some basics systems of SPAM recognition. These systems can act in different ways, and being free or under fee license. Everything depends on the provider where your e-mail is hosted.

A common protection system is that one that after parsing the e-mail or checked against some other methods (eg DNS blacklisting) assign to the e-mail a weight as a numerical value; such value is applied by the mail system according to a table values (not directly editable) and let the mail server classifies e-mails as SPAM in three levels (low, medium and high).

This system, with the addition of a good anti virus, and with the proper configuration of the rules of incoming e-mails permits - in most cases - to group in a single place unsolicited e-mails; giving them a fleeting glance is necessary to avoid false positive, After that is possible to safely delete them altogether without worrying about important e-mail lost.

However, this system does not prevent the receipt of SPAM messages, as both the sender that the recipient is potentially good (except Whitelist rules and blacklists, or SPF record).

In this scenario, a system which is very effecicient to the combat SPAM is the Greylist, which reduces the 99.9% of SPAM.
Yes, you read that right; Your mailbox would not be affected by these messages anymore - at least after one month of test I could certainly said this.

Before I explain how this system works, let me say how spammers collect e-mail addresses of Internet users. We must not think at people who are writing the same message millions of times and press send or forward. Your E-mail can be get - broadly - in 5 different ways:

  1. through programs, BOT, which go around the network to collect e-mail addresses and store them in a database;
  2. added by hand by spammers in his database;
  3. when you register in some websites, especially those which propose free services (photos, ring tones for mobile, sms free, etc.. Etc.);
  4. when our address is recklessly inserted into "S. Antonio" chains or other user improperly use the command "forward to all people" or write an e-mail adding the contacts alltogether in the destination address field so everybody could see the addresses of all people that had been added;
  5. through virus (Worm), which infects the system and spread your e-mail address list to the spammers; 


The dispatch systems used by spammers, considering the amount of e-mail that must manage, once sent mail not bother to check whether it was received or not, because so - assuming also that 10% of these users receiving the e-mail-the spammer has always fulfilled its task: to create unease.

Under this circumstance the use of Greylist is perfect.

 

What are the Greylist

The Greylist are an intermediate level between the Whitelist (users always accepted) and blacklists (users always rejected). The task of these Greylist is to refuse in the first instance any email from anyone (except those in Whitelist) returning an error code that informs the sending mail server that the receving server have experienced potential trouble (like a network problem) and that the message should be dispatched at a later time.

The SMTP protocol (the protocol in charge to send and receive e-mail) rules when get this kind of message add the message into a queque list to process it later and destroy it after a number of failed attempts, that in our case never happen.

Since spammers generally use stand-alone software that take care just to send e-mail, they don't process at all any answer sent by the receiving server and they assume that delivery process has gone fine going through next e-mail.In normal e-mail server, instead, the message will be processed again and on next delivery the e-mail will be accepted and regularly delivered to the destination address. 

 

Advantages and disadvantages of Greylist

The Gray list allows to eliminate the 99% of spam. It required an initial period of tuning, because it could be that some mail servers hasn't been setup for resubmitting the message.
In this case, the server or the sender should be whitelisted to avoid greylist check; leaving standard anti-spam filter is enough to classify those sender and avoid too much noise.

Another disadvantage, I believe almost acceptable, is a minimal delay during the delivery of the first message. Indeed, as mentioned above, the message is initially refused. Between the first and second attempt there is a short time (setup by the sender server' system administrator) that may be not tolerated by people in a hurry.

Is necessary to remind that the this delay occurs every time the server is not able to authorize the sender and that periodically the Greylist address are purged.

Example: suppose today is Monday and user A send an e-mail to the user X. The e-mail is refused and sending server get the error code. The server continue its works and after a certain period of time (usually 5 minutes) it try to delivery to X the e-mail that in this case will pass over the check and will correctly delivered 6-7 minutes later than when A has sent the message. 
Tuesday A sends a message back to X. The X server has authorized A day earlier, remembers him and let pass his e-mail immediately without delays. 
After an entire week, so at the following Wednesday, supposing user A no longer sent messages to X (and then the list of authorized users is changed removing user A) during first delivery, the message of A should pass against the verification process; unlike - in the case of continuity - address always remain alive and so do not suffer further delays.

In short, despite an early stage of tuning and a small slowdown, implementing the Greylist is - at least for the time being - the ultimate resource to the SPAM problem. Of course, maybe in a few months (I hope some years or better not ever), spammers take measures and will review their delivery method. But since progress always goes ahead with giant steps, it could also be that tomorrow a new and efficient system will be developed.

I conclude by saying that obviously the Greylist is not something within everyone, but is applicable only by person who runs their own mail system and has a bit of experience.
We can then make use of what if the mailbox is hosted somewhere. In this case we need only to ask the provider / host if the greylist system is running, but basing on my experience I can tell you that even if the mail server used supports Greylist, rarely it is activated because not all users are ready to support this slight delay in receiving.

I find this a very ridiculous answer ... expecially if we think about that also today many time we comes through express mail and delivery system that often losts our correspondence.

Other client base SPAM filter are described in Top Anti-Spam Filter Reviews by Elmo Kandel

 

Technorati Tags: ,

 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Internet Explorer, printing and the error in preview.dlg

August 21, 2007 16:00 by Blog Author

The day before holiday closing, a customer who recently we developed a web site calls me and say "Do you see our web site? Is impossibile to print due an error on script xyz"

On a firtst moment I got down from the clouds, also because AFAIK the print function is totally idipendent from the web site showed. In addition, customer wasn't using a custom print button, but that one in the IE toolbar.

Since it was the day before holidays, both customer and us decided to shift the debug till today when we re-opened our office. Capture

After some tests (IE 7, Firefox, Safari, Opera), I wasn't able to repro the error, so in a first moment I thought to a problem connected to it's computer (also becuase that machine was recently infected by a virus) . But after a while, I think to his pc, an XP Sp2 with a slow Internet connection and so to the fact that he never update his pc with IE 7. So I open the virtual machine, load the XP Sp2 and ... patatrac. Get the error.

Line 1401, then line 1200 ... and so on. Lines that obviously wasn't into html code that was just 100 rows. So the error couldn't be in the html file (at least it wasn't seem) also because the file was XHTML and CSS valid. But unfortunately the error was in every page, and get sistematically every time I was pressing the print button.

After some google research and some possible solutions like corrupted file (impossible to understand if file article speaks was the html file or IE file), unrealistic dll registration, I start to clear small parts of html code until I delete a div tag which id param was setup to tags. That was the matter: simply renaming the tag and magically all start back to work.

Once again a prove that IE should be trashed.

Technorati Tags: ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

DataFormatString won't be applied.

July 2, 2007 19:40 by Blog Author

If you are looking for an answer why DataFormatString won't be applied at your BoundField, the most reasonable answer is "It's a bug". A bug for which nobody at Microsoft seems to be responsible for.

In few words, if you have a BoundField object bound to a field of type DateTime (or whatever you want) with a DataFormatString like this:

<asp:BoundField DataField="DateOfBirth" DataFormatString="{0:MM/dd/yyyy}" />

when you will run your web application, the output instead to be as everybody would expect (MM/dd/yyyy) appears to be formatted using its ToString() method like so:

07/02/2007 7:35:54 PM

The problem is reconducible to an effort of preventing cross site scripting attacks, so the field value is HtmlEncoded before the new formmating is applied. This internally changes the output that doesn't match anymore to a suitable Date format and for this reason the format requested won't apply.

The resolution is to set up the HtmlEncode to false like so:

<asp:BoundField DataField="DateOfBirth" DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="false"/>

Technorati Tags: ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5