Tuesday, December 24, 2013

The type or namespace name 'AjaxControlToolkit' could not be found in the global namespace

The type or namespace name 'AjaxControlToolkit' could not be found in the global namespace (are you missing an assembly reference?)

Most of the times when we are using Ajax Control Toolkit  we are getting an error when compiling our web application I've added the toolkit countless times before but for some reason, I keep getting this. How can I resolve this issue so I can use the toolkit? It is recommended to add reference to the AjaxControlToolkit.dll(right click on the bin directory, and choose "Add Reference"), and then AjaxControlToolkit.dll will be added to the bin directory automatically. But even after adding the reference to AjaxControlToolkit the project was complaining that "The type or namespace name 'AjaxControlToolkit' could not be found (are you missing a using directive or an assembly reference?)". How to solve this. The answer is that the project is still using Microsoft ASP.NET 2.0 AJAX Extensions 1.0 so it can not use .net v3.5 or above. So how to fix? Turns out that the toolkit relies on 2 additional assemblies, these are:
System.Web.Extensions.dll
System.Web.Extensions.Design.dll
See in your Refrences if both of these are present. You can download these files from here

Saturday, September 21, 2013

How to make a directory as git repository


Many a times we have  non directory and we want to make them as git repository.In such a situation open git bash and follow following steps
git init

git add .

git commit -m 'message'

git remote add origin <url of remote repository>

git push -u origin master

Working with Git

Step 1. Clone your repository to your local system
first create a new directory which you want to be as repository
Open Git Bash move to the directory by using  cd path/to/my/repo
Now clone the repository using

$ git clone https://url of your remote repository/newuserme/repository.git
you will get a message like this
Cloning into 'repository'...
Password
warning: You appear to have cloned an empty repository.

Step 2. Explore your repository and fix a problem

$ ls -al 
This will give the list of files in repository.

Step 3. Create a README, add it locally, and push it to the remote server

create readme file  with content about file and save it in local folder .This file is a text file.
Now check the status of file on Git Bash

$ git status 

Now add the Readme file using 

$ git add README

commit the changes using following command

$ git commit -m "Here should always be some meaning full message".

Now we can push the changes to the remote server using following command

$ git push -u origin master

It will ask for you for password.
Password: 
Note:

Sometimes while commiting you we get an error like 
*** Please tell me who you are.

Run

git config --global user.email "you@example.com"

git config --global user.name "Your Name"

to set your account's default identity.

Omit --global to set the identity only in this repository.

In such a situation enter these two commands

 git config --global user.email "here you should put your email address"

  git config --global user.name "Your Name"


Now if someone else working on same code has updated the code then we can get the updated code using git Pull command

$ git pull origin master

Thursday, June 27, 2013

The requested page cannot be accessed because the related configuration data for the page is invalid error when hosting WCF service in iis

