Tech blog

Solving problems

About
Contact

Archive for the ‘ASP.NET’ Category

PDF files not Publish in ASP.NET MVC when deploying

leave a comment

We faced a problem when we added some PDF files into our media library of ASP.NET MVC website and noticed that these files are not Published automatically.
So you need in Visual Studio to click on each PDF file and under Properties (F4) just choose

  • Build Action=Content
  • Copy to Output Directory=Copy Always
VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)

Written by Avivo

June 1st, 2010 at 1:28 pm

Comparison: ASP .NET WebForms vs MVC

leave a comment

Comparison: ASP .NET WebForms vs MVC

WebForms MVC
  • Requires .NET 2.0
  • Event model – button click triggers an event in code-behind
  • ViewState – server-based forms for easier management
  • Existing third party controls
  • Requires .NET 3.5 and MVC library
  • Requires IIS 6.0 or later for URL rewritting – btw, max IIS version for WinXP is 5.1
  • Backward compatible – developer can include WebForms pages into MVC website and vice-versa
  • Dividing an application into the model, the view, and the controller – data, design and code are separated
  • For large teams of developers and designers (parallel work)
  • No ViewState means smaller output and cleaner html
  • Portable among other languages (like php) – similar file hierarchy, object names, different syntax
  • 30-50% faster than Web Forms, 100-800 requests per second
  • Native URL rewritting
  • Skinnable, suitable for websites that are viewed in computer browsers and mobile browsers
  • Unit testing
  • VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: +3 (from 3 votes)

    Written by Avivo

    January 30th, 2010 at 11:41 pm

    Firefox very (extremely) slow on Vista Cassini web server (local webserver in VS)

    leave a comment

    It turns out that the slowness is caused by an IPv6 issue with DNS and can easily be resolved by turning IPv6 support off in Firefox while doing localhost testing.

    To make the change do this:

    1. type about:config in the address bar
    2. locate the network.dns.disableIPv6 setting
    3. double-click on it to set it to true.

    This does the trick for the Firefox localhost issue on Vista and everything is running fast again.

    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    December 2nd, 2009 at 5:07 pm

    Hosting ASP.NET MVC on IIS7 and “Could Not Load Type” error

    one comment

    1. If you want to host ASP.NET MVC on IIS7 don’t forget to copy also MVC DLLs to bin directory when publishing.
      • If you have ASP.NET 3.5 SP1 installed on server copy only System.Web.Mvc
      • If you don’t have ASP.NET 3.5 SP1 installed on server copy
        System.Web.Mvc
        System.Web.Routing
        System.Web.Abstractions
    2. You need to copy also web.config that is under directory where your Views are – it is not included in your project by default so it will not be published. Copy this manually or include this web.config in your project and then Publish.
    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    September 14th, 2009 at 4:15 pm

    SelectedValue not working in ASP.NET MVC

    leave a comment

    <%= Html.DropDownList(“Salutation”, (IEnumerable<SelectListItem>)ViewData["Salutation"])%>

    We just did not use properties in our viewdata that had the same name as any of the dropdowns , so above example is wrong and it will not select value properly. Instead of this use something like this:

    <%= Html.DropDownList(“Salutation”, (IEnumerable<SelectListItem>)ViewData["SalutationList"])%>

    And in controller:

    ViewData["SalutationList"] = new SelectList(userModel.Salutations, “Value”, “Title”, user.Salutation);

    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    August 17th, 2009 at 3:27 pm

    Check if image (url) exists in ASP.NET

    leave a comment

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");
    request.Method = "HEAD";
    
    bool exists;
    try
    {
        request.GetResponse();
        exists = true;
    }
    catch
    {
       exists = false;
    }
    
    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    August 14th, 2009 at 11:07 am

    Silverlight 2.0 – Resolved issue: InitializeError #2103 – Invalid or malformed application

    one comment

    Intro

    I am working on a project that includes ASP .NET MVC web site and Silverlight 2.0 application. Initialy a Visual Studio solution with both project types has been created. At the beginning, sample Silverlight application worked fine, then most of the time development was going on MVC side. Now, when development should continue on Silverlight side browser throws an error:

    This blog post explains how the issue has been solved. Resolving issue step by step…

    1.Check namespaces

    App.xaml should have x:Class attributes formatted as “Namespace.ClassName” (e.g. “StudioBikini.ClientSide.App”).

    Same namespace and class name should also appear in App.xaml.cs. Note that namespace and class name are separated in C# file while glued together in XAML.

    2. Change project properties

    When you change a namespace for App in either C# or XAML the Startup object value in properties still holds the previous value.
    Right click on a project in Visual Studio and select Properties.
    Click on the Startup object combobox should open a list of available startup object and select the Namespace.ClassName.

    Also make sure that Generate Silverlight manifest file checkbox is checked and an existing manifest file is selected.

    3. Check manifest file

    Some text editors add 3 garbage bytes at the beginning of a file which represent encoding. Those three bytes are invisible by some editors and may cause xml parsing exception.
    Remove Properties\AppManifest.xml file and create it again.

    4. Other possibilities:

    • Try to set assembly name and default namespace in the project properties to the same value. Namespace in properties should be the same as namespace in App.
    • Try with relative or absolute uri or false uri – if .xap file cannot be found Silverlight plug-in returns error #2104, that is different than #2103. So #2103 indicates that file has been found.
    • Clear browser’s cache (downloaded data) and reload the page with Silverlight.
    • Turn off virus scanner, as some scanners block loading unknown or hidden extensions (I had problems with .xaml.js for Silverlight 1.0).
    • If you are using object tag in html to load .xap file, try to change height in pixels (in case it works on IE7 but not in Firefox 3.0).
    • There may be an old .xap build. Try to rebuild VS solution or delete bin and obj folders from all projects – those folders are generated again on next build.
    • AppManifest.xml file can be read-only, usually happens when under a source control system (e.g. sourcesafe, svn), so check it out first.
    • Finally, delete AppManifest.xml, create new one and paste next lines into the file:

    <Deployment xmlns=”http://schemas.microsoft.com/client/2007/deployment”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
    <Deployment.Parts>
    </Deployment.Parts>
    </Deployment>

    Solution

    It appears that file was under Visual SourceSafe, problem with locked file. Solution has been found progressively, step by step as described above.

    Another time, another project, same error. Problem with an included assembly reference – a Silverlight Class Library project with web service reference and Silverlight Application project with reference System.ServiceModel… Resolved by commeting code that uses System.ServiceModel (code when calling web service generated classes). Alternative is to use  release settings instead of debug.

    Any other suggestions?

    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    June 29th, 2009 at 9:59 am

    Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 0

    3 comments

    If you get an error:

    Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 0

    just add this code in HEAD section of your page/masterpage:

    <script language="javascript" type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
    function endRequest(sender, args)
    {
    	// Check to see if there's an error on this request.
    	if (args.get_error() != undefined)
    	{
    	  //$get('Error').style.visibility = "visible";
    	  // Let the framework know that the error is handled,
    	  // so it doesn't throw the JavaScript alert.
    	  args.set_errorHandled(true);
    	}
    }
    </script>
    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    June 16th, 2009 at 7:48 pm

    Storing and retrieving images in MS SQL Server

    leave a comment

    This is a tutorial from very nice Blog:

    Hi, I saw many developers are asking this questions in different forums. Recently I saw this question on MSDN forum and I thought let me write a blog on this. I know many of us found this too easy however for new bees its bit hard.

    In this article, I had used SQL Server 2005 as back end and C# as front end. SQL Server has “Image” data type to store the image. In Oracle and some other database you can use a data type which is used to store binary value (may be BLOB). I have created a simple aspx which has File upload control and a button. When user selects a file to upload, I am checking it for valid image type and converting it to array of Bytes. Then I will store that byte array into database. Below is the code,

    if (objFileUpload.PostedFile !=null)
    {
    if (objFileUpload.PostedFile.ContentLength > 0)
    {
    HttpPostedFile objHttpPostedFile = objFileUpload.PostedFile;
    if (CheckValidFileType(objHttpPostedFile.FileName))
    {
    int intContentlength = objHttpPostedFile.ContentLength;
    byte[] bytImage =new Byte[intContentlength];
    objHttpPostedFile.InputStream.Read(bytImage, 0, intContentlength);
    }
    }
    }

    Read Uploaded file (here Image) in Byte Array

    Pass this Byte array to you DAL and use it for storing image in database. I am using Enterprise Library as DAL so my code will look like,

    Database db =DatabaseFactory.CreateDatabase();
    string sqlCommand ="StoredProcedureName";
    DbCommand dbCommandWrapper = db.GetStoredProcCommand(sqlCommand);
    db.AddInParameter(dbCommandWrapper,"@Image",DbType.Binary,bytImage );
    try
    {
    db.ExecuteNonQuery(dbCommandWrapper);
    }
    catch {throw; }

    Insert Image in to database

    This is how you can store the Image in database. Retrieving the image is the same process. Write a SP which will return your image. Store this value in a Byte Array. Once you get the image in Byte array, you just have to write it on form as shown below,

    Byte[] bytImage =Byte array retrieved from database.
    if (bytImage !=null)
    {
    Response.ContentType = "image/jpeg";
    Response.Expires = 0;
    Response.Buffer =true;
    Response.Clear();
    Response.BinaryWrite(bytImage);
    Response.End();
    }

    Code to display Byte array as Image on form.

    To use this at multiple places in your application, you create a page to which you can pass ID of Image and it will retrieve image from database and create image. To do this copy paste above code in aspx.cs file. Now on every page you require to show this image take on that page and set its ImageURL property to the path of newly created user control. See the code below,

    Image control on any aspx page (Lets say Sample.aspx).

    string strURL ="~/ViewImage.aspx?ID= 1";
    ViewImage.ImageUrl = strURL;

    set Image URL for image control on code behind (Sample.aspx.cs)

    You can see the image will be displayed in your page where you had put Image tag.
    Happy Programing.

    VN:F [1.9.3_1094]
    Rating: 5.0/5 (1 vote cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    April 16th, 2009 at 9:22 am

    Showing PNG images in Internet Explorer 6 (IE6)

    leave a comment

    In HEAD section put this:

    <script language="JavaScript">
    function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
    {
         var arVersion = navigator.appVersion.split("MSIE")
         var version = parseFloat(arVersion[1])
         if ((version >= 5.5) && (document.body.filters))
         {
                for(var i=0; i<document.images.length; i++)
                {
                     var img = document.images[i]
                     var imgName = img.src.toUpperCase()
                     if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
                     {
                            var imgID = (img.id) ? "id='" + img.id + "' " : ""
                            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                            var imgStyle = "display:inline-block;" + img.style.cssText
                            if (img.align == "left") imgStyle = "float:left;" + imgStyle
                            if (img.align == "right") imgStyle = "float:right;" + imgStyle
                            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                            var strNewHTML = "<span " + imgID + imgClass + imgTitle
                            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                            img.outerHTML = strNewHTML
                            i = i-1
                     }
                }
         }  
    }
    </script>

    And in onload event put this

    <body onload="correctPNG();">
    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

    Written by Avivo

    April 1st, 2009 at 10:38 am