Tuesday, December 6, 2011

Search Algorithm


public class FuzzySearch
    {
        public static int LevenshteinDistance(string src, string dest)
        {
            int[,] d = new int[src.Length + 1, dest.Length + 1];
            int i, j, cost;
            char[] str1 = src.ToCharArray();
            char[] str2 = dest.ToCharArray();

            for (i = 0; i <= str1.Length; i++)
            {
                d[i, 0] = i;
            }
            for (j = 0; j <= str2.Length; j++)
            {
                d[0, j] = j;
            }
            for (i = 1; i <= str1.Length; i++)
            {
                for (j = 1; j <= str2.Length; j++)
                {

                    if (str1[i - 1] == str2[j - 1])
                        cost = 0;
                    else
                        cost = 1;

                    d[i, j] =
                        Math.Min(
                            d[i - 1, j] + 1,     // Deletion
                            Math.Min(
                                d[i, j - 1] + 1,    // Insertion
                                d[i - 1, j - 1] + cost));  // Substitution

                    if ((i > 1) && (j > 1) && (str1[i - 1] == str2[j - 2]) && (str1[i - 2] == str2[j - 1]))
                    {
                        d[i, j] = Math.Min(d[i, j], d[i - 2, j - 2] + cost);
                    }
                }
            }

            return d[str1.Length, str2.Length];
        }


        public static List<string> Search(string word, List<string> wordList, double fuzzyness)
        {
            
            //List<string> foundWords = new List<string>();

            //foreach (string s in wordList)
            //{
            //    // Calculate the Levenshtein-distance:
            //    int levenshteinDistance =
            //        LevenshteinDistance(word, s);

            //    // Length of the longer string:
            //    int length = Math.Max(word.Length, s.Length);

            //    // Calculate the score:
            //    double score = 1.0 - (double)levenshteinDistance / length;

            //    // Match?
            //    if (score > fuzzyness)
            //        foundWords.Add(s);
            //}

   // Tests have prove that the !LINQ-variant is about 3 times
   // faster!
   List<string> foundWords =(from s in wordList
     let levenshteinDistance = LevenshteinDistance(word, s)
     let length = Math.Max(s.Length, word.Length)
     let score = 1.0 - (double)levenshteinDistance / length
     where score > fuzzyness
     select s
    ).ToList();

            return foundWords;
        }

    }
 

Monday, September 19, 2011

Could not load file or assembly Microsoft.SqlServer.Management.Sdk.Sfc

This error comes when you are trying to access SQL 2005 stuff from Visual Studio 2008. Download the following stuff

Microsoft SQL Server System CLR Types
Microsoft SQL Server 2008 Management Objects
Microsoft SQL Server 2008 Native Client

Monday, September 12, 2011

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

This error came because, in my master page there was a java script function like below

document.getElementById("<%=lblShoppingCart.ClientID %>").style.color = "#6CA2DE"

I used <%# instead of using <%=. It's work fine.

Here some valuable links related to this topic.

http://leedumond.com/blog/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks/

http://www.west-wind.com/weblog/posts/2006/May/27/The-Controls-collection-cannot-be-modified-because-the-control-contains-code-blocks-ie-

Monday, August 15, 2011

Pass TextBox ID to javascript function


TextBox2.Attributes.Add("onkeyup", "Fill('" + TextBox1.ClientID.ToString() + "','" + TextBox2.ClientID.ToString() + "','" + TextBox3.ClientID.ToString() + "')")
 

<script type="text/javascript">
    function Fill(x, y, z) 
    {
            val1 = parseFloat(document.getElementById(x).value);
            val2 = parseFloat(document.getElementById(y).value);   
//code here         
    }
    </script>
 

Thursday, August 4, 2011

Light Box withing GridView Template Feild.

Hi,
In my web application there was a function to send Messages. I used jquery Light Box to pop up the message form. But when i hit GridView button for each row, it display only firstly created light box every time. Take a lookat code so u can understand.

<ItemTemplate>
<asp:Label ID="mn" runat="server" Text='<%#Eval("MobileToNum") %>' CssClass="dn"></asp:Label>
<a href="#" runat="server" id="cli" data-reveal-id="m" class="phone-number-click my-anc"><img src="../images/SMS.jpg" /></a>

<asp:Label ID="smsresultlbl" runat="server" Font-Size="XX-Small" Font-Bold="true"></asp:Label>
   <div id="m" class="reveal-modal mydiv">
   <table class="noborder">