Very often while hosting a wcf service in iis we get the error "The requested page cannot be accessed because the related configuration data for the page is invalid ". The reason it cannot read the config file is because the process running your web app does not have permission to access the file/directory. So you need to give the process running your web app those permissions. The access rights should be fairly straightforward, i.e. at least Read, and, depending on your app, maybe Write. Above, you mention IUSR etc. not being in the properties for web.config. If by that you mean that IUSR is not listed in the security tab of the file then it's a good thing. One doesn't want to give IUSR any kind of permission to web.config. The role IUSR is an anonymous internet user. The file web.config should only be accessible through your application. You need to assign permissions for IIS_IUSRS on the local machine (but you don't have to assign for IUSR, in fact it will work even if you explicitly deny permissions). To assign permissions, just right click on the folder and on the security tab make sure to grant the correct permissions, and if the user is not listed then click "ADD", and enter IIS_IUSRS (and make sure that under "domain" the local computer is selected, or enter in the name fieldYourLocalComputerName\IIS_IUSRS), and then you are good to go.

Monday, May 27, 2013

How to handle null value returned when using Linq to get Max Value for a column

Very often we use Select query to get Max value for a column in Ado.net like
 SELECT MAX(UnitPrice) FROM products
. We can do the same thing in Linq but what about if we donot have any row to return.In sich a case you will probably rest up in getting casting error "Unable to convert null to specific type".
How to handle such situations in Linq
.net framework provides nullable type Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
Now if we write the same query in Linq
int? query = (from o in context.Products select (int?)o.UnitPrice).Max(); 
This query will result in null value.We can cast this null value into our requested datatype Convert.ToInt32(query);

Monday, May 6, 2013

Copy Sql server database files(MDF and LDF) without stopping SQL Server services


The better approach for transferring database is to take a backup of database and move backup file anywhere but even if you wish to copy MDF and  LDF file, you can have above approach. If you are using your database, you are not able to copy the data or log files.For copying these files you need to stop sql services but  you can do it without even stopping services of SQL with following small script.

 ALTER DATABASE <Databasename>
 SET OFFLINE WITH ROLLBACK IMMEDIATE;

 It's not good but better than stopping SQL Server services
ALTER DATABASE <Databasename> SET ONLINE;

Monday, April 29, 2013

Access Page Methods Using Script Manager In Asp.net

Sometimes we want to execute server side code from clientside using ajax then we can do this in two ways:-
  • Using jQuery to directly call ASP.NET AJAX page methods.
  • Using Script manager to access page methods.
Here i am going to explain how to use Script manager to call server side methods.There are 5 basic things we have to keep in mind while doing this.
  1. The Page Method should be static.
  2. Set the script manager enable PageMethods="true".
  3. Use java script PageMethods.<Method Name>(value, OnSucceeded, OnFailed).
  4. OnSucceeded - function to executed on success.
  5. OnFailed - function to executed on fail.
Default.aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<html>
<head id="Head1" runat="server">
    <title></title>
        <script type="text/javascript">
        function validatuser(soruce) {
            var valueuseremail = soruce.value;
            if (valueuseremail != "") {
                PageMethods.ValidateUser(valueuseremail, OnSucceeded, OnFailed);
            }
        }
        function OnSucceeded(result, usercontext, methodName) {
            document.getElementById('<%= lblValidation.ClientID %>').innerHTML = result;
        }
        function OnFailed(error, userContext, methodName) {
            alert("Error");
        }
         </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager 
            ID="ScriptManager" 
            runat="server" 
            EnablePageMethods="true" />
        <asp:TextBox 
            ID="txtEmail" 
            runat="server" 
            onkeyup="validateuser(this);">
        </asp:TextBox>
        <asp:Label 
            ID="lblValidation" 
            runat="server">
        </asp:Label>
    </form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
       public static string ValidateUser(string struname)
    {
        string uerror = string.Empty;
        try
        {
            bool userExists = false;
            ///
            /// Check if user exists
            ///
            if (struname.ToLower().Equals("bob"))
            { userExists = true; }
            if (userExists)
            { uerror = "UserName already exists!"; }
            else
            { uerror = "UserName available!"; }
        }
        catch
        {
            uerror = "Error";
        }
        return uerror;
    }        
}

Wednesday, April 17, 2013

Data Text Field Showing System.Byte[] in Radio Button List when concatenating multiple columns

