Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

17 September 2014

Convert C# DataTable to JavaScript 2D Array

Hi All,

Lets see how to send the DataTable from Code behind to JavaScript.  Some time we face the problem when we need to array the value from C# code behind to JavaScript use use script tag <%=variable_name%> Right we are also going to use the same approach. But the main point is how to convert the DataTable(or Dictionary or List of object) from C# to JavaScript.

Someone might come up with the thought to use the Repeater control.  But its really typical,  What about if I say you can get the C# DataTable  as 2D array in JavaScript with no extra efforts??

:) Cool...

you just need to pass your DataTable in this method and it will create the Json Serialized array to be used in JavaScript. :)

   public partial class RepeaterControlTesting : System.Web.UI.Page
   {
      public string dataTable;        
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            dataTable = ConvertDataTabletoString(getDT());                
         }
      }
      public string ConvertDataTabletoString(DataTable dt)
      {            
          JavaScriptSerializer serializer = new JavaScriptSerializer();
                   
          List<List<object>> rows = new List<List<object>>();
          List<object> row;
          foreach (DataRow dr in dt.Rows)
          {
             row = new List<object>();
             foreach (DataColumn col in dt.Columns)
             {
                row.Add(dr[col]);
             }
             rows.Add(row);
          }

          return serializer.Serialize(rows);
      }
      public DataTable getDT()
      {
          /// or get the DataTable from Database.. 
          DataTable dt = new DataTable();
          dt.Columns.Add("Col_int", typeof (int));
          dt.Columns.Add("Col_string", typeof(string));
          dt.Columns.Add("Col_bool", typeof(bool));
          dt.Columns.Add("Col_4th", typeof(string));
          dt.Columns.Add("Col_float", typeof(float));

          DataRow dr;
          for (int i = 1; i <= 5; i++)
          {
              dr = dt.NewRow();
              dr[0] = i;
              dr[1] = i + "  Col_string";
              dr[2] = (i%2 == 0);
              dr[3] = i + " Col_4th";
              dr[4] = (float)i;

              dt.Rows.Add(dr);
          }

          return dt;
      }

  }

Thats it.. now just goto you aspx file and access the "dataTable" in your JavaScript code..

<body>
    <div id="main">
                
    </div>
        
    <script>        
        var dataTable = <%= this.dataTable %>;
        for (var i = 0; i < dataTable.length; i++) {
            $("#main").append("| "+dataTable[i][0] + " | ");
            $("#main").append(dataTable[i][1] + " | ");
            $("#main").append(dataTable[i][2] + " | ");
            $("#main").append(dataTable[i][3] + " | ");
            $("#main").append(dataTable[i][4] + " |<br/><br/>");
        }
    </script>
</body>



Good to go.. :) Happy Code sharing.. :)

26 March 2014

Parent Div height zero(0) even child div has content

Hi,

Let see what happened when we float the child div to Left or Right. Parent Div shows the height as 0.