<tr>
<td>Mobile No:</td><td><asp:TextBox ID="mobileNoTxt" runat="server" CssClass="textarea-medium"></asp:TextBox><%-- <asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter Mobile Number" ControlToValidate="mobileNoTxt" ValidationGroup="sms" Display="Dynamic"></asp:RequiredFieldValidator>--%></td>
</tr>
<tr><td></td><td><asp:Button ID="confirmbtn" runat="server" onclick="confirmbtn_Click" Text="Send"></asp:Button></td></tr>
</table>
   <a class="close-reveal-modal">×</a>
  </div>  
                </ItemTemplate>
 
The reason was data-reveal-id and pop up div id not in same name. I used javascript code for match these.

<script type="text/javascript">

     $(".phone-number-click").click(function() {
         //console.log($("span", $(this).parent()).html());
         $("#" + $(this).attr("mobnum")).val($("span", $(this).parent()).html());
     });

     $(".my-anc").each(function(e) {
         var id = "id-" + e;
         $(this).attr("data-reveal-id", id);
         $(".mydiv:eq(" + e + ")").attr("id", id);
     });

   </script>
 

Wednesday, August 3, 2011

CS0123: No overload for 'smsbtn_Click' matches delegate 'System.EventHandler'

There was a ImageButton in my aspx page.

protected void smsbtn_Click(object sender, ImageClickEventArgs e)
{
}

I changed the code. I used LinkButton instead of ImageButton.
protected void smsbtn_Click(object sender, ImageClickEventArgs e)
{
}

But i fogot to change the ImageClickEventArgs to EventArgs. That was the reason for getting this error. :)

Tuesday, August 2, 2011

A potentially dangerous Request.QueryString value was detected from the client (M=""'>").

I saw this strange error when i request a page. The reason was i have registered a usercontrol which was not in project.

<%@ Register src="../../UserControl/SearchCurrency.ascx" tagname="SearchCurrency" tagprefix="uc1" %>

Simply remove it, now works fine :)

Sunday, July 31, 2011

Fire validations even causesvalidation property already set to false.

In this case there are Required Feild Validator, Comapire Validator and one button and Link button. I set a validation group to Req.. validator, com.. validator and button. And set causesvalidation property false in link button. but when i click the link button, compaire validator fires. I can't understand this behaviour, anyone know this please let me know.

However i resolved it in this way.

http://forums.asp.net/t/1702558.aspx/1?Validation

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

This will occur due to Responce.Redirect() method.

Why we use false to the second argument in above method?
The second argument to Redirect is the boolean literal false, which indicates we do not want an exception to be thrown to terminate the page. If you do not pass false, an exception will occur and this can slow down websites and complicate error handling.

:)

Wednesday, June 22, 2011

RequireField Validator in gridview template feild(fire all validators when i click button in each row)


 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
   TextBox t1= (TextBox)e.Row.FindControl("t1");
                CompareValidator cv = (CompareValidator)e.Row.FindControl("cv");
                Button btn = (Button)e.Row.FindControl("btn");

                if (t1 != null)
                {
                    t1.ValidationGroup = e.Row.RowIndex.ToString();
                    cv.ValidationGroup = e.Row.RowIndex.ToString();
                    btn.ValidationGroup = e.Row.RowIndex.ToString();
}
}
}
 

Name start with D came first, although i used ascending order

There was a space character in the name feild in the database. That was the reason for D came first :)

Thursday, May 12, 2011

Configuration Error - Unrecognized attribute 'type'.

I got this error message when i host a web application in server. Go to properties of the web site and change the asp.net version.

Monday, May 9, 2011

Timeout message before session expire

Here a javascript solution for detecting session expire.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
 
<style type="text/css">
        .message
        {
            border: 1px solid #CCCCCC;
            position: absolute;
            width: 400px;
            border: 1px solid #c93;
            background: #ffc;
            padding: 5px;
            left: 0px;
            top: -170px;
        }
    </style>    
<script language="javascript" type="text/javascript">
        function ShowAlert() {
            //get the height and width of the screen
            var windowWidth = document.documentElement.clientWidth;
            var windowHeight = document.documentElement.clientHeight;

            //get the height and width of the message box
            var popupHeight = $("#TimeoutMessage").height();
            var popupWidth = $("#TimeoutMessage").width();

            //show the message box
            $("#TimeoutMessage").animate({
                "top": windowHeight / 2 - popupHeight / 2,
                "left": windowWidth / 2 - popupWidth / 2
            }, 1000);

            //close the message box when cross red image is clicked
            $("#close_message").click(function() {
                $("#TimeoutMessage").fadeOut("slow");
            });

            setTimeout('Redirect()', 300000); //15 minutes in milliseconds
        }

        function Redirect() {
            window.location = "../../logout.aspx";
        }

    </script>
  
