Category Archives: ASP.NET

Solution: Live Writer Error “Invalid Response Document” while connecting to WordPress

If you’re trying to connect to your WordPress blog from Windows Live Writer desktop client, you may get this dreaded error message:

Invalid Server Response – The response to the blogger.getUsersBlogs method received from the blog server was invalid: Invalid response document returned from XmlRpc Server

Invalid Response

This means that instead of expected XML response your blog sent back plain html or text message which is most likely some kind of error message. To see actual message you can either trace request response in an HTTP sniffer like Fiddler or simple enter endpoint url for your blog remote access (e.g. http://your.site.com/wordpress/xmlrpc.php) into your browser address bar.
Continue reading →

Pebble Time: Draw transparent text over color bitmap background

Pebble SDK has had a feature allowing to combine 2 images with transparency for a while via different composition modes. Unfortunately this doesn’t apply to texts, so, for example, if you need to display transparent time over bitmap background – you had to draw time digits as custom bitmaps. What’s worse – composition modes do not apply to colors, the result is always black-and white.

But there is a way. Pebble allows you to capture graphics context of a layer as a standard bitmap in the layer update callback. You can access that bitmap as raw data. So if you have another bitmap with the background you want to show through current layer, all you have to do is copy it byte by byte into captured bitmap, but only if pixel of specified color, that you use as a mask is encountered.

For example if your current layer needs to show background bitmap “s_bitmap” thru whatever is drawn in white color (255) you can use following snippet:

GBitmap *fb = graphics_capture_frame_buffer_format(ctx, GBitmapFormat8Bit);
  
uint8_t *fb_data =  gbitmap_get_data(fb);
uint8_t *background_data =  gbitmap_get_data(s_bitmap);
  
for (int i=0; i < 144*168; i++) {
  if (fb_data[i] == 255) {
    fb_data[i] = background_data[i];
  }
}
    
graphics_release_frame_buffer(ctx, fb);

Here Line 1 captures context as a bitmap, Lines 3-4 access captured bitmap and background bitmap as raw data. Lines 6-10 loop thru the captured data (each pixel takes a byte and in this example we’re going thru full 144×168 screen). If pixel of a white color is encountered – it is replaced with pixel from the same address of the background bitmap. And finally Line 12 releases captured framebuffer.

And if you combine this approach with APNG support that Pebble Time features, you can even create animated texture for your texts.

UPDATE: Thanks to @Jnm for this tip: If your masking layer is black-and white (00 & FF) that entire IF block can be replaced with bitwise AND:

fb_data[i] &= background_data[i];

And effect will be the same.

UPDATE 2 You can further optimize this code in 2 ways: First, let’s say your mask begins at Y = 50 and ends at Y = 100 – you don’t have to loop thru entire screen – you can use the loop below. It also demonstrates how you can jump 8 pixels/bytes at a time by utilizing 64-bit type:

uint64_t *fb_data = (uint64_t *)gbitmap_get_data(fb);
uint64_t *background_data = (uint64_t *)gbitmap_get_data(s_bitmap);
  
for (int i=50*144/8; i < 100*144/8; i++) {
  fb_data[i] &= background_data[i];
}

Thanks rajrdajr for the tip!

Useful Links:

Pebble: How to autoscroll large text

Last time i described how to load random string from resource. If you recall the code ended up with the line

text_layer_set_text(s_textlayer_quote, (char *)quote);

to display loaded text on the screen. But what if text is too large to fit on the screen? If you’re building a watchface, there’s no scrolllayer with user interaction available. But what we can do is automatically scroll the text for user convenience to gradually reveal entire content.

The trick is to create text layer larger than it’s container. In my case I am displaying text full screen on Pebble window which is 144×168 pixels, but I will create text layer with the height of 2000:

#define WINDOW_HEIGHT 168
#define WINDOW_WIDTH 144  
#define TEXTBOX_HEIGHT 2000
...
s_textlayer_quote = text_layer_create(GRect(0, 0, WINDOW_WIDTH, TEXTBOX_HEIGHT));

If the loaded text is larger then container window we now can dynamically detect the difference:

text_layer_set_text(s_textlayer_quote, (char *)quote);
  
// if height of quote > height of window, initiate animation to scroll
GSize text_size = text_layer_get_content_size(s_textlayer_quote);
int number_of_pixels = WINDOW_HEIGHT - text_size.h;
if (number_of_pixels < 0) {
    animate_quote(number_of_pixels);
}

Here we get dynamic size of loaded text content and if the difference between window height and actual text height is negative – call animation function, passing number of pixel we need to shift by.

Now to animation function. Continue reading →

Pebble: How to load random string from resource

There’s no doubt that Firefly is a greatest TV series in the history of all creation. That is why when I was learning resource handling in Pebble SDK I have decided to create a watchface that would display a random quote from Firefly. And thanks to Bill Hatcher of http://cubemonkey.net/quotes/ I obtained a plain TXT file with almost 500 quotes.

The file is in the format "quote1%quote2%quote3..." e.g. there is a “%” separator between the quotes, so I quickly wrote a small script that gives me a position of each percentage sign within the file, so I can create an array of the positions in my C code for Pebble:

#define NO_OF_QUOTES 472
int aQuotePointers[NO_OF_QUOTES] = {0, 206, 354, 417, 480, 554, 662, 695,... 88825}

which basically gave me position of each quote in the file and which I prepended with 0 and appended with filesize. Then I added the resource to my project (in CloudPeble environment it’s as easy as loading a BLOB resource and giving it a name). A Pebble watchface or watchapp can handle resources of up to 96K, fortunately file with quotes was less, otherwise some kind of string compression would have to be implemented.

After that it’s a trivial matter to generate random position, retrieve quote from that position and display it on a text layer:

// determining number of quote (that will give us address of begining and end)
srand(time(NULL));
int number_of_quote = rand() % NO_OF_QUOTES;
  
//determining size of quote and allocating memory
int size_of_quote = aQuotePointers[number_of_quote + 1] - aQuotePointers[number_of_quote] - 1;
uint8_t *quote = malloc(size_of_quote);

//loading quote, displaying and freeing memory
ResHandle rh = resource_get_handle(RESOURCE_ID_FIREFLY_QUOTES);
resource_load_byte_range(rh, aQuotePointers[number_of_quote] + 1, quote, size_of_quote);
quote[size_of_quote] = 0; //null terminating string
text_layer_set_text(s_textlayer_quote, (char *)quote);

Lines 2-3 generate random index for the array of quote pointers
Lines 6-7 calculate size of the quote (based on position of current and next quote) and allocate memory for the quote
Lines 10-11 load range from the resource based on index and size
Lines 12-13 0-terminate the loaded range and display data on the text layer.

It’s all pretty straightforward and works like a magic and the result you can see in published watchface: Blue Sun Quotes.

Some useful links:

Next time I will describe how I handled situation when loaded quote is too long to display on a text layer

ASP.NET WebForms: Safe refresh after postback

It’s all too commons scenario in a Web Application, you initiate a postback by clicking a button (basically submitting a form), some action is performed, perhaps database is written to, all fine and good. And then you refresh the page. Or even page is refreshed for some purpose by a client-side JavaScript code. And the dreaded “resubmit” message appears, it differs from browser to browser, e.g. Firefox would say

“To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier”

And if you agree – the form is resubmitted again along with all the actions performed – not good.

This issue happens because the page is submitted via POST request and in order to refresh the page – POST request has to be resubmitted along with form action. And the solution is Post/Redirect/Get pattern. The idea is to take the page submitted via POST request and convert it into GET. In ASP.NET this can be achieved via simple Response.Redirect. You can redirect to another page or you can reload your current one:

Response.Redirect(Request.RawUrl)

This code redirects to original page URL, essentially reloading the from page server side. But now it’s a GET page, safe to refresh

WriteEndObject of JSON.NET ouptuts NULL literal

JSON.NET is a very popular framework to process JSON data in .NET. We recently upgraded from v4 to v6 and noticed strange thing it started to output null to JSON strings created by JsonTextWriter object.

For example if JSON produced by v4 would look like this:

{"param1":"value1", "param2":"value2",
"someArray":[{"arrParam1": "arrValue1"}, {"arrParam2": "arrValue2"}]}

Same code, using v6, would prodcuce

{"param1":"value1", "param2":"value2",
"someArray":[{"arrParam1": "arrValue1"}, {"arrParam2": "arrValue2"}]null}

that extra “null” makes it invalid and unusable JSON.

The .NET function to create JSON writes it into a StringBuilder and is pretty straighforward.

  1. It starts with call to WriteStartObject method of JsonTextWriter
  2. Then it creates parameter name via WritePropertyName
  3. Depending on whether primitive value or raw string needs to be written WriteValue or WriteRaw methods are used respectfully
  4. Repeat steps 2 and 3 as needed
  5. Call to WriteEndObjectto finish writing.

This worked perfectly well when version 4 of Newtonsoft.Json.dll was used. After upgrading to version 6 last method – “WriteEndObject” began to output “null” to resulting JSON.

The solution is to use WriteRawValue method instead of WriteRaw – it still outputs raw string, but at the end WriteEndObject doesn’t output “null” anymore.

Access nested controls in ASP.NET Page PreInit event (when no Master Page is involved)

There’re situations when you need access ASP.NET web controls very early in page lifecycle, more specifically – in Page PreInit event – and you can, but only top-level controls. But what if you need to access child/nested controls? The example below uses Infragistics WebHierarchicalDataGrid as a child of Infragistics WebSplitter, but this pretty much applies to any such scenario.

Let’s say you have following layout

<ig:WebSplitter ID="WSP" runat="server">
   <Panes>
      <ig:SplitterPane runat="server">
         <Template>

            <ig:WebHierarchicalDataGrid ID="WHG" runat="server">
            </ig:WebHierarchicalDataGrid>

         </Template>
      </ig:SplitterPane>
      <ig:SplitterPane runat="server"></ig:SplitterPane>
   </Panes>
</ig:WebSplitter>

As you can see grid “WHG” is nested withing first pane of splittet “WSP. Let’s see what happens if you try access the controls in PagePreInit event: Continue reading →

Developing first Pebble.js app

    

Pebble Smartwatch has offered SDK to develop watchfaces and watchapps in C language for a while now. But most recently they tried something different: Pebble.JS a project that lets you code for Pebble in JavaScript. Unlike native app – JS code runs on your phone, so it’s not as fast, and Bluetooth communication required to display any data, but there’re numerous advantages as well.

To test it I decided to write a simple app that would use basic, but important features of Pebble.JS: displaying of information card (a la Pebble notifcation), using menu and executing an AJAX call to bring information from the Net.

Enter AutoInsult for Pebble – application that is based on autoinsult.com – it generates a random insult based on style you selected.
Continue reading →

Access jQueryUI dialog buttons after dialog was created

If you’re using jQuery UI Dialog, you know sometimes there’s a need to access dialog’s button objects after the dialog has already been created. This can be easily done via

$(dialogElement).dialog("option").buttons

command. One possible scenario where this can be useful – is executing specific button click function when user clicks [X] in dialog title. Imagine that buttons are set via array and the last object in this array is always something like CANCEL or NO or DISREGARD – and you want to simulate click of that last button whenever user clicks [X]. Using above command it’s pretty straightforward:

$(oDivDialog).dialog({
   //... some dialog parameters
   buttons: arrayOfButtonObjects,
   //... some more parameters
   close: function () {
      var buttons = $(this).dialog("option").buttons;
      buttons[buttons.length - 1].click();
   }
})

Line 5 begins close event which is called on dialog closing.
Line 6 retrieves array of buttons for the dialog
Line 7 calls click() function of the last button in the array

Infragistics WebDataMenu: Manual postback from client-side Click event

There’s a a few possible scenarios when you need to manually to initiate server-side Click event of Infragistics WebDataMenu control. For example in client side click event you do some verification/user confirmation and upon positive confirmation (e.g. user clicks YES) – server-side Click event should kick in.

In a normal flow of event you can use set_cancel(bool) method to allow/disallow natural menu postback e.g.

function Menu_ItemClick(sender, eventArgs) {

   if (confirm('Are you sure?'))
       eventArgs.set_cancel(false)
   else
       eventArgs.set_cancel(true)

}

This works because this dialog stops code execution waiting for the user input. But what if you use something like jQueryUI dialog that relies on callback functions to get user feedback? In this case execution of the code continues immediately so you have to cancel postback right away and instead in the callback of the dialog initiate manual postback e.g

function Menu_ItemClick(sender, eventArgs) {

   $("#dialog").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "Yes": function() {
          $(this).dialog("close");
          __doPostBack(sender.get_id(), 'ItemClick' + eventArgs._getPostArgs());
        },
        "No": function() {
          $(this).dialog("close");
        }
      }
   });  

   eventArgs.set_cancel(true)

}

The example above initiates modal confirmation jQuery UI dialog and immediately cancels menu postback (Line 18). Later if user clicks “Yes” button – dialog is closed and manual menu postback is initiated (Line 10) – it passes menu ID and correct postback argruments which result in server-side Click event of menu control. If user clicks “No” – dialog is closed and nothing else happens.