DCSIMG
Avi Pinto

Avi Pinto

על הבלוג

Follow uberPinto on Twitter

View Avi Pinto's profile on LinkedIn

Subscribe in a reader Subscribe by Email

 


Two new sculptures

View my Air Brush Work at Avipinto.com

Helping a friend, great tool for fixing file names

JavaScript Tutorial


Disclaimer All postings/content on this blog are licensed under a Creative Commons Attribution By license and provided "AS IS" with no warranties, and confer no rights.
All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors.

double scrollbars with "overflow-y: scroll" on IE7 when using cssstickyfooter

The Point:

cssstickyfooter is a great solution for a sticky footer(works even at the crappy IE6).
Alas, when trying to set body{overflow-y: scroll} you get a double scroll on IE7(which is also pure crap and should die).

The solution for this one is to set the style on the html: html{overflow-y:scroll} 

 

Some details:

doubleScroll

Abused the cssstickyfooter site(as it uses it’s technique) to show the double scroll.

To try it just open it in IE compatibility mode, hit f12 and at the script tab type: document.getElementsByTagName("body")[0].style.overflow = "scroll"

 

I like having a vertical scrollbar on my designs,

this way if a page is loaded without a scroll and then some action loads data that adds the scroll,

the page doesn’t “jump” as the scroll is added.

Usually I add the scroll to the body, but that caused the double scroll on IE7 when I used the cssstickyfooter.

 

Didn’t have the time to check why, and most of the pages in my app have a big scroll,

so left it for later and removed the definition.

Till saw @getify’s confession which triggered my interest to check this once again,

the answer came from @Brodingo , feel stupid I haven’t tried it when I encountered the problem.

 

This is one of the things that are great about twitter - one confession can lead to the solution of a long time annoying problem :-)

IModelBinder and property key for successful binding at the ModelState + partial form validation

I’m talking about asp.net MVC2

The point:

if you are implementing an IModelBinder for a type, you should add a call to
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueFromRequest);

this is done to make sure that at your controller action you can access ModelState[nameOfThisProperty] and nameOfThisProperty  will be present as a key at ModelState also for successful binding.

 

And for the details: (  Partial form validation including custom modelBinding  for trimming strings)

why am I using ModelState[nameOfThisProperty] ??

usually you don’t need to access ModelState[nameOfThisProperty]  like this, it is ugly and stringly typed Smile

but lets say you have a form  that has two options: “save”,”save draft”

“save” should  trigger the  entire  form’s validation.

”save draft”  should trigger  validation only on a filed named Title.

 

I’m using the DataAnnotations  validation  attributes and no chance in hell that I’m going to create two  separate objects to enforce this validation rules.

so I have two separate action methods and at SaveDraft I have this code:

public ActionResult SaveDraft(ArticleModel articleModel ) 

     if (ModelState[ArticleModel .ARTICLE_TITLE_FIELD_KEY].Errors.Count > 0) 
     { 
         ModelStateDictionary mDic = new ModelStateDictionary(); 
         ModelState titleModelState = ModelState[ArticleModel .ARTICLE_TITLE_FIELD_KEY]; 
         ModelState.Clear();

         //ugly way to preserve this error message if it exists 
         ModelState.Add(ArticleModel .ARTICLE_TITLE_FIELD_KEY, titleModelState); 
         return View(“New", articleModel ); 
      }

      //party with  articleModel  ignoring all other validation errors

      ..

At the client side  I have this function(I use jQuery and jQuery validation):

function BindSaveDraftButton()
{
    var jqBtnSave = $("#btnSaveDraft");
    jqBtnSave.click(function ()
    {
        var jqTxbTitle = $(".txbTitle:first");
        if (!jqTxbTitle.valid()) //trigger only this field’s validation manually
        {
            jqTxbTitle.focus();
            return false;
        }

        //  the button holds the saveDraft action at a specific actionUrl attribute

        // (I know I know I shuld change this to  data-actionUrl
        $("#formPostArticle").attr("action", $(this).attr("actionUrl"));

        //NOTE: I don’t return anything here so the form will submit as a regular form, just to a different action
    });
}

oh.. and the button for  “save draft” has the class “cancel” so it won’t trigger client validations

 

And the connection to custom ModelBinding??

Everything was working great(some bits a it ugly, but this is the case for now) till I decided to implement a TrimmedStringModelBinder so all bound strings will be trimmed during binding.

public class TrimmedStringModelBinder : IModelBinder

{

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }
       ValueProviderResult valueFromRequest =

                                                     bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
       bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueFromRequest);  

       if (valueFromRequest == null)
       {
            return null;
       }
       if (!string.IsNullOrEmpty(valueFromRequest.AttemptedValue))
       {
            return valueFromRequest.AttemptedValue.Trim();
       }
       return valueFromRequest.AttemptedValue;

   }

}