</head>
<body>
    <form id="form1" runat="server">
     <div id="TimeoutMessage" class="message">

        <p>
            You will be logged out due to inactivity in 5 minutes.<br /><br />
            Please refresh this page, or click on an action to refresh your session.</p>
    </div>
 
    </form>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            setTimeout('ShowAlert()', <%=((Session.Timeout * 60) * 1000) - 300000 %>);
        });
    </script>
</body>
</html>

Thursday, April 28, 2011

Microsoft Community Contributor Award - 2011

I’m very pleased and honored to share this with all of you that my community contributions have been recognized by Microsoft. I have received the Microsoft Community Contributor Award for year 2011. This was a big and very special surprise to me…

This is great motivation to continue contributing and become even bigger influencer in online and offline community, locally and worldwide!

Microsoft, Thank you.



Wednesday, April 27, 2011

Tool Tip for GridView Header


 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
    
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    cell.Attributes.Add("title",cell.Text);
                }

            }
        }
 

Wednesday, March 9, 2011

Sys.WebForms.PageRequestManagerTimeoutException: The server request timed out.

I saw this problem when i send a mail.The mail button withing a update panel and used a UpdatePanelAnimationExtender. This occured because mail operation relatively long 30 sec or more. What i did, there is a property called AsyncPostBackTimeOut in ScriptManager and set its timeout to 500. Default value is 90.

<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="500">
</asp:ScriptManager>
 

Monday, March 7, 2011

How to check a file if is in use


protected virtual bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

 

Firefox doesn't know how to open this address, because the protocol (d) isn't associated with any program.

I saw this error message when i was trying to open a PDF document which in web folder, to a new window. This will take place when you are trying to go to a link to a file on your local disk. In my application i gave the http path like this http://localhost:4150/Admin/doc/invoice/12.pdf. Its working now.
here another reference link
http://forums.mozillazine.org/viewtopic.php?f=38&t=617197

Open new window when button click within updatepanel


protected void printbtn_Click(object sender, ImageClickEventArgs e)
{
 StringBuilder sb = new StringBuilder();
 sb.Append("<script>");
 sb.Append("window.open('"+path+"', '', '');");
 sb.Append("</script>")
 ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "test", sb.ToString(), false);
}
 

Monday, February 28, 2011

Cannot remove an entity that has not been attached.

You will not be able to use attach on a context other then the original context the item was received on unless the entity has been serialized.


public bool deleteslabrecord(TSummeryReport deletetsr)
{
EntityManager.TSummeryReports.DeleteOnSubmit(EntityManager.TSummeryReports.Single(theItem=>theItem==deletetsr));
return SaveChanges();
} 

Wednesday, February 23, 2011

Merge dynamically create PDF at runtime

I played with this more than 3 days. Finally got the solution.


protected void Button1_Click(object sender, EventArgs e)
{
 Guid uniqueid = Guid.NewGuid();
 string uniqueidStr = uniqueid.ToString();
 int cnt = 0;
 string file = Server.MapPath("~/Admin/doc/invoice/Invoice.pdf");
 string masterPDfFile = Server.MapPath("~/Admin/doc/invoice/result.pdf");
 PdfCopyFields myPdfCopy = new PdfCopyFields(new FileStream(masterPDfFile, FileMode.Create));

while (cnt < 3)
{
PdfReader tmpReader = new PdfReader(file);
string tmpFilePath = Server.MapPath("~/Admin/doc/invoice/" +uniqueidStr+ cnt.ToString() + ".pdf");
FileStream tmppoutputFile = new FileStream(tmpFilePath, FileMode.Create);
PdfStamper tmpoutStamper = new PdfStamper(tmpReader, tmppoutputFile);
AcroFields testform = tmpoutStamper.AcroFields;
testform.SetField("T1","Lasantha");
tmpoutStamper.Close();
PdfReader nwpgReader = new PdfReader(tmpFilePath);
PdfTemplate page = tmpoutStamper.GetImportedPage(nwpgReader, 1);
myPdfCopy.AddDocument(nwpgReader);
cnt += 1;
}

myPdfCopy.Close();
cnt = 0;

while (cnt < 3)
{
string tmpFilePath = Server.MapPath("~/Admin/doc/invoice/" + uniqueidStr+cnt.ToString() + ".pdf");
System.IO.File.Delete(tmpFilePath);
cnt += 1;
}

 PdfReader reader = new PdfReader(masterPDfFile);
string resultpath = Server.MapPath("~/Admin/doc/CustomerReports/result.pdf");
 FileStream resultstr=new FileStream(resultpath,FileMode.Create);
PdfStamper result = new PdfStamper(reader, resultstr);
result.Close();
reader.Close();
System.IO.File.Delete(masterPDfFile);
} 

