Get URL without QueryString in ASP.NET

Is there an easy way to get the url part without the query string of a given Url?

Yeap .

string  sample = Request.Url.GetLeftPart(UriPartial.Path);

Or long way:

string stringUri = “http://blog.bugrapostaci.com/test.aspx?lang=en”;
Uri uri = new Uri(stringUri);
string query = uri.Query;
string url = stringUri.Substring(0, stringUri.Length – query.Length);

happy tips.bye.

Advertisements

Asp.net Disable postback LinkButton

Add fallowing code to your page_load HTML:

<asp:LinkButton ID="myLinkButton" runat="server" Text="Click Me"></asp:LinkButton>

Code:
protected void Page_Load(object sender, EventArgs e)
{
myLinkButton.Attributes.Add("onClick", "return false;");
}

Happy tips&tricks :)

[Solved] Ninject ‘System.Runtime.CompilerServices.ExtensionAttribute’ is defined in multiple assemblies

Ninject Bug with .net framework 3.5

If you getting this error with your application that using ninject dependency injector.

System.Runtime.CompilerServices.ExtensionAttribute’ is defined in multiple assemblies in the global alias; using definition from  [….]\Ninject.Core.dll
Or
Missing compiler required member ‘System.Runtime.CompilerServices.ExtensionAttribute..ctor’

This is a know bug with ninject.NET 2.0 build would work for .NET 3.5 as well, but the extension method patch will screw things up.
http://bugs.ninject.org/jira/browse/NINJECT-4

Solution is:

 You can solve it by yourself

1)  Download source , extrat it some folder and open with VS IDE.
http://ninject.org/assets/dist/Ninject-1.0-src.zip

2) There are two project   “Core” and “Tests” that we change .

3) Open project properties windows by click solution explorer-> Core (Right Click ) -> Properties

4)Click “Application” Tab on the left side

5) Select  “.NET 3.5 framework ” in Target Framework combobox. 

6) Click  “Build” Tab on the left side

7)  type “NET_35” in Conditional Compilation Symbol box (Preprocessor flag)

8) Do it same with “Tests” Project

9) Rebuild solution.

Its worked for me 🙂

ASP.NET store Viewstate data in Session

Consider you have a web control as an assembl y and you dont have the source code of this . And the control store its data in viewstate and that data is really big. You can not able to change viewstate usage for this control . And much worse you have to use this important control.Thats may be help you to reduce output and use viewstate process at same time.

I mean you can use viewstate and store in session and reduce the weight of output.Ok that cost as server resources. And I dont really discuss it is proper or efficent or not. I Just show how to do it.

My other article about viewstate deal with compression and how to override base page functions of
LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium
I also use that functions in this article.
http://blog.bugrapostaci.com/2010/02/02/asp-net-compress-viewstate/

We are using one unique session key as path  for each page in session like
 Session[“ViewState_” + this.Request.Path]
You should better if you define a specific Guid value in your pages and use it for Session key.

protected override object LoadPageStateFromPersistenceMedium()
{
    string viewState = string.Empty;
    // try to get state data form Session.
    viewState = Session["ViewState_" + this.Request.Path] != null ? Session["ViewState_"
                      + this.Request.Path].ToString() : string.Empty;
 
    // Decompress the encoded and compressed state data than return it.
    byte[] bytes = Convert.FromBase64String(viewState);
    bytes = Utilities.MemoryCompressor.Decompress(bytes);
    LosFormatter formatter = new LosFormatter();
    return formatter.Deserialize(Convert.ToBase64String(bytes));
}
protected override void SavePageStateToPersistenceMedium(object state)
{
    //Encode state data
    LosFormatter formatter = new LosFormatter();
    StringWriter writer = new StringWriter();
    formatter.Serialize(writer, state);
    string viewStateString = writer.ToString();
    byte[] bytes = Convert.FromBase64String(viewStateString);
    bytes = Utilities.MemoryCompressor.Compress(bytes);
    //Save to session
    if (Session["ViewState_" + this.Request.Path] != null)
        Session["ViewState_" + this.Request.Path] = Convert.ToBase64String(bytes);
    else
        Session.Add("ViewState_" + this.Request.Path, Convert.ToBase64String(bytes));
}
Happy Codding...

ASP.NET Compress ViewState

