Tuesday, November 22, 2011

Windows Application Error Handling & Check Allready Application Running

Windows Application Error Handling :

In the windows entire application or while opening an application if you get any exception means the below code will help you to capture the error log. The application error or exception handling you can identify the error message. This will help you to understand the problem in your windows application using C#.Net. The below code is start up point of the win application. The program.cs class only first fire in the application.



Application Error Log


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
 
namespace MyProject
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 

 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
          
            Control.CheckForIllegalCrossThreadCalls = true;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
 
            //get the name of current process, i,e the process 
            //name of this current application
 
            string currPrsName = Process.GetCurrentProcess().ProcessName;
 
            //Get the name of all processes having the 
            //same name as this process name 
            Process[] allProcessWithThisName= Process.GetProcessesByName(currPrsName);
 
            //if more than one process is running return true.
            //which means already previous instance of the application 
            //is running
            if (allProcessWithThisName.Length > 1)
            {
                MessageBox.Show("The Application Already Running""MY APP"MessageBoxButtons.OK);
                Application.Exit();
               // allProcessWithThisName[0].Kill();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else
            {  
                frmMain mainForm = new frmMain(); //this takes ages 
                Application.Run(mainForm);
            }
        }
 
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject != null)
                ErrorLog((Exception)e.ExceptionObject);
        }
 
        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            if (e.Exception != null)
                ErrorLog(e.Exception);
        }            
 
    }
}





 //Windows application Error Log

using System.IO;
       
 public static void ErrorLog(string sMessage)
        {
            StreamWriter objSw = null;
            try
            {
                string sFolderName = Application.StartupPath + @"\Logs\";
                if (!Directory.Exists(sFolderName))
                    Directory.CreateDirectory(sFolderName);
                string sFilePath = sFolderName + "Error.log";

                objSw = new StreamWriter(sFilePath, true);
                objSw.WriteLine(DateTime.Now.ToString() + " " + sMessage + Environment.NewLine);

            }
            catch (Exception ex)
            {
                Comman.ErrorLog("Error -" + ex.Message);
            }
            finally
            {
                if (objSw != null)
                {
                    objSw.Flush();
                    objSw.Dispose();
                }
            }
        }





Check Allready Application Running:

string currPrsName = Process.GetCurrentProcess().ProcessName;

//Get the name of all processes having the
//same name as this process name
Process[] allProcessWithThisName
= Process.GetProcessesByName(currPrsName);

//if more than one process is running return true.
//which means already previous instance of the application
//is running
if (allProcessWithThisName.Length > 1)
{
MessageBox.Show("Application Already Running", "Test", MessageBoxButtons.OK);
Application.Exit();
}
else
{
Application.Run(new frmMain());
}

-->

Friday, September 2, 2011

Adding Row in SQL SELECT Query statment


select 'Select All' as RallyNumber
union all
Select RallyNumber from MatchData

Tuesday, July 19, 2011

CSS for ASP.Net Button mouse over to change button colour

