November 2008 - Posts

Java Script ,OOP

Now , this is something that is worthwhile to take a look and have a good understanding.

Most of most that use the higher level of API build on top of Asp.net 2.0, Will rarely use client side scripting, so many people that even start jump to asp.net but does not even know what html is. but really at the end what you eventually will produce is merely HTML,DHTML and JavaScript.

I bet those that talk a lot about this and that technology still lacking of the fundamental concept.

this is the trickiest interpreter language, lousiest.

  • Even Function return as Object,
  • every thing works with name value pair { xxx:value }
  • If you haven't declare a method or member of a class,the interpreter will create it for you and it becomes global , on window.youmember
 function test() {
        foo = "test";
    }
    test();
    alert(window.foo == "test");
  • You can change the Execution Context by functionname.call(context,param1,n)  or functionname.apply(context,param1,n)

When EcmaScript interpret your code, it has the internal [[scope]] property that make a chain scope, the last scope only contains the global object. Scope can be Global, belongs to the window object. or Private , belongs inside a function

The prototype also make a chain , if an object refer to another one object, it keeps searching for it.Lastly the script will try to get the value into string if you access the value. while it build the variable/activation object the interpreter add arguments property that you can access inside any function .

Closures

an inner function that use and manipulate the outer function variable member or parameter.because of this comes the private and public member

Public Member

You can set directly on the

constructor

   1:  Function user(name,age)
   2:   
   3:  {
   4:   
   5:  this.name=name;
   6:   
   7:  this.age=age;
   8:   
   9:  }
  10:   

or by attaching on prototype

user.prototype.getname()=function{return this.name;};

Private Member Go here

Static method

