Monday, January 18, 2010

How to Connect remote SQL Server 2005 database via CC Proxy-googl

Most of organizations use proxy server shared internet connection for their internal network. Browsing websites via proxy server requires few settings in browser itself where we set proxy server IP and port to 8080 which is default port, doing so is enough for any 1 to surf internet. But as an SQL server database programmers/developers uses SQL server management studio to connect to remote database from their client computers. Problem arises when a developer tries to connect a remote database server through SQL server management studio but CC Proxy won’t allow connecting to database directly even if developer uses all details correctly. 


Why is SQL server management studio not able to connect a remote database?


A very basic thing about proxy server is that all client computers must have to pass all requests to proxy server IP, requests may be from internet browser Or FTP client Or even if its SQL server management studio.

So now if we try to connect a database with original details, proxy server (say proxy server IP is : 48.152.16.36 ) will not allow connecting to database using original Host name.


Because proxy cannot process any request directly, it must come to Proxy server IP first which is 48.152.16.36 (this is a dummy IP, I have used).


How to solve the problem:


Solution is simple; we just have to follow 2 steps as described below. Here we will be configuring CC proxy, SQL server management studio & SQL server configuration manager.


Step 1: Client side settings 
Say for example we have following database server details:

Server name : hostname
Login ID : username
Password : password
Port : 1433 [ SQL server uses 1433 port by default, in case if its different then we have to do settings in CC proxy accordingly  ]

Traditionally we use above given details directly to connect, if we connect from SSMS (SQL server management studio), it will take user to the screen as shown blow.




Now in above screen if we use Server name:  hostname then proxy will not process the request and SSMS will fail to connect to database server.

So rather than providing Server name:  hostname we have to set CC Proxy’s server IP which is 48.152.16.36. But only this much will not work, because we also need to request CC proxy to a specific port which is not used anywhere else in proxy server. So we will use any port, say we use PORT: 1444 instead 1433 which is default port in SQL server.

So now in above screen we have to set [Server name: 48.152.16.36, 1444] by keeping userID password as it is.


Ok so we are now done with client side settings. But this much will also not work as we have to do few port map settings in CC proxy on server as well.




Step 2: Proxy server side settings


Setting up above step 1 setting in client machine will now request proxy server with the port 1444. So we have to define a PORT MAP setting in CC proxy for port: 1444.

Below are the steps to follow for port map settings:

  1. Open CC proxy 6.0
  2. Go to OPTIONS
  3. Click on port map, it will take you to the screen as shown below


In above screen set the following:



            Dest Host : hostname


              Port type :  TCP


              Local Port : 1444


              Dest Port :  1433


Save all above details , and we are done.

After this step all client machines must have to connect to database server using Proxy server IP only with a specific port ( in our case its 1444, however we can use any port but it should not be used anywhere else in proxy server).

Tuesday, January 12, 2010

How to: publish a blog article via MS word 2007

It always becomes a headache for any blog writers while publishing any article with a rich formatting like a word document, with lots of pictures added inside the blog post.

For all the bloggers like me who have faced problem of rich formatting while posting an article in blog, so guys here is the easiest way to publish your well formatted articles from MS word 2007 itself , even without going to your Blog's dashboard J

Microsoft word 2007 is providing a great functionality of publishing your fully formatted word document direct to your blog from word 2007 itself. And it's even easier from the traditional way.

Here are the few steps you have to follow and you are DONE!!



Creating Blog article in word

Step 1: CREATING A NEW WORD BLOG POST

Open MS word 2007, go to menu and select NEW,

You will get the screen as shown below. Now choose "New blog post" as the RED arrow indicates below.






Step 2: WRITING A BLOG POST

Once you choose new blog post you will find the screen as shown below.




Now just like we prepare a word document prepare your full article here, with all formatting and pictures added.



Step 3: SETTING BLOG POST TITLE

As shown in below screen shot set your article title at marked place.






Publishing Blog article to your wordpress blog

Step 1: REGISTER YOUR BLOG ACCOUNT IN WORD 2007






As show in above picture, clicking on PUBLISH will ask you to register your existing blog account by using Blog URL and username/password.


  




CHOOSE YOUR BLOG PROVIDER as shown below. – I have configured with my wordpress Blog





Fill out all your blog details as shown below.




After submitting above form MS word will validate the details, after verification it will pop up a success message as given in below screen.

With above step now your Blog account got registered in MS word 2007.