Short definition of ViewState from MSDN:
Microsoft® ASP.NET view state, in a nutshell, is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks. In my experiences as a trainer and consultant, view state has caused the most confusion among ASP.NET developers. When creating custom server controls or doing more advanced page techniques, not having a solid grasp of what view state is and how it works can come back to bite you. Web designers who are focused on creating low-bandwidth, streamlined pages oftentimes find themselves frustrated with view state, as well. The view state of a page is, by default, placed in a hidden form field named __VIEWSTATE. This hidden form field can easily get very large, on the order of tens of kilobytes. Not only does the __VIEWSTATE form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.

The Cost of View State and Why we should consider to compress it:
Nothing comes for free, and view state is no exception. The ASP.NET view state imposes two performance hits whenever an ASP.NET Web page is requested:

  1. On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __VIEWSTATE form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.
  2. The __VIEWSTATE hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __VIEWSTATE form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.

Where is in the Pipeline ?
The view state is serialized to the hidden form field in the Page class’s SavePageStateToPersistenceMedium() method during the save view state stage, and is deserialized by the Page class’s LoadPageStateFromPersistenceMedium() method in the load view state stage. With just a bit of work we can have the view state persisted to the Web server’s file system, rather than as a hidden form field weighing down the page. To accomplish this we’ll need to create a class that derives from the Page class and overrides the SavePageStateToPersistenceMedium() and LoadPageStateFromPersistenceMedium()methods.

After some boring information  lets Compress our  ViewState

First for compressing a byte array add this code to your project.

using System;
using System.Text;
using System.IO;
using System.IO.Compression;
 
public static class MemoryCompressor
{
    /// <summary>
    /// Compress given data with Gzip
    /// </summary>
    /// <param name="unCompressedData">the data to compress as byte array </param>
    /// <returns>Compressed data as byte array </returns>
    public static byte[] Compress(byte[] unCompressedData)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            //Select as compress
            CompressionMode cmode = CompressionMode.Compress;
            //Compress Data dont forget to leave open true..
            using (GZipStream gzip = new GZipStream(ms, cmode, true))
            {
                gzip.Write(unCompressedData, 0, unCompressedData.Length);
            }
            return ms.ToArray(); //Return as byte []
        }
    }
 
    /// <summary>
    /// Decompress given data with Gzip
    /// </summary>
    /// <param name="compressedData">the data to decompress as byte array </param>
    /// <returns>Decompressed data as byte array </returns>
    public static byte[] Decompress(byte[] compressedData)
    {
        GZipStream gzip;
        using (MemoryStream ms = new MemoryStream())
        {
            ms.Write(compressedData, 0, compressedData.Length);
            // Reset the memory stream 
            ms.Position = 0;
            //Decompress
            CompressionMode mode = CompressionMode.Decompress;
            //Get Stream 
            gzip = new GZipStream(ms, mode, true);
 
            using (MemoryStream outMs = new MemoryStream())
            {
                // 4096 bytes as buffer gives you best performance..
                byte[] buffer = new byte[4096];
                int byteReaded = -1;
                byteReaded = gzip.Read(buffer, 0, buffer.Length);
                while (byteReaded > 0)
                {
                    //write to output stream
                    outMs.Write(buffer, 0, byteReaded);
                    //keep going...
                    byteReaded = gzip.Read(buffer, 0, buffer.Length);
                }
                gzip.Close();//Dont forget to close it.
                return outMs.ToArray(); //return as byte array
            }
        }
    }
}

Add this code to your Page or BasePage code

public class BasePage:System.Web.UI.Page
{
    ...
    protected override object LoadPageStateFromPersistenceMedium()
    {
        string viewState = string.Empty;
        // try to get state data form RequestForm.
        viewState = Request.Form["__COMPRESSEDVSTATE"];
        // Decompress the encoded and compressed state data than return it.
        byte[] bytes = Convert.FromBase64String(viewState);
        bytes = Utilities.MemoryCompressor.Decompress(bytes);
        LosFormatter formatter = new LosFormatter();
        return formatter.Deserialize(Convert.ToBase64String(bytes));
    }
    protected override void SavePageStateToPersistenceMedium(object state)
    {
        //Encode state data
        LosFormatter formatter = new LosFormatter();
        StringWriter writer = new StringWriter();
        formatter.Serialize(writer, state);
        string viewStateString = writer.ToString();
        byte[] bytes = Convert.FromBase64String(viewStateString);
        bytes = Utilities.MemoryCompressor.Compress(bytes);
        //Save to page hidden field
        ClientScript.RegisterHiddenField("__COMPRESSEDVSTATE", Convert.ToBase64String(bytes));
    }
    ...
}