<html>
  <head>
    <style>
      #parent
      {
        width:100%;
        height:auto;
      }
      #child
      {
        float:right;
        width:25%;
        height:auto;
        border:1px solid black;
        margin:10px;
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="child">
        this is the content inside the child
      </div>
    </div>
  </body>
</html>

It shows the result as -


Notice child div has content so it has the height but if child div has the height why parent div showing height as zero(0)??

Its because of you set the
float:right; 
on child div which make it position:absolute and thats why parent div height is zero.  To correct is you just need to set the overflow:hidden on parent div.

modified the css part as below -
      #parent
      {
        width:100%;
        height:auto;
        overflow:hidden;
      }
And you are good to go you will get the correct result as -

Happy Blogging and Sharing.. ☺☻

20 January 2014

C# Extension Methods

Hi All,

Lets see whats the extension method in C# and whats the main use of it.  Sometime we want to add a method in existing class.  This class can be from the .net library or any third party class.  To do so we generally extends the existing class in our new class and then compile it and use that new class.

Like in c# library class - "string" does not have any such method to count if we want such method we have to design our own method.  Remember you can not inherit the "string" class as its sealed.

static class MyClass
{
  public static int WordCount(string line)
  {
      line = line.Trim();
      return line.Split(' ').Length;
  }
}


now you have to call this method like -

int n = MyClass.WordCount("String whatever we want to pass");


but if we want to merge this method with existing c# library string class?  but as we dont have source code of string class we can not edit the source code write?

Extension method do this job.  Using the extension method we can add the method in compiled class without needing source code, so that you can call your own method like the previous existing method in string class.

string str = "string whatever we want to pass";
int n = str.WordCount();


to add an extension method to existing class you just need to class a static class and static method like we created earlier.  The only change we required in passing parameter we need to add the "this" keyword.

static class MyClass
{
    public static int WordCount( this string line)
    {
        line = line.Trim();
        return line.Split(' ').Length;
    }
    
    public static int WordCountStartsWith( this string line, char c)
    {
        int result = 0;
        line = line.Trim();
        
        var word = from wrd in line.Split(' ')
                   where wrd.First() == c
                   select wrd;
        result = word.Count();

        return result;
    }

    public static int WordCountContains( this string line, string str)
    {
        int result = 0;
        line = line.Trim();

        var word = from wrd in line.Split(' ')
                   where wrd.Contains(str)
                   select wrd;
        result = word.Count();

        return result;
    }
}


Now to call these method we can just use the object of string class.

This is the beauty of the extension method, we do not need to recompile the parent class(in this case string class).  We just need to remember when want to design an extension method -
  1. static class
  2. static method
  3. this keyword just before the passing parameter class, whose extension we want. 
Download Sample


See we are getting our own three extension method on string class.

string line = "string value or line whose word we want to count";
int n = line.WordCountContains("nt");

Happy Coding and Blogging.. !! :)

27 September 2013

Chat using WCF

Hi Friends,

Let see how can we create Chat app using WCF.  This is the basic app we can modify a lot in this sample project.  Its just a sample. You can download the sample from here.

1.  First create the WCF Services Library project in Visual Studio and give a name (FirstWCF).


