asp.net: how to make asp:button render a button tagname with type=submit

March 25th, 2011 admin

Sometimes when I try to style the asp:button I get pretty frustrated because it has its limitations as it's not a container so you can't add any elements inside it. The real question is - why did Microsoft not make it possible to change the asp:button behaviour so it would be the option which tag you want to render? [sigh]
There are some articles in the internet saying how you can fix that by using web control adaptors or even javascript.
But what I really wanted is to have a different control that would render what I wanted it to. So I came up with the solution of extending the standard asp:button and overriding a couple of methods in it. The code is below. It's very simple and seems to work for me.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls;
 
namespace MyControls
{
    /// Class extending Button, but rendering button type='submit'
    public class ButtonSubmit : Button
    {
        public ButtonSubmit()
            : base()
        { }
 
        public string Value
        {
            get
            {
                string str = (string)ViewState["Value"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set { ViewState["Value"] = value; }
        }
 
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Button);
        }
 
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (HasControls())
                base.RenderChildren(writer);
            else
                writer.Write(Text);
        }
 
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            // substitute "text" with "value" because the base class uses "text" for "value"
            string strText = Text;
            Text = Value;
            base.AddAttributesToRender(writer);
            Text = strText;
        }
    }
}
 

Posted in asp.net, c#, development, Uncategorized | No Comments »

Difference between ref and out in .net

July 28th, 2009 admin

There are a couple of ways getting output parameters from .net procedures: you can use the keyword out or the keyword ref. Like so:

public void DoSmth(ref int nRefVar){}

or

public void DoSmth(out int nOutVar){}

What's the difference? Well, that's pretty easy. To pass a variable by reference, first you have create that reference by initializing the variable. Usually you want to use this way when you're gonna use the value of the variable inside the function.

public void DoSmth(ref int nRefVar)
{
if (nRef > 10)
nRef = 5;
else
nRef = 25;
}
int nRefVar = 10;
DoSmth(ref nRefVar);

To pass a variable as an out parameter you have only to declare it first. This way is just for getting the value. Usually you will need it when you have to get more than one return value from a procedure.

public void DoSmth(out int nOutVar1, out int nOutVar2)
{
nOutVar1 = 1;
nOutVar2 = 2;
}
int nOutVar1, nOutVar2;
DoSmth(out nOutVar1, out nOutVar2);

Good Luck

Posted in asp.net, c#, development | No Comments »

asp.net interview question

July 24th, 2009 admin

Here is a list of some basic ASP.Net interview question. I've come across them here: http://weblogs.asp.net/anasghanem/archive/2008/02/22/common-net-technical-questions-that-you-will-be-asked-about-in-the-interviews.aspx

For those who looks for a new job :)

1. Explain the life cycle of an ASP .NET page.
2. Explain the .NET architecture.
3. What are object-oriented concepts?
4. How do you create multiple inheritance in c# and .NET?
5. When is web.config called?
6. Differences between DLL and EXE?
7. Can an assembly have EXE?
8. Can a DLL be changed to an EXE?
9. Compare & contrast rich client (smart clients or Windows-based) & browser-based Web application
10. Compare Client server application with n-Tier application
11. Can a try block have more than one catch block?
12. Can a try block have nested try blocks?
13. How do you load an assembly at runtime?
14. If I am writing in a language like VB or C++, what are the procedures to be followed to support .NET?
15. How do you view the methods and members of a DLL?
16. What is shadowing?
17. What are the collections you’ve used?
18. What is a static class?
19. What is static member?
20. What is static function?
21. What is static constructor?
22. How can we inherit a static variable?
23. How can we inherit a static member?
24. Can we use a static function with a non-static variable?
25. How can we access static variable?
26. Why main function is static?
27. What is garbage collection?
28. Can we force garbage collector to run?
29. What is reflection?
30. What are different type of JIT?
31. What are Value types and Reference types?
32. What is concept of Boxing and Unboxing?
33. What’s difference between VB.NET and C#?
34. What’s difference between System exceptions and Application exceptions?
35. What is CODE Access security?
36. What is a satellite assembly?
37. How to prevent my .NET DLL to be decompiled?
38. What’s the difference between Convert.toString and .toString() method ?
39. What is Native Image Generator (Ngen.exe)?
We have two version of the same assembly in GAC? I want my client to make choice which assembly to choose?
40. What is CodeDom?

Posted in asp.net, c# | No Comments »

Uploading and executing an SQL Script File using ASP.Net and osql

April 11th, 2008 admin

Now I am gonna tell how to upload a file containg T-SQL script using ASP.Net and execute entire of the file using osql utility tool.
Note: This example is using the UploadFile method from the previous article

 
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;    
 
// some code goes here
// ..................
// ...................    
 