Note: You always consider that you need viewstate if not you should disable it or disable controls viewstates that not need to be store data in viewstate. And also there is a better way to use compress data that HttpCompress look for it.
Another artice of mine about storing viewstate data in Session:
http://blog.bugrapostaci.com/2010/02/04/asp-net-store-viewstate-data-in-session/

For more information about viewstate
http://msdn.microsoft.com/en-us/library/ms972976.aspx

May the code be with you..

Some way to modify rendered output html

Another way to use a global variable in your page as overriding render method of your form. Ok its not a good and suggested way and also have performance problems but strangely it will work sometimes and also provide writing less code in html side.

Our form’s html view:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”WebForm1.aspx.cs” Inherits=”MultiLangTest.WebForm1″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>

$$GlobalVariable

<a href=”http://www.google.com” >$$GlobalVariable</a>

<div title=”$$GlobalVariable” > </div>
<div title=”$$GlobalVariable” > </div>
<div title=”$$GlobalVariable” > </div>
<div title=”$$GlobalVariable” > </div>
<div title=”$$GlobalVariable” > </div>

$$GlobalVariable

<!–
<asp:Label ID = “Label1″  runat=”server”
Text =”<%= You know Its not working with asp:x tags
and also not necessery but sometimes strangely
you want to use this %>” />

than You can do it like this:
–>
<asp:Label ID = “Hello”  runat=”server” Text =”$$GlobalVariable” />

</div>
</form>
</body>
</html>

Our form’s codebehind:

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected override void Render(HtmlTextWriter writer)
        {
            //we will create a memory stream for holding data
            using (MemoryStream ms = new MemoryStream())
            {
                //A streamwriter to write memory
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    //this is our html writer.
                    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
                    //Complete other renders
                    base.Render(htmlWriter);

                    htmlWriter.Flush();

                    //Set memory stream to start position.
                    ms.Position = 0;

                    //read the data
                    using (System.IO.StreamReader _Reader = new System.IO.StreamReader(ms))
                    {
                        string txt = _Reader.ReadToEnd();
                        //replace global variable
                        txt = txt.Replace("$$GlobalVariable", "Hello World" );
                        Response.Write(txt);
                        _Reader.Close();
                    }
                }
            }
        }
    }

Here is the output:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head><title>

</title></head>
<body>
<form name=”form1″ method=”post” action=”WebForm1.aspx” id=”form1″>
<div>
<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wEPDwUKMTg3NjI4NzkzNmRkxS9N0UwBHiMGrNo9vYAKQmdAfAc=” />
</div>

<div>

Hello World

<a href=”http://www.google.com” >Hello World</a>

<div title=”Hello World” > </div>
<div title=”Hello World” > </div>
<div title=”Hello World” > </div>
<div title=”Hello World” > </div>
<div title=”Hello World” > </div>

Hello World

<!–
<span id=”Label1″><%= You know Its not working with asp:x tage
and also not necessery but sometimes strangely
you want to use this %></span>

than You can do it like this:
–>
<span id=”Hello”>Hello World</span>

</div>
</form>
</body>
</html>

Asp.net c# save scroll position when postback

this is the mana:
Page.MaintainScrollPositionOnPostBack Property

Msdn say  “gets or sets a value indicating whether to return the user to the same position in the client browser after postback. This property replaces the obsolete SmartNavigation property.When Web pages are posted back to the server, the user is returned to the top of the page. On long Web pages, this means that the user has to scroll the page back to the last position on the page.When the MaintainScrollPositionOnPostback() property is set to true, the user is instead returned to the last position on the page.”

Usage:
<asp:Page MaintainScrollPositionOnPostBack=”True|False” />

Or  you can add your web config like this for all pages
<system.web>
<pages validateRequest=”true”  maintainScrollPositionOnPostBack=”true”>
</system.web>

Important Note: There is also a problem with this . Does not work with other browsers except ie.

Source:
Happy codding !!