Saturday 24 October 2009

"Control can not be created because visual studio can not find the controls 's type in control assembly"

This error message was suddenly popping up in visual studio when I tried to drag my custom web control on a web page then tried to compile the code and found two main error messages in error list. Some thing like
"only one section per config file is allowed" since I had just added ajax configuration to web.config file like

<httpModules >

<add type="URLRewrite" name="URLRewrite" />

<httpHandlers>

<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

>

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>


httpmodule tag has been declared twice in web.config.

Solution:

merge two httpModules tags in one tag.

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add type="URLRewrite" name="URLRewrite" />

These two sections of httpmodules in web.config were causing this error.

Monday 10 August 2009

Building Application for iphone in C#

Its wonderful to write application for iphone c# . It is called Mono , a cross platform open source environment to develop application for linux, mac and iphone in c# with c# IDE(mono IDE for C#).



Sunday 24 May 2009

How to fix MS Visual studio Error " The filename, directory name, or volume label syntax is incorrect.(Exception from HResult:0x8007007B) "

I keep getting this error while trying to add a project under a folder in blank solution using Microsoft visual studio 2005. I did not use any character like .? etc in filename but still got the error until i just figured out that the directory path of project contained & character.e.g my project had a directory path C:\My Projects & research\myproject\ where directory My Projects & research contained '&' sign.


I changed directory path to MyprojectsandResearch and it worked fine.I also changed name of file to myprojects.objects and did not give me any error. so the Error was generating from path and not by filename.I think it is some kind of bug in Visual studio 2005.

Thursday 16 April 2009

AJAX in ASP.NET Part-2

Following AJAX example demonstrates how to update partial page without postback or refreshing page.

  1. AddNew Item->Web Form in Your website .
  2. Place Script manger and UpdatePanel from toolbox on form.

<asp:ScriptManager ID="ScriptManager1" runat="server">

asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

ContentTemplate>


After placing these components,VS automatically place this directive in html designer view.

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI" TagPrefix="asp" %>




In web.config Add following Httphandler and HttpModule section.

<httpHandlers>

<remove verb="*" path="*.asmx"/>

<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

httpHandlers>

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

httpModules>

system.web>





You can also copy paste this section from web.config file of AJAX ENABLED ASP.NET WEBSITE Template


If you are new to httphandlers and httpmodule , read this post
Httphandlers and HttpModules
Place a calendar and label control in update panel.Place a label control outside updatepanel .

<ContentTemplate>

<asp:Label ID="LBLDateselected" runat="server">asp:Label>

<asp:Calendar ID="Calendar1" runat="server" BackColor="#FFFFCC" BorderColor="#FFCC66"

BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"

ForeColor="#663399" Height="200px" OnSelectionChanged="Calendar1_SelectionChanged"

ShowGridLines="True" Width="220px">

<SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />

<SelectorStyle BackColor="#FFCC66" />

<TodayDayStyle BackColor="#FFCC66" ForeColor="White" />

<OtherMonthDayStyle ForeColor="#CC9966" />

<NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />

<DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />

<TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt" ForeColor="#FFFFCC" />

asp:Calendar>

ContentTemplate>




on page load place code

Label2.Text = DateTime.Now.ToLongTimeString();

and on calendar's Calendar1_SelectionChanged event place this code

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
LBLDateselected.Text = Calendar1.SelectedDate.ToLongDateString();
}

as you can see page is not postingback while clicking on calendar, it means code that has been placed in page load event wont be executed. only code for controls or in events of controls that are placed in update panel will be executed.

Wednesday 15 April 2009

AJAX in ASP.NET Overview Part-1

Asynchronous Javascript and XML is a technique that used to execute server side code and return data back to the browser without postbacks or refreshing page.Let's take an example of Google Suggest where return results of query are filled in drop down list while typing the query without refreshing or posting back the page.AJAX pages contains Client side script and Server side code which exchange information through XML and communication between client side and server is carried asynchronously.

Main Object in AJAX is XMLHttpRequest ,with this object,clients can submit and retrieve XML data to /from server without postbacks or reloading page.

var _reqObject= new XMLHttpRequest();

Every latest browser support this object however Internet explorer 6 or old versions doest not.To declare XMLHttpRequest for older browser compatibility,following active- X syntax is used as it would be treated as active-X control.

var _reqObject = new ActiveXObject("MSXML2.XMLHTTP.3.0");

So basically there is lot of workaround for browser checks in code.AJAX components in ASP.NET made it all easier.

ASP.NET AJAX Contains Server side and clients side components. Where Client side components contains Javascript libraries (.js) that can be extended and can also be used in non-asp.net page. It also contains cross browsers compatibility scripts.
Server side contains Controls, UpdatePanel,ScriptManager.

AJAX Library can also be used to call web service(.asmx extensions) .

Before processing to our sample, we need to download