string strResult = string.Empty;
// first of all the file should be uploaded
// let's use the UploadFile procedure from the previous article
string strFileName = string.Empty;
string strBaseFolder = "c:\uploads";
string strFolder = Path.Combine(strBaseFolder, Guid.NewGuid().ToString());
bool bIsOk;
try
{
	bIsOk = UploadFile(FileInputControl, strFolder, ref strFileName);
}
catch
{
	bIsOk = false;
}    
 
if (bIsOk)
{
	// getting full file path
	string strFilePath = Path.Combine(strFolder, strFileName);    
 
	// here we should set connection parameters (i.e. they could be taken from web.config)
	string strServerName = "", strDBName = "", strUserName = "", strPassword = "";    
 
	// executing entire script
	using (Process proc = new Process())
	{
		proc.StartInfo.FileName = "osql";
		proc.StartInfo.Arguments = string.Format("/S {0} /U {1} /P {2} /d {3} /i {4}",
			strServerName, strUserName, strPassword, strDBName, strFilePath);
		proc.StartInfo.UseShellExecute = false;
		proc.StartInfo.RedirectStandardOutput = true;
		proc.StartInfo.RedirectStandardError = true;
		proc.StartInfo.CreateNoWindow = true;
		try
		{
			proc.Start();
			proc.WaitForExit();
			strResult = proc.StandardOutput.ReadToEnd();
			proc.Close();
		}
		catch
		{
			strResult = @"The script can not be executed.
                                           Make sure there is osql utility on the server.";
		}
	}    
 
	// now lets delete the file as we don't want it to be saved on the server
	Directory.Delete(strFolder, true);
}
else
{
	strResult = "The file cannot be uploaded to the server";
}    
 
// now we could display strResult variable containg information about script execution
// i.e. using Response.Write method
Page.Response.Write(strResult);

Good luck!

Posted in asp.net, c#, sql | No Comments »

Uploading a file using ASP.Net

April 10th, 2008 admin

I know there are loads of articles related to uploading a file usin ASP.Net application. But still there is my method of doing that. Usually while creating a web application all my pages extend one base class but not the Page class. I always create some base class which extends the Page, so I could add some basic functionality and it and use it on any page I want. So the UploadFile procedure would on the methods of my base page class.

 
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;    
 
public class MyPage : Page
{
..........
    // strUploadFolder - full path to the folder in which we are gonna store the file (i.e c:\savehere)
    // strFileName - return parameter, that will store upaded file's name
    // function returns true if uploading has been successfull, otherwise we get false
    protected bool UploadFile(HtmlInputFile fileinput, string strUploadFolder, ref string strFileName)
    {
        HttpPostedFile myFile = fileinput.PostedFile;
        int nFileLen = myFile.ContentLength;
        strFileName = string.Empty;
        if (nFileLen > 0)
        {
            byte[] myData = new byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);
            strFileName = Path.GetFileName(myFile.FileName);    
 
            try
            {
                if (!Directory.Exists(strUploadFolder))
	       Directory.CreateDirectory(strUploadFolder);
                using (FileStream newFile = new FileStream(Path.Combine(strUploadFolder, strFileName),
                                       FileMode.Create))
	   {
	       newFile.Write(myData, 0, myData.Length);
	       newFile.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }
        else
            return false;
    }
..........
}

Posted in asp.net, c#, development | No Comments »

ASP.Net QueryString Builder

March 25th, 2008 admin

I was trying to find any classes allowing easily modify querystring. I have found a couple of good ones but not ideal for me. So I have created my own class. It has a number of static functions which could be called without creating an instance of the class - if you need to use some basic stuff. Here it is:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Specialized;
 
namespace ClassLibrary
{
    public class QueryStringBuilder
    {
        protected NameValueCollection m_QueryString;
 
        public QueryStringBuilder(NameValueCollection nvcQueryString)
        {
            m_QueryString = new NameValueCollection(nvcQueryString);
        }
 
        // static function returning a new querystring with a new parameter
        public static NameValueCollection QSWithParameter(NameValueCollection nvcCurrentQS,
                                                      string strParameterName, string strParameterValue)
        {
            NameValueCollection nvcQS = new NameValueCollection(nvcCurrentQS);
 
            for (int i = 0; i < nvcQS.Count; i++)
            {
                if (nvcQS.GetKey(i) == null)
                {
                    nvcQS.Remove(null);
                    break;
                }
            }
            if (nvcQS.GetValues(strParameterName) == null)
                nvcQS.Add(strParameterName, strParameterValue);
            else
                nvcQS[strParameterName] = strParameterValue;
            return nvcQS;
        }
 
        // function returning a new querystring with a new parameter
        public NameValueCollection QSWithParameter(string strParameterName, string strParameterValue)
        {
            return QSWithParameter(m_QueryString, strParameterName, strParameterValue);
        }
 
        // static function returning a querystring without a parameter
        public static NameValueCollection QSWithoutParameter(NameValueCollection nvcCurrentQS,
                                                                               string strParameterName)
        {
            NameValueCollection nvcQS = new NameValueCollection(nvcCurrentQS);
            if (nvcQS.GetValues(strParameterName) != null)
                nvcQS.Remove(strParameterName);
            return nvcQS;
        }
 