2. Delete the pre-created files IServices1.cs and Services.cs
3. Add a class into project and named it (Message) and paste the following code. I will use it as a message object to communicate and transfer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace FirstWCF
{
  [DataContract]
  public class Message
  {
     [DataMember]
     public string toUser;
     [DataMember]
     public string fromUser;
     [DataMember]
      public string msg;
  }
}
4. Add another class into project and named it (ISendMsg) and make it interface by paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace FirstWCF
{
  [ServiceContract]
  public interface ISendMsg
  {
     [OperationContract]
     string SendMsg(Message msg);
     [OperationContract]
     List getAllMsg(string toUser);
     [OperationContract]
     List getSentItem(string fromUser);
     [OperationContract]
     string DeleteMsgFrom(string fromUser, string toUser);
  }
}
5. Add another class into project and named it(MsgCollection), it implement the interface defined in previous step.  I implement the method define in interface. Paste the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace FirstWCF
{
  [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
  class MsgCollection:ISendMsg
  {
  List<Message> AllMsgs = new List<Message>();
  public string SendMsg(Message msg)
  {
      try
      {
        AllMsgs.Add(msg);
        return "Message Send Successfully..!!";
      }
      catch (Exception e)
      {
        return "Message Failed..!!";
      }
    }

    public List<Message>  getAllMsg(string toUser)
    {
      List<Message> filterMsgs = new List<Message>();
      foreach (Message msg in AllMsgs)
      {
        if(msg.toUser.Equals(toUser))
        {
          filterMsgs.Add(msg);
        }
      }
      return filterMsgs;
    }

    public List<Message> getSentItem(string fromUser)
    {
      List<Message> filterMsgs = new List<Message>();
      foreach (Message msg in AllMsgs)
      {
        if (msg.fromUser.Equals(fromUser))
        {
          filterMsgs.Add(msg);
        }
      }
      return filterMsgs;
    }

    public String DeleteMsgFrom(string fromUser, string toUser)
    {
      try
      {
        AllMsgs.RemoveAll(e => (e.fromUser.Equals(fromUser) && e.toUser.Equals(toUser)));
        return "Message deleted successfully..!!!";
      }
      catch (Exception e)
      {
        return "Deleting message failed..!!!";
      }
    }    
  }
}
6.  Now you can run it, but it will open a client provided by Microsoft to test the WCF apps. But I would say to design you own client and use that to test this chatting application.
7. Right click the project solution file in project explorer in Visual Studio and Add -> Project->Console Application give name (ClientForFirstWCF) to project and click OK.
8. Now you need to add the reference of WCF you created, for that you must know the metadata exchange URL. You can get it from the App.config file under the FirstWCF project you created.
..
..
<host>
  <baseAddresses>
    <add baseAddress="http://localhost:8732/Design_Time_Addresses/FirstWCF/Service1/" />
  </baseAddresses>
</host>
..
..
get this baseAddress and add "mex" at all this would be your metadata exchange URL
http://localhost:8732/Design_Time_Addresses/FirstWCF/Service1/mex
9. Now we need to add reference of this WCF to the client project we created in Step 7.
   Right click ClientForFirstWCF project and say 'Add Service Reference' and provide the URL of metadata exchange we found in previous step. Select the Service found on that URL and click Ok.
10. Open Program.cs file of client project and overwrite with following content.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClientForFirstWCF.MsgCollectionServices;

namespace ClientForFirstWCF
{
  class Program
  {
    static string loginName = "";
    static SendMsgClient client = new SendMsgClient("WSHttpBinding_ISendMsg");
    static void Main(string[] args)
    {
      try
      {
        client.Open();      
        int choice=0;
        bool flag = true;
        do
        {
          Console.Clear();
          Console.WriteLine("--------- WCF messaging --------");
          Console.WriteLine("");
          Console.Write("Enter Your name : ");
          loginName = Console.ReadLine();
        } while (loginName.Length == 0);
      
        while (flag)
        {
          Console.Clear();
          Console.WriteLine("--------- WCF messaging --------");
          Console.WriteLine("Hello " + loginName);
          Console.WriteLine("");
          Console.WriteLine("Enter You Choice..");
          Console.WriteLine("1. Compose");
          Console.WriteLine("2. Inbox");
          Console.WriteLine("3. Sent Item");
          Console.WriteLine("4. Delete Messages");
          Console.WriteLine("5. Exit");
          Console.Write("Your Choice : ");
          try
          {
            choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
              case 1:
                SendMsg();
                break;
              case 2:
                ReadMsg();
                break;
              case 3:
                SentItem();
                break;
              case 4:
                DeleteMsg();
                break;
              default:
                flag = false;
                break;
            }
          }
          catch (Exception e)
          {
          }          
        }

        client.Close();
      }
      catch (Exception e)
      {
        Console.WriteLine("Sorry.!!WCF is down. Please set it up and running.");
        Console.ReadKey();
      }      
    }

    static void SendMsg()
    {
      Message msg = new Message();
      msg.fromUser = loginName;
      msg.toUser="";
      msg.msg = "";
      do
      {
        Console.Clear();
        Console.Write("To : ");
        msg.toUser = Console.ReadLine();
      } while (msg.toUser.Length == 0);
      
      do
      {
        Console.Write("Content : ");
        msg.msg = Console.ReadLine();
      } while (msg.msg.Length == 0);

      //sending message 
      Console.WriteLine(client.SendMsg(msg));
      Console.ReadLine();
    }


    static void ReadMsg()
    {
      Console.Clear();
      Message []all = client.getAllMsg(loginName);
      foreach (Message msg in all)
      {
        Console.WriteLine("From :"+msg.fromUser);
        Console.WriteLine("Content :"+msg.msg);
        Console.WriteLine();
      }
      Console.ReadLine();
    }

    static void SentItem()
    {
      Console.Clear();
      Message[] all = client.getSentItem(loginName);
      foreach (Message msg in all)
      {
        Console.WriteLine("To :" + msg.toUser);
        Console.WriteLine("Content :" + msg.msg);
        Console.WriteLine();
      }
      Console.ReadLine();
    }

    static void DeleteMsg()
    {
      string fromUser="";
      do
      {
        Console.Clear();
        Console.WriteLine("Delete the message came from User");
        Console.Write("Enter the User Name : ");
        fromUser = Console.ReadLine();
      } while (fromUser.Length == 0);
      
      Console.WriteLine(client.DeleteMsgFrom(fromUser, loginName));
      Console.ReadLine();
    }
  }
}
11. Now if you try to run the WCF project it will again open the default Microsoft client, so you have to assign your own client. Select your WCF project -> right click -> Properties -> Debug and change the command line argument
/client:"../../../ClientForFirstWCF/bin/debug/ClientForFirstWCF.exe"