ASP.NET AJAX 1.0

download it from above link for visual studio 2005. This toolkit is for ASP.NET 2.0, for ASP.NET 3.5, ASP.NET AJAX is built-In feature.After Installation of ASPAJAXExtSetup.msi and restarting Visual studio, AJAX extensions is installed in toolbox.
AJAX Extensions contains server side controls, Following controls will be our target to build up a AJAX style Web page.
  1. ScriptManager.
  2. UpdatePanel
  3. Timer

ScriptManager must be placed on page before placing any other AJAX server control o page, as it manages all AJAX Script libraries and files.

END of PART-1

Monday 6 April 2009

Integrating Instant MSN messenger in ASP.NET

Though this feature may be available in MS sharepoint portals but some time we need to embed MSN windows(not live messenger) Messenger in our own non portal website .Before starting our mission, we need RCW(Runtime callable Wrapper) interfaces for messenger so .Net Environment can understand old Com's Methods and properties.
Note:You also need to know about STA and MTA Thread pool.
  • Open Menu->Type "C:\Program Files\Messenger" in Run.
  • msmsgs.exe is our target to convert it to .Net assembly.
We will use TLBImp.exe tool that will import metadata from msmsgs type library and convert it to .Net assembly where Metadata will be stored in assembly manifest.All Methods and properties from Com components will be exposed through new generated dll. However it is nessary that old COMs should be existed and should be registered in registry before Generating RCW wrapper(.Net dll).

  • Goto MS visual studio 2005 tools->open Visula studio 2005 Command prompt.
  • type following command
C:\Program Files\Microsoft Visual Studio 8\VC>tlbimp.exe "C:\Program Files\Messe nger\msmsgs.exe" /out:C:\inetpub\wwwroot\myWebsitedirectory\inetpubdotnetmsgr.dll
  • On Solution Explorer in VS 2005 , right click and Add Reference
Select Converted Dll from Add refernence window.

Now Switch to code view and this code.

Normal 0 false false false MicrosoftInternetExplorer4

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using inetpubdotnetmsgr;

public partial class Messenger : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (IsPostBack==false)

{

MsgrObjectClass _messngerobject = new MsgrObjectClass();

_messngerobject.Logoff();

//IMsgrService _ImessngerService = _messngerobject.IMsgrObject_Services.PrimaryService;

_messngerobject.Logon("myuserid@hotmail.com", "mypassword", _messngerobject.Services.PrimaryService);

IMsgrUsers _Users = _messngerobject.get_List(MLIST.MLIST_CONTACT);

foreach (IMsgrUser _user in _Users)

{

ListBox1.Items.Add(_user.EmailAddress.ToString());

}

}

}

}



You aslo need to set permission on new generated Dll for asp.net User.

Friday 3 April 2009

Converting classic ASP page to ASP.NET aspx page

If you have already developed some asp page , cut & paste that server code in asp.net page(not on designer) but in html view. In page directive add this code.

<%@ Page AspCompat ="true" %>



<%@ ASPCOMPAT="true" %> directive, is for STA Single threaded apartment pool.

We use such syntax , reason is we use use com components in classic asp that are not developed in .Net and ASP.NET use multithreaded apartment (MTA) by default

Late Binding


as always, asp might contain adodb library and connection to database. C# is strongly typed language , we can not simply use ADODB in it.

so we need reflection namespace for binding.

<%@ Import Namespace="System.Reflection" %>


for instance if you ve created
connection object,
conn=Server.create("ADODB.Connction");
its methods(Open) and recordset's execute will be invoked thought late binding.
conn.GetType().InvokeMember("Open",BindiingFlags.InvokeMethod,...)(see MSDN for full parameters details).


It is always a better idea to use early binding for performance reason therfore one can use TLBimp.exe tool to convert old Com components into .Net assemblies.

Wednesday 1 April 2009

Detecting and recording key strokes in C#

There are two APIs are used for this purpose.

DllImport("User32.dll")]

private static extern short GetAsyncKeyState(

System.Windows.Forms.Keys vKey);

[DllImport("User32.dll")]

private static extern short GetAsyncKeyState(

System.Int32 vKey);


Note that this type of coding in .Net environment is called PInvoke
( platform invoke) feature as we are declaring and calling unmanaged libraries in .Net environment.

This Code works for all kind of Application domains running in Windows OS whether it is notepad, Messenger etc.
Calling APIs


(int)Keys

enumeration in calling function.


for example

// Check for keypresses

if (GetAsyncKeyState((int)Keys.Down) != 0)


or

// Check for keypresses

if (GetAsyncKeyState((int)Keys.Up) != 0)



use stringbuilder variable to store all captured keystrokes in that variable.




Tuesday 24 March 2009

Implementing Fragment caching in ASP.NET 2.0