Next to this step it will again ask for your blog's admin username/password to publish the blog on your original blog account.

Finally you will get your article posted onto your blog and will get the message as shown below.




Managing blog accounts and setting article categories in wordpress article

Later on whenever you use word for publishing your blog articles, you will get your account registered and you can manage all your blog accounts as shown below. And also can mark any blog as default.




INSERT ARTICLE CATEGORIES IN BLOG POST

Again setting categories for your blog post is been very easy, all you have to do is just click on "insert category" button as shown below

It will show a full list of all your wordpress blog existing categories in a drop down.

You can also type any new category over here if not in list of existing.




  


For this article I have given example of WORD PRESS blog, but we can also configure for other blog providers like blogger etc...

!!! ENJOY BLOGGING!!! J

Monday, December 21, 2009

Custom error tracking library in asp.net using XML & C#

Being an asp.net developers we develop a web project and get it completed in a months of time as there are many organizations which works on very tight bound timeline for developing web sites Or web application projects. And delivers the project to client in months of time
While after project delivery if client come up saying that they are facing problems or application is giving errors, that time it always becomes a headache for a developer to test each things even whole project sometimes to find a smaller errors (by means of error here we are not talking about logical errors, we talking about exceptions which mostly responsible for errors in the application), there are many exceptions .net framework fires which we never come to find out while debugging or developing the application. Those exceptions never affect directly to the application but each small exception puts the unnecessary load on the server.
Here is the solution to track each and every smallest things happening inside your asp.net web application. Which I named as “Custom error tracking library
Custom error tracking library
Very first question will come is that, what is the core concept for this.                                     
Concept is like we will be maintaining an XML file with a predefined structure which I have built which will contain all the required fields as nodes and subs. Which we call as errorlog.xml
There will be a CS library file which will track each and every minor errors/exceptions happens inside the application or .net framework and will put the error details inside the XML file.
Once we got CS library ready with us we just have to a simple function with 2 overload methods as per requirement in each try/catch blocks of the code and also in Application_Error event of Global.asax file.

XML File (errorlog.xml)


xml version="1.0" encoding="utf-8"?>
<errorlog>
  <error>
    <datetime>datetimedatetime>
    <filename>filenamefilename>
    <classname>classnameclassname>
    <methodname>methodnamemethodname>
    <errormethod>errormethoderrormethod>
    <messsage>ErrorMessagemesssage>
    <errordetails>Details goes hereerrordetails>
    <IP>IP adressIP>
    <url>URLurl>
  error>
  <error>
errorlog>

Root node of XLM file will be inside root node there will be a sub node  which will get duplicated for each error. For each error, library will generate a node will all the below listed details in XML file. Next to last error node. So for each error there will be a seaprate ERROR node.
Each fields of the above XML file is descibed beloe :
1.       Datetime : date and time of the error/exception
2.       File name : file name where exception or error happens
3.       Class name : classname in which error occurred
4.       Methodname : function name where errored
5.       Errormethod : name of the function which contains error code.
6.        Message : error message/exception message
7.       Error details: detailed error description which will show whole stack trace of the functional execution.
8.       IP : client IP address  
9.       URL : absolute error ULR


CS library


There will be a CS library file where we will write all functionality for error handling and writing errors into XML file.
errorHamdler.cs file will have 2 statis methods named WriteError(), there will be 2 overloaded methods for same functions with diff. parameters.
CS file will look as given below. We name it as errorHamdler.cs

errorHandler.cs


