Tuesday, October 5, 2010

Grouping in Linq

A simple grouping in linq

var lst = (from employee in lstEmployee
select employee)
.OrderBy(emp => emp.ID)
.GroupBy(emp => emp.Name)
.ToList();


Use the following to union the collection

List<Employee> lstEmployeeCollection = new List<Employee>();
int Seq=1;

foreach (var employeeGrop in lst)
{

//Logic should go here for the existing collection modification 
//Use Union for making as a single collection
lstEmployeeCollection = (from employee in employeeGrop
select new Employee { ID = Seq, Name = employee.Name }
).Union<Employee>(lstEmployeeCollection).ToList<Employee>();
++Seq;
}

Another way of grouping is as follows .In this way we are not using the anonymous variable rather we are using typed variable

This Class will be as follows

public class Student 
{

public string Name { get; set; }
public int DeptID{ get; set; }
public int Marks { get; set; }

}


public class StudentDetails
{
public string Name { get; set; }
public List<Marks> lstCount { get; set; }

}

public class MarkDetails
{
public int DeptID { get; set; }
public int Marks { get; set; }

}

Now if we want the Studentdetails Group by student name ,and the result should contain the a list of studentsdetails that contains the dept as well as marks also...

The following lambda will gives this ...

List<StudentDetails> lstStudentDetails = lst
.GroupBy(x => x.Name)
.Select
(   x => new StudentDetails
{ Name = x.Key, lstCount = x.ToList()
.Select(y=>new MarkDetails{Marks =y.Marks ,DeptID =y.DeptID })
.ToList<MarkDetails>()
}
)
.ToList<StudentDetails>();


This way we can use the group by in a very simple way....



Enjoy coding........................

Tuesday, September 7, 2010

Download a file in Silverlight from the server

For downloading a file form  the server we have several ways .The following  example i have used the traditional asp.net handlers ie the ashx.

All that what we have to do when downloading a file from silverlight is that
we need to navigate to handler that have created for the download.

The  following code sippnet shows the handler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;

namespace SLMemoryLeakSample.Web
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    public class FileDownload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
            context.Response.ContentType = "application/ms-Excel";
            context.Response.WriteFile("New Microsoft Office Word Document.docx");
            context.Response.Flush();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
As you can see the the code that have written inside the Process Request basically  we just write the file into the output stream so that the file will be available in the client

Now step is the real magic of the silvelight especally the HyperLink button we have something called the NavigateUri which actually  call this handler

We can set the TagetName property to what ever you want from the avaiable .If we didnt set the target property name we will probably  get an error since the silverlight expects another xaml page

Enjoy coding............................

Export Document in ASP.NET

Here we are exporting the data from a grid to word,

       Response.Clear();
       Response.Buffer = true;
       Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
       Response.ContentType = "application/ms-word";
       StringWriter stringWriter = new StringWriter();
       HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
       gvwEmployeeGrid.RenderControl(htmlTextWriter);
       Response.Output.Write(stringWriter.ToString());
       Response.Flush();
       Response.End();



Make EventValidation to false for the page and also override VerifyRenderingInServerForm in code behind,

       public override void VerifyRenderingInServerForm(Control control)

       {

       }


Export a file in ASP.NET

Here we are exporting a file to the client this will ask a open save cancel dialog

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
    Response.ContentType = "application/ms-Excel";
    Response.WriteFile("New Microsoft Office Word Document.docx");
    Response.Flush();
    Response.End();

Monday, September 6, 2010

Writting a file throught Silverlight .