Get DataTable From Linq query

Here code example



public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{

if (query == null)
{
 throw new ArgumentNullException("query");
}

 IDbCommand cmd = ctx.GetCommand(query as IQueryable);
 SqlDataAdapter adapter = new SqlDataAdapter();
 adapter.SelectCommand = (SqlCommand)cmd;
 DataTable dt = new DataTable("sd");

try
{
 cmd.Connection.Open();
 adapter.FillSchema(dt, SchemaType.Source);
 adapter.Fill(dt);
}

finally
{
 cmd.Connection.Close();
}

 return dt; 

} 

Split DataTable in to several DataTables

I achieved this requirement from this code snippet.


public DataTable[] getDataTables(DataTable tableToClone, int seperateVal, int val)
{
 DataTable[] tables = new DataTable[val];
 int count = 0;
 int index = 0;

 DataTable copyTable = null;
 foreach (DataRow row in tableToClone.Rows)
 {
 if ((count++ % seperateVal) == 0)
 {
 copyTable = new DataTable();
 copyTable = tableToClone.Clone();

 tables[index] = copyTable;
 index++;
 }

 copyTable.ImportRow(row);
 }
 return tables;
 } 

Monday, February 14, 2011

Invalid length for a Base-64 char array

This error gave me when i try to encrypt the query string. I solved this issue by http://forums.asp.net/t/1222829.aspx.
It worked fine. But now for some query string values it gives same error. The reason is there was a space character in the query string value. Then i replaced space character with "+". Its working now.

64-bit encoding does not work well with spaces in the string for some odd reason.

Sunday, February 6, 2011

UpdatePanelAnimationExtender FadeIn FadeOut problem-page styles issue

not resolved yet

UpdatePanelAnimationExtender FadeIn FadeOut problem-page resize issue

Basically the problem is after animation worked page is not resize properly.what i did is put div tag name it as rightContainer and place the code whithing it what i need to update.Then Set the  AnimationTarget="rightContainer".

Here the Code.

<FadeIn AnimationTarget="rightContainer" minimumOpacity=".6" />
<
FadeOut AnimationTarget="rightContainer" minimumOpacity=".6" />

Wednesday, February 2, 2011

Get visible false asp Lable value from java script


<style>
.lbl{
display:none;
}
</style>

<asp:Lable ID="label1" runat="server" CssClass="lbl"/>
var val=document.getElementById("<%=label1.ClientID%>").innerHTML;
 

Monday, January 24, 2011

Row Count is always equal to page size when allow paging set to true.

This can be resolved by adding followings before call row count


Gridview1.AllowPaging=false;
GridView1.Datasource=yourdatasource;
Gridview1.DataBind();
//row count
GridView1.AllowPaging=true;
 

Friday, January 21, 2011

Formating issues in Html to Pdf using iTextSharp

When generating pdf documents Html to pdf using iTextSharp i have to face formatting issues. Here the solution.Use PDF Template

 You can use Adobe Acrobat professional to create a PDF form template.Put a TextFeild and give a name for that as text1.Then set the formattings.

In the c# code follow these steps

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using System.Xml.Linq;
/* reference to the itextsharp */
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
namespace ItextSharpTut
{
  public class UtilityMethod
  {
    public void generatePDF()
    {
      try
      {
        string pdfTemplate = System.Web.HttpContext.Current.Server.MapPath("~/doc/new.pdf");
        PdfReader pdfReader = null;
        // Create the form filler
        FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
        string path = System.Web.HttpContext.Current.Server.MapPath("~/doc/template.pdf");
        pdfReader = new PdfReader(path);
        PdfStamper pdfStamper = null;
        pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
        // Get the form fields
        AcroFields testForm = pdfStamper.AcroFields;
        testForm.SetField("text1", "Lasantha");
        PdfContentByte overContent = pdfStamper.GetOverContent(1);
        pdfStamper.FormFlattening = true;
        pdfStamper.Close();
        pdfReader.Close();
      }

 catch (Exception ex)
 {
   throw ex;
 }

}
}
} 

Enjoy it.

Learn more how amazing programing with itextsharp


Wednesday, January 19, 2011

Monday, January 17, 2011

Bind Both string and int value to a label


<asp:Label ID="lbltimezoneedit" runat="server" Text='<%#Eval("tzoperation")+Eval("tzhour").ToString()+"."+Eval("tzmin").ToString()%>' Visible="true">
</asp:Label>
 

TinyMCE Insert/Edit link not editable

 To fix this add  e.stopImmediatePropagation()  as below. $(document).on('focusin', function (e) {             if ($(e.target).close...