registered it as follows at the Global.asax

ModelBinders.Binders.Add(typeof(string), new TrimmedStringModelBinder());

 

Note the row with yellow BG – it was missing  at the first implementation  because I had no idea I need it.

without it the check for  -

ModelState[ArticleModel .ARTICLE_TITLE_FIELD_KEY].Errors.Count

threw  an exception since this property was valid(had value in it) so during the server validation this key wasn’t entered into the ModelState.

when I removed the registration to the TrimmedStringModelBinder  I saw that even if the property is valid – a key would be added the ModelState stating there are no errors here.

 

Looked a bit at Stackoverflow but didn’t find anything useful..

The  solution can  always be found at the source:

So opened the  mvc2-rtm-sources\src\SystemWebMvc\Mvc\DefaultModelBinder.cs

and the solution is right there at the  BindModel method :

            // Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))
            // or by seeing if a value in the request exactly matches the name of the model we're binding.
            // Complex type = everything else.
            if (!performedFallback) {
                ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (vpResult != null) {
                   return BindSimpleModel(controllerContext, bindingContext, vpResult);
                }
            }.

went directly to the Simple model condition since this is what I’m binding(string remember?)

that led to the  BindSimpleModel method, where the first line is:

bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

 

So here it is:

you must add all all the keys to the ModelState , during the binding, the validation only updates faulty ones.

(it is so awesome that we have access to the MVC code,  it is not a huge codebase it is self explanatory, and have some comments where needed) .

 

This post has become too long, and I have more  things to elaborate on the TrimmedStringModelBinder  - so will do it at another  post later.

 

till then  - happy coding

Good talk on JavaScript performance + some notes

Smashing magazine posted a Seven Must-See Videos and Presentations for Web App Developers
finally had the chance to start watching these videos(on the bus :))
 
The first one deals with Speeding up your JavaScript by Nicholas C. Zakas
Very interesting talk:


 

While watching this remember that you should take the problematic places that need to perform better and make the changes there(as Nicholas also stated at the beginning of the talk and also in this post following the talk).
I think that performance should also guide us while writing the code,
BUT in most cases - the alternative that uses code that is a bit slower(say using jQuery that makes using closures very easy) - is more readable and maintainable and should be used.

 