The following code sipnet shows how we can open a file dialog from
the Silverlight Applcation and write to the server .
This is done via in conjection with the Asp.net handlers.


 private void FileUpLoader()
      {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        bool? retVal = openFileDialog.ShowDialog();

        if (retVal != null && retVal == true)
          {
            UploadFile(openFileDialog.File.Name,openFileDialog.File.OpenRead());
            tblStatus.Text = openFileDialog.File.Name;
          }
        else
          {
             tblStatus.Text = "Please select a file";
          }
       }




 private void UploadFile(string fileName, Stream data)
        {
            UriBuilder uriBuilder =
             new UriBuilder("http://localhost/SLMemoryLeakSample.Web/FileUploader.ashx");
            uriBuilder.Query = string.Format("filename={0}", fileName);

            WebClient webClient = new WebClient();
            webClient.OpenWriteCompleted += (sender, e) =>
            {
                WriteStream(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            webClient.OpenWriteAsync(uriBuilder.Uri);
        }



 private void WriteStream(Stream input, Stream output)
        {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }


The FileUploader.ashx will be as following


 public class FileUploader : IHttpHandler
    {

        #region FileUploader
        public void ProcessRequest(HttpContext context)
        {
            string filename = context.Request.QueryString["filename"].ToString();

            using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    fs.Write(buffer, 0, bytesRead);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        } 
        #endregion
    }

Enjoy Coding ............................................

Thursday, August 19, 2010

Swaping on Refrence

C# does manipulate objects by reference, and all object variables are references. On the other hand, C# does not pass method arguments by reference; it passes them by value, (even if the method arguments are of reference type). Thus, a regular swap method will not work!
Let's come from the beginning, we know that there are four kinds of formal parameters in a C# method declaration, namely
  • Value parameters, which are declared without any modifiers. (default)
  • Reference parameters, which are declared with the ref modifier.
  • Output parameters, which are declared with the out modifier.
  • Parameter arrays, which are declared with the params modifier.
Thus if there is no any method parameter keyword (ref or out), the parameter can have a value associated with it. That value can be changed in the method, but that value will not be reflected when the control passes back to the calling procedure. This is true for all value types. Now, consider a reference type, an object. If we pass an object to a method and if the value of its member is changed, it will be retained even when the control is passed back to the calling procedure! This is because objects are manipulated by reference.

If so, then, if we pass two objects to a regular swap method and come back to the calling procedure to see whether they have got swapped, they would have not! Look down the code below,


public class SwapClass
    {
        public int x;
        public int y;
        public SwapClass(int xval, int yval)
        {
            x = xval;
            y = yval;
        }
    }
    public class Swaper
    {
        public static void SwapWithRef(ref SwapClass param1, ref SwapClass param2)
        {
            param1.y = 2000;
            param1.x = 1000;
            SwapClass temp = param1;
            param1 = param2;
            param2 = temp;
        }

        public static void SwapWithOutRef(SwapClass param1, SwapClass param2)
        {
            param1.y = 2000;
            param1.x = 1000;
            SwapClass temp = param1;
            param1 = param2;
            param2 = temp;
        }

      
    }

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            SwapClass obj1 = new SwapClass(0, 0);
            SwapClass obj2 = new SwapClass(10, 20);
         
            Response.Write("
");
            Response.Write("
X1: " + obj1.x + " Y1: " + obj1.y);
            Response.Write("
X2: " + obj2.x + " Y2: " + obj2.y);
            Response.Write("
");
          
            Swaper.SwapWithOutRef(obj1, obj2);
            Response.Write("
After SwapWithOutRef");
            Response.Write("
X1: " + obj1.x + " Y1:" + obj1.y);
            Response.Write("
X2: " + obj2.x + " Y2:" + obj2.y);
            Response.Write("
");

            Response.Write("
After SwapWithRef");
            Swaper.SwapWithRef(ref obj1, ref obj2);
            Response.Write("
X1: " + obj1.x + " Y1:" + obj1.y);
            Response.Write("
X2: " + obj2.x + " Y2:" + obj2.y);
            Response.Write("
");
            Response.Write("---------------------------------");

            SwapClass obj3 = new SwapClass(0, 0);
            SwapClass obj4 = new SwapClass(100, 200);
            obj3.x = 10;
            obj3.y = 20;
            SwapClass temp = obj3;
            obj3 = obj4;
            obj4 = temp;

            Response.Write("
After Normal Swap Without passing the parameter towards a method");
            Response.Write("
X3: " + obj3.x + " Y3:" + obj3.y);
            Response.Write("
X4: " + obj4.x + " Y4:" + obj4.y);
            Response.Write("
");
        }
    }

Enjoy swapping

Tuesday, August 17, 2010

Classic Ajax Using the ActiveX object - XMLHTTP

The follwing code sipnet will gives an overview on the classic way of
 using the ajax call for getting the data from the webserver .

This is the way that we get the data from the web server .
In all the frameworklike the asp.net ajax,jquery Ext,.......are
make use of this.

The following activeX will only work with the IE, not in any other browser



function XmlHttpFunctionExample() {

    if(window.ActiveXObject) {

        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

    }

    else {

        xmlhttp = new XMLHttpRequest();

    }

    xmlhttp.open("GET", "Time.aspx", true);

    xmlhttp.onreadystatechange = readyStateChangedHandler;

    xmlhttp.send();    

}


This is the function pointer that actually handles the response form the webserver


function readyStateChangedHandler() {

    if(xmlhttp.readyState == 4) {

        alert(xmlhttp.responseText);

    }    

}
Please see the previous post for the readyState/StatusCode used in web technologies.

Ajax Server Control to Control Multiline entry

In the Visual studio 2008 , we have option to create a Ajax Server Control which actually create a Client Side controls  ie on the java script.The only thing is that this requires a script managers on the page,without this these client side controls wont work because the all the stuff is made on the asp.net Ajax.

Following is a small code spinet for a custom control that is build on the Ajax Server Control.

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AjaxServerControl1
{
  
    public class ServerControl1 :TextBox,IScriptControl
    {
        private ScriptManager _scriptManager;

        private ScriptManager ScriptManager
        {
            get
            {
                if (_scriptManager == null)
                {
                    _scriptManager = ScriptManager.GetCurrent(Page);
                    if (_scriptManager == null)
                        throw new InvalidOperationException(String.Format("The control with ID '{0}' requires    ScriptManager on the page."+
                    "The ScriptManager must appear before any controls that need it.", ID));
                }
                return _scriptManager;
            }
        }

        public ServerControl1()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public  virtual IEnumerable GetScriptDescriptors()

        {

            ScriptControlDescriptor descriptor = new                                                                                                                       ScriptControlDescriptor("AjaxServerControl1.ClientControl1", this.ClientID);

            yield return descriptor;

        }

       

        public virtual IEnumerable GetScriptReferences()

        {

            yield return new ScriptReference("AjaxServerControl1.ClientControl1.js",                                                       this.GetType().Assembly.FullName);

        }



        protected override void OnPreRender(EventArgs e)

        {

            ScriptManager.RegisterScriptControl(this);

            base.OnPreRender(e);

           

        }



        protected override void Render(HtmlTextWriter writer)

        {

            writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());

            ScriptManager.RegisterScriptDescriptors(this);

            base.Render(writer);

        }



        

    }

} 


Here is the sample script the that will actually  do this ...................
/// <reference name="MicrosoftAjax.js"/>


Type.registerNamespace("AjaxServerControl1");

AjaxServerControl1.ClientControl1 = function(element) {
    AjaxServerControl1.ClientControl1.initializeBase(this, [element]);
    this.ctrl = element;
    this.ml = this.ctrl.getAttribute("maxlength");
}

AjaxServerControl1.ClientControl1.prototype = {
initialize: function() {
    
        AjaxServerControl1.ClientControl1.callBaseMethod(this, 'initialize');
        this.ctrl.attachEvent('onkeypress', this.createDelegate(this, this._keypress));
        this.ctrl.attachEvent('onpaste', this.createDelegate(this, this._paste));
        this.ctrl.MaxLength = this.ml;
        
    },
    _keypress: function(evt) {
    
        var select = document.selection.createRange();
        var len;        
        if (select.parentElement() === this.ctrl)
            len = this.ctrl.value.length - select.text.length;
        else
            len = this.ctrl.value.length;
        if (evt.keyCode === 13 && len == this.ctrl.MaxLength - 1 || len >= this.ctrl.MaxLength)
            evt.keyCode = '';
        delete len; delete select;
    },
    _paste: function(evt) {
    
        var data = new String(clipboardData.getData("text"));
        var select = document.selection.createRange();
        var len;
        if (select.parentElement() === this.ctrl)
            len = this.ctrl.value.length - select.text.length;
        else
            len = this.ctrl.value.length;
        len = len + data.length;
        if (len > this.ctrl.MaxLength) {
            if (evt.preventDefault) { evt.preventDefault(); }
            else if (window.event) { window.event.returnValue = false; }
        }
        delete data; delete select; delete len;
    },
    createDelegate: function(instance, method) {
    
        if (Function.createDelegate)
            return Function.createDelegate(instance, method);
        return function() { return method.apply(instance, arguments); }
    },
    dispose: function() {    
       
        AjaxServerControl1.ClientControl1.callBaseMethod(this, 'dispose');
    }
}
AjaxServerControl1.ClientControl1.registerClass('AjaxServerControl1.ClientControl1', Sys.UI.Control);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();



Now a small magic .Please see the previous post on the asp.net related to the tag mapping .

Enjoy coding

Monday, August 16, 2010

Methods, Delegates, Anonymous Delegates, and Lambda Expressions

Methods, Delegates, Anonymous Delegates, and Lambda Expressions


If we have a method declared as follows:

     static Int32 SomeMethod(Int32 input)
    {
            return input + 1;
    }


We can explicitly call it in a way every C# programmer should be familiar with:


    Int32 y = SomeMethod(5);
    Console.WriteLine(y);

Using a Delegate...

Now, we may want to wrap this call so we can execute it from somewhere else.
This is done through a delegate.

What's a delegate?

A delegate is an object instance  that "wraps" a method call (pretty much everything in the .NET framework in an object).
An easy way to think of it is as a reference to a method that we can pass around separately from the object
that "ownes" the method.  In order to "wrap" the method call, the delegate needs two things:

   1.      A reference to the instance of the object it will be calling the method on.
   2.      A reference to the method.


To create a delegate we first declare our delegate type.
We can think of this as being similar to declaring a new class:


       delegate Int32 SomeMethodDelegate(Int32 input);


And then we can use an instance of this delegate to "wrap" our method call:

Using the same method we had earlier...


    static Int32 SomeMethod(Int32 input)
    {
            return input + 1;
    }


Somewhere else in our code we can instantiate the delegate as follows.
(note: in the sample below, "Program" is a static class)


// f is a delegate object that "wraps" the call
SomeMethodDelegate f = new SomeMethodDelegate(Program.SomeMethod);

Now we can use our delegate instance to call the same method.


    Int32 y = f(5);


The compiler is smart enough to figure out which kind of delegate to instantiate 
so we can use a shorter syntax if we want. We are actually still very explicitly instantiating a delegate
by telling the compiler what kind of delegate we want with the declaration on the left hand side of the assignment operator.
(note: I don't need to specify the object in the following code sample because
the delegate instantiation is in the same class as "SomeMethod()".)


    // f is a delegate object that "wraps" the call
    SomeMethodDelegate f = SomeMethod;



Adding Generics in the Mix....

We may not need a bunch of explicit delegate types lying around in our project
(although sometimes it is good to have a few for more readable code) and can use generics to consolidate all delegates
with similar surface areas (the same input and output types):


    delegate TOutput GenericDelegate(TInput input);


Now we can wrap our method using our generic delegate just as before:

    // using generic delegate definition

    GenericDelegate f = SomeMethod;

    Int32 y = f(5);


Note: this GenericDelegate<>  is the same as the Func<> delegate defined in the 3.0 framework

    // using built-in Func<> generic delegate definition (3.0 framework)

    Func f = SomeMethod;

    Int32 y = f(5);


We also have the generic Action<> delegate which wraps a method with no return value and
a Predicate<> delegate which is usually used to perform tests returns a Boolean and
a Comparison<> delegate to compare two objects.

Anonymous Delegate....

We may want to have a method that does not belong to a class (which is why we call it anonymous)
and can declare it in-line using  the following syntax.  Notice how the method has no "outer shell" definition.
The "SomeMethodDelegate" object is still instantiated and points to the in-line method.


    // in-line method definition... it has no name so it is anonymous

    SomeMethodDelegate f = delegate(Int32 x) { return x + 1; };

    Int32 y = f(5);


We could use the same syntax to instantiate our anonymous delegate as well

    // in-line method definition... it has no name so it is anonymous

    Func f = delegate(Int32 x) { return x + 1; };

    Int32 y = f(5);


If you haven't done it already, it is worth taking some time and using the debugger to step
through code containing anonymous method to get a better understanding of how the execution of the code flows.

Closures...

One of the ultra-cool features of anonymous methods is that they support closures which is a concept
coming out of functional programming languages.  Closures are VERY powerful and can help us keep code more concise.
When a language supports closures it basically  means that the a method body has
access to any local variable declared outside it's scope.


    String hi = "Hello World";

    Action myAction = Console.WriteLine;

    Func myStringGetter = delegate()

    {

            // the variable "hi" is available here because

            // anonymous methods support closure

            return hi;

    };



    myAction(myStringGetter());


Lambda Expressions...

The syntax for declaring an anonymous delegate is pretty verbose (and kind of ugly). 
With the 3.5 Framework, we have a much shorter (and nicer) way to instantiate anonymous delegates using lambda expressions.
    SomeMethodDelegate f = x => { return x + 1;  };

    Int32 y = f(5);


The input parameter is the variable before the => symbol.
    x => { return x + 1;  };


The body of the method is what appear after the => symbol.

    x => { return x + 1;  };


Because the "SomeMethodDelegate" signature says we have to input a Int32 and output an Int32,
the compiler knows that our "x" variable should be an integer (see if makes more sense if you try and
match the delegate signature (below) up with our lambda expression (above).
delegate Int32 SomeMethodDelegate(Int32 input);


We can use an even shorter syntax for declaring simple anonymous methods with the lamba expression and
 leave off the brackets and the "return" keyword.  The following code uses the simpler syntax:
    // can use shorter syntax if you don't want brackets or "return" keyword

    SomeMethodDelegate f = x => x + 1;

    Int32 y = f(5);

    Console.WriteLine(y);


Of course we can use lambda expressions with generic delegates as well.  The following shows the lambda expression syntax
for instantiating a generic delegate with two input parameters.  If our delegate has multiple input parameters,
we must group them in parenthesis:
    Func add = (m, n) => m + n;

    Int32 y = add(3, 4);


What Are They Good For?

Delegates are used most frequently for subscribing to events
so we'll look at how we can utilize delegates with an object that exposes an event.

Here is our dummy event raising object which could just as easily be a UI form or control.

    class Broadcast

    {

            private event EventHandler m_somethingHappened;

            public event EventHandler SomethingHappened

            {

                add { m_somethingHappened += value; }

                remove { m_somethingHappened -= value; }

            }



            public void Fire()

            {

                if (null != m_somethingHappened)

                    m_somethingHappened(this, EventArgs.Empty);

            }

    }


Example 1:

Let's say we instantiate a new Broadcast object and want to wire up the events using anonymous delegates:

    Broadcast bc = new Broadcast();



    bc.SomethingHappened += delegate(Object sender, EventArgs args)

    {

            Console.WriteLine("Something Happened (anonymous method)");

    };



    bc.Fire();


Example 2:

We can also wire up our Broadcast object using a lambda expression:

    Broadcast bc = new Broadcast();

    bc.SomethingHappened += (snd, arg) => Console.WriteLine("Something Happened (Lambda)");

    bc.Fire();


Example 3:

There are also many other places where delegates can be useful.
Another scenario is when we need to pass a delegate to another method for execution.
See if you can figure out what's happening in the following code.

If we have a method declared that accepts a delegate and another item defined as its input parameters
it will execute the method using the second parameter as input.

    static TOutput ExecuteSomething(Func mthd, TInput input)

    {

            return mthd(input);

    }



    Console.WriteLine(ExecuteSomething(g => g - 5, 20));

Setting Margin for the Rich TextBox like controls

Setting Margin for the Rich TextBox like controls


.P
{
  MARGIN: 0in 0in 0pt
 }


If the set the above  margin then the space between the line will be diplayed as normal in the Rich TextBox type of controls such as a div with attribute  contenteditable="true"  At this point the div is editable and if we press a enter key then there will be additional space that will be generated .To a void this situation we can use the above CSS class.

Disable Selection On Webpages

onselectstart="return false;" style="user-select:none;-moz-user-select:none;"

if we have given like this then we can block the selection on a webpage
basically this will not allow a copy paste.

onselectstart="return false - is basically for the IE

;-moz-user-select:none - is for mozilla

and

user-select:none is the W3 standards which should follow in all the browsers  :)

Friday, August 13, 2010

using java.util.zip for Zipping the files

 The follwoing code snippet is to Zip multiple files into a single file using java.util.zip .


private void ZipFiles()
        {
           OpenFileDialog fd1 = new OpenFileDialog();
            fd1.Multiselect = true;
            
            if (fd1.ShowDialog() == DialogResult.OK)
            {
               SaveFileDialog sf1 = new SaveFileDialog();
               sf1.Filter = "ZIP Files|*.zip";
                //sf1.Filter = "RAR Files|*.rar";
                if (sf1.ShowDialog() == DialogResult.OK)
                {
                    
                    string zipFileName = sf1.FileName.ToString();
                    ZipOutputStream os = new ZipOutputStream(new java.io.FileOutputStream(zipFileName));
                    java.io.FileInputStream fs;

                    for (int i = 0; i < fd1.FileNames.Length; i++)
                    {
                        string[] arr = fd1.FileNames;

                        string sourceFileName = arr.ToString();
                       
                        string path = Path.GetFileNameWithoutExtension(sourceFileName);
                        string path2 = Path.GetFullPath(sourceFileName);
                        string path1 = Path.GetExtension(path2);
                        if (path1 == ".pdf")
                        {
                            ZipEntry ze = new ZipEntry(path + ".pdf");
                            ze.setMethod(ZipEntry.DEFLATED);
                            os.putNextEntry(ze);
                            //java.io.FileInputStream fs = new java.io.FileInputStream(str);
                            fs = new java.io.FileInputStream(sourceFileName);

                            sbyte[] buff = new sbyte[1024];
                            int n = 0;
                            while ((n = fs.read(buff, 0, buff.Length)) > 0)
                            {
                                os.write(buff, 0, n);

                            }
                            fs.close();
                        }
                        if (path1 == ".txt")
                        {
                            ZipEntry ze = new ZipEntry(path + ".txt");
                            ze.setMethod(ZipEntry.DEFLATED);
                            os.putNextEntry(ze);
                            //java.io.FileInputStream fs = new java.io.FileInputStream(str);
                            fs = new java.io.FileInputStream(sourceFileName);

                            sbyte[] buff = new sbyte[1024];
                            int n = 0;
                            while ((n = fs.read(buff, 0, buff.Length)) > 0)
                            {
                                os.write(buff, 0, n);

                            }
                            fs.close();
                        }
                        if (path1 == ".doc")
                        {
                            ZipEntry ze = new ZipEntry(path + ".doc");
                            ze.setMethod(ZipEntry.DEFLATED);
                            os.putNextEntry(ze);
                            //java.io.FileInputStream fs = new java.io.FileInputStream(str);
                            fs = new java.io.FileInputStream(sourceFileName);

                            sbyte[] buff = new sbyte[1024];
                            int n = 0;
                            while ((n = fs.read(buff, 0, buff.Length)) > 0)
                            {
                                os.write(buff, 0, n);

                            }
                            fs.close();
                        }
                        if (path1 == ".xls")
                        {
                            ZipEntry ze = new ZipEntry(path + ".xls");
                            ze.setMethod(ZipEntry.DEFLATED);
                            os.putNextEntry(ze);
                            //java.io.FileInputStream fs = new java.io.FileInputStream(str);
                            fs = new java.io.FileInputStream(sourceFileName);

                            sbyte[] buff = new sbyte[1024];
                            int n = 0;
                            while ((n = fs.read(buff, 0, buff.Length)) > 0)
                            {
                                os.write(buff, 0, n);

                            }
                            fs.close();
                        }
                    }

                    //fs.close();
                    os.closeEntry();
                    os.close();
                    // }

                    MessageBox.Show("Compression ok!");
                }
            }
            else
            {

            }

        }

Tag Mapping in ASP.NET


Tag Mapping in ASP.NET

 Tag mapping allows you to swap compatible controls at compile time on every page in your web application. A useful example is if you have a ASP.NET control, such as a TextBox, and you want to replace it with a customized control that is derived from TextBox. Instead of editing every web form and replacing the built in TextBox with your custom version, you can have ASP.NET in effect do it for you by modifying web.config:


<pages>

  <tagMapping>

    <clear />

    <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="TextBox"/>

  </tagMapping>

</pages>


When you run your application, ASP.NET will replace every instance of TextBox with CustomTextBox, which is derived from TextBox:


public class CustomTextBox : TextBox

{

    public CustomTextBox()

    {

    }



    // Control the multline length here 

}


In this way you can write the custom logic that controls the multiline length ie its not controled on version 2.0
The only thing that we need to remember is that when we do a tag mapping in the web.config file we need to derive form the WebControls ie there will always be a base class for the tag mapping .
Internally how it works is that when the asp.net creates/manulpulates the control,it actually check inside the web.config and picks the mapped controls

Thursday, August 12, 2010

Common Table Expressions

Using Common Table Expressions
A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.
A CTE can be used to:
  • Create a recursive query. For more information, see Recursive Queries Using Common Table Expressions.
  • Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.
  • Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access.
  • Reference the resulting table multiple times in the same statement.
Using a CTE offers the advantages of improved readability and ease in maintenance of complex queries. The query can be divided into separate, simple, logical building blocks. These simple blocks can then be used to build more complex, interim CTEs until the final result set is generated.
CTEs can be defined in user-defined routines, such as functions, stored procedures, triggers, or views.
Structure of a CTE 
A CTE is made up of an expression name representing the CTE, an optional column list, and a query defining the CTE. After a CTE is defined, it can be referenced like a table or view can in a SELECT, INSERT, UPDATE, or DELETE statement. A CTE can also be used in a CREATE VIEW statement as part of its defining SELECT statement. 
The basic syntax structure for a CTE is:

WITH expression_name [ ( column_name [,...n] ) ]
AS
( CTE_query_definition )
The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.
The statement to run the CTE is:
SELECT
FROM expression_name;

Example

 

The following example shows the components of the CTE structure: expression name, column list, and query. The CTE expression Sales_CTE has three columns (SalesPersonID, SalesOrderID, and OrderDate) and is defined as the total number of sales orders per year for each salesperson.

USE AdventureWorks2008R2;
GO
-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;
GO

Tuesday, August 10, 2010

Globalization of Resources

ASP.NET 2.0 has greatly improved the tools and functionality to create localized applications. One of the new key components is the introduction of a provider model for resource localization that makes it possible to use resources from sources other than ..Resx files.

We need to add the globalization tag inside the web.config like the following

 <globalization resourceProviderFactoryType="SLMemoryLeakSample.Web.Global.ResourceProviderFactoryExt" />

The next step is the  implement the abstract class ResourceProviderFactory as follows ...

     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Compilation;

    namespace SLMemoryLeakSample.Web.Global
    {
        public class ResourceProviderFactoryExt : ResourceProviderFactory
        {
            public override IResourceProvider CreateGlobalResourceProvider(string classKey)
            {
                //Here the ClassKey will be the TestLoaction 
                return new CustomResourceProvider();
            }

            public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
            {
                throw new NotImplementedException();
            }
        }

        public class CustomResourceProvider : IResourceProvider
        {
            #region IResourceProvider Members

            Dictionary dictionary;

            public CustomResourceProvider()

            {

                dictionary = new Dictionary();

                dictionary.Add("lblName", "Name");

                dictionary.Add("lblAge", "Age");

            }

            public object GetObject(string resourceKey, System.Globalization.CultureInfo culture)

            {

                //Here the resourceKey will be the lblName 

                //From the CultureInfo we can get the culture.

                return dictionary[resourceKey];

            }



            public System.Resources.IResourceReader ResourceReader

            {

                get { throw new NotImplementedException(); }

            }



            #endregion

        }

    }



Inside the aspx page all that we have to do is the following 



 < asp:Label ID="Label1" runat="server"  Text="<%$Resources:TestLoaction, lblName%>" ></asp:Label>


that all ...........Wow .
This is post is for my friend abi

Wednesday, August 4, 2010

Constraints
When you define a generic class, you can apply restrictions to the kinds of
types that client code can use for type arguments when it instantiates your
class. If client code tries to instantiate your class by using a type that is
not allowed by a constraint, the result is a compile-time error. These
restrictions are called constraints. Constraints are specified by using the
where contextual keyword. The following
table lists the six types of constraints
Examples
Constraint Description

where T: struct

The type argument must be a value type. Any value type except
Nullable
can be specified. See
Using Nullable
Types (C# Programming Guide)
for more information.

where T : class

The type argument must be a reference type; this applies also to any class,
interface, delegate, or array type.

where T : new()

The type argument must have a public parameterless constructor. When used
together with other constraints, the new()
constraint must be specified last.

where T : <base class name>

The type argument must be or derive from the specified base class.

where T : <interface name>

The type argument must be or implement the specified interface. Multiple
interface constraints can be specified. The constraining interface can also be
generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied
for

Sunday, July 25, 2010

ACID properties

When a transaction processing system creates a transaction, it will ensure that the transaction will have certain characteristics. The developers of the components that comprise the transaction are assured that these characteristics are in place. They do not need to manage these characteristics themselves. These characteristics are known as the ACID properties. ACID is an acronym for atomicity, consistency, isolation, and durability.

Atomicity

 

The atomicity property identifies that the transaction is atomic. An atomic transaction is either fully completed, or is not begun at all. Any updates that a transaction might affect on a system are completed in their entirety. If for any reason an error occurs and the transaction is unable to complete all of its steps, the then system is returned to the state it was in before the transaction was started. An example of an atomic transaction is an account transfer transaction. The money is removed from account A then placed into account B. If the system fails after removing the money from account A, then the transaction processing system will put the money back into account A, thus returning the system to its original state. This is known as a rollback, as we said at the beginning of this chapter..

Consistency

 

A transaction enforces consistency in the system state by ensuring that at the end of any transaction the system is in a valid state. If the transaction completes successfully, then all changes to the system will have been properly made, and the system will be in a valid state. If any error occurs in a transaction, then any changes already made will be automatically rolled back. This will return the system to its state before the transaction was started. Since the system was in a consistent state when the transaction was started, it will once again be in a consistent state.
Looking again at the account transfer system, the system is consistent if the total of all accounts is constant. If an error occurs and the money is removed from account A and not added to account B, then the total in all accounts would have changed. The system would no longer be consistent. By rolling back the removal from account A, the total will again be what it should be, and the system back in a consistent state.

Isolation

 

When a transaction runs in isolation, it appears to be the only action that the system is carrying out at one time. If there are two transactions that are both performing the same function and are running at the same time, transaction isolation will ensure that each transaction thinks it has exclusive use of the system. This is important in that as the transaction is being executed, the state of the system may not be consistent. The transaction ensures that the system remains consistent after the transaction ends, but during an individual transaction, this may not be the case. If a transaction was not running in isolation, it could access data from the system that may not be consistent. By providing transaction isolation, this is prevented from happening.

Durability

 

A transaction is durable in that once it has been successfully completed, all of the changes it made to the system are permanent. There are safeguards that will prevent the loss of information, even in the case of system failure. By logging the steps that the transaction performs, the state of the system can be recreated even if the hardware itself has failed. The concept of durability allows the developer to know that a completed transaction is a permanent part of the system, regardless of what happens to the system later on.

Monday, July 5, 2010

WCF Windows Authentication

When the We want to get the Windows identity inside the WCF that was hosted inside the IIS we need to do the some configuaration inside the service configuration.We will always get the Windows identiy inside the WCF service when we are working on the development server .Since the develpment server is always runs inside the integrated web server (ie inbuild webserver from VS2005).


So inorder to get the Windows identity  first and for most  we need to add the following config


   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

This  is to enable the asp.net Compatibility then only we can acess the HTTP Context that contains the User Identity


The follwing binding which will give the Current user identity
<bindings>
    <basicHttpBinding>
      <binding name ="BasicHttpBindingConfig">       
        <security mode="TransportCredentialOnly">
          <transport clientCredentialType="Windows" />
        </security>
      </binding>
    </basicHttpBinding>
</bindings>

we need to add this Binding inside the service where we need to access the windows identity like

<service behaviorConfiguration="SecurityConfigurationServiceBehavior" name="SecurityConfigurationService">
<endpoint address="" binding="basicHttpBinding" contract="ISecurityConfigurationService" behaviorConfiguration="SilverlightFaultBehavior"                  bindingConfiguration ="BasicHttpBindingConfig" >
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
       
</service>

After this configuration we have to ensue that no more end points are configured.

We need to enable some settings inside the IIS  to get the Windows Identity i.e  enable is Windows integrated  options

Wednesday, June 30, 2010

HTTP Request Processing in IIS 7

IIS 7 has a similar HTTP request-processing flow as IIS 6.0. The diagrams in this section provide an overview of an HTTP request in process.

The following list describes the request-processing flow that is shown in Figure 1:

1.    When a client browser initiates an HTTP request for a resource on the Web server, HTTP.sys
        intercepts   the request.
2.    HTTP.sys contacts WAS to obtain information from the configuration store.
3.    WAS requests configuration information from the configuration store, applicationHost.config.
4.    WWW Service receives configuration information, such as application pool and site configuration.
5.    WWW Service uses the configuration information to configure HTTP.sys.
6.    WAS starts a worker process for the application pool to which the request was made.
7.    The worker process processes the request and returns a response to HTTP.sys.
8.    The client receives a response.

In a worker process, an HTTP request passes through several ordered steps, called events, in the Web Server Core. At each event, a native module processes part of the request, such as authenticating the user or adding information to the event log. If a request requires a managed module, the native ManagedEngine module creates an AppDomain, where the managed module can perform the necessary processing, such as authenticating a user with Forms authentication. When the request passes through all of the events in the Web Server Core, the response is returned to HTTP.sys. Figure 2, below, shows an HTTP request entering the worker process.

Yeild

One interesting new feature of the C# 2.0 is the "yield" keyword.  Basically it is used to iterate through objects returned by a method. It creates a state engine in IL so you can create methods that retain their state and dont have to go through the pain of maintaining state in your code.

Here is a simple example that demonstrates how yield return can be used to maintain state in a method. Every time you call  GetInt() you will receive a new incremented integer.
public static IEnumerable GetInt()
{
   for (int i = 0; i < 5; i++)
       yield return i;
}


Here's the implementation.

public partial class Yield : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (int i in GetInt())
            Response.Write(i.ToString());
    }

    public static IEnumerable GetInt()
    {
          for (int i = 0; i < 5; i++)
            yield return i;
    }
}
Here  is the difference  on the execution

Typical Implementation                                  Yield Implementation 


Caller calls function                                            Caller calls function
Function executes and returns list                       Caller requests item
Caller uses list                                                    Next item returned
                                                                          Goto step #2


Although the execution of the yield implementation is a little more complicated, what we end up with is an implementation that "pulls" items one at a time instead of having to build an entire list before returning to the client.


Usually, the "yield" keyword will be useful when you implement the GetEnumerator() method of the IEnumerable interface
After all the Yield is creating addional overhead and use when required exactly.

Friday, June 25, 2010

const vs. readonly

const and readonly perform a similar function on data members, but they have a few important differences.
const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;

    public class MyClass
           {
               public const double PI = 3.14159;
           }
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Constants can be marked as public, private, protected, internal, or protected internal.

Constants are accessed as if they were static fields, although they cannot use the static keyword.

To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

readonly

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:

          public class MyClass
            {
               public readonly double PI = 3.14159;
            }
           or

          public class MyClass
            {
              public readonly double PI;

              public MyClass()
               {
                 PI = 3.14159;
               }
             }
Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used. A readonly field can also be used for runtime constants as in the following example:

public static readonly uint l1 = (uint)DateTime.Now.Ticks;


    * readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly  field explicitly if required.

    * A readonly member can hold a complex object by using the new keyword at initialization.

    * readonly members cannot hold enumerations.

static

Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. For example:

          public class Car
             {
               public static int NumberOfWheels = 4;
             }
The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.

static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

            int i = Car.NumberOfWheels;

Thursday, June 24, 2010

System.Web Element

Specifies the root element for the ASP.NET configuration section and contains configuration elements that configure ASP.NET Web applications and control how the applications behave.


<system.web> 
   <anonymousIdentification> 
   <authentication> 
   <authorization> 
   <browserCaps> 
   <caching> 
   <clientTarget> 
   <compilation> 
   <customErrors> 
   <deployment> 
   <deviceFilters> 
   <globalization> 
   <healthMonitoring> 
   <hostingEnvironment> 
   <httpCookies> 
   <httpHandlers> 
   <httpModules> 
   <httpRuntime> 
   <identity> 
   <machineKey> 
   <membership> 
   <mobileControls> 
   <pages> 
   <processModel> 
   <profile> 
   <roleManager> 
   <securityPolicy> 
   <sessionPageState> 
   <sessionState> 
   <siteMap> 
   <trace> 
   <trust> 
   <urlMappings> 
   <webControls> 
   <webParts> 
   <webServices> 
   <xhtmlConformance> 
</system.web>


Element
Description
Configures anonymous identification for application authorization. This is required to identify entities that are not authenticated when authorization is required.
Configures ASP.NET authentication support.
Configures ASP.NET authorization support.
Configures the settings for the browser capabilities component.
Configures the cache settings for a Web application.
Adds aliases for specific user agents to an internal collection of user agent aliases.
Contains all compilation settings that are used by ASP.NET.
Defines custom error messages for an ASP.NET application.
Defines configuration settings that are used to support the deployment of a Web application.
Specifies a device or a device class in the ASP.NET MobileCapabilities class based on the user agent or browser. A page or application developer can use a device filter to override control properties or to define blocks of content or templates to change layout and appearance.
Configures the globalization settings of an application.
Configures an application for health monitoring.
Defines configuration settings that control the behavior of the application hosting environment.
Configures properties for cookies that are used by a Web application.
Maps incoming URL requests to IHttpHandler classes.
Adds, removes, or clears HTTP modules within an application.
Configures ASP.NET HTTP run-time settings.
This section can be declared at the machine, site, application, or subdirectory level.
Controls the application identity of the Web application.
Configures keys to use for encryption and decryption of Forms authentication cookie data.
This section allows you to configure a validation key that performs message authentication checks on view-state data and Forms authentication tickets.
This section can be declared at the machine, site, or application levels but not at the subdirectory level.
Configures parameters for managing and authenticating user accounts for ASP.NET membership.
Defines adapter sets that map ASP.NET mobile controls to corresponding adapters within the system.web section of the Web.config file.
Identifies page-specific configuration settings.
Configures the ASP.NET process model settings on Internet Information Services (IIS) Web server systems.
Configures parameters for managing user values by using the ASP.NET profile.
Configures an application for role management.
This element is new in the .NET Framework version 2.0.
Defines valid mappings of named security levels to policy files.
This section can be declared at the machine, site, or application levels.
Configures page view-state settings for an ASP.NET application.
Configures the session-state module.
Configures the navigation infrastructure support for configuring, storing, and rendering site navigation.
Configures the ASP.NET trace service.
Configures the code access security permission set that is used to run a particular application.
This section can be declared at the machine, site, and application levels.
Defines a mapping that hides the real URL and maps it to a more user friendly URL.
Specifies the shared location of the client script files.
Specifies a Web Parts personalization provider, sets personalization authorizations, and adds custom classes that extend the WebPartTransformer class for use by Web Parts connections.
Controls the settings of XML Web services that are created using ASP.NET.
Configures XHTML 1.0–conforming control rendering.