November 2009 - Posts

.Net support for XSLT 2.0

On my way of searching Simple URL ENcode on xslt. there are few solution which i haven’t test, using encoding, Calling a built in template.

It turns out that there’s a built in function in xslt 2.0 : encode-for-uri.

And .Net support under that msscript namespace is Still 1.0.

On MSDN , when .net 2.0 released it support 1.0 because simply 2.0 is not ready yet.

There are library for this which is build by Microsoft MVP, called MVP.XML

Share this post: | | | |
Posted by cipto with no comments

XSLT Support for Calling .Net Function

.Net Support only xslt 1.0

I’ve just found out that We can call .net function inside XSLT, Example.

using msxsl:script tag

You can Make a C# function and use on your template

ain’t it cool? But read more that It’s Evil and Here:

“The problem is that when XSLT stylesheet is loaded in .NET, msxsl:script is compiled into an assembly via CodeDOM and then loaded into memory, into the current application domain. Each time the stylesheet is loaded above process is repeated - new assembly is being generated and loaded into the application domain. But it's impossible to unload an assembly from application domain in .NET!”

Share this post: | | | |
Posted by cipto with no comments

Client Side Repeater and Paging

Aloha.. So on this Article lest discuss How to Do a Repeater From Template But Client Side and Paging We are going to Use JTemplate and jquery Pagination. Imagine that a repeater that does not use server memory and Adding something to The Control Tree. :) Feed Them Json and They shall work, Neat.. So First We need a div container for Paging and the content it self, News-Pagination Div would be the paging container, and Mycontainer is End result container for our data

   1:  <div>
   2:      <div style="width:100%;">
   3:      <div id="News-Pagination" style="float:right" class="pagination"></div>
   4:      </div>
   5:      <div style="clear:both;margin-bottom:10px"></div>
   6:      
   7:      <div class="front64" id="MyContainer"></div>
   8:  </div>

On first Call we need to Set the Total Row That return (line 17), so that the paging can runs. What i don’t like about this is we have to make a double call.

We Can set The Template By URL or Feed String directly , The pattern is like line 27-28. On Next or Prev The Event Handler is Line 39

   1:  function MyInitialClass{
   2:  this.pagenumber=1,
   3:  this.pagesize=4,
   4:  this.totalmessage=0
   5:  }
   6:  var popMessage = new MyInitialClass();
   7:   
   8:  $(document).ready(function() {
   9:     FirstCall(popMessage.pagenumber, popMessage.pagesize);  
  10:   
  11:  });
  12:   
  13:  function FirstCall(pageindex, pagesize) {
  14:   
  15:      $.getJSON('services/MyHandler.ashx?p=' + pageindex + '&s=' + pagesize, function(messages) {
  16:          popMessage.totalmessage = messages.totalmessage;
  17:          $("#News-Pagination").pagination(popMessage.totalmessage, {
  18:              items_per_page: popMessage.pagesize,
  19:              callback: handlePaginationClick        
  20:          });
  21:   
  22:      });
  23:  function GetNext(pageindex, pagesize) {
  24:      $('#MyContainer').fadeOut('medium');
  25:      $.getJSON('services/MyHandler.ashx?p=' + pageindex + '&s=' + pagesize, function(messages) {
  26:          //Set and Apply template
  27:          var template = $('#item_template').html();
  28:          $('#MyContainer').setTemplate(template);
  29:          $('#MyContainer').processTemplate(messages);
  30:          //set total
  31:          for (var a = 0; a < messages.messages.length; a++) {
  32:              document.getElementById(messages.messagesAngel.rootmessageid).innerHTML = messages.messageAngel.message;
  33:          }
  34:          $('#MyContainer').hide().fadeIn('slow');
  35:         popMessage.totalmessage = messages.totalmessage;
  36:      });
  37:   
  38:  }
  39:  function handlePaginationClick(new_pageindex, pagination_container) {
  40:      GetNext(new_pageindex + 1, popMessage.pagesize);            
  41:       return false;
  42:      }
  43:   
  44:   
  45:  }

Another Trick would Be, if you see on Line 27. We are Getting Template From a Script Type=text/html.

If you put script type=text/html ,this will hide any markup in the document without interfering with HTML validator.we can put inline our Template in the Same page with out any Error and it will not displayed on page.