Caching in ASP.Net world means to store whole rendered html page or data e.g dataset or a part of page such as controls in server's memory for specific period of time and that cached items would be accessed for short period of time without executing code to process same data or page again. Whole idea behind this is to minimize the execution of code to do same task on consecutive clicks by one or more users increase performance.
However one should be careful in selecting caching techniques as it is not always an option for all kind of web applications e.g Displaying Real Pricing or showing Real time Tennis,Cricket match score.

What is fragment caching?
to store a part of page in memory rather than whole page for a specified period of time.Fragment caching is done by using User controls.

Here is Steps for implementing Fragement caching.

  1. Create a web site(or open a website you already created)
  2. Right click on project and select Add new Item from pop-up menu.
  3. Select WebUserControl from Templates.



In fragment caching , output directive is used in user control .ascx file.It should not be placed in main page(page which host user control).Set the duration for outputcache to 20 seconds.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CachedContent.ascx.cs" Inherits="CachedContent" %>

<%@ OutputCache Duration ="20" VaryByParam="None" %>

<div id="outputdiv" style="clear: none; display: block; left: 50px; visibility: visible; width: 752px; position: relative; top: 50px; height: 100px; background-color: powderblue;">

cached Time

<asp:Label id="head1" runat="server" Font-Bold="True" Font-Names="Tahoma" Font-Size="XX-Large"><%# DateTime.Now.ToLongTimeString() %>asp:Label>

div>

On page load of user control , use this code.

head1.DataBind();

on user control hosting page(main page) place this code on declarative part of the page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OutputcacheTest.aspx.cs" Inherits="OutputcacheTest" %>

<%@ Register Src="CachedContent.ascx" TagName="CachedContent" TagPrefix="uc1" %>


then place this code after form tag in same page.

<div id="H2" style="clear: none; display: block; left: 34px; visibility: visible; width: 752px; position: relative; top: 30px; height: 100px; background-color: gainsboro;">

Non cache Time

<h1 id="H1_1" runat="server">

<%# DateTime.Now.ToLongTimeString() %>

h1>

div>

<asp:Button ID="gettime" runat ="server" style="clear: none; display: block; left: 271px; visibility: visible; position: relative; top: 269px; background-color: gainsboro;" Height="47px" Text="Get time" Width="177px" OnClick="gettime_Click" />

<uc1:CachedContent ID="CachedContent1" runat="server" />


on page load of main page write down tis code.



using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class OutputcacheTest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

System.Web.UI.HtmlControls.HtmlGenericControl header2 = new HtmlGenericControl();

header2 = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.FindControl("H1_1");

header2.DataBind();

}

protected void gettime_Click(object sender, EventArgs e)

{

}

}


I placed header tag and bind it with current datetime on page while I also placed User control which displays current datetime with declarative Output cache.

when I execute main page ,I see new datetime for the code i placed on main page each time refresh the page(page is posted back to server), however, user control time didnt change it retrives the rendered html from memory until specified period is elapsed.






Monday 16 March 2009

Code for creating PieChart in ASP.NET 2.0

GDI+ is great innovation in .NET and it is not limited to desktop applications , you can also use it in ASP.net pages.Here in example code is used to draw a pie chart in asp.net web page using GDI+ Classes of drawings.

Import all Drawings name spaces.


using System.Drawing.Drawing2D;

using System.Drawing;

using System.Drawing.Design;

using System.Drawing.Imaging;

using System.Drawing.Text;

Since to determine the angle of each sector in pie chart we follow following math formula

x°=value of Item A/Total value of all items * 360°


Place a listbox and a button on page. fill listbox with some items





float angletosweep=0;

float totalangle=0;

int _TotalvalueOfAllItems = 0;

for (int index = 0;
index &lt; ListBox1.Items.Count; index++)

{

_TotalvalueOfAllItems += Convert.ToInt32(ListBox1.Items[index].Text.Trim());

}

Bitmap _InMemoryBitmap = new Bitmap(200, 200);

Graphics g = Graphics.FromImage(_InMemoryBitmap);

Pen _pen = new Pen(Color.Indigo);

Rectangle _rectangle = new Rectangle(20, 20, 100,
100);

SolidBrush _brush = new
SolidBrush(Color.Indigo);

for(int
item=0;item<ListBox1.Items.Count;item++)

{

angletosweep = 360 *(Convert.ToInt32(ListBox1.Items[item].Text)) /
(_TotalvalueOfAllItems);

g.FillPie(new SolidBrush(ColorCodes(item)), _rectangle, totalangle,
angletosweep);

//some code omitted.


}

_InMemoryBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

g.Dispose();

_InMemoryBitmap.Dispose();

}

private Color
ColorCodes(int item)

{

Color[] _colorcodes = new Color[] { Color.Green, Color.Yellow ,
Color.LightCoral, Color.Turquoise , Color.Tomato ,
Color.Tan };

return _colorcodes[item];

}


call this page from another page and place the url into img tag of calling page.