using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
namespace code_center
{
    public class errorHandler
    {
        string _strErrorMessage, _strDetails, _strClassName, _strMethodName;
        DateTime _dtOccuranceTime = new DateTime();
        public errorHandler()
        {

        }
        public errorHandler(DateTime time, string className, string methodName, string errorMessage, string details)
        {
            _dtOccuranceTime = time;
            _strClassName = className;
            _strDetails = details;
            _strErrorMessage = errorMessage;
            _strMethodName = methodName;
        }
        public static void WriteError(Exception ex)
        {
            WriteError(ex, "");
        }
        public static void WriteError(Exception ex, string fileName)
        {
            XmlDocument doc = new XmlDocument();
            string strRootPath = System.Configuration.ConfigurationManager.AppSettings["logfilepath"].ToString();
            string xmlPath = System.Web.HttpContext.Current.Server.MapPath(strRootPath);
            doc.Load(@xmlPath);
            XmlNode newXMLNode, oldXMLNode;
            oldXMLNode = doc.ChildNodes[1].ChildNodes[0];
            newXMLNode = oldXMLNode.CloneNode(true);

            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(1);
            MethodBase methodBase = stackFrame.GetMethod();

            newXMLNode.ChildNodes[0].InnerText = DateTime.Now.ToString();
            newXMLNode.ChildNodes[1].InnerText = fileName;
            newXMLNode.ChildNodes[2].InnerText = methodBase.DeclaringType.FullName;
            newXMLNode.ChildNodes[3].InnerText = methodBase.Name;
            newXMLNode.ChildNodes[4].InnerText = ex.TargetSite.Name;
            newXMLNode.ChildNodes[5].InnerText = ex.Message;
            newXMLNode.ChildNodes[6].InnerText = ex.StackTrace;
            newXMLNode.ChildNodes[7].InnerText = System.Web.HttpContext.Current.Request.UserHostAddress;
            newXMLNode.ChildNodes[8].InnerText = System.Web.HttpContext.Current.Request.Url.OriginalString;
            doc.ChildNodes[1].AppendChild(newXMLNode);
            doc.Save(@xmlPath);
            doc.RemoveAll();
        }
    }
}


In above code there is a line “string strRootPath = System.Configuration.ConfigurationManager.AppSettings["logfilepath"].ToString();
We need to give XML file path also where we have placed XML file in the project, so just have to add 1 line in web.config file as given below to store actual XML file path, which will be used in abiove functon.

Code inside web.config


<appSettings>
    <add key="logfilepath" value="~/errorHandling/errorlog.xml"/>   
  appSettings>

 

How to use error handler in application


Now everything is ready to be used in real time application. In each try/catch block we have to call
Writeerror() function as described below .

Code inside Default.aspx.vb


    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            throw new Exception("Custom error");           
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            code_center.errorHandler.WriteError(ex, "Default.aspx.vb");
        }
    }

Apart from each try/catch blocks we will put some code in Global.asax file also, as given below.

    void Application_Error(object sender, EventArgs e)
    {
        code_center.errorHandler.WriteError(Server.GetLastError().GetBaseException(), "Global.asax");
    }

The reason behin putting code in Global.asax file is very important and necessory as there might be many exceptions which occurs at application level and canot be tracable in any try/catch blocks in any function or events. So anyerror except try/catch blocks will come in this event (Application_Error) and will get inserted intoXML file.

That’s it, we have done with the error handling, and all errors will be tractable from the XML file which is being generated via the error handler.


Developing custom AD rotator control with multiple Image Mapping using C#.net & XML








We are all familiar with AD rotator control asp.net provides to show rotating/random ads on every page refresh.

But I found a limitation of this control while I needed to develop functionality where AD banners get changed on every page refresh as well as each banners should have multiple links which navigates to diff. URLs ( multiple image mapping in each AD banners )
As this is not possible with AD rotator I have developed a custom asp.net control which provides all this flexibilities with all AD rotator features.
Basic Concept:
To make the control easy to use & understand we will be keeping the concept of defining Ads same like AD rotator control using XML file.
Control will read the Ad banners from the XML file and render all the details with multiple image mappings in the aspx page.
XML file structure:
First and foremost step is to finalize the XML file structure that to be used in custom control to render the ads on random bases.
XML file will look as given in below sample file.

bannes.xml

xml version="1.0" encoding="utf-8" ?>
<banbers>
      <banner>
            <ImageUrl>http://xyz.com/banner1.jpgImageUrl>
            <AlternateText>Site1 MainAlternateText>
            <mappings>
                  <map>
                        <left>0left>
                        <top>0top>
                        <right>50right>
                        <bottom>50bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>
            mappings>
      banner>
      <banner>
            <ImageUrl>banners/5.jpgImageUrl>
            <AlternateText>b5AlternateText>
            <mappings>
                  <map>
                        <left>10left>
                        <top>10top>
                        <right>10right>
                        <bottom>10bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>
                  <map>
                        <left>25left>
                        <top>25top>
                        <right>25right>
                        <bottom>25bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>
                  <map>
                        <left>10left>
                        <top>10top>
                        <right>10right>
                        <bottom>10bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>
                  <map>
                        <left>25left>
                        <top>25top>
                        <right>25right>
                        <bottom>25bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>
                  <map>
                        <left>10left>
                        <top>10top>
                        <right>10right>
                        <bottom>10bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>
                  <map>
                        <left>25left>
                        <top>25top>
                        <right>25right>
                        <bottom>25bottom>
                        <navigateUrl>google.comnavigateUrl>
                  map>                 
            mappings>
      banner>