So Put our template on page. Below is only Example

   1:  <script type="text/html" id="item_template">    
   2:  <div>
   3:      <ul>   
   4:          {#foreach $T.messages as record}
   5:          <li>
   6:              <div class="vcard">
   7:                  <strong><a href="{$T.record.fullname}/{$T.record.shortname}" title="{$T.record.firstname} {$T.record.lastname}">
   8:                      <span class="userImage">
   9:                          <img class="photo" alt="alt tag here" src="services/imageHandler.ashx?image=images/upload/photos/c{$T.record.clientid}avbig.jpg&amp;w=63&amp;h=63&amp;always=true&amp;aspec=true&amp;nopic=noavatarl&amp;resizeby=w"
  10:                              height="63" width="63"></span><span class="nickname">{$T.record.firstname} {$T.record.lastname}</span></a></strong>&nbsp;wrote:<br>
  11:                 
  12:                  <div id="{$T.record.rootmessageid}" class="hr3"></div>
  13:              </div>
  14:          </li>
  15:         
  16:          {#/for}
  17:      </ul>
  18:  </div>
  19:  </script>
 
 
On Your Handler Do A Paging On Your Store Proc,Receving P as page and S as size and Output The endresult with Json, I use Newtonsoft.Json.Linq.JObject for a long time.
 
   1:   var json = JObject.FromObject(new
   2:                                                    {
   3:                                                        messages = (from c in result
   4:                                                                    select
   5:                                                                        new
   6:                                                                            {
   7:                                                                                fullname = c.fullname,
   8:                                                                                firstname = c.firstname,
   9:                                                                                lastname = c.lastname,
  10:                                                                                clientid = c.clientid,
  11:                                                                                shortname = c.shortname,
  12:                                                                                message = c.message,
  13:                                                                                messagetypeid = c.messagetypeid,
  14:                                                                                rootmessageid = c.rootmessageid,
  15:                                                                                sum = c.sum
  16:                                                                            }),
  17:                                                        totalmessage = howmanyitems
  18:                                                    });
  19:                  context.Response.Write(json.ToString());
  20:                  context.Response.End();

That’s it . See you again Folks

Share this post: | | | |
Posted by cipto with no comments

Port your Flash to Silverlight

I've got a scenario where the flash is already running and need to port the vector or even the full application to silverlight. To port the vector ,ask your flash programmer to export to SVG or AI then With Inkspace, an open source Vector Editor. you can export that svg/ai To XAML I tried the SilverX , it ports From FLash to silverlight project etc, it runs. but could be because my silverlight is simple,
Share this post: | | | |
Posted by cipto with no comments
Filed under:

How To Scale your silverlight app

I’ve got a scenario that the Silverlight app need to resize according to browser width and height. So that means on browser resize your silverlight app resize too

First make your usercontrol under a Canvas and Name it ex:Layout

add skewtransform on your root canvas

<Canvas.RenderTransform>
        <ScaleTransform  ScaleX="1" ScaleY="1" x:Name="LayoutScale" />

    </Canvas.RenderTransform>

On your Code Constructor

   1:  public MainPage()
   2:  {
   3:  //for first time 
   4:              this.SizeChanged += new SizeChangedEventHandler(MainPage_SizeChanged);
   5:  //on browser resize execute this event
   6:              App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
   7:       
   8:  }
   9:   void Content_Resized(object sender, EventArgs e)
  10:          {
  11:              double height = App.Current.Host.Content.ActualHeight;
  12:   
  13:              double width = App.Current.Host.Content.ActualWidth;
  14:              LayoutScale.ScaleX = width / (Layout.Width);
  15:   
  16:              LayoutScale.ScaleY = height / (Layout.Height);
  17:          }
  18:   
  19:          void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
  20:          {
  21:              double height = App.Current.Host.Content.ActualHeight;
  22:   
  23:              double width = App.Current.Host.Content.ActualWidth;
  24:              LayoutScale.ScaleX = width / (Layout.Width);
  25:   
  26:              LayoutScale.ScaleY = height / (Layout.Height);
  27:          }

Share this post: | | | |
Posted by cipto with no comments
Filed under:

Possible of Memory Leak?

I’ve done my reading on this article and this relates to my client question, “Why is your FLV Converter Consume 50% of System Resources Although there’s no Video/Task to convert?”..

Lets dig into this.

Memory Leak is a consumption of memory by a program where the program is unable to release the memory it has acquired

Is it possible to have a memory leak on .Net? Yes, although we have the GC.. the garbage management

How?  Remember the Our garbage man rule? it can only collect an object that is Not Referenced Any More (Unreachable).

So if we still have an object Link To (reference) some Event/Object Than That is the source of evil.

based on the article, what is the common mistake?:

  • Static Field
  • Static Event
  • Improperly Disposed object.
  • Event not unregistered
  • etc

The point is after you add Event myclass.SomeEvent+=Someevent_Handler

You need to unregistered it properly on disposed event.   myclass.SomeEvent-=Someevent_Handler

Static Events

For instance , if we subscribe to System.Events.some of the events are static .

When subscribing to a static event, it is important to remember to detach from the event before your application closes or the object subscribing to the event is disposed. Failing to do so can result in memory leaks for your application since the event subscription will not be broken automatically when the object closes.”

after you closed it It stays and live… Think about that. because GC can’t collect whatever still alive. Static type Lives Forever

The problem becomes bigger, because 1 object reference another, and that another contains lots of object, if the root stays and so is the descendent.

This Leak can happen on most application type,winform, wpf, prism pattern, mvp pattern.it’s not about the type but more to how .net works :) so understanding will be the Key here to write better code and Not bloating the memory. :)

