Thursday, July 28, 2016

Downloading Files in ASP.NET MVC


namespace My.Models
{
    public class DataClasses
    {
        public List<FileNames> GetFiles()
        {

            List<FileNames> lstFiles = new List<FileNames>();
            DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Files"));

            int i = 0;
            foreach (var item in dirInfo.GetFiles())
            {

                lstFiles.Add(new FileNames()
                {

                    FileId = i + 1,
                    FileName = item.Name,
                    FilePath = dirInfo.FullName + @"\" + item.Name
                });
                i = i + 1;
            }

            return lstFiles;
        }
    }
    public class FileNames
    {
        public int FileId { get; set; }
        public string FileName { get; set; }
        public string FilePath { get; set; }
    }
}

namespace My.Controllers
{
    public class ReportsController : Controller
    {
        DataClasses objData;

        public ReportsController()
        {
            objData = new DataClasses();
        }

        //
        // GET: /Reports/

        public ActionResult Index()
        {
            var files = objData.GetFiles();
            return View(files);
        }


        public FileResult Download(string id)
        {
            int fid = Convert.ToInt32(id);
            var files = objData.GetFiles();
            string filename = (from f in files
                               where f.FileId == fid
                               select f.FilePath).First();
            string contentType = "application/pdf";
            //Parameters to file are
            //1. The File Path on the File Server
            //2. The content type MIME type
            //3. The parameter for the file save by the browser
            return File(filename, contentType, "Report.pdf");
        }

    }
}

model IEnumerable<my.models.filenames>

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>

    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table>
        <tr>
            <th>
                FileId
            </th>
            <th>
                FileName
            </th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.FileId)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.FileName)
                </td>
                <td>
                    @Html.ActionLink("Download", "Download", new { id = item.FileId })

                </td>
            </tr>
        }

    </table>



The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

https://www.google.com/settings/security/lesssecureapps

Not Working https://ci4.googleusercontent.com/proxy/1G6grh1raakXp8PvPCJANFOKCJ4nFF3nuJoQB4sGWQ94Dm0Mqs2rQ8WgrOlEAqRPe54_zJ3s48ydA8foxj3S7ye7o3rlGCBYE1LCc0EGCFFRXRO2fiZxfgkjoOk=s0-d-e1-ft#https://IMAGEURL

This is something related to CACHING concept. suppose, you have recently deployed your php code on your server but you forgot to upload images. you tested once with your email logic. your system generated an HTML email. When this email will hit the gmail server GoogleImageProxy will try to fetch and store the images from your site to its own proxy server. while fetching the images, GoogleImageProxy found some 404 statuses against your missing images and 403 against some protected images. GoogleImagesProxy has stored these statuses into its own proxy server.
Now tried to open your email, you noticed some 404 statuses against your images. This is something understandable. You immediately realized that you forgot to upload some images, so you uploaded them to your server. and also you have fixed some permissions against protected images.
You are all done now. Now you try to run your php-email script once again. As a result you receive another email in your Gmail or Hotmail inbox. you had fixed all the issues with your images. Now the images must be displayed in your email content. but you are still unable to see the images.
Ah, possibly you forgot to clear your browser's cache. Clear your browser's cache and load the gmail or hotmail page once again. But the result will be still the same. Try to apply dozens of fixes/patches and try to run your php-email script a thousands time. But the result will be still the same. No improvement.
THE REAL PROBLEM
What the hell is going on? Let me explain it to you. Go to your access log and try to find requests from GoogleImageProxy. You'll be surprised to see that there will be only 2 or 3 three requests from GoogleImageProxy depending on the number of different images used in your email. GoogleImageProxy never tried to fetch images Even after you have fixed the issues with your images by uploading missing images and setting permissions for protected images. Why? Clearing your browser's cache has no impact. GoogleImageProxy will never fetch the fresh images even for your newer email because the images are now cached into GoogleImageProxy along with their last status code and not cached in your own browser's.
GoogleImageProxy has set its own expiry date for the images. I think one month. so now the fresh copy of images will be fetch after expiry date. I mean after one month. You can not force GoogleImageProxy to fetch the images. But its important for you to display images in your email. What can be the solution?
THE SOLUTION
Following is the only way to force GoogleImageProxy to fetch your images
  • Rename your images to something else with png, jpg or gif extensions only.
  • Don't use any kind of query string in your image url like ?t=34343
  • your image must include png, jpg or gif as an extension.
  • your image url must be mapped onto your image directly.
  • If you need to use some proxy url for your protected images then your response must include the proper header like Content-Type: image/jpeg
  • File extension and content-type header must match
  • Status-code must be 200 instead of 403, 500 etc
IMPORTANT NOTE
Try to repeat the whole process for every run of php-email script. because every time GoogleImageProxy will cache your images and you'll have to repeat the same process for every new try.

Wednesday, July 20, 2016