.forbuttons
{
border-style: none;
background-color: #0079C1;
color: #FFFFFF;
font-family: arial;
font-size: 13px;
font-weight: bold;
padding-top: 4px;
padding-bottom: 4px;
/* Mozilla: */
background: -moz-linear-gradient(top, #2bc4f3, #0095da);
/* Chrome, Safari:*/
background: -webkit-gradient(linear,
left top, left bottom, from(#2bc4f3), to(#0095da));
/* MSIE < 8 */
filter: progid:DXImageTransform.Microsoft.Gradient(
StartColorStr='#2bc4f3', EndColorStr='#0095da', GradientType=0);
/* IE 8*/
-ms-filter: progid:DXImageTransform.Microsoft.gradient(
startColorstr='#2bc4f3', endColorstr='#0095da');

}
.forbuttons:hover{
background: -moz-linear-gradient(top, #0095da, #2bc4f3);
/* Chrome, Safari:*/
background: -webkit-gradient(linear,
left top, left bottom, from(#0095da), to(#2bc4f3));
/* MSIE < 8 */
filter: progid:DXImageTransform.Microsoft.Gradient(
StartColorStr='#0095da', EndColorStr='#2bc4f3', GradientType=0);
/* IE 8*/
-ms-filter: progid:DXImageTransform.Microsoft.gradient(
startColorstr='#0095da', endColorstr='#2bc4f3');
}

.forbuttons:active{
background-color:#3399FF;
color:#FFF;
}

Thursday, December 3, 2009

Default Button click

Default button click in asp.net:

Form.DefaultButton = imgLogin.UniqueID;

Friday, November 20, 2009

How to use Google Map in ASP.NET

The Javascript:


<head runat="server">

<title>Google map Page</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAA6TS6WR4jbbUjikFVO_rihBSsoQeukxbo2NPugNeooGWFf_yQhRSk4JGGBtb5COzcswcwgPpu5XJo3Q"

type="text/javascript"></script>
<script type="text/javascript">

var map=null;

var Head = 'style="color:White;background-color:#339900;font-family:Verdana;font-size:11px;font-weight:bold;"';

var Data = 'style="background-color:#ffff99;font-family:Verdana;font-size:11px;overflow:auto; "';

var gmarkers = [];

var ghtml = [];

var m = 0;



function load()

{

if (GBrowserIsCompatible())

{

var LatitudePoint='<%= LatitudePoint %>';

var LongitudePoint='<%= LongitudePoint %>';

var RestaurantName='<%= RestaurantName%>';

var RestaurantAddress='<%=RestaurantAddress%>';



var map = new GMap(document.getElementById("map"));

var point = new GPoint(LatitudePoint,LongitudePoint);

map.addControl(new GLargeMapControl());

map.setCenter(new GLatLng(LatitudePoint,LongitudePoint), 5 );



function createMarker(point,Html)

{

var marker = new GMarker(point);



GEvent.addListener(marker, "click", function()

{

//marker.openInfoWindowHtml('<div class="infodescription">'+Html+'</div>');

marker.openInfoWindowHtml(Html);

});

return marker;

}

var request = GXmlHttp.create();

request.open("GET", "parks.xml", true);

request.onreadystatechange = function()

{

if (request.readyState == 4)

{

var xmlDoc = request.responseXML;

var points = xmlDoc.documentElement.getElementsByTagName("park");

for (var i = 0; i < points.length; i++)

{

var point = new GPoint(LongitudePoint,
LatitudePoint);

var cHtml = '<table cellspacing=0 cellpading=0 border=1>' +
'<tr>' +
'<td align="center">' + RestaurantName + '</td>' +
'</tr>'+
'<tr>' +
'<td>' + RestaurantAddress + '</td>' +
'</tr>' +
'</table>';


var marker = createMarker(point,cHtml);

map.addOverlay(marker);

marker.openInfoWindowHtml(cHtml);

}
}
}
request.send(null);

}
}
</script>
</head>

<body onload="load()">

<form id="form1" runat="server">

<div>

<div id="map" style="width: 700px; height: 590px;">

</div>
</div>
</form>
</body>


The XML File: (parks.xml)


<parks>

<park FullName="Test" address="8,GN Road" lng="80.2385401725769" lat="13.048898223457536"/>

<park FullName="Birds Fort Trail Park" address="575 North Usman Road" lng="80.2496401725769" lat="13.059898223457536"/>

</parks>


Asp.Net C# Coding:


public string LatitudePoint = "12.916051";

public string LongitudePoint = "80.024414";

public string RestaurantName = "Rangish";

public string RestaurantAddress = "";

public string strRestaurantID = string.Empty;

protected void Page_Load(object sender, EventArgs e)

{



LatitudePoint = "70.5896";

LongitudePoint = "80.2568";

RestaurantName = "Test Name";

RestaurantAddress = "Dharapuram";

}

}

Monday, July 13, 2009

image Insert & Select

Insert:

string strImageFileExt;
string imageName;

if (fuProductImage.FileName.ToString().Trim() != "")
{
strImageFileExt = fuProductImage.FileName.Substring(fuProductImage.FileName.LastIndexOf(".") + 1).ToLower();
imageName = ddlMovieName.SelectedItem.Text.Trim()+ "." + strImageFileExt;;
Save(imageName);

}



string strtest = "insert into Abirami_MovieDetails values('" + ddlMovieName.SelectedItem.Text.Trim() + "','" + imageName + "')";

SqlCommand sqlCmd = new SqlCommand(strtest, conn);
sqlCmd.ExecuteNonQuery();


Save Image Function:
private void Save(string imageName)
{

if (imageName != null && imageName.Trim() != "")
{
System.Drawing.Image objImage = null;
if (fuProductImage.HasFile)
{
objImage = System.Drawing.Image.FromStream(fuProductImage.FileContent);
System.Drawing.Image objSmallImage = objImage.GetThumbnailImage(161, 206, objTIA, IntPtr.Zero);
objSmallImage.Save(Server.MapPath("../AbiramiImages/" + imageName.Trim().Replace(" ", " ").Replace(" ", "_").Replace(":", "_").Replace("(", "_").Replace(")", "_")));
}
}
}



select:

SqlCommand cmd = new SqlCommand("select V_MovieProducer,V_MovieDirector,V_MovieMusicDirector,V_MovieWriter,V_MovieCast,V_MovieImage,V_Synopsis,V_StartDate,V_EndDate from Abirami_MovieDetails where V_MovieName='" + ddlMovieName.SelectedItem.Text.Trim() + "'", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtProducer.Text = dr["V_MovieProducer"].ToString();
strImage = "../AbiramiImages/" + dr["V_MovieImage"].ToString().Trim();
if (System.IO.File.Exists(Server.MapPath(strImage)) == true)
{
Image1.ImageUrl = strImage;
}
else
{
Image1.ImageUrl = "../MovieImages/Image_Not_Available.gif";
}
}
dr.Close();

Thursday, July 9, 2009

Stored Procedure code in DAL

public DataSet GetOnlineTicketsReport(DateTime dStartDate,DateTime dEndDate,string strScreenName, string strShowTime)
{

MySqlCommand cmd = new MySqlCommand("LMT_GetReport", Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("?DD_StartDate", MySqlDbType.Datetime);
cmd.Parameters["?DD_StartDate"].Value = dStartDate;
cmd.Parameters.Add("?DD_EndDate ", MySqlDbType.Datetime);
cmd.Parameters["?DD_EndDate "].Value = dEndDate;
cmd.Parameters.Add("?VV_ScreenName ", MySqlDbType.VarChar, 50);
cmd.Parameters["?VV_ScreenName "].Value = strScreenName;
cmd.Parameters.Add("?VV_ShowTime ", MySqlDbType.VarChar, 50);
cmd.Parameters["?VV_ShowTime "].Value = strShowTime;
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}