here are some of my notes(for me.. you shuold just watch it)
* mind your scope, minimizing the scope chain is better(don't use with, try/catch)
* try to use less closures
* property accessing is costly(store it at a var in the function)

Loops:
* don't use for-in for itertating arrays
* shorten loops and the amount of work in each step
for(var i=0, len=values.length ;i<len;i++)
{
  process(values[i]);
}

//flip loops (50% less time)
var len=values.length
for(var i=len;i--;)
{
  process(values[i]);
}

$.each(function... - this creates a closure for each iteration - use regular loop if you can

Dom
* HTMLCollections - BAD - and are evaluated always(sort of live objects)
  if you need to access it frequently - copy it to an array.
* eliminate Reflow(when adding items to a dom list for example)
* use DocumentFragment as a container document.createDocumentFragment- and then add this to the dom.
* do dom manipulations outside of the dom
* don't touch the style a lot - define a class instead that contains all of these if possible

 

MVC2 ActionFilterAttribute - During OnActionExecuting Don't use Redirect Use RedirectResult

Still haven't upgraded to the visual studio 2010 RTM, so I'm talking about version RC1 of MVC2(the one that shipped with VS2010 RC),
But i guess this is also the case with the RTM version.

We followed the excellent post by Rob Conery and implemented our own ActionFilterAttribute
to validate that only authenticated users gain access to some of the actions.
At OnActionExecuting we checked for anonymous users and redirected them to the login page.

All went well till Accidentally i stumbled upon an exception right before the user was redirected to the login page,
users will never see this exception, but the server will suffer.
i usually check the "Remember Me" checkbox to save time...
(it is always a good idea to check the "Thrown" checkbox for the "Common Language Runtime Exceptions"
at the Exceptions window => click on Ctrl+Alt+e to open it).

It turns  out that calling filterContext.HttpContext.Response.Redirect(loginUrl, true);
will redirect to the requested Url, but it doesn't stop the Action execution,
so the Action is called and also the OnActionExecuted(of the controller) event is called.

In my case i had an exception at one of the actions trying to get some user data,
and then an exception at OnActionExecuted where i set expiration headers on the request
(got the"Server cannot append header after HTTP headers have been sent.").

The solution:
Use filterContext.Result = new RedirectResult(sUrl); instead of the redirect.
this will skip the Action and of course redirect to the Url.

Note that although the requested Action was skipped, OnActionExecuted will be executed,
but the filterContext.Canceled property will be set to true so you can stop unwanted execution inside it as well

hope this helps.



Alt.Net Israel #3 - the programming languages talk(mostly on F#)

מאוד נהנתי בכנס האלט נט ביום שישי שעבר, גדי תאר אותו בצורה מצויינת.

צילמתי את הקבוצה שדנה בנושא שפות תכנות, אבל תכלס בעיקר דיברנו שם על F# ותכנות פונקציונאלי בכלל, והאם זה טוב לנו.
מצטער מראש על האיכות(למרות שהופתעתי לטובה) והחלוקה לחמישה חלקים - צילמתי במצלמת סטילס (canonPowerShot s3),
שמסוגלת לצלם עד 10-15 דקות בכל פעם(אני יודע שאני יכול לאחד אל הסרטונים, אבל זו התעסקות שלוקחת זמן).
 
למעט הדגמה קצרצרה על הלוח, היו בעיקר דיבורים, כך שאם יותר נוח לכם, תמירו ל MP3 ותהנו משיחה מעניינת.
תהנו:
חלק 1:
 
חלק 2:

 
חלק 3:

 
חלק 4:

 
חלק 5:

Simple RTFEM OR why asp.net MVC [ValidateInput(false)] doesn't disable request validation on asp.net 4

Have been doing a lot of asp.new MVC the past three months, learning it as we build the project(hope to share more in the near future).
We are using visual studio 2010, so now we're stuck with MVC2 RC1 since RTM wasn't shipped for the the RC version of 2010 (and yes this is a huge rant!!, we are stuck with 2010 since we also chose to work with entity framework 4 which only work on framework 4.0).
This is why i suspect every feature that doesn't work well as a problem of an early release.

Before i get to the point, just wanted to state that i really like the MVC framework, and i don't even consider moving back to WebForms.
it is much more natural to write code this way, and the thing i like the most is that it is extensible and Microsoft have released all it's code, so if something doesn't behave well - ditch it and replace it, using the supplied code as a reference.

Now to the point - RTFEM == Read The Fucking Error Message.
well.. nobody hardly does, and if the error is too long - nobody reads it.
At one of my forms i use a Rich Text Editor (TinyMCE if you must know), so i have to disable request validation or else i'll get a server error for posting potentially....

In WebForms you just set the validateRequest="false" at the page level, and you're OK.
in MVC
disabling this feature is a bit different,
setting validateRequest="false" on the aspx or at the web.config won't cut it since these are only views, the controller handles the request first and just use the view as template.
So the MVC team gave us the [ValidateInput(false)] attribute to disable this annoying feature.
But just setting it on an action will also fail, you still have to set one more setting at the web.config for this to work(if you are working with asp.net 4):
<system.web>
...
<httpRuntime requestValidationMode="2.0" />
...
</system.web>

you can read at the ASP.NET 4 Release Candidate (RC) Breaking Changes that now all requests to the server "enjoy" this validation,
and not just aspx pages, which is OK and more secure, but MS should have gave us a better way to disable it for specific requests, instead of just reverting to the 2.0 mode.
as the above paper states,request validation is enabled before the beginRequest stage, so i don't believe that at the RTM it will be fixed.

As for the time it took me to realize that and add the web.config entry, the answer was in front of me all the time in the ugly YSOD(yes i feel stupid now),
I just ignored it because it had all this WebForms specific error data and instructions that i know are not the answer.

I would expect a change at the error message from MS for the MVC people(or better - that putting [ValidateInput(false)]will just work) , but that's just me dreaming.

The error message(the yellow part is the relevant part for me): 

A potentially dangerous Request.Form value was detected from the client (SomeLie="<b>Bold Lie</b>").

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. To allow pages to override application request validation settings, set the requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0". Example: <httpRuntime requestValidationMode="2.0" />. After setting this value, you can then disable request validation by setting validateRequest="false" in the Page directive or in the <pages> configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. For more information, see http://go.microsoft.com/fwlink/?LinkId=153133.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (SomeLie="<b>Bold Lie</b>").

 

P.S.
when looking for the solution, encountered this http://stackoverflow.com/questions/1461330/validateinput-attribute-doesnt-seem-to-work-in-asp-net-mvc
This shows another thing to look for - "If there are any calls to other actions in the request context (e.g. from the Master Page or child partials) these actions also need to have [ValidateInput(false)] set appropriately"

hope this helps.

והסבר קצר בעברית: יתווסף פה בהמשך.. עייף מידיי כרגע, מצטער.
רק תקפידו לקרוא את הודעות השגיאה, גם אם נראה שהן לא לגמריי קשורות.

 
 

jQuery Gotcha: val() might select the wrong option at a select element

Let's imagine you have the following select element:

<select id="someSelect">
  <option value="">-Select-</option>
  <option value="12">21</option>
  <option value="11">20</option>
  <option value="10">19</option>
  <option value="9">18</option>
  <option value="8">17</option>
  <option value="7">16</option>
  <option value="6">15</option>
  <option value="5">14</option>
  <option value="4">13</option>
  <option value="3">12</option>
  <option value="2">11</option>
  <option value="1">10</option>
</select>

Notice that the text in some options appears as value in other options.
you can get a select like this when composing an age drop down for example.

Now for the Gotcha: which option will be chosen as a result of the following expression:
$("#someSelect").val("12");
???
Answer: the selected option will be <option value="3">12</option>
and not the option with the value of 12 as we intended.

Why this happened?
Let's look at the part of the jQuery(varsion 1.3.2) val() function that handles the Select:

...
else if ( jQuery.nodeName( this, "select" ) )
{
  var values = jQuery.makeArray(value);
  jQuery( "option", this ).each(function()
  {
    this.selected = (jQuery.inArray( this.value, values ) >= 0 || jQuery.inArray( this.text, values ) >= 0);
  });
  if ( !values.length )
    this.selectedIndex = -1;
}
...

it loops on all the items of the select and tries to match either the value or the text against the input value,
it was designed to help us select options by text, but i find it a bit annoying...

How to avoid this Gotcha?
for select elements of this nature you can use:
$("#someSelect option[value=" + val + "]").attr("selected", "selected");
or
jqThePrefoundSelect.find("option[value=" + val + "]").attr("selected", "selected");
or... well you get the point - just make sure you find the option by it's value and not it's text.

hope this helps.

והסבר קצר בעברית:
שימו לב ל select שהצגתי לעיל,
בחלק מה options שלו יש ערכים שמופיעים כטקסט ב options אחרים.
זהו תרחיש אפשרי למשל במתן אפשרות לבחירת גיל של משתמש.

במידה ונרצה לבחור ערך באמצעות jQuery בצורה הבאה:
$("#someSelect").val("12");

במקום שתיבחר ה option בעלת הערך 12(כמו שרצינו), תיבחר ה option בעלת הערך 3, כיוון שהטקסט שלה מכיל 12
את הסיבה לכך הצגתי בקטע הקוד מהפונקציה val לעיל(קטע הקוד הבעייתי מסומן בצהוב):
רצים בלולואה על כל ה options ומנסים למצוא התאמה לערך ולטקסט,
זה נועד לאפשר בחירה קלה של ערך לפי הטקסט שלו, אבל במקרה שלנו זה משבש את העניינים.

אז מה עושים?
מוודאים שבוחרים את ה option הנכון לפי הערך שלו, ולא לפי הטקסט.
הצגתי לעיל שתי אפשרויות(כמובן שאפשר בעוד דרכים, גם לולאה פשוטה ב JS תעשה את העבודה)
אחת מהצורות שהצגתי:
$("#someSelect option[value=" + val + "]").attr("selected", "selected");
 
 

ALT.NET Israel #3 - Spring 2010

שריינו את יום שישי ה 26.3.10 (ואת הערב של יום חמישי שלפניו).
בשעה טובה כנס alt.net israel נוסף יוצא לדרך.
 
כל הפרטים נוספים בקבוצה בגוגל

ולמי שאין פייסבוק, הנה הפרטים המינימלים שצריך לדעת ע"מ להגיע:
תאריך התחלה: Thursday, March 25, 2010 at 6:00pm
תאריך סיום:  Friday, March 26, 2010 at 4:00pm
מיקום: משרדי חברת סירס ישראל (SHC) - המנופים 9 הרצליה פיתוח (מפה)
         בניין אקרשטיין A, קומה 3, על הדלת כתוב SHC ISRAE
 

הייתי בשני הכנסים הקודמים והיה ממש מעניין, וכמובן, אחלה אנשים.
קצת הרצאות מהכנס הקודם בפוסט ישן שלי
ועוד לינקים להרצאות מהכנס הראשון בדלישס שלי.
 
וכמובן תודה לחן אגוזי (AKA ken) על היוזמה והארגון,
לחברת סירס ישראל על האירוח
ולחברת טייפמוק על הכיבוד
 
נתראה שם.
 
 
 
 
 
 

How to change ASP.NET MVC 2 default folder structure in Visual studio 2010 Beta 2

החלטנו בצוות לכתוב את המערכת החדשה ב MVC 2 (נשבר כבר מזמן מ web Forms).
מבנה הספריות הדיפולטי לא מתאים לנו - לוגית האפליקציה שלנו מחולקת לשני תחומים עיקריים, לכן רצינו פיצול של הקוד, בעיקר מטעמי תחזוקה.

ב web Forms היינו יוצרים שתי ספריות ומתחת לכל ספריה היו נמצאים הקבצים הרלוונטים אליה.
ב MVC 2 התווסף הפיצ'ר Areas, או יותר נכון single-project area (בגרסא הסופית של MVC 2 לא ישוחרר הפיצ'ר של פיזור areas בפרוייקטים שונים, אבל מי צריך את זה בכלל)-
     הכוונה - הוספת ספריה בשם Areas ב root של הפרוייקט,
                ומתחתיה יש ספריה לכל area - בעצם ספריה שמכילה את ה controllers ו views עבור אותו area
                מאוד נח לחלוקת הפרוייקט, מה גם שיכול להיות לכם controller בשם זהה בשני איזורים שונים(שכמובן יעשה פעולות שונות)
הסבר על areas אפשר לראות בהרצאה מ PDC2009 בשם Microsoft ASP.NET MVC 2: The New Stuff בערך מדקה 12

בצורה מפתיעה, ב 2 visual studio 2010 beta לא קיים התפריט של הוספת area (חבל שהבחור מה PDC לא ציין זאת, ותודה לנעם קינג שהעלה את הנקודה הזו בפניי והפנה אותי לכאן)
קצת מתסכל שבכל חיפוש כמעט הגעתי אל הפוסט של Phil Haack, שמסביר איך לממש areas אבל גם מציין בראשית הפוסט ש "Single project areas are a core part of ASP.NET MVC 2"

איזו התרגשות,יש תמיכה, ויהיו תפריטים בגרסה של visual studio שתצא בפבואר, אבל איך בונים את זה עכשיו??
חיפושים העלו את ההסבר הבא Walkthrough: Organizing an ASP.NET MVC Application using Functional Areas ששוב מראה שימוש בכלים, שכרגע קיימים רק עבור visual studio 2008 מול asp.net mvc 2 rc, אבל יש שם פרוייקט דוגמא :-).
1. תורידו את פרוייקט הדוגמא.
2. צרו בפרוייקט שלכם מבנה ספריות דומה למבנה שיש שם תחת ספרית areas,
    ואל תשכחו להעתיק את קובץ הרישום AreaRegistration.cs בכל אחד מהאיזורים שלכם.