So i try to use the Jetbrain dottrace, although it’s explained in graphical and legend , i seems to quite not happy about it.so i use .Net memory Profiler.. It’s better , i like the way it Shows error similar to visual studio.

ex: it says “This object type is not properly disposed but being collected”, and i put a dispose in the end, or use Using on c#

and i can see another dumb of my coding.

If you use Console the Main Must be Static, and you can only access static type Member/method from static method. First thinking, make everything static. Yeah right, you are making living monster.

Example So instead of

   1:  class program
   2:   
   3:  {
   4:   
   5:  Private Static List<string> GetListVideo(){
   6:   
   7:  //do bla bla bla
   8:   
   9:  };
  10:   
  11:  Static Main(arg[] string)
  12:   
  13:  {
  14:   
  15:  mylistvideo=GetListVideo();
  16:   
  17:  //do something with mylistvideo
  18:   
  19:  }
  20:   
  21:  }
  22:   

Put on another class or make it initiate able

   1:  class program
   2:   
   3:  {
   4:   
   5:  Private List<string> GetListVideo(){
   6:   
   7:  //do bla bla bla
   8:   
   9:  };
  10:   
  11:  Static Main(arg[] string)
  12:   
  13:  {
  14:   
  15:  mylistvideo=new program().GetListVideo();
  16:   
  17:  //do something with mylistvideo
  18:   
  19:  }
  20:   
  21:  }

we can also use weakreferences.

So i need to Detail my application More, Do more Reading and Back Update with report on this writing.

19/11/2009

Solved

After doing profiling on my application using windbg(?? ugh hard one), dottrace,.NetMemprofiler(yes, more human)

I put dispose on the place that it should,Put The close of Process (because i open an external process on task) on the finally clause and remove static to something initiate able.

but what really solve is .. something really back to basic

On my loop forever, add a sleep

   1:  While(true)
   2:  {
   3:  //check Task Collection
   4:  //Initiate SubThread
   5:  //Give every sub thread a Signal call back using autoreset event
   6:  //Start the Task
   7:   
   8:  Thread.Sleep(300);
   9:  }

This cool down the CPU time.. When there is no task .

Btw FYI FFmpeg will use 50% of your cpu during convertion and 50% of other on dual core processor. you can force ffmpeg to use full use 100% available resouce with a param ‘-thread2’

 

Share this post: | | | |
Posted by cipto with no comments

A Generic error occured GDI+ and Create High Quality Thumbnail

Wuiihh… what a pain in the ass. I’ve got a scenario to generate 3 different size of thumbnail on single upload

Microsoft is so lazy to named the error on GDI. so if something goes wrong it’s ‘A Generic error occurred in GDI+’ message.

After struggling on this. which can be caused by anything… from Folder permission to Not disposed correctly.

I’ve tried everything and in the final end, it’s because the naming of the file.. Weird… so i changed from xxx_AvBig.jpg to just xxxavbig.jpg . It runs correctly .

What a Not scientific Reason..

And then another problem is i Use this Image.CreateThumbnail , which will not Create a nice high quality thumbnail , it’s crappy..

The solution comes from this Guy

So to conclude the pattern would be:

   1:   using (Bitmap originalImage = new Bitmap(myFile.InputStream))
   2:  {
   3:  //ex:
   4:                  int width = 250;
   5:                  double ratio = Convert.ToDouble(250) / Convert.ToDouble(originalImage.Width);
   6:                  int height = Convert.ToInt32(ratio * originalImage.Height);
   7:  // superior image quality
   8:                  using (Bitmap bmpResized = new Bitmap(width, height))
   9:                  {
  10:                      string thumbnailFileName = fileUserBig;
  11:                      using (Graphics g = Graphics.FromImage(bmpResized))
  12:                      {
  13:                          g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  14:                          g.DrawImage(originalImage,
  15:                                      new Rectangle(Point.Empty, bmpResized.Size),
  16:                                      new Rectangle(Point.Empty, originalImage.Size),
  17:                                      GraphicsUnit.Pixel);
  18:                      }
  19:                      bmpResized.Save(thumbnailFileName);
  20:   
  21:                  }             
  22:  //do another thumbnail here like above …
  23:  }

 

Make sure that the height or width new size is not Small enough or Height is larger than width. i used fixed height and width for the small one. or it will throw that ‘gdi’ again

 10-11-2009

 I've got that Throw Exception with 'generic error again' this time i change all the Image.FromFile and Bitmap x=New Bitmap(filepath) To

using ( FileStream fs = new FileStream( filename, FileMode.Open ) )
bmp = (Bitmap)Image.FromStream( fs );

 Hmm also add the GC.waitforpendingfinalizer(); and GC.collect(); on the spot where it throws that GDI

Because The File Handle Sometimes Take A Time to Released or Not disposed Properly.

Share this post: | | | |
Posted by cipto with no comments
Filed under: