ASP.NET MVC Multiple models binding to a single view.

I came to know that there is a very hot topic that how to bind multiple models to a single view.

I saw developers approached very touch way to acheived this tiny task.Mostly following Implementing IEnumerator Interface. If a developer doesn’t know the complete knowledge about the GetEnumertor function or how to implement and how further bound, It will stuck at some place. I will cut it short.

I suppose you have two classes.

Class 1 named : GetPackages which returns credit card list.

 public class GetPackages
    {
        private List<SelectListItem> _creditCardType =
new List<SelectListItem>();
        public List<SelectListItem> CreditCardTypeList
        {
            get
            {
                _creditCardType.Add(new SelectListItem()
{ Text = "Visa", Value = "Visa" });
                _creditCardType.Add(new SelectListItem()
{ Text = "MasterCard", Value = "MasterCard" });
                _creditCardType.Add(new SelectListItem()
{ Text = "AmericanExpress", Value = "AmericanExpress" });
                _creditCardType.Add(new SelectListItem()
 { Text = "Discover", Value = "Discover" });
                return _creditCardType;
            }
        }
    }

Class2: Month list

public class Month
{
        public List<SelectListItem> MonthList
        {
            get
            {
                _monthList.Add(new SelectListItem()
{ Text = "Jan", Value = "01" });
                _monthList.Add(new SelectListItem()
 { Text = "Feb", Value = "02" });
                _monthList.Add(new SelectListItem()
{ Text = "Mar", Value = "03" });
                _monthList.Add(new SelectListItem()
{ Text = "Apr", Value = "04" });
                _monthList.Add(new SelectListItem()
{ Text = "May", Value = "05" });
                _monthList.Add(new SelectListItem()
{ Text = "Jun", Value = "06" });
                return _monthList;
            }
        }
}

At Controller side:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            GetPackages getPackage = new GetPackages();
            Month monthlist = new Month();
            ViewBag.GetPackages = getPackage;
            ViewBag.month = monthlist;
            return View();
        }
    }

At View using Razor

 @foreach (var type in ViewBag.GetPackages.CreditCardTypeList)   �
       {     �
           <a href="@type.Text">@type.Text</a>     �
       }  
 @foreach (var month in ViewBag.month.Monthlist)   �
       {     �
           <a href="@month.Text">@month.Text</a>     �
       }

Its a very easy way to bind through Viewbag.
ViewBag which can be used to pass data from Controllers to Views same as you use ViewData[] dictionary.
I am running out of time, I will explain in detail about Viewbag and Viewdata.

Regards,
Joggee.

MVC , , , , ,

Steps to implement Elmah with your website.

ELMAH is an application – wide exception logging system that logs unhandled exceptions. you can add ELMAH assembly in your developing project or you can configure it and add dynamically in you running Asp.net application
Background

1.Logs all the unhandled exceptions
2.Gives custome exceptions even thought the custome exception mode is off
3.An RSS feed of the exception.
4.Email the exceptions

 Implementation
1.Add ELMAH assembly in your project.

To download elmah assembly:
http://code.google.com/p/elmah/wiki/Downloads?tm=2

Also, ELMAH is available here
2.Configur your web.config

For latest web.config configuration:
http://elmah.googlecode.com/svn-history/r761/tags/REL-1.2-BETA/samples/web.config

Here is a sample web config setting

<?xml version=”1.0″ encoding=”utf-8″?>
<configuration>
  <configSections>
    <sectionGroup name=”elmah”>
      <section name=”errorLog” requirePermission=”false” type=”Elmah.ErrorLogSectionHandler, Elmah” />
      <section name=”errorMail” requirePermission=”false” type=”Elmah.ErrorMailSectionHandler, Elmah” />
      <section name=”errorFilter” requirePermission=”false” type=”Elmah.ErrorFilterSectionHandler, Elmah”/>
    </sectionGroup>
  </configSections>
  <connectionStrings >
    <add name=”elmah-sql” connectionString=”Data Source=xxx;Initial Catalog=ELMAH;Trusted_Connection=True” />
  </connectionStrings>
  <elmah>
    <errorLog type=”Elmah.SqlErrorLog, Elmah” connectionStringName=”elmah-sql”   >
    </errorLog>
  </elmah>
  <system.web>
    <httpModules>
      <add name=”ErrorLog” type=”Elmah.ErrorLogModule, Elmah”/>
    </httpModules>
    <httpHandlers>
      <add verb=”POST,GET,HEAD” path=”elmah.axd” type=”Elmah.ErrorLogPageFactory, Elmah” />
    </httpHandlers>
    <customErrors mode=”On” defaultRedirect=”CustomeErrorPage.htm” />
  </system.web>
</configuration>

3.Script to create required tables and stored procedure

CREATE TABLE dbo.ELMAH_Error
(
    ErrorId     UNIQUEIDENTIFIER NOT NULL,
    Application NVARCHAR(60)  NOT NULL,
    Host        NVARCHAR(50)  NOT NULL,
    Type        NVARCHAR(100) NOT NULL,
    Source      NVARCHAR(60)  NOT NULL,
    Message     NVARCHAR(500) NOT NULL,
    [User]      NVARCHAR(50)  NOT NULL,
    StatusCode  INT NOT NULL,
    TimeUtc     DATETIME NOT NULL,
    Sequence    INT IDENTITY (1, 1) NOT NULL,
    AllXml      NTEXT  NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE dbo.ELMAH_Error WITH NOCHECK ADD
    CONSTRAINT PK_ELMAH_Error PRIMARY KEY
    (
        ErrorId
    )  ON [PRIMARY]
GO

ALTER TABLE dbo.ELMAH_Error ADD
    CONSTRAINT DF_ELMAH_Error_ErrorId DEFAULT (newid()) FOR [ErrorId]
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.ELMAH_GetErrorXml
(
    @Application NVARCHAR(60),
    @ErrorId UNIQUEIDENTIFIER
)
AS

SET NOCOUNT ON

SELECT
    AllXml
FROM
    ELMAH_Error
WHERE
    ErrorId = @ErrorId
AND
    Application = @Application

 

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.ELMAH_GetErrorsXml
(
    @Application NVARCHAR(60),
    @PageIndex INT = 0,
    @PageSize INT = 15,
    @TotalCount INT OUTPUT
)
AS

SET NOCOUNT ON

DECLARE @Page TABLE
(
    Position INT IDENTITY(1, 1) NOT NULL,
    ErrorId UNIQUEIDENTIFIER NOT NULL,
    Application NVARCHAR(60) NOT NULL,
    Host NVARCHAR(30) NOT NULL,
    Type NVARCHAR(100) NOT NULL,
    Source NVARCHAR(60) NOT NULL,
    Message NVARCHAR(500) NOT NULL,
    [User] NVARCHAR(50) NOT NULL,
    StatusCode INT NOT NULL,
    TimeUtc DATETIME NOT NULL
)

INSERT
INTO
    @Page
    (
        ErrorId,
        Application,
        Host,
        Type,
        Source,
        Message,
        [User],
        StatusCode,
        TimeUtc
    )
SELECT
    ErrorId,
    Application,
    Host,
    Type,
    Source,
    Message,
    [User],
    StatusCode,
    TimeUtc
FROM
    ELMAH_Error
WHERE
    Application = @Application  �
ORDER BY
    TimeUtc DESC,
    Sequence DESC

SELECT
    @TotalCount = COUNT(*)
FROM
    @Page

DECLARE @FirstPosition INT
SET @FirstPosition = @PageIndex * @PageSize + 1

DECLARE @LastPosition INT
SET @LastPosition  = @FirstPosition + @PageSize – 1

SELECT
    errorId,
    application,
    host,
    type,
    source,
    message,
    [user],
    statusCode,
    CONVERT(VARCHAR(50), TimeUtc, 126) + ‘Z’ time
FROM
    @Page error
WHERE
    Position >= @FirstPosition
AND
    Position <= @LastPosition
ORDER BY
    Position
FOR
    XML AUTO

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.ELMAH_LogError
(
    @ErrorId UNIQUEIDENTIFIER,
    @Application NVARCHAR(60),
    @Host NVARCHAR(30),
    @Type NVARCHAR(100),
    @Source NVARCHAR(60),
    @Message NVARCHAR(500),
    @User NVARCHAR(50),
    @AllXml NTEXT,
    @StatusCode INT,
    @TimeUtc DATETIME
)
AS

SET NOCOUNT ON

INSERT
INTO
    ELMAH_Error
    (
        ErrorId,
        Application,
        Host,
        Type,
        Source,
        Message,
        [User],
        AllXml,
        StatusCode,
        TimeUtc
    )
VALUES
    (
        @ErrorId,
        @Application,
        @Host,
        @Type,
        @Source,
        @Message,
        @User,
        @AllXml,
        @StatusCode,
        @TimeUtc
    )

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
In order to get the details just append “/elmah.axd to you browser to the default page.

e.g. http://localhost/sitename/elmah.axd

Thank to Mr. Gautam Sharma

http://www.codeproject.com/KB/aspnet/ELMAHDemo.aspx

 

 

ASP.NET, Visual Studio ASP.NET ,

Bill Gates’ last day at Microsoft (video)

A video spoof shown during the CES 2008 keynote by Bill Gates about his last full day at Microsoft in July starring himself, Brian Williams, Steve Ballmer, Matthew McConaugheyr, Robbie Bach, Jay-Z, Bono, Steven Spielberg, George Clooney, Jon Stewart, Kevin Turner, Hillary Clinton, Barack Obama, Al Gore, Ray Ozzie and Craig Mundie.

Can check out a wide screen version with high quality

http://www.istartedsomething.com/20080107/bill-gates-last-day-microsoft-video/

Funny , , , ,

Mouse over effect

This is so simple and can found thousand places but I tried to make it more easier who doesnt know the different between <asp:linked button> or anchor.

Copy below code in your ASPX page.
 

 <table width=”50%” border=”1″ cellspacing=”0″ cellpadding=”0″>

<tr>
<td align=”center” class=”topmenulink”>
<a href=”<%=ResolveURL(“~/Default.aspx”) %> class=”topmenulink”>Home</a></td>
<td align=”center” class=”topmenulink”>
<a href=”http://blog.joggee.com/?page_id=11″ class=”topmenulink”>About Us</a></td>
<td align=”center” class=”topmenulink”>
<a href=”http://blog.joggee.com” class=”topmenulink”>Blog</a></td>
<td align=”center” class=”topmenulink”>
<a href=”http://www.joggee.com” class=”topmenulink”>Contact Us</a></td>
</tr>
</table>
create a CSS (Style sheet)

 copy below code in your CSS

.topmenulink

{
font-family: tahoma;
font-size: 13px;
font-weight: normal;
color:Blue;
text-decoration: none;
}
.topmenulink:hover
{
font-family: tahoma;
font-size: 13px;
font-weight: normal;
color: Blue;
text-decoration: none;
background-color: Khaki;
}

Note: you can change color scheme as per your site theme.

YOU CAN DOWNLOAD SAMPLE PROJECT HERE

I have used above ResolveURL Method,Just to give hint if you are using MASTER Page, then its recommendable to use ResolveURL to avoid any Warning or Problem.

If you want to how the hyperlink on the complete Button instead of TEXT then bring anchor link tag outside <TD> tag

<table width=”50%” border=”1″ cellspacing=”0″ cellpadding=”0″>

<tr>
<a href=”<%=ResolveURL(“~/Default.aspx”) %> class=”topmenulink”>Home

<td align=”center” class=”topmenulink”>

</td></a>

</tr>
</table>

Enjoy

Joggee

ASP.NET Tips ,

How to remove recent project history from Visual Studio Start Page

Time comes when recent project list over crowded and its hard to find particular project which doesnt display in the list.

Question arises how to delete the recent project history or the list from the main dashboard of the visual studio.

Follow these steps to remove unused project shown in the list.

1.        HKEY_CLASSES_ROOT

1.1.      Software

1.1.1.    Microsoft

1.1.1.1.    VisualStudio

1.1.1.1.1.    8.0  (Version which you are currently working)

1.1.1.1.1.1.    ProjectMRUList

Graphicial Steps :

step0-recentproject

step1-recentproject

 Finally check the hierarchy of the steps.

stepsregistry

 

Joggee

ASP.NET Tips ,

Google NoteBook

Once again Google shock me with new idea. You can access your favorites links anywhere in the world and they are just on one click , no more complication.

Clip information with a single click.
Quickly add clippings of web content (images, text and links) straight to your notebook by highlighting the content you want and clicking the “Clip” button in the mini Google Notebook

Google NoteBook

Take a tour
http://www.google.com/googlenotebook/tour1.html


Google

Recall or Recover Deleted Items from MailBox, Outlook

RECALL MESSAGES FROM MAILBOX

There are times when we send an e-mail and immediately realize that it contains an error or is missing important information. You wish you could go back in time and fix it, but it’s too late; the message has been sent. Fortunately, Outlook includes a recall feature that allows for a “do over” in the real world.

1. To recall a sent message, begin by locating the message in your sent items folder. 4. Open the e-mail message.
2. From the “Actions” dropdown list in the main menu, select “Recall This Message…”
3. Once selected, the Recall This Message dialog box will appear. It contains three options.

I. Delete unread copies of this message – This option will delete all sent copies of the message that have not been opened.
II. Delete unread copies and replace with a new message – In cases where only an error needs to be corrected, or slight information added, this option will first delete the original sent message, and then it will send a replacement message.
III. Tell me if recall succeeds or fails for each recipient – If checked, the user will receive e-mail confirmation if each individual message was successfully recalled or not.

Note: A read message cannot be recalled.

4. Press “OK” to initiate the recall.

Recall
 

RECOVER DELETED ITEMS FROM MAILBOX

How many times have we deleted an e-mail message and then wished we hadn’t or needed it later? Now it’s okay, because deleted items aren’t really gone forever; they can be recovered.

1. To recover deleted items, begin with the Deleted Items folder open.
2. With the folder open, select “Tools” from the main menu and then “Recover Deleted Items…”
3. A new dialog box will appear.
4. Use the tool buttons in the upper left to perform actions:

“Select All” – This button selects all of the deleted items in the list.

“Recover Selected Items” – To Recover Selected Items press this button.

The delete button will Purge Selected Items, meaning that they will be deleted permanently and will not be recoverable.

Recover Deleted

Hint : Use Ctrl+Left-Click to select multiple items that are not next to each other.


OutLook , ,

How To Use Medium Trust in ASP.NET 2.0

Its hard to explain why this is happening to every 2nd developer and he is complaining about medium trust level problem with hosting company.

Microsoft explain step by step but still this problem doenst resolve WHY?

These steps are enough for developer. Why they are still complaining.

SOLUTION:

DONT USE DATAREADER WHEN YOU ARE BINDING YOUR DATA WITH DATAGRID, GRIDVIEW OR ANY CONTROL.

USE DATASET

NO need to follow below steps
NO need to do settings locally for your Application for Medium Trust Level.
Once you will deployed at hosted server, it will automatically inherit as medium trust level.

Microsoft said :

Summary of Steps
To use medium trust in your ASP.NET applications:

Step 1. Configure medium trust.
Step 2. Lock the trust level.
Step 3. Optionally create a custom policy based on medium trust.
Step 1. Configure Medium Trust
To configure an application to run with medium trust, add the following element to either the application’s specific Web.config file in the application’s virtual root directory or to the machine-level Web.config file.

 Copy Code
<trust level=”Medium” originUrl=”" />
  Note   If present, the originUrl attribute can be used by some permissions, such as WebPermission, to restrict connectivity to a defined set of addresses.
To configure all Web applications on a server to run with medium trust, add this element to the machine-level Web.config file located in the following folder: %windir%\Microsoft.NET\Framework\{version}\CONFIG.

By default, Web applications are configured to run with full trust as shown in the following default configuration from the machine-level Web.config file.

 Copy Code
<location allowOverride=”true”>
 <system.web>
   <securityPolicy>
     <trustLevel name=”Full” policyFile=”internal” />
     <trustLevel name=”High” policyFile=”web_hightrust.config” />
     <trustLevel name=”Medium”
                 policyFile=”web_mediumtrust.config” />
     <trustLevel name=”Low”  policyFile=”web_lowtrust.config” />
     <trustLevel name=”Minimal”
                 policyFile=”web_minimaltrust.config” />�
   </securityPolicy>
   <trust level=”Full” originUrl=”" />
 </system.web>
</location>
  To review the full set of permissions available to medium trust applications, view the Web_mediumtrust.config file.

Step 2. Lock the Trust Level
Application service providers or anyone responsible for running multiple Web applications on the same server should apply the medium trust policy setting in the machine-level Web.config file and then lock the trust level for all Web applications.

To do this, set the allowOverride attribute to false in the machine-level Web.config file, as shown in the following code example.

 Copy Code
<location allowOverride=”false”>
 <system.web>
   <securityPolicy>
     <trustLevel name=”Full” policyFile=”internal” />
     <trustLevel name=”High” policyFile=”web_hightrust.config” />
     <trustLevel name=”Medium”
                 policyFile=”web_mediumtrust.config” />
     <trustLevel name=”Low”�
                 policyFile=”web_lowtrust.config” />
     <trustLevel name=”Minimal”
                 policyFile=”web_minimaltrust.config” />�
   </securityPolicy>
   <trust level=”Medium” originUrl=”" />
 </system.web>
</location>
  By setting allowOverride=”false”, an individual developer is unable to override the medium trust policy setting in their application’s Web.config file.

Yours comments are valuable for me

Joggee

Ajax, ASp.NET 2005, ASP.NET Tips, DataReader , ,

Google’s latest ideas

Google is always experimenting with new features aimed at improving the search experience.

I dont know what to say its a latest or copied from YAHOO. But I one good thing is, Google take this idea and make it more freindly and give statistic,Keyword suggestions,Keyboard shortcuts,Alternate views for search results. I would say GOOGLE ALWAYS A HEAD than any search engine.

for more information http://www.google.com/experimental/index.html

what you say ?

Google, Latest Hi-Tech Updates ,

SQL Server Incremental Years Value

I am unable to find something good and fast where without involving master database years value in the sql server. I found below query but I dont wanted to involve master database.

SELECT TOP 11000 –equates to more than 30 years of dates
        IDENTITY(INT,1,1) AS N
   INTO dbo.Tally
   FROM Master.dbo.SysColumns sc1,
        Master.dbo.SysColumns sc2

Here is something i made simple and fast.

DECLARE @TILL INT — define your end year value I am taking till 2008 + 2 = 2010

SET @TILL = YEAR(GETDATE())+2

DECLARE @FIRSTVALUE INT

SET @FIRSTVALUE=2001 – declaring first value

CREATE TABLE #TEMP
(
YEARID INT
)

WHILE  @FIRSTVALUE<=@TILL
BEGIN
INSERT INTO #TEMP SELECT @FIRSTVALUE
SET @FIRSTVALUE=@FIRSTVALUE+1
END

SELECT * FROM #TEMP

DROP TABLE #TEMP

RESULT:

Year

 kick it on DotNetKicks.com

SQL Server 2005, SQL Tips and Tricks ,