        // function returning a querystring without a parameter
        public NameValueCollection QSWithoutParameter(string strParameterName)
        {
            return QSWithoutParameter(m_QueryString, strParameterName);
        }
 
        // static function returning url with a querystring
        public static string UrlWithQueryString(NameValueCollection nvcQueryString, string strUrl)
        {
            int nQS = strUrl.IndexOf("?");
            if (nQS > -1)
                strUrl = strUrl.Substring(0, nQS);
            if (nvcQueryString.Count > 0)
            {
                for (int i = 0; i < nvcQueryString.Count; i++)
                {
                    strUrl += String.Format("{0}{1}={2}", i == 0 ? "?" : "&", nvcQueryString.Keys[i],
                                                                                    nvcQueryString[i]);
                }
            }
            return strUrl;
        }
 
        // static function returning RawUrl with a querystring
        public static string UrlWithQueryString(NameValueCollection nvcQueryString)
        {
            return UrlWithQueryString(nvcQueryString, HttpContext.Current.Request.RawUrl);
        }
 
        // function returning url with a current querystring
        public string UrlWithQueryString(string strUrl)
        {
            return UrlWithQueryString(m_QueryString, strUrl);
        }
 
        // function returning RawUrl with a current querystring
        public string UrlWithQueryString()
        {
            return UrlWithQueryString(m_QueryString);
        }
 
        // procedure removing a parameter from a current querystring
        public void RemoveQSParameter(string strParameterName)
        {
            m_QueryString = QSWithoutParameter(strParameterName);
        }
 
        // procedure adding a parameter to a current querystring
        public void SetQSParameter(string strParameterName, string strParameterValue)
        {
            m_QueryString = QSWithParameter(strParameterName, strParameterValue);
        }
    }

Posted in asp.net, c#, development | No Comments »

ASP.Net 3.5. Where?

March 22nd, 2008 admin

Just found a funny article explaining why after installing .Net 3.5 we can't select ASP.Net 3.5 under a ASP.Net version tab in IIS while setting up a site. I thought the answer was obvious - nobody had said about changing a version of ASP.Net - it is still 2 :)

Posted in asp.net | No Comments »

Coding web forms html

March 21st, 2008 admin

Coding client html of web-forms is not the easiest and not the most interesting part of developing a web-application. There are loads of ways of doing that. But the question is - which one is the right one? The html code should be semantyc, accessible and obvious for other developers. So I tried googling and found this article that seemed very interesting to me. How that could've been more obvious that fieldsets and labels should be used for developing web-forms? And by using CSS we could make the form look in many different ways!

Have a look at the following example:

 
<fieldset class="form-fieldset">
    <label class="textbox surname">
        <span>Surname</span>
<input name="surname" id="surname" type="text" />
    </label>
</fieldset>
 

Now with a help of CSS we could access any element of this form. Very flexible. We could use as many fieldsets as we could wish. We could even have fieldsets inside fieldsets.

Alright. Later I started thinking how I could use that for simplify the way of creating asp.net web forms. So I created a class FieldSet

 
    public class FieldSet : HtmlGenericControl
    {
        public FieldSet()
            : base("fieldset")
        { }
 
        public FieldSet(string strLegend)
            : this()
        {
            HtmlGenericControl legend = new HtmlGenericControl("legend");
            Controls.Add(legend);
            legend.InnerText = strLegend;
        }
 
        // as an example I have created this simple method which allows add a new input text to the fieldset
        public HtmlInputText AddInputText(string strLabel, string strCSSClass)
        {
            HtmlInputText txt = new HtmlInputText();
            AddControl(strLabel, txt, strCSSClass);
            return txt;
        }
 
        public HtmlInputText AddInputText(string strLabel)
        {
            return AddInputText(strLabel, null);
        }
 
        // this method is used for adding any web contol to the fieldset
        public void AddControl(string strLabel, Control cntrl, string strCSSClass)
        {
            HtmlGenericControl label = new HtmlGenericControl("label");
            Controls.Add(label);
            label.Controls.Add(new LiteralControl("<span>" + strLabel + "</span>"));
            if (strCSSClass != null)
                label.Attributes["class"] = strCSSClass;
 
            label.Controls.Add(cntrl);
            cntrl.ID = ID + "_cntrl_" + Controls.Count.ToString();
            label.Attributes["for"] = cntrl.ClientID;
        }
 
        public void AddControl(string strLabel, Control cntrl)
        {
            AddControl(strLabel, cntrl, null);
        }
    }

So now while developing another asp.net web-form I just could write the code:

 
.....
FieldSet fs = new FieldSet("Editing surname");
Controls.Add(fs);
HtmlInputText txtSurname = fs.AddInputText("Surname:", "surname");
.....

See? Just three lines of code.

Posted in asp.net, development, html | No Comments »