3. עכשיו שנו את שמות האיזורים בקובץ הרישום,
    ואל תשכחו לשנות את ה  namespace (שימו לב שה namespace צריך להכיל .Areas. בשביל שיעבוד).
4. תוסיפו AreaRegistration.RegisterAllAreas(); בפונקציה RegisterRoutes  שב global.asax מיד אחרי ה IgnoreRoute.

סיימנו Happy Happy Joy Joy

הסיבה להיצמדות לקונבנציות האלה קשורה למציאת ה views ע"י ה view engine הדיפולטי של asp.net MVC
יכולנו לכתוב View Engine משלנו ואז לבנות את הפרוייקט באיזו צורה שנרצה (המיקום של ה controller-ים פחות משנה, הם בכל מקרה יזוהו)
אבל אני מעדיף להיצמד לקונבנציה במקרה זה.

הסבר קצרצר באנגלית אפשר למצוא בתשובה שלי ב stackoverflow ועוד הסברים על פתרון בעיות בפוסט הבא


מקווה שזה עוזר למישהו


Refactoring Principles & Web on the next WDC - 24.1.2010

חבר'ה, החודש אורי לביא, חבר קרוב ומקצוען אמיתי, מעביר הרצאה על refactoring עם אוריאנטציה ל WEB,
בזמנו כבר יצא לי להיות נוכח בהרצאה כללית יותר על refactoring שהוא העביר, והיה מצויין.