12. Congratulation you have created the chat app using WCF. Its basic chat you can still modify it.

You can download the sample from here.
Output - 
When I start two client (deepak and gaurav)to communicate to each other (send/receive message)

When first client(deepak) send the message to second client(gaurav)


When second client(gaurav) check his Inbox

Happy Coding.. :)


11 September 2013

IIS7 : An error occurred on the server when processing the URL. Please contact the system administrator

Hello Friends,

If you have worked with Classic ASP with IIS5 or IIS6, that is easy to recognize the error occurred in code.  IIS send the error information to client which show the file name, line no. and other information to understand where and what error occurred.  But now a days if you use IIS7 and trying to publish your classic ASP web application in IIS7, you may see a message like -

An error occurred on the server when processing the URL. Please contact the system administrator

After investigating a bit here and there I find out because scriptErrorSentToBrowser by default is false in IIS7 so we are unable to get the proper error message.  We need to change the default value(false) to true for the scriptErrorSentToBrowser flag in IIS7. Here is how to change it -

Open your cmd prompt "As Administrator" and run the following command -

%windir%\system32\inetsrv\appcmd set config -section:asp -scriptErrorSentToBrowser:true

now you'll be able to see the proper error message. I would suggest you to set the flag to false after debugging because sometimes it shows very critical imp details to end user that can be harmful. You can use the same command just replace the 'true' by 'false'

%windir%\system32\inetsrv\appcmd set config -section:asp -scriptErrorSentToBrowser:false

Happy knowledge sharing.. :)


30 August 2013

Assign VS2010 to devenv when we have VS2007 as default

Hi Friends,


We generally face this problem if we have Visual Studio 2007 and as well as Visual Studio 2010.  To
start Visual Studio we use the shortcut command devenv stands for development environment, but as we have installed VS 2007, this devenv commend is assigned to Visual Studio 2007 so it starts the Visual Studio 2007  not 2010.  Even I we installed Visual Studio 2010 after  VS2007 but it do not update the registry to open 2010 with that shortcut command.

To assign the Visual Studio 2010 to that shortcut command devenv you have to modify the registry.  You can go to the following path and change the value by the

"C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe"


here this value is the path of your 2010 Visual Studio installed directory.

1.  Open the Run prompt by pressing (Window Key + R)

2. type regedit and hit enter

3. due the some security setting it will prompt you to continue or not  click 'OK'

4. goto the following path
     
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\dev.exe


5. In right pane you will find a single REG_SZ entry with the name 'default', double click it.

6. provide the installed directory path in text box (like the path I provided very top)

7.  in previous step this textbox contains the path of VS2007 IDE path you have to overwrite it by the Visual Studio 2010 path.

8. Its done.



Or you can download the registry file directly from here and just double click it and its done..

if you are using Window 64-bit download from Here

if you are using Window 32-bit download from Here

the code of reg file looks like.


Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\devenv.exe]
@="C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE\\devenv.exe"



Happy Tricks.. :)