banbers>


Inside main banners TAG there will be multiple banners TAG to be added for each AD banner,
Each banner TAG will have child nodes(attributes) as listed below:
1.       Image URL – AD image URL to be specified here
2.       Alternate text – alt attribute for image
3.       Mappings  - list of all mappings with relative  left-right-top-Bottom  attributes
a.       Left – left side relative axis
b.      Right – right side relative axis
c.       Top– Top relative axis
d.      Bottom– Bottom relative axis
e.      Navigate URL – URL to navigate



Developing Custom Control:

Now next step is to build a custom asp.net control which will read the above XML structure and renders the data accordingly on ASPX page.




C# code file will be as given below:

ad-banners.cs

this control will have 1 public property where the XML file path will be given called


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace InfoquestLibrary.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:banner runat=server />")]
    public class banner : System.Web.UI.WebControls.WebControl
    {

        string _strImageURL, _strXMLpath;

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]

        public string ImageURL
        {
            get { return _strImageURL; }
            set { _strImageURL = value; }
        }
        public string XMLpath
        {
            get { return _strXMLpath; }
            set { _strXMLpath = value; }
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode xRandomNode;
            bool useMapping = true;
            int xIntRandomNumber;
            Random r = new Random();           
            xDoc.Load(System.Web.HttpContext.Current.Server.MapPath(this.XMLpath));

            xIntRandomNumber = r.Next(xDoc.ChildNodes[1].ChildNodes.Count);

            xRandomNode = xDoc.ChildNodes[1].ChildNodes[xIntRandomNumber];

            if (xRandomNode.ChildNodes[2].Equals(null))
            {
                useMapping = false;
            }
            else
            {
                if (xRandomNode.ChildNodes[2].ChildNodes.Count == 0)
                    useMapping = false;
            }

            if (xRandomNode.HasChildNodes)
            {
                this.ImageURL = xRandomNode.ChildNodes[0].InnerText;
            }

            output.AddAttribute(HtmlTextWriterAttribute.Src, this.ImageURL);
            if (useMapping)
            {
                output.AddAttribute(HtmlTextWriterAttribute.Usemap, "#map" + this.ID);
            }
            output.AddAttribute(HtmlTextWriterAttribute.Border, "none");
            this.AddAttributesToRender(output);
            output.RenderBeginTag(HtmlTextWriterTag.Img);

            if (useMapping)
            {
                int xIntMaps, xIntCounter;
                xIntMaps = xRandomNode.ChildNodes[2].ChildNodes.Count;

                output.AddAttribute(HtmlTextWriterAttribute.Name, "map" + this.ID);
                output.AddAttribute(HtmlTextWriterAttribute.Id, "map" + this.ID);
                this.AddAttributesToRender(output);
                output.RenderBeginTag(HtmlTextWriterTag.Map);

                for (xIntCounter = 0; xIntCounter < xIntMaps; xIntCounter++)
                {
                    XmlNode xMap = xRandomNode.ChildNodes[2].ChildNodes[xIntCounter];
                    if (xMap.HasChildNodes)
                    {
                        output.AddAttribute(HtmlTextWriterAttribute.Shape, "rect");
                        output.AddAttribute(HtmlTextWriterAttribute.Coords, xMap.ChildNodes[0].InnerText + "," + xMap.ChildNodes[1].InnerText + "," + xMap.ChildNodes[2].InnerText + "," + xMap.ChildNodes[3].InnerText);
                        output.AddAttribute(HtmlTextWriterAttribute.Href, xMap.ChildNodes[4].InnerText);
                        output.AddAttribute(HtmlTextWriterAttribute.Title, "");
                        output.AddAttribute(HtmlTextWriterAttribute.Alt, "");
                        output.RenderBeginTag(HtmlTextWriterTag.Area);
                        output.RenderEndTag();
                    }
                }

                output.RenderEndTag();
            }
        }
        protected override void OnPreRender(EventArgs e)
        {
        }
    }
}



Using customer control in ASPX page:

Now we are done with developing customer control with all the required functionality.
And control now ready for use.

Registering custom control




Defining Custom control in ASPX page

<TCC:banner ID="ads" runat="server" XMLpath="~/banner-mapping/bannes.xml" />