Object.Staticmethodname=function{//your code here}; 

Can Javascript do Inheritance and Polymorphism?

Yes , with a little help from some wrapper, You can choose:

  1. Crockford Helper to refer to the base class function use the this.uber('functionname')
  2. DeanEdwards Base Lib this is more readable, since like if we want to refer to the base class function , just use this.base() , it will figure out itself which method
  3. Prototype Library 

 Name Space and Packaging

  1. Dojo Framework: dojo.js 77kb, include Ajax, widget, namespace ,etc.check it out
  2. YUI. yahoo user interface

Share this post: | | | |
Posted by cipto with 3 comment(s)
Filed under:

Simple Visual Studio Add in

Along the way to the office, I am  curious about visual studio add in , so i try to make and find the useful Link resources about this, one of them is mztools.com which make the mztool that i mention on previous post.

 

so just a straight and simple one, I would like to open the active window on Windows Explorer.Actually I have add a form and combo box and it will list all the file in current solution, but apparently the IDE hang every time the form load during adding the combobox item. some body suggest using threading. now I haven't got quite far. but it's the power of extensibility that make us does not do the repetitive task.

 

To create one just new project->other->addin . and then follow the wizard and choose the option as you needed.

I add another form

image

open the connect.cs that supplied for you.this is the main process goes to

every time your add in is clicked it will trigger the exec event.

the onconnection is the event usually where you want to change the icon.see the integer 100? that's the default icon , to get the complete listing i've to download the working with visual studio ebooks, which i haven't done so.

Command command = commands.AddNamedCommand2(_addInInstance, "CiptoAddin", "CiptoAddin", "Executes the command for CiptoAddin", true, 100

put this code before the handled, this variable name already implies it's usage...

Connect.cs

   1:  public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
   2:          {
   3:              handled = false;
   4:              if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
   5:              {
   6:                  if(commandName == "CiptoAddin.Connect.CiptoAddin")
   7:                  {
   8:                      FrmOpen frmopen = new FrmOpen();
   9:                      frmopen.m_applicationobject = (DTE)this._applicationObject;
  10:                      frmopen.Show();
  11:                      handled = true;
  12:                      return;
  13:                  }
  14:              }
  15:          }

Form1.cs

   1:   public partial class FrmOpen : Form
   2:      {
   3:          public DTE m_applicationobject { get; set; }
   4:          public FrmOpen()
   5:          {
   6:              InitializeComponent();
   7:              
   8:          }
   9:   
  10:          private void button1_Click(object sender, EventArgs e)
  11:          {
  12:            Window active = m_applicationobject.ActiveWindow;
  13:            System.Diagnostics.Process.Start(active.Document.Path);
  14:          }
  15:          private void FrmOpen_Activated(object sender, EventArgs e)
  16:          {
  17:              //get the current solution opened
  18:              //Solution2 temp = (Solution2)m_applicationobject.Solution;
  19:              //foreach (Project objproject in temp.Projects)
  20:              //{
  21:              //    foreach (ProjectItem item in objproject.ProjectItems)
  22:              //    {
  23:              //        //if(cmbfile.InvokeRequired)
  24:              //        if (item != null)
  25:              //            cmbfile.Items.Add(item.Name.ToString() + " " + item.Document.Path.ToString());
  26:   
  27:              //    }
  28:              }
  29:          }
  30:      }

 

Now the form activated run just once, after that the IDE will hang every time on the loop so I just uncommented it, but it's the way to iterate it

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

Generic Delegates,Lambda Expression

MSDN:

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types

(type param1, type param2,..n)=>{expression1;expression2;expression3;..n}

'=>' means goes to

 

the system have 3 generic delegates type

  • Action delegate , Action <T>,     for non returning value, or void use
  • Func<param1,param2...n,Result> , for returning function ,remember there's always a result in the end
  • Predicate<T>                                   , for searching a criteria use

Action sample

   1:       Action<double> printnumber = amount => Console.Write("{0:c} " + Environment.NewLine, amount);
   2:              Action<double> potongpph = amount => printnumber(amount * 0.1);
   3:   
   4:              var gaji = new double[] { 2700000.00, 5000000.00,6000000.00, 8500000.00, 10000000.00,15000000.00 };
   5:              Array.ForEach<double>(gaji, potongpph);
   6:              //kiri parameter,kanan functional body
   7:              Array.ForEach<double>(gaji.Where(sal => sal < 6000000.00).ToArray(), printnumber);
   8:   
   9:              Console.ReadLine();

func sample

   1:   Func<int, int, int> add = (int x, int y) => x + y;
   2:              Console.WriteLine(add(5, 4));

predicate sample

   1:  private static void Predicate()
   2:          {
   3:              List<int> fibolist = new List<int>() {1,1,2,3,5,8,13,21,34,55};
   4:              Predicate<int> matchfibo = n => n % 2 == 1;
   5:              List<int> SearchResult= fibolist.FindAll(matchfibo);
   6:              ObjectDumper.Write(SearchResult);
   7:          }

Bind to event sample

   1:  button1.Click += (s, e) => MessageBox.Show(“Click!”);

Now , When lambda is hooked up to a variable ,field ,delegate it creates the function and the contents that required, create the instance.

lambda 

When it bind to an expression ,System.Linq.Expressions.Expression<TDelegate>

it will generate the expression tree required. Expression Tree

lambda2

There's a precaution when using outer variable with lambda. because delegate will invoke only when it's used,  it will saves a copy of it.

Variables that are captured in this manner are stored for use in the lambda expression even if variables would otherwise go out of scope and be garbage collected . MSDN Example

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

another tool and components, and books arrived @ 10-11-2008

Component

 

Component one for WPF

Demo

Component one for asp.net 2.0

what's unique is there's paypal component,and webflash component

Component one spell checker

, add your menu IDE, check your projects spelling against you regional setting, important tools or not?

Component one DocToHelp2009

this is the tool for creating help file for our projects. in chm files format,java help,microsoft help2.0,nethelp,printed manual,winhelp 4.0

Component one activexstudio, the name implies

Component one Studio Mobile,the name implies

 

Tools

Linqer

Ever try the LinqPad? for trying linq syntax and get the result? , here is the opposite , enter your sQl Query it will translate to linq syntax

 

Books

Sams.Linq.unleashed

Professional WCF

Professional Web APIs Google Ebay Paypal Amazon Mappoint Fedex

OReilly - Programming WPF 2nd Edition

OReilly - JavaScript The Definitive Guide

OReilly - Programming WCF Services

 

Why does human create books? Why not create the brain like USB , so you can copy paste the books to human brains :P

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

Another Rich DHTML libraries Script.Aculo.US

http://script.aculo.us/
http://wiki.script.aculo.us/scriptaculous/
http://wiki.script.aculo.us/scriptaculous/show/Demos/

 

Check it out.

well, after finishing chapter 7 of pro JavaScript techniques ..

Now i check to this script aculo. when you see the demo then you will agree with the books, it's the king of DHTML.

Now apperantly when you want to work with cross browser issue. you'll find it's a hard way to event get the properties, on ie it's like this

on others w3c compliance like that. and so on.

so think of using like this one, jquery or moo.fx.

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

LINQ and DISTINCT using IEqualityComparer

Lagi kurang kerjaan nich ....  :P tapi bukan berarti minta boss(Buat bos gue kalo baca artikel ini)

 

this case is from Jimmy's blog

it raise a question  in my mind because i've used distinct in one column ,it works but when used on multiple column it doesn't

First of all disctinct is a set, so you can't use Lambda here, and only have to overload, whether nothing or iequalitycomparer.

 

Because of behind the hood disctinct use GetHashCode. http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

So you Have to Define your own GetHashCode , this is all main key here. else it won't work

Now from the link of msdnlocal use the XOR.

 

because if you use iequalitycomparer will not work if the hashcode doesnot return unique combination of those fields.

Now what i want to add is using iequality, same result as jimmy.

the comparer

   1:   public class DistinctNameBirtDay : IEqualityComparer<Person>
   2:          {
   3:              public bool Equals(Person x, Person y)
   4:              {
   5:                  return x.Name.Equals(y.Name) && x.BirthDate.Equals(y.BirthDate);
   6:              }
   7:   
   8:              public int GetHashCode(Person obj)
   9:              {
  10:                  return obj.Name.GetHashCode() ^ obj.BirthDate.GetHashCode(); ;
  11:              }
  12:          }
 
the main and distinct
   1:   static void Main(string[] args)
   2:          {
   3:              var people = new[] {
   4:   
   5:                  new Person("Unyil", DateTime.Today),
   6:   
   7:                  new Person("Cuplis", DateTime.Today.AddDays(1)),
   8:   
   9:                  new Person("Ucok", DateTime.Today.AddDays(2)),
  10:   
  11:                  new Person("Unyil", DateTime.Today),
  12:   
  13:                  new Person("Cuplis", DateTime.Today.AddDays(1)),
  14:   
  15:                  new Person("Pak Raden", DateTime.Today.AddDays(-5))
  16:   
  17:              };
  18:   
  19:   
  20:              

             var query = people.Distinct(new DistinctNameBirtDay());

  21:             // var query = people.Distinct();
  22:   
  23:              
  24:   
  25:              foreach(var o in query)
  26:   
  27:              {
  28:   
  29:                  Console.WriteLine(o.ToString());
  30:   
  31:              }
  32:              Console.ReadLine();
  33:   
  34:          }
  35:      }