לא תראו בהרצאה את רק את תפריטי refactoring של visualstudio אלא תהליך מחשבתי מובנה, שבסופו מתקבל קוד יותר נקי וברור - פשוט תענוג.

להרשמה לאירוע: http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032439188&culture=he-IL

לאור הגידול במצבת כח האדם המשפחתית שלי :-) , אני לא בטוח שאצליח להגיע, אבל בהחלט אעשה מאמץ.

לכל חובבי האומנות - מכירת סוף שנה בארטא

כמו בכל שנה, גם השנה בשני סופי השבוע האחרונים של השנה - מבצע בארטא - כמעט על כל המוצרים ניתנת הנחה של 1+1.
פרטים נוספים בפוסט שלי משנה שעברה.

אמנם פספסתי את שבוע שעבר,
וקרוב לוודאי שלא אוכל להגיע השנה(כל מיני אילוצים שגם עכבו את הפוסט הזה), אבל ממש ממליץ לכם להגיע,
כי אומנות יש לא רק בקוד. 

My simple JSON flavor - JavaScriptSerializer at the server and json2.js at the client

קודם כל, עבור הקורא היחידי שלי, אני מתנצל על העדר הכתיבה בבלוג, אוסף של תירוצים הוביל טיוטות של פוסטים אל ה GMAIL שלי ואני מקווה שייצאו בקרוב. 

עכשיו לעניין הפוסט, זהו אמנם לא סיפור חדש בכלל, אבל אולי יחדש למישהו משהו.
אין  שום סיבה לבנות/לפרסס מחרוזת JSON בעצמנו,

some assembly required


בצד השרת:
קיימות כבר זמן רב ספריות מוכנות חיצוניות כמו JSON.net by Newton או זו של Ajax Pro
ושתיים שמגיעות עם ה framework:
JavaScriptSerializer
DataContractJsonSerializer
תוך כדי כתיבת שורות אלו, מצאתי את הפוסט המצויין של Rick Strahl מאוגוסט 2008, JSON Serializers in .NET - not there yet,
בו הוא מסביר מדוע כתב ספריה משלו לפרסוס JSON, מראה את ההבדלים בין שתי המחלקות + יתרונות וחסרונות, שהובילו אותו לכתיבת ספריה משלו.

בזמנו, כשעלה הצורך, חסרון מרכזי של DataContractJsonSerializer היה שלא ניתן לסרייל באמצעותו טיפוסים אנונימיים (שימושי מאוד, אם מעוניינים להעביר מידע אל JS),
ובנוסף ה API שלו דיי מגעיל.
ובאותו זמן, כפי שציין Rick, המחלקה JavaScriptSerializer (שכן יודעת לסרייל טיפוסים אנונימיים) הוכרזה כ deprecated ע"י מייקרוסופט,
לא רציתי להשתמש בקוד שיותר לא יתוחזק (מסיבה זו גם נטשתי את הספריה המצויינת Ajax Pro ),
לכן השתמשתי בספריה של Newton (שעובדת מצויין).