While working on one of the project's i came across a scenario when data text field i binded in radio button list showed data on local but online it showed System.Byte[] instead of text.I was using Mysql database and for data text field i was concatenating 3 values .When i run that query on mysql it returned me data.I got expected results while running on local but when same code was deployed on server an unexpected thing occur. After lot of investigation and goggling i found one interesting thing that it was not the problem with code,it was merely a mysql .NET connector, version 5.1.6.Actually on local i was having .NET connector, version 3.51 According to mysql.com it is not a bug ,but it is expected behaviour.According to mysql.com if we are having any query that concatenates two or more columns ,Then one of the scenario will occur:-
  • mysql> SELECT CONCAT("Tonci", " ", "Grgin") AS Name; Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are non-binary strings, the result is a non-binary string.
  • mysql> SELECT CONCAT("Tonci ", 1, " Grgin") AS Name; BINARY flag is set (this is where your problem is!) This will return binary string.
  • Now here is the solution to the problem: Cast the result of concatenate query as Char and then use it.Hence the issue of System.Byte array in Data Text Field will be solved. mysql> SELECT CAST(CONCAT("Tonci ", 1, " Grgin") AS CHAR) AS Name; For further details Visit:http://bugs.mysql.com/bug.php?id=37485

    Friday, April 12, 2013

    How to view parameterised query parameters that are passed to a command in visual studio during debugging

    The Immediate window is used to debug and evaluate expressions.To access the immediate window in debug mode one has the following options: Type Control-Alt-I In the command window, type imme Or find the option “Immediate Window” in the “view” menu. Most often we want to view what exactly is going into parametrized query at run time,in such a scenario immediate window can be very helpful to us.If we want yo view any parameters value in sql command we can just view those values in immediate window. Eg:- Suppose we are passing parameters to a command object as db.cmd.parameters.AddWithValue("@id",somevalue) Now if we want to know what exactly has gone as parameter in cmd we can view that in Immediate Window ?db.cmd.Parameters("@id").Value For more details regarding various commands for immediate window please visit the following URL http://msdn.microsoft.com/en-in/library/f177hahy(v=vs.80).aspx

    Monday, April 8, 2013

    Insert Explicit Value for Identity Column in Table

    When we want to insert explicit value for a column that is already set to identity and auto incrment,then we are likely to gt an error"Cannot insert explicit value for identity column in table 'IdentityTable' when IDENTITY_INSERT is set to OFF."
    The trick is to enable IDENTITY_INSERT for the table.
    
    SET IDENTITY_INSERT IdentityTable ON
    
    INSERT IdentityTable(TheIdentity, TheValue)VALUES (3, 'First Row')
    
    SET IDENTITY_INSERT IdentityTable OFF
     
    Note:
    Identity_Insert can be enabled  on only one table in database if you enable on second table .you will get error in first and we have to provide value for identity column when we use identity _insert enabled  as On.
    After we insert identity as off again,sql server set identity seed as current value.
    
    

    Conversion from type 'DBNull' to type 'String' is not valid Invalid Cast Exception

    Many a times when we are getting data from database and showing them on page in asp.net we came across this error "Conversion from type 'DBNull' to type 'String' is not valid Invalid Cast Exception"
    The main reason for this error is that when we are getting data from database and we get Null value and we try to cast it into string or any other data type .We can easily resolve this error by just adding small condition before casting into any data type
    I have included syntax in vb  as well as c#.Here is the trick what we have to do:
    Vb.Net
    string s=IIf(IsDBNull(db.rd("column")), String.Empty, db.rd("column"))
    C#
    string s = ( IsDBNull(db.rd("column")) ? String.Empty : db.rd("column") );
    

    Upload To FTP with FileUpload control

    Sometimes we come across a situation when we want get file from user through file upload and upload it to remote server through ftp.In this type of situation we can just create  a request stream variable and using that request stream we can write the contents of fileupload to remote server.For this we have to get the content of file upload control in bytes.Here is  a sample how i accomplish the same thing.Here spath is the path ftp path to remote server.ftpuser is user name and ftppassword is password to remote server.
    
    Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(spath), System.Net.FtpWebRequest)
    request.Credentials = New System.Net.NetworkCredential(ftpuser, ftppassword)
    request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
    Dim ftpStream As Stream = request.GetRequestStream()
    ftpStream.Write(FileUpload1.FileBytes, 0, FileUpload1.FileBytes.Length)
    ftpStream.Close()
    ftpStream.Dispose()
    Note:Don't forget to add following lines at the end of the code
    ftpStream.Close()
    ftpStream.Dispose()
    
    

    Thursday, April 4, 2013

    Ternary operator in VB.Net

    Recently in one of the project I was working with VB.NET language and I was eager to know if there is a ternary operator equivalent there or not. After searching on internet I have found two ways to do it.
    We have two operators in vb.net to accomplish this task
    1) if(condition,true,false)
    2) iif(condition,true,false) You can see that both IIF and If operator has three parameter first parameter is the condition which you need to check and then another parameter is true part of you need to put thing which you need as output when condition is ‘true’.
    We can use any of the two operators and get same output.

    Monday, April 1, 2013

    Create setup that runas administrator using Visual Studio

    Here is a property named "AdminUser" which can help to achieve your goal.
    Please follow these steps.
    1) Open your Setup Project, View->Launch Conditions.
    2) Right click on Launch Conditions, and add a new Condition in your Launch Conditions.
    3) Right click the Condition, choose Properties Window.
    4) Set Condition to AdminUser.
    5) Build and install.
    

    Wednesday, March 27, 2013

    Property Does not initialise even though we assign value to it in VB.net

    I have came around a strange situation in vb.net when i was assigning value to property it was not at all taking the value.When i debug it ,i was getting Nothing.Actually when i was creating property i got the intellisense.This intellisense created structure of the property.
    Now the problem comes when we use this property for setting value.The structure we got for property was
            
    Public Property runs As String
              Get
    
              End Get
              Set(value As String)
    
              End Set
            End Property
    Now when we assign value to the property it will not even go to the property in debug mode.After investigating i found that there is a small change that we have to make while using intellisence.In Set we have to give ByVal the all wioll be fine. So the structure of property should be like Public Property runs As String Get End Get Set(ByVal value As String) End Set End Property

    Monday, March 25, 2013

    Cyrillic(Russian ) characters not displaying in asp.net using mysql 3.5.1

    When we are using .net with mysql many a times we face a problem that cyrillic(russian)or any other language characters dont display on page or console as expexted .Instead we get ???.The solution to this problem is that we might be using mysql connector driver that does not support cyrillic characters.I was using mysql connector 3.5.1 and faced the same problem.After lot of googling i didn't get any result.So i changed my mysql connector driver from 3.5.1 to 5.1.12 and it worked . The reason for this is MySQL does not support the full UTF8 character set, 4-byte characters are not allowed.

     MYsql 3.5.1 connector does not support all UTF_8 Characters.

    Also i changed my connection string as 

    {Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;User=myUsername; Password=myPassword;Option=3;}

    Friday, March 22, 2013

    Format text returning from query having newline character.

    Sometime we come across a situation that user enter the data with line breaks into database but when we display that data in page it shows data as a single line without formatting.To solve this situation before showing data we have to convert newline characters with "<br/>"
     

    s.Replace(Environment.NewLine, "<br/>")

    Linkify all URLs that appear in a paticular div

    Many times we come accross situation that our webpage contains urls but we
    forget to give links to it at the time of uploading.
    Now here is a simple javascript code that we can give at body load and it will search all urls in page and give them links.
    
    <script>function linkify(text){
        if (text) {
            text = text.replace(
       /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
                function(url){
                    var full_url = url;
                    if (!full_url.match('^https?:\/\/')) {
                        full_url = 'http://' + full_url;
                    }
                    return '<a href="' + full_url + '">' + url + '</a>';
                }
            );
        }
            document.getElementById("hi").innerHTML = text;
    }</script>
    
    <body onload="linkify(document.getElementById('hi').innerHTML)"> 
    
    Note: here "hi" is the div that contains text to be converted into links.

    Monday, March 18, 2013

    My simple tool tip on mouse over and mouse click

    Create a tooltip.js file.

    function ToolTip(id,isAnimated,aniSpeed)
    { var isInit = -1;
      var frm,divWidth,divHeight;
      var xincr=10,yincr=10;
      var animateToolTip =false;
      var html;
      
      function Init(id)
      {
       frm = document.getElementById(id);
       if(frm==null) return;
       
       if((frm.style.width=="" || frm.style.height==""))
       {alert("Both width and height must be set");
       return;}
       
       divWidth = parseInt(frm.style.width);
       divHeight= parseInt(frm.style.height);
       if(frm.style.overflow!="hidden")frm.style.overflow="hidden";
       if(frm.style.display!="none")frm.style.display="none";
       if(frm.style.position!="absolute")frm.style.position="absolute";
       
       if(isAnimated && aniSpeed>0)
       {xincr = parseInt(divWidth/aniSpeed);
        yincr = parseInt(divHeight/aniSpeed);
        animateToolTip = true;
        }
            
       isInit++; 
       
      }
      
        
      this.Show =  function(e,srcpath)
      {
        if(isInit<0) return;
        
        var newPosx,newPosy,height,width;
        if(typeof( document.documentElement.clientWidth ) == 'number' ){
        width = document.body.clientWidth;
        height = document.body.clientHeight;}
        else
        {
        width = parseInt(window.innerWidth);
        height = parseInt(window.innerHeight);
        
        }
        var curPosx = (e.x)?parseInt(e.x):parseInt(e.clientX);
        var curPosy = (e.y)?parseInt(e.y):parseInt(e.clientY);
        
        frm.src=srcpath;
        
        if((curPosx+divWidth+10)< width)
        newPosx= curPosx+10;
        else
        newPosx = curPosx-divWidth;
    
        if((curPosy+divHeight)< height)
        newPosy= curPosy;
        else
        newPosy = curPosy-divHeight-10;
    
       if(window.pageYOffset)
       { newPosy= newPosy+ window.pageYOffset;
         newPosx = newPosx + window.pageXOffset;}
       else
       { newPosy= newPosy+ document.body.scrollTop;
         newPosx = newPosx + document.body.scrollLeft;}
    
        frm.style.display='block';
        //debugger;
        //alert(document.body.scrollTop);
        frm.style.top= newPosy + "px";
        frm.style.left= newPosx+ "px";
    
        frm.focus();
        if(animateToolTip){
        frm.style.height= "0px";
        frm.style.width= "0px";
        ToolTip.animate(frm.id,divHeight,divWidth);}
          
        
        }
    
        
    
       this.Hide= function(e)
        {frm.style.display='none';
        if(!animateToolTip)return;
        frm.style.height= "0px";
        frm.style.width= "0px";}
        
        
        ToolTip.animate = function(a,iHeight,iWidth)
      { a = document.getElementById(a);
             
       var i = parseInt(a.style.width)+xincr ;
       var j = parseInt(a.style.height)+yincr;  
       
       if(i <= iWidth)
       {a.style.width = i+"px";}
       else
       {a.style.width = iWidth+"px";}
       
       if(j <= iHeight)
       {a.style.height = j+"px";}
       else
       {a.style.height = iHeight+"px";}
       
       if(!((i > iWidth) && (j > iHeight)))      
       setTimeout( "ToolTip.animate('"+a.id+"',"+iHeight+","+iWidth+")",1);
        }
        
       Init(id);
    }
    
    

    Now add these functions to thee page where you want to call tooltip

    <script language="javascript">
            var t1;
    var timeout;
            function showDetails(e, empid) {
                if (t1) t1.Show(e, "<br><br>Loading...");
    document.getElementById("a1").style.display = "none";
    
    //these lines are used when we are having multiple tootlips in page.
                document.getElementById("a2").style.display = "none";
                var url = 'defectstooltip.aspx?def_id=' + empid;
                document.getElementById("a").src = url;
            }
    
            function hideTooltip(e) {
                if (t1) t1.Hide(e);
            }
    
    </script>
    
    add events to links onmouseover ="showDetails(e, empid);" and onmouseout="hideTooltip(e)"
    
    

    Note we can also call this tooltip on click event just make small change in function

    function showDetails1(e, empid) {
                setTimeout(function () {
                   
                    if (t2) t2.Show(e, "<br><br>Loading...");
                    document.getElementById("a").style.display = "none";
                    document.getElementById("a2").style.display = "none";
                    var url = 'commentbox.aspx?def_id=' + empid;
                    document.getElementById("a1").src = url;
                }, 1000);
            }
    
    
    
    

    Calling javascript function when using update panel

    Sometimes we come across situation that we want to call some javascript function from code inside update panel and javascript function didn't execute at all.In 
    such situations we can use Script Manager class RegisterStartupScript Method
    and it will easily call javascript function.
    
    Eg:- 
    ScriptManager
    .RegisterStartupScript(Me.Page, Me.GetType(), "temp", 
    "<script type='text/javascript'>
    window.parent.document.getElementById('a2').style.display='none';
    </script>", False)

    Sunday, March 17, 2013

    'If', 'ElseIf', 'Else', 'End If', or 'Const' expected error while using eval

    Sometimes when we are binding any control using eval or bind we come across
    
    an error "'If', 'ElseIf', 'Else', 'End If', or 'Const' expected " the most common is reason that there should be no space between # and directive.

    Friday, February 22, 2013

    Show fixed text in div and append ... using css

    white-space: nowrap;
    width: 100%;
     overflow: hidden;
     text-overflow: ellipsis;


    The ellipsis value causes three periods to be appended to the text.

    Wednesday, February 13, 2013

    Enable slow query log in Mysql


    set global slow_query_log = 'ON';
     show variables like '%slow%';
    set global log_queries_not_using_indexes = 'ON'
    set global slow_query_log_file ='/var/log/mysql/slow-query.log';
    set global long_query_time = '20';  

    Monday, February 4, 2013

    Mysql In clause V/S Find_in_set

     In Clause in Mysql

    In clause is used to pass multiple values for a column in where clause.We can also pass subquery to it .But in mysql there is one strange thing that if you pass a subquery in In clause.it may return unusual results.But there is a reason for this.

    SELECT name FROM orders,company WHERE orderID = 1 AND companyID IN (select id from companyids)

    the subquery here in In clause returns comma seperated value and mysql picks up only first value till comma.so you are expected to get unwanted results.

    The solution to this problem is a function in mysql

    FIND_IN_SET(,).This function returns 

      Returns 0 if str is not in strlist or if strlist is the empty string.
     Returns NULL if either argument is NULL. 
    This function does not work properly if the first argument contains a comma (“,”)
     character. 
    Returns a value in the range of 1 to N if the string str is in the string list
    
    SELECT name FROM orders,company WHERE orderID = 1 
    AND Find_In_set(companyID ,select id from companyids)
    
     
    

    Monday, January 28, 2013

    Get all rows for paticular column in one column.

    For getting records returned by a sql query in one column  comma seperated we can use 
    SELECT GROUP_CONCAT(columnname) AS columnname FROM tablename WHERE condition .
    This query will return all query results for paticular column in one column comma seperated.

    Tuesday, January 15, 2013

    Use Mysql stored procedure in Vb.net

    To use mysql stored procedure in vb.net we have to create command object and pass it text as call sp_name


                Dim cmd As New OdbcCommand()
                cmd.Connection = myConnection
                cmd.CommandText = " CALL getcatid(?)"
                cmd.CommandType = CommandType.StoredProcedure

                cmd.Parameters.AddWithValue("@catname1", "Kitchen")
                cmd.Parameters("@catname1").Direction = ParameterDirection.Input