Share this post: | | | |
Posted by cipto with 2 comment(s)
Filed under:

Just a Simple sample Json and Json Web Service

The Web Service
   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.Services;
   6:  using System.Web.Script.Services;
   7:      /// <summary>
   8:      /// Summary description for WebService
   9:      /// </summary>
  10:      [WebService(Namespace = "http://tempuri.org/")]
  11:      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  12:      // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
  13:      [System.Web.Script.Services.ScriptService]
  14:      public class WebService : System.Web.Services.WebService
  15:      {
  16:   
  17:          public WebService() { }
  18:          [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
  19:          [WebMethod]      
  20:          public Chapter GetNextChapter(int bookid, int currentchapter,int currentpage)
  21:          {
  22:              return new Chapter(bookid,currentchapter,++currentpage,"Texbox begin with Txt ,ComboBox begin with Cmb","Naming Convention") ;
  23:          }
  24:          [WebMethod]
  25:          [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
  26:          public string test()
  27:          {
  28:              return "Tweweweweweu";
  29:          }
  30:      }
  31:      public class Chapter
  32:      {
  33:          public int BookID;
  34:          public int currentChapter;
  35:          public int page;
  36:          public string content;
  37:          public string chaptertitle;
  38:          public Chapter(int bookid, int currentchapter, int page, string content,string chaptertitle)
  39:          {
  40:              this.BookID = bookid;
  41:              this.currentChapter = currentchapter;
  42:              this.page = page;
  43:              this.content = content;
  44:              this.chaptertitle = chaptertitle;
  45:          }
  46:          public Chapter() { }
  47:      }
 
Let's make a html page call mypage.htm or whatever
 
   1:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2:   
   3:  <html xmlns="http://www.w3.org/1999/xhtml" application="manifest-file">
   4:  <head>
   5:      <title>c#</title>
   6:  </head>
   7:  <body>
   8:  <input type="hidden" id="bookid" value="123" />
   9:  <input type="hidden" id="currentchapter" value="1" />
  10:  <input type="hidden" id="currentpage" value="1" />
  11:  <div id="ChapterTitle"><h3 id="ChapterTitleBar">Introduction</h3></div>
  12:  <div id="ChapterContent" >
  13:  <textarea id="ChapterContentText" style="width:600px;height:600px">
  14:  Whether you picked up this book from the bookstore, ordered it from an online site, or just got lucky and got a free copy, you had some notion of what you expected to be inside of it from the moment you first laid eyes on it. We discussed the concept with the publisher and others and it was interesting to hear the various perceptions that people had. The actual intent of this book is not to teach you how to "hack" ASP.NET applications from a security perspective, nor is it a guide about how to hack together a poorly written application. Its intent is to give you insight into techniques that you can use to build and deliver real-life applications using ASP.NET.
  15:   
  16:  Now that we have clarified the book's simple purpose, we should probably explain more about what it is and why it should be one of the few books you buy and recommend to everyone you know. Each of the authors of this book is a seasoned professional and is experienced with the .NET platform. All of us are Microsoft MVPs (Most Valuable Professionals) and have answered thousands of ASP.NET developer questions in various online and offline communities. In this book we share our insights into solutions for many questions we answer all the time. You can benefit from the cumulative experience we have gained in building real-life applications. Additionally, with the release of ASP.NET 2.0, we discuss a whole set of new issues in print for the first time.
  17:   
  18:  This is not an introductory book on ASP.NET, as you can find several on the market already that provide an excellent overview and introduction to ASP.NET application development. Further, this is not intended to be a reference guide that explains every feature and option in ASP.NET. Again, between the numerous books that focus on providing a reference source and the ever-improving MSDN documentation, the sources of rich reference information are numerous.
  19:   
  20:  What Is a Hack?
  21:  We are using the term hacks to refer to little-known solutions, undocumented features, and tips and tricks. Some people call them hacks; others call them creative solutions. You might have your own name for them, but they are all basically the same thing. Every application of any significance pushes the capabilities of ASP.NET and uses some form of a hack as part of the overall solution.
  22:   
  23:  Some of the past hacks that you might recognize are page templates, multiple forms, URL rewriting, and SQL cache dependencies. These popular hacks have found their way into countless production applications. For each of these there are hundreds of other hacks that simply did not become as widely accepted, and therefore the community (meaning ASP.NET developers) suffered from the lack of opportunity. This book exposes several little-known, but useful hacks that you, as developers, can employ in production environments.
  24:  </textarea>
  25:  </div>
  26:  <input type="button" value="GetPreviousChapter" />   
  27:  <input type="button" value="GetNextChapter" onclick="getnext();"/>
  28:  <input type="button" value="test" onclick="gettest();"/>
  29:   
  30:  <script type="text/javascript">
  31:   
  32:      function makePOSTRequest(url, parameters) {
  33:          http_request = false;
  34:          if (window.XMLHttpRequest) { // Mozilla, Safari,...
  35:              http_request = new XMLHttpRequest();
  36:              if (http_request.overrideMimeType) {
  37:                  // set type accordingly to anticipated content type
  38:                  // http_request.overrideMimeType('text/xml');
  39:                  http_request.overrideMimeType('text/html');
  40:              }
  41:          } else if (window.ActiveXObject) { // IE
  42:              try {
  43:                  http_request = new ActiveXObject("Msxml2.XMLHTTP");
  44:              } catch (e) {
  45:                  try {
  46:                      http_request = new ActiveXObject("Microsoft.XMLHTTP");
  47:                  } catch (e) {
  48:                      alert("not good at all..");
  49:                  }
  50:              }
  51:          }
  52:          if (!http_request) {
  53:              alert('Cannot create XMLHTTP instance');
  54:              return false;
  55:          }
  56:   
  57:          http_request.onreadystatechange = confirmResponse;
  58:          http_request.open('POST', url, true);
  59:          http_request.setRequestHeader("Content-Type", "application/json");
  60:          http_request.send(parameters);
  61:      }
  62:   
  63:      function confirmResponse() {
  64:          if (http_request.readyState == 4) {
  65:              if (http_request.status == 200) {
  66:                  result = http_request.responseText;
  67:                  DisplayResult(result);
  68:                  alert('Response:\n\n' + result);
  69:              } else {
  70:                  alert('There was a problem with the request.');
  71:              }
  72:          }
  73:      }
  74:      function DisplayResult(result) {
  75:         var thejson= eval("(" + result+ ")");
  76:         var dc = document.getElementById('ChapterContentText');
  77:         var ct = document.getElementById('ChapterTitleBar');
  78:         dc.innerHTML = thejson.d.content;
  79:         ct.innerHTML = thejson.d.chaptertitle;
  80:      }
  81:   
  82:      function getnext() {
  83:          var url = 'http://localhost:9999/WebSite2/WebService.asmx/GetNextChapter';
  84:          var bookid = document.getElementById('bookid').defaultValue.toString();
  85:          var currentchapter = document.getElementById('currentchapter').defaultValue.toString();
  86:          var currentpage = document.getElementById('currentpage').defaultValue.toString();
  87:          var string="{ 'bookid': " + bookid + ", 'currentchapter': " + currentchapter + ", 'currentpage': " +currentpage + "}";
  88:          var request = makePOSTRequest(url, string);
  89:      }
  90:      function gettest() {
  91:          var url = 'http://localhost:9999/WebSite2/WebService.asmx/test';
  92:          var request = makePOSTRequest(url, "");
  93:      }
  94:  </script>
  95:  </body>
  96:  </html>
Now when you click next chapter it's going to get from the web service.
To consume it json from a raw string notice the eval function.
notice how to pass the parameter to the web service it's pattern {'paramname':valueifinteger,'paramname2','valueifstring'}
 
27 November 2008
Or you can use jquery plugin,  
$(document).ready(function() {
$.ajaxDotNet('WebService.asmx/GetNextChapter',
{
verb: "POST",
	data: {param1,param2,..n},
error: function(d){alert(d.responseText);},
success: function(obj) {
//do what you want
		//$("#Text1").attr('value',obj.d);
}
});
});
 
Update 2010-11-05
There are People asking me about this, on the method above we just override the format,
We can also use the already supplied asp.net ajax to parse the return result of the Asmx which we already set [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
By Adding a ScriptManager and Register our service on the  Script Manager , Ex:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>
than We can Call The Object directly on Javascript, and the return result would be on Json or Javascript dynamic Object
 <script>
WebService.HelloWorld(OnMethodSucceeded, OnMethodFailed);
function OnMethodSucceeded(result, eventArgs) {
alert(result.toString());
}
function OnMethodFailed(error) {
alert(error.get_message());
}

WebService.GetProduct(OnProductSucceeded, OnMethodFailed);
function OnProductSucceeded(result, eventArgs) {
debugger;
for (var i = 0; i < result.length; i++) {
alert(resultIdea.Nama);
}
}
function OnMethodFailed(error) {
alert(error.get_message());
}
</script>
WebService
------------ 
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Collections.Generic;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ScriptService()]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Product> GetProduct()
{
List<Product> products=new List<Product>();
products.Add(new Product() { Nama = "A", Description = "DescA" });
products.Add(new Product() { Nama = "B", Description = "DescB" });


return products;
}
}
 Product Class
[DataContract]
public class Product
{
[DataMember]
public string Nama
{
get;
set;
}
[DataMember]
public string Description
{
get;
set;
}
}
 
 
Share this post: | | | |
Posted by cipto with 3 comment(s)
Filed under:

Exporting Template

Visual Studio Magazine Online | C# Corner: Define Your Own Item Templates

Did you know what i like most of this guy WOrd is below.

Developers are lazy. I don't mean that in a bad way, but in the same way that a smart horse is a lazy horse. Developers just don't stand for repeating the same tasks without finding a way to automate them. I count myself among the lazy developers. I'm quite willing to spend time figuring out how to automate those repetitive tasks that I find myself doing often. Visual Studio provides enough extensibility points that I've made a new rule for myself: If I do the same task twice, I figure out how to automate it.

 

I'm a very lazy developers , i don't like to go to the same spot twice, Oooo n mmm I hate Repetitive TASK

i love finding new way . new solution, Faster, Performance :D

enough about me

 

You can export the template Item as, from previous post, i would like to export a page template aspx.

Now as i tried , it will not generate the Code behind code Class As the name generated by Input.

 

Now here 's the trick

from downtown,

Defining Custom Item Templates in Web Projects with VS 2005 - ScottGu's Blog

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MyProject.$safeitemname$" %>

 

public partial class $safeitemname$ : BasePage
{

  protected void Page_Load(object sender, EventArgs e)
    {

    }

}
}

