Wednesday, April 10, 2013

Could not load file or assembly App Web Version=0.0.0.0

If you are getting this error for a WCF service hosted within an ASP.Net application.


Could not load file or assembly 'App_Web_picmgxwx, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'App_Web_picmgxwx, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Source Error:


An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'App_Web_picmgxwx, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].


You can fix this issue by turning off the batch compilation. Add following tag in Web.Config under ,
 <compilation batch="false">

Export Datagrid Gridview to Excel CSV format on the fly in asp.net

First need to bind grid control( Gridview, Datagrid, Datalist, repeater).  I used the current UTC datetime as name if downloaded file. when Download PopUp will open user can save that file anywhere on his local drive. In this example, you can also see how to show "DownLoad PopUp" in asp.net on the Fly. No need to place control in aspx page. Just create the data control at runtime and bind with data.
 private  void ExportToExcel()
{
 SqlDataAdapter adpgetData = new SqlDataAdapter("Your DB Query", ConfigClass.DbConn);
                    DataSet dsGetData = new DataSet();
                    adpgetData.Fill(dsGetData);
                    if (dsGetData.Tables[0].Rows.Count > 0)
                    {
                        DataGrid dg = new DataGrid();
                        dg.DataSource = dsGetData.Tables[0];
                        dg.HeaderStyle.BackColor =System.Drawing.Color.FromName("#c0c0c0");
                        dg.HeaderStyle.ForeColor = System.Drawing.Color.FromName("#000000");
                        dg.HeaderStyle.Font.Bold = true;// = Color.FromName("#000000");
                        dg.DataBind();
                      string reportName = Convert.ToString(DateTime.UtcNow).Replace("/", "_").Replace(" ", "_").Replace(":", "_");
        ExportGridView(dg, reportName);
                   }
}

 private  void ExportGridView(DataGrid dg, string reportName)
    {
        Response.AddHeader("Content-Disposition", "attachment;filename=" + reportName + ".xls");
        Response.AddHeader("Status", "200 OK");
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(Encoding.Unicode.GetPreamble());
        Response.ContentType = "application/vnd.ms-excel";
        //dg.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        dg.RenderControl(hw);
        Response.Write(RenderGridView(dg));
        Response.End();
    }
    public  string RenderGridView(DataGrid dg)
    {
        string returnvalue = string.Empty;
        try
        {
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(stringWrite);
             VerifyRenderingInServerForm(dg);
            dg.RenderControl(writer);
            returnvalue = writer.InnerWriter.ToString();
        }
        catch (Exception ex)
        {

        }
        return returnvalue;
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        return;
    }

Export to excel Download popup window not working in asp.net

f you are using  asp:ScriptManager  and UpdatePanel to use ajax and Download Popup is not showing you then you have to use Trigger as you can see in below code.
 <asp:ScriptManager ID="scmSearch" runat="server">
        </asp:ScriptManager>

        <asp:UpdatePanel ID="up" runat="server">
         <Triggers>
            <asp:PostBackTrigger ControlID="btnExport" />
        </Triggers>

            <ContentTemplate>


private  void ExportGridView(DataGrid dg, string reportName)
    {

        Response.AddHeader("Content-Disposition", "attachment;filename=" + reportName + ".xls");
        Response.AddHeader("Status", "200 OK");
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(Encoding.Unicode.GetPreamble());
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        dg.RenderControl(hw);
        Response.Write(RenderGridView(dg));
        Response.End();
    }
    public  string RenderGridView(DataGrid dg)
    {
        string returnvalue = string.Empty;
        try
        {
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(stringWrite);
             dg.RenderControl(writer);
            returnvalue = writer.InnerWriter.ToString();
        }
        catch (Exception ex)
        {

        }
        return returnvalue;
    }

Displaying the Files from a Directory using a DataGrid ASP.Net

In the code snippet, we show you how you can get the files from a folder and show in a grid

Call this Namespace alobg with default namespaces in .cs page.
using System.IO;
 private void GetFilesFromFolder()
    {

        String FilePath = Server.MapPath("../uploads/photos/");
        //Create the DataTable, with columns in which to add the file list
        DataTable dt = new DataTable();
        dt.Columns.Add("FileName", typeof(System.String));
        dt.Columns.Add("FileSize", typeof(System.String));
        DataRow dr = null;
        DirectoryInfo dir = new DirectoryInfo(FilePath);
    
        // adding file to a datatable one by one in new row, along with the  filesize to each file
        foreach (FileInfo fi in dir.GetFiles())
        {
            dr = dt.NewRow();
            dr[0] = fi.Name.ToString();
            dr[1] = fi.Length.ToString("N0");  //'N0'formats the number with commas
            dt.Rows.Add(dr);
        }
        datagridFiles.DataSource = dt;
        datagridFiles.DataBind();
     
    }

In ShowFiles.aspx page, add the datagrid, gridview etc
<form id="form1" Runat="server">
    <div style="text-align:center">
        asp:DataGrid ID="datagridFiles" runat="server"></asp:DataGrid >
   </div>
</form>

Remove Html Tags from A String in ASP.net

This code snippet will strip a string of all Html tags and replace a tag with a blank space. We used the regular expression for this. Use RegularExpressions namespace
using System.Text.RegularExpressions;

  public string RemoveHTML(string in_HTML)
        {
            return Regex.Replace(in_HTML, "<(.|\n)*?>", "");
        }

 

Read-Write or Add-Update HTML or Text files in ASP.Net

Sometimes we need to edit or create new HTML files for Email Templates or to make new HTML page. Using this code you can do add/edit /Append in HTML files in asp.net C#. Use Namespace
using System.IO;
Read Existing HTML File
        FileStream objFileHandler = null;

        StreamReader objWriter;

        String strMailMessageBody = String.Empty;

        String strFileName = String.Empty;

        strFileName = Server.MapPath("HTMLTemplates/"+ EnterYourFileName);

        objFileHandler = new FileStream(strFileName, FileMode.Open, FileAccess.Read);

        objWriter = new StreamReader(objFileHandler);

        strMailMessageBody = objWriter.ReadToEnd();
        txtDescription.Text = strMailMessageBody;

        objWriter.Close();

        objFileHandler.Close();

Edit HTML Files:
using (FileStream fs = new FileStream(Server.MapPath("HTMLTemplates/" + YouFileName), FileMode.Create, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                string str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"http://infoa2z.com/Includes/css/style.css\" /><title>http://infoa2z.com/</title></head><body>";

                str = str + txtDescription.Text +"</body></html>";

                sw.Write(str);

                sw.Close();
            }
         
        }

There are different options to handle files: Create, Create New,  Append, Open, OpenOrCreate etc. that you can use  in FileMode

using (FileStream fs = new FileStream(Server.MapPath("HTMLTemplates/" + YouFileName), FileMode.Create, FileAccess.Write))

Format Phone Numbers in US (United States Phone Number format) in asp.net

You can give any style to phone number or any other texual content. Use String.Format.
You can also apply check on phone number if already dash is used then no repeat of dash in phone number
 string PhoneNumber=  Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Phone"));

 if (!phoneNumber.Contains("-"))
{
lblPhoneNumber.Text  = string.Format("{0}-{1}-{2}", PhoneNumber.Substring(0, 3), PhoneNumber.Substring(3, 3), PhoneNumber.Substring(6));
}
else
lblPhoneNumber.Text = PhoneNumber;

Then Phone number will display like 123-456-7890
To make format like (123) 456-7890 use
You can also use this format in   "({0}) {1}-{2}"