asp.net mvc @Html.CheckBoxFor dynamic

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

 namespace CorePartners_Site2.Models
 {
public class CareerForm
     {
    //....
    public List<CheckBoxes> EmploymentType { get; set; } 
      }
 }

 public class CheckBoxes
 {
     public string Text { get; set; }
     public bool Checked { get; set; }
 }
and added at my form
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_1" })
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_2" })
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_3" })
CheckBoxFor takes a bool, you're passing a List<CheckBoxes> to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor for the Text property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType list is null when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
    CareerForm model = new CareerForm();

    model.EmploymentType = new List<CheckBox>
    {
        new Checkbox { Text = "Fulltime" },
        new Checkbox { Text = "Partly" },
        new Checkbox { Text = "Contract" }
    };

    return View(model);
}

Set the Reference Path (C#)

To set a reference path

  1. In Solution Explorer, select the project.
  2. On the Project menu, click <Project Name> Properties.
  3. Click Reference Paths.
  4. In the Folder text box, specify the path of the folder that contains assemblies. To browse to the folder, click the ellipsis (…).
  5. Click Add Folder.

To overwrite a reference path

  1. In Solution Explorer, select the project.
  2. On the Project menu, click <Project Name> Properties.
  3. Click Reference Paths.
  4. In the Reference Path box, select the path to overwrite.
  5. In the Folder text box, specify the path of the folder that contains assemblies. To browse to the path, click the ellipsis (…).
  6. Click Update. The path selected in the Reference Path box is overwritten with the path specified in the Folder text box.

To remove a reference path

  1. In Solution Explorer, select the project.
  2. On the Project menu, click <Project Name> Properties.
  3. Click Reference Paths.
  4. In the Reference Path box, select the path to remove.
  5. Click Remove.

Monday, July 18, 2016

auto focus text box

$(".inputs").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.inputs');
      if ($next.length)
          $(this).next('.inputs').focus();
      else
          $(this).blur();
    }
});
<input class="inputs" type="text" maxlength="4" />
<input class="inputs" type="text" maxlength="4" />
<input class="inputs" type="text" maxlength="4" />
<input class="inputs" type="text" maxlength="4" />
<input class="inputs" type="text" maxlength="4" />
<input class="inputs" type="text" maxlength="4" />

The breakpoint will not currently be hit. No symbols have been loaded for this document.

Start debugging, as soon as you've arrived at a breakpoint or used Debug > Break All, use Debug > Windows > Modules. You'll see a list of all the assemblies that are loaded into the process. Locate the one you want to get debug info for. Right-click it and select Symbol Load Information. You'll get a dialog that lists all the directories where it looked for the .pdb file for the assembly. Verify that list against the actual .pdb location. Make sure it doesn't find an old one.
In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it.


Sunday, July 17, 2016

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll in C#.net application..What is a first chance exception?

"First chance exception messages most often do not mean there is a problem in the code." 
When an application is being debugged, the debugger gets notified whenever an exception is encountered  At this point, the application is suspended and the debugger decides how to handle the exception. The first pass through this mechanism is called a “first chance” exception. Depending on the debugger’s configuration, it will either resume the application and pass the exception on or it will leave the application suspended and enter debug mode. If the application handles the exception, it continues to run normally.

In Visual Studio, you may see a message in the output window that looks like this:

A first chance exception of type ‘System.ApplicationException’ occurred in myapp.exe

In Visual Studio 2005 Beta2, you will see this message anytime a first chance exception is encountered in your application’s code.  If you are using Visual Studio .NET 2003, this message is shown if you have configured the debugger to stop when the specific exception type is thrown.

If the application does not handle the exception, the debugger is re-notified. This is known as a “second chance” exception. The debugger again suspends the application and determines how to handle this exception. Typically, debuggers are configured to stop on second chance (unhandled) exceptions and debug mode is entered, allowing you to debug. 

Does a first chance exception mean there is a problem in my code?First chance exception messages most often do not mean there is a problem in the code. For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled.

For code without exception handling, the debugger will receive a second chance exception notification and will stop with a unhandled exception. 
ref: https://msdn.microsoft.com/en-us/library/dd997368(v=vs.110).aspx

Friday, July 15, 2016

What is the difference between bool and Boolean types in C#?

bool is an alias for System.Boolean just as int is an alias for System.Int32.
C# Type.NET Framework Type
bool System.Boolean
byte System.Byte
sbyte  System.SByte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
object System.Object
short System.Int16
ushort System.UInt16
string System.String

Folder Permissions on Windows Azure Web Sites

What you can do is change permissions on a local instance of the application and then deploy it with Web Deploy. When you do that, Web Deploy will use the SetAcl operation to change permissions.
SetACL – Automate Permissions and Manage ACLs...
----------------------------------------------------------------------------------------------------------------------

Folder permissions cannot be set/customized. This means whatever location your app writes to should be under your site root.