Visual studio Will replace the $safeitemname$ with the name that you type in. and as you might suspected it replace with what you generated

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

More On Compressing Asp Page and performances

3 days ago i've got a phone call from some project support. And i asked him how about the Bandwith test? did it passed?. Well he said that Compare to the last one, the size is Smaller 40%.

How is it possible?

1.Enable the Gzip content, which is already support by most browser and the feature is already exists since web 1.1

How to do this? there are many ways,westwind way, And i followed the omar way again, Enabling the IIS6 GZip compression by changing the metabase , though i already implemented it, but i haven't take a look the response content using tool. but it supposed to run , i already take a look at the Windows\temporaryiisfiles everything has a GZIP_what_.css or js or html,but to see the asp page is on the response content equals gzip .

2.I'm using the ViewState Compressor

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:   
   6:  /// <summary>
   7:  /// Summary description for Compressor
   8:  /// </summary>
   9:  using System.IO;
  10:  using System.IO.Compression;
  11:   
  12:  public static class Compressor
  13:  {
  14:   
  15:      public static byte[] Compress(byte[] data)
  16:      {
  17:          MemoryStream output = new MemoryStream();
  18:          GZipStream gzip = new GZipStream(output,
  19:                            CompressionMode.Compress, true);
  20:          gzip.Write(data, 0, data.Length);
  21:          gzip.Close();
  22:          return output.ToArray();
  23:      }
  24:   
  25:      public static byte[] Decompress(byte[] data)
  26:      {
  27:          MemoryStream input = new MemoryStream();
  28:          input.Write(data, 0, data.Length);
  29:          input.Position = 0;
  30:          GZipStream gzip = new GZipStream(input,
  31:                            CompressionMode.Decompress, true);
  32:          MemoryStream output = new MemoryStream();
  33:          byte[] buff = new byte[64];
  34:          int read = -1;
  35:          read = gzip.Read(buff, 0, buff.Length);
  36:          while (read > 0)
  37:          {
  38:              output.Write(buff, 0, read);
  39:              read = gzip.Read(buff, 0, buff.Length);
  40:          }
  41:          gzip.Close();
  42:          return output.ToArray();
  43:      }
  44:  }
  45:                     
  And i moved it to the BasePage
   1:  using System;
   2:  using System.IO;
   3:  using System.Web;
   4:  using System.Web.UI;
   5:   
   6:  /// <summary>
   7:  /// Summary description for BasePage
   8:  /// </summary>
   9:  public class BasePage : Page
  10:  {
  11:      /// <summary>
  12:      /// Give the Page Title
  13:      /// </summary>
  14:      /// <param name="e"></param>
  15:      protected override void OnLoadComplete(EventArgs e)
  16:      {
  17:          if (string.IsNullOrEmpty(Page.Title) || Page.Title == "Untitled Page")
  18:          {
  19:              //ambil nama dari halaman
  20:              string fileName = Path.GetFileNameWithoutExtension(Request.PhysicalPath);
  21:              Page.Title = fileName;
  22:          }
  23:          //var anevent = new PipeLineEvent(HttpContext.Current.User.Identity.Name + " Visit This Page", this);
  24:          //anevent.Raise();
  25:          base.OnLoadComplete(e);
  26:      }
  27:      /// <summary>
  28:      /// Handles on Load ViewState Zip from Page
  29:      /// </summary>
  30:      /// <param name="viewState"></param>
  31:      protected override object LoadPageStateFromPersistenceMedium()
  32:      {
  33:          string viewState = Request.Form["__VSTATE"];
  34:          byte[] bytes = Convert.FromBase64String(viewState);
  35:          bytes = Compressor.Decompress(bytes);
  36:          LosFormatter formatter = new LosFormatter();
  37:          return formatter.Deserialize(Convert.ToBase64String(bytes));
  38:   
  39:      }
  40:      /// <summary>
  41:      /// Handles on Save ViewState Zip to Page
  42:      /// </summary>
  43:      /// <param name="viewState"></param>
  44:      protected override void SavePageStateToPersistenceMedium(object viewState)
  45:      {
  46:          LosFormatter formatter = new LosFormatter();
  47:          StringWriter writer = new StringWriter();
  48:          formatter.Serialize(writer, viewState);
  49:          string viewStateString = writer.ToString();
  50:          byte[] bytes = Convert.FromBase64String(viewStateString);
  51:          bytes = Compressor.Compress(bytes);
  52:          ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
  53:      }
  54:      /// <summary>
  55:      /// Move View State to Below Page
  56:      /// </summary>
  57:      /// <param name="writer"></param>
  58:      protected override void Render(System.Web.UI.HtmlTextWriter writer)
  59:      {
  60:          System.IO.StringWriter stringWriter = new System.IO.StringWriter();
  61:          HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
  62:          base.Render(htmlWriter);
  63:          string html = stringWriter.ToString();
  64:         // int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");
  65:          int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"__VSTATE\"");
  66:   
  67:          if (StartPoint >= 0)
  68:          {
  69:              int EndPoint = html.IndexOf("/>", StartPoint) + 2;
  70:              string viewstateInput = html.Substring(StartPoint, EndPoint - StartPoint);
  71:              html = html.Remove(StartPoint, EndPoint - StartPoint);
  72:              int FormEndStart = html.IndexOf("</form>");
  73:              if (FormEndStart >= 0)
  74:              {
  75:                  html = html.Insert(FormEndStart, viewstateInput);
  76:              }
  77:          }
  78:          writer.Write(html);
  79:       
  80:      }
  81:  }

Now all you've gotta do is inherit from this base page. I'll make another post on creating simple template

Losformater is the forgotten formater.

"The limited object serialization (LOS) formatter is designed for highly compact ASCII format serialization. This class supports serializing any object graph, but is optimized for those containing strings, arrays, and hashtables. It offers second order optimization for many of the .NET primitive types"

 

For addition in performance

Well, Do As Yslow suggest us.

1.Move every javascript at the end of the body

2.CSS always on top

3.CN

4.and so on and so on

Share this post: | | | |
Posted by cipto with 2 comment(s)