עבר קצת זמן מאז ועם יציאת ASP.NET MVC מיקרוסופט החזירו לחיים את JavaScriptSerializer, לכן,למרות שהוא לא מושלם(חסרונות בפוסט של Rick),
הוא מספיק טוב בשבילי, וחוסך לי התעסקות עם עוד dll חיצוני, בסה"כ צריך להוסיף reference ל System.Web.Extensions
עטפתי את הקריאות ל JavaScriptSerializer בשתי פונקציות סטאטיות פשוטות משלי עבור היום שבו הוא אולי לא יספק אותי יותר(עדיין לא קרה).

using System.Web.Script.Serialization;

public class JsonSerializer

{

    /// <summary>

    /// uses the old JavaScriptSerializer (which is no longer deprecated)

    /// the beauty is it can Serialize annonymous types

    /// </summary>

    public static string Serialize(object Contents)

    {

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        string ret = serializer.Serialize(Contents);

        return ret;

    }

 

    public static T Deserialize<T>(string input)

    {

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        T ret = serializer.Deserialize<T>(input);

        return ret;

    }

}

בצד הלקוח:
גם כאן קיימים פתרונות כבר זמן רב,
הפתרון הנאיבי הרע!!! הוא שימוש ב eval על המחרוזת שמתקבלת, זהו פתרון רע כיוון שאם יש סקריפט מרושע בתוך המחרוזת, הסקריפט יופעל.
אני משתמש ב http://json.org/js.html הוא לא מרחיב את ה prototype ולכן לא מתנגש עם jQuery  לינק ישיר להורדת הסקריפט: http://json.org/json2.js ויש גם גרסא מכווצת שלו ששוקלת פחות מ 2.5.
דוגמת שימוש(עוד דוגמאות בתיעוד):

//turn js object to a string to send to server
var myJSONText = JSON.stringify(myObject, replacer); 

//parse result from ajax call - i don't usually use the reviver
var myObject = JSON.parse(myJSONtext, reviver); 


אם אתם שולחים בקשות עם content type מסוג JSON אל service שיודע לקבל JSON אז לא תצטרכו לבנות/לפרסס בעצמכם, אבל יש מקרים שבהם זה נדרש, ואני מקווה שיהיה לי זמן לכתוב כמה דוגמאות בנושא.

קידוד נעים.

When build fails because it can't register a dll to the GAC

תופעה מרגיזה שיכולה להתרחש אצלכם בזמן העבודה(שרפה לי לא מעט זמן):

מדובר על עבודה עם dll-ים שמועתקים אל ה GAC ("תענוג" שיצא לי להתעסק איתו לא מעט לאחרונה),

במהלך העבודה, לפתע, הפרויקט מפסיק להתקמפל, ומודיע שהפקודה:

d:\...\gacutil -i $(TargetFileName)

נכשלה, מה שאומר שלא הצליח הרישום ב GAC (פקודה זו נקראת ב post build event ).

סגירת ה visual studio או מחיקת קבצים זמניים של asp.net ו iisreset לא יעזרו לכם פה (למרות שלפעמים נראה שזה פותר את הבעיה).

מה שגיליתי(יותר נכון אמיתי גילה לי) זה שה indexing service (ב vista שינו את שמו ל Windows search ) גורם לבעיה (כנראה תופס את הקבצים)

 

הפתרון – פשוט לעצור אותו ולנטרל אחת ולתמיד, הרי אף אחד לא משתמש ב search המובנה של windows:

1. start ->run

2. services.msc

3. select the "indexing service" / "Windows search" service and then stop it and then set the startup type to Disabled.

indexingService

on server 2003

 

(אם זה לא פותר את הבעיה, הנה לינק שמצאתי בעניין, מדבר על פתרונות ב    VISTA או בצורת הרישום:

http://social.msdn.microsoft.com/Forums/en-US/clr/thread/2c1c5363-1c48-40b3-bfa1-41d24c1a885b

 

ממתי שניטרלתי את השירות הארור הזה, כל קימפול גם לוקח פחות זמן, ממש תענוג.

Little LifeHack - editing your Hosts file in one click

בתור מפתח WEB יוצא לי לא מעט להתעסק עם קובץ ה hosts.

אני מקווה שאני לא מחדש לאף אחד שום דבר,אבל יוצא לי לא מעט לראות מפתחים שבכל פעם פותחים את הקובץ בצורה הבאה:

1. ניגשים אל התקייה C:\Windows\System32\drivers\etc

2. מנסים לפתוח את הקובץ

3. נפתח הדיאלוג של open with (יכול להיות ממש מעיק, כיוון שלפעמים לוקח לו המון זמן להיפתח)

4. בוחרים ב notepad  וממשיכים

 

יש כאלה שמחזיקים בקיצור דרך אל הקובץ, אבל עדיין בכל פעם בוחרים באיזו תוכנה לפתוח את הקובץ.

פתרון פשוט: להגדיר את notepad כתוכנה שתריץ את הקובץ מתוך קיצור הדרך:

1. צרו קיצור דרך אל קובץ ה hosts

2. במאפיינים של קיצור הדרך, ערכו את ה target (בטאב shortcut ) בצורה הבאה:
    במקום

C:\Windows\System32\drivers\etc\hosts

רשמו

      notepad "C:\Windows\System32\drivers\etc\hosts"

3. למי שלא רוצה בכלל לגעת בעכבר, אפשר בנקודה זו גם להכניס קיצור מקשים

4. אם אתם עובדים עם vista אז צריך גם להגדיר שקיצור הדרך ירוץ כ administrator:
    בטאב ה shortcut ללחוץ על advanced > לסמן run as administrator

ב vista:

hosts

תהנו

נפתח עוד מסלול - קדימה להירשם - IDCC

בחרתם, הצבעתם  ונרשמתם ובזכותכם נפתח עוד מסלול!!
תודה לכל הנרשמים.
ולאלה שלא נרשמו עדיין, נשארו עוד מקומות, וחבל לפספס.
 
. idcc2009
נכון לעכשיו:
רישום, התכנסות וכיבוד קל
08:30-09:00
 
15:30-16:45
 
מליאת סיום חלוקת פרסים
16:45-17:00
מצפה לנו כנס מרתק.
ניפגש ביום שני במרכז הבינתחומי בהרצליה.
 
ייתכן ויהיו שינויים בלו"ז או בסדר של ההרצאות, לכן מומלץ לעקוב אחרי האתר של הכנס.
וכמעט שכחתי, יש גם אירוע בפייסבוק למי שמעוניין לעקוב דרכו.
 
More Posts Next page »