11 Replies - 1321 Views - Last Post: 17 March 2014 - 09:08 AM Rate Topic: -----

#1 icebox68   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-February 14

Classes and Functions in C#

Posted 07 March 2014 - 04:57 AM

Hello,

I am new to using C# for producing web forms and just wondered if someone could please help clarify a few questions I have regarding classes and functions.

1.) Is it generally recommended to use classes for every function that you have? For example, if you have the below function, would it be recommended to encapsulate this in a class?

public string testFunction()
{
//Perform function functionality
}

public string anotherTestFunction()
{

}

Is This A Good Question/Topic? 0
  • +

Replies To: Classes and Functions in C#

#2 icebox68   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-February 14

Re: Classes and Functions in C#

Posted 07 March 2014 - 05:03 AM

2.) Should you only use classes for a group of functions that relate to a particular task? For example, would the following be a good use of classes?

Class Person
{
function string getAge(int age)
{

}

function string getHeight(int height)
{

}
}

public string getPersonDetails
{
Person myPerson = new Person();
myPerson.getAge(12);
myPerson.getHeight(123);

}

Any help would be much appreciated.
Was This Post Helpful? 0
  • +
  • -

#3 AndrewMack   User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 55
  • Joined: 12-April 13

Re: Classes and Functions in C#

Posted 07 March 2014 - 05:21 AM

You need to understand the purpose of classes/OOP.

This will get you started - the man is a great teacher.
Classes and Objects tutorial
Was This Post Helpful? 0
  • +
  • -

#4 Momerath   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1021
  • View blog
  • Posts: 2,463
  • Joined: 04-October 09

Re: Classes and Functions in C#

Posted 07 March 2014 - 07:06 AM

View Posticebox68, on 07 March 2014 - 03:57 AM, said:

1.) Is it generally recommended to use classes for every function that you have? For example, if you have the below function, would it be recommended to encapsulate this in a class?

Not only is it recommended, it is required. C# does not allow methods to exist outside of a class.
Was This Post Helpful? 0
  • +
  • -

#5 icebox68   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-February 14

Re: Classes and Functions in C#

Posted 07 March 2014 - 07:11 AM

I thought this too, but I managed to call a function from within another function without encapsulating it within a class, as shown below:

	 protected void GridView1_RowCreated(object sender, GridViewCommandEventArgs e)
	 {
		 // We are checking against the "ADD" 
 
		if (e.CommandName == "ADD")
 
		{
 	
		string dob = ((TextBox)display_data.FooterRow.FindControl("txtAddDOB")).Text;
 
		string email = ((TextBox)display_data.FooterRow.FindControl("txtAddEmail")).Text;
 
		AddNewRecord(email, dob); 
 
		}
 
	 }
	 
	 private void AddNewRecord(string email, string dob) 
	 {
		 	OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
			dbconn.Open();  
		 	
 			string strUpdate = ("INSERT INTO tbl_clients (client_email, client_dob) VALUES ('" + email + "', '" + dob + "')");
			
			OleDbCommand cmdUpdate = new OleDbCommand(strUpdate, dbconn);

    		cmdUpdate.ExecuteNonQuery();
        	dbconn.Close();
			
			display_data.EditIndex = -1;
			
					confirmation.InnerHtml="Add command triggered";
        
			BindData();

	 }



This is what has confused me. I know that it is general practice when writing programs in C# but thought the rules might be slightly different when developing websites in C#.
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6817
  • View blog
  • Posts: 23,191
  • Joined: 05-May 12

Re: Classes and Functions in C#

Posted 07 March 2014 - 07:30 AM

Really now? Show us all your code. I'm quite sure there is a class encapsulating those methods.

If you are using WebForms, the @Page directive actually starts a class definition.
Was This Post Helpful? 0
  • +
  • -

#7 icebox68   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-February 14

Re: Classes and Functions in C#

Posted 07 March 2014 - 07:34 AM

This is the code I am using, which runs perfectly fine:

<%@ Page Language="C#"%>

<%@ import namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.Mail" %>
<%@ Import Namespace="System.Globalization" %>
<%@ import Namespace="System.Collections.Generic" %>
<%@ import Namespace="System.Drawing" %>

<script runat="server">

protected void page_load()
{

}

private void Send_Emails(object sender, EventArgs e)
{
		try
		{
		
		OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
			
		dbconn.Open();
		
		//string strSQL = "SELECT * FROM tbl_clients";
		
		string strSQL = "SELECT * FROM tbl_clients WHERE client_DOB IS NOT NULL AND client_DOB NOT LIKE '%/' AND client_email IS NOT NULL AND client_email NOT LIKE '%NA' AND client_email NOT LIKE '%N/A'";
		
		OleDbDataReader reader1;
		OleDbCommand cmd1 = new OleDbCommand(strSQL, dbconn);	
		
		DataSet ds = new DataSet();
		OleDbDataAdapter da = new OleDbDataAdapter(strSQL, dbconn);  
		
		da.Fill(ds);   
		
		display_data.DataSource = ds;
        display_data.DataBind();     
  	
		reader1 = cmd1.ExecuteReader();
		
		DateTime todaysDate;
		todaysDate = DateTime.Today;
		
		string strTodaysDate;
		
		strTodaysDate = todaysDate.ToString("dd/MM");
		
		string email = null;
		string dob = null;
		
		//List<string> newList = new List<string>();
				
		if (reader1.HasRows)
		{
			while (reader1.Read())
			{
				
			dob = Convert.ToString(reader1["client_dob"]).Substring(0,5);
			
			//DateTime.ParseExact(Convert.ToString(reader1["client_dob"]), "dd/MM", CultureInfo.InvariantCulture);
			
			email = Convert.ToString(reader1["client_email"]);

			if (email != null && email.Contains("@"))
			{
				if (dob == strTodaysDate)
				{		
					//newList.Add(email);
					
					string message;
		
					message = "Happy Birthday from The Beauty Retreat!";

					MailMessage mail = new MailMessage();

					mail.From = "[email protected]";
					
					mail.To = email;
					mail.Subject = "Happy Birthday";
					mail.Body = message;
					mail.BodyFormat = MailFormat.Text;
					SmtpMail.SmtpServer = "217.174.252.38";
					SmtpMail.Send(mail);
	
				}
			 }

		  }
		}	
		
		btnRun.Visible = false;
		confirmation.InnerHtml = "Emails sent! Please now close this browser window and do not run again until tomorrow.";
		btnClose.Visible = true;
				
		reader1.Close();
		dbconn.Close();
		
		}
		catch(Exception ex)
		{
			confirmation.InnerHtml = "An error has occured with this process:" + ex; 
		}
		
			/*string str = null; 
				
				  	foreach(string value in newList)
			{
					str = str + value + ". ";
			}
			
			confirmation.InnerHtml = str;*/

	}
	
	private void BindData()
	{
		OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
			
		dbconn.Open();
		
		//string strSQL = "SELECT * FROM tbl_clients";
		
		string strSQL = "SELECT * FROM tbl_clients WHERE client_DOB IS NOT NULL AND client_DOB NOT LIKE '%/' AND client_email IS NOT NULL AND client_email NOT LIKE '%NA' AND client_email NOT LIKE '%N/A'";
		
		DataSet ds = new DataSet();
		OleDbDataAdapter da = new OleDbDataAdapter(strSQL, dbconn);  
		
		da.Fill(ds);        
        
        display_data.DataSource = ds;
        display_data.DataBind();
		
		dbconn.Close();
		
	}

	protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
	{
   		display_data.EditIndex = e.NewEditIndex;
   		BindData();        
	}

	protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
	{
   		e.Cancel = true;
   		display_data.EditIndex = -1;
   		BindData();        
	}

	protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
	{
   		GridViewRow row = display_data.Rows[e.RowIndex];
		
		int id = Convert.ToInt32(display_data.DataKeys[e.RowIndex].Value.ToString());
   
   		//TextBox txtEmail = (TextBox)row.FindControl("txtEmail");
		//TextBox txtID = (TextBox)row.Cells[1].Controls[0];
		
		string email = ((TextBox)display_data.Rows[e.RowIndex].FindControl("txtEmail2")).Text;
		string dob = ((TextBox)display_data.Rows[e.RowIndex].FindControl("txtDOB2")).Text;
		
		//TextBox txtEmail = (TextBox)row.Cells[1].Controls[0];
		//TextBox txtDOB = (TextBox)row.Cells[3].Controls[0];

   		//int productID = Convert.ToInt32(display_data.DataKeys[e.RowIndex].Value["client_id"].ToString());
		//string email = display_data.DataKeys[e.RowIndex].Values["lblEmail"].ToString();
		//int productID = Convert.ToInt32(display_data.DataKeys[e.RowIndex].Value.ToString());
		
		//int ID = (int)display_data.DataKeys[e.RowIndex].Value;
   
   		//int id = Convert.ToInt32(txtID.Text);
   		//string email = txtEmail.Text;
		//string dob = txtDOB.Text;

		OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
		dbconn.Open();
		
		string strSQL = "UPDATE tbl_clients SET client_dob = '" + dob + "', client_email = '" + email + "' WHERE client_id = " + id + "";
			
		OleDbCommand cmdUpdate = new OleDbCommand(strSQL, dbconn);
        
        cmdUpdate.Connection = dbconn;

        cmdUpdate.CommandText = strSQL;
   
   		//cmdUpdate = new OleDbCommand(strUpdate, dbconn);

        cmdUpdate.ExecuteNonQuery();
		
		dbconn.Close();
		
		display_data.EditIndex = -1;
        
		BindData();

	}
	
	protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        display_data.PageIndex = e.NewPageIndex;
        BindData();
    }
	
	 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
     {
		GridViewRow row = display_data.Rows[e.RowIndex];
		
		int id = Convert.ToInt32(display_data.DataKeys[e.RowIndex].Value.ToString());

		OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
		dbconn.Open();
		
		string strSQL = "DELETE FROM tbl_clients WHERE client_id = " + id + "";

		OleDbCommand cmdUpdate = new OleDbCommand(strSQL, dbconn);
        
        cmdUpdate.Connection = dbconn;

        cmdUpdate.CommandText = strSQL;
   
   		//cmdUpdate = new OleDbCommand(strUpdate, dbconn);

        cmdUpdate.ExecuteNonQuery();
		
		dbconn.Close();
		
		display_data.EditIndex = -1;
        
		BindData();
		
	 }

	 
	 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
	 { 
		OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
		dbconn.Open();     
		 
        switch (e.SortExpression)
            {
                case "Email":
                    if (e.SortDirection == SortDirection.Ascending)
                    {
						string strSQL1 = "SELECT * FROM tbl_clients WHERE client_DOB IS NOT NULL AND client_DOB NOT LIKE '%/' AND client_email IS NOT NULL AND client_email NOT LIKE '%NA' AND client_email NOT LIKE '%N/A' ORDER BY client_email ASC";
		
						OleDbDataAdapter dataadapter1 = new OleDbDataAdapter(strSQL1, dbconn);
		
						DataSet ds1 = new DataSet();
		
        				dataadapter1.Fill(ds1);   
						
                        display_data.DataSource = ds1;
                        display_data.DataBind();
                    }
                    else
                    {
						string strSQL2 = "SELECT * FROM tbl_clients WHERE client_DOB IS NOT NULL AND client_DOB NOT LIKE '%/' AND client_email IS NOT NULL AND client_email NOT LIKE '%NA' AND client_email NOT LIKE '%N/A' ORDER BY client_email DESC";
		
						OleDbDataAdapter dataadapter2 = new OleDbDataAdapter(strSQL2, dbconn);
		
						DataSet ds2 = new DataSet();
		
        				dataadapter2.Fill(ds2);  
						
                        display_data.DataSource = ds2;
                        display_data.DataBind();
                    }

                    break;
					
					case "DOB":
					if (e.SortDirection == SortDirection.Ascending)
                    {
						string strSQL3 = "SELECT * FROM tbl_clients WHERE client_DOB IS NOT NULL AND client_DOB NOT LIKE '%/' AND client_email IS NOT NULL AND client_email NOT LIKE '%NA' AND client_email NOT LIKE '%N/A' ORDER BY client_dob ASC";
		
						OleDbDataAdapter dataadapter3 = new OleDbDataAdapter(strSQL3, dbconn);
		
						DataSet ds3 = new DataSet();
		
        				dataadapter3.Fill(ds3);   
						
                        display_data.DataSource = ds3;
                        display_data.DataBind();
                    }
                    else
                    {
						string strSQL4 = "SELECT * FROM tbl_clients WHERE client_DOB IS NOT NULL AND client_DOB NOT LIKE '%/' AND client_email IS NOT NULL AND client_email NOT LIKE '%NA' AND client_email NOT LIKE '%N/A' ORDER BY client_dob DESC";
		
						OleDbDataAdapter dataadapter4 = new OleDbDataAdapter(strSQL4, dbconn);
		
						DataSet ds4 = new DataSet();
		
        				dataadapter4.Fill(ds4);  
						
                        display_data.DataSource = ds4;
                        display_data.DataBind();
                    }

                    break;
			}
	}
	
		 
	 protected void GridView1_RowCreated(object sender, GridViewCommandEventArgs e)
	 {
		 // We are checking against the "ADD" 
 
		if (e.CommandName == "ADD")
 
		{
 	
		string dob = ((TextBox)display_data.FooterRow.FindControl("txtAddDOB")).Text;
 
		string email = ((TextBox)display_data.FooterRow.FindControl("txtAddEmail")).Text;
 
		AddNewRecord(email, dob); 
 
		}
 
	 }
	 
	 private void AddNewRecord(string email, string dob) 
	 {
		 	OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("main2.mdb"));
			dbconn.Open();  
		 	
 			string strUpdate = ("INSERT INTO tbl_clients (client_email, client_dob) VALUES ('" + email + "', '" + dob + "')");
			
			OleDbCommand cmdUpdate = new OleDbCommand(strUpdate, dbconn);

    		cmdUpdate.ExecuteNonQuery();
        	dbconn.Close();
			
			display_data.EditIndex = -1;
			
					confirmation.InnerHtml="Add command triggered";
        
			BindData();

	 }
	 
	 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
     {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // determine the value of the UnitsInStock field
            int ID = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "client_id"));
            if (ID == 1735)
                // color the background of the row yellow
                e.Row.BackColor = System.Drawing.Color.Brown;
        }
 
    }


</script>



Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Classes and Functions in C#

Posted 07 March 2014 - 07:50 AM

There is a tutorial linked in my signature block for classes. Also just about every intro book published covers this.
Was This Post Helpful? 0
  • +
  • -

#9 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5105
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Classes and Functions in C#

Posted 07 March 2014 - 02:03 PM

As Skydiver mentioned, in WebForms, the @Page directive is actually a class definition, so your functions are encapsulated in a class.

C# is not C++. Named Methods/Functions are members of classes and structs. That's it. They can't exist outside them. It's not just organization, it's a property of the language itself.
Was This Post Helpful? 0
  • +
  • -

#10 icebox68   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-February 14

Re: Classes and Functions in C#

Posted 17 March 2014 - 07:17 AM

Thanks for your help everyone. I understand the @Page directive is actually a class definition, so functions are encapsulated in a class, however, is it still thought good practice in web forms to include more specific classes that represent specific functionality areas? For example, if I just included methods without any classes (knowing that they are encapsulated in a class anyway) would this be considered acceptable? I ask this because sometimes it's not always possible to organise methods into classes.

Thanks in advance!
Was This Post Helpful? 0
  • +
  • -

#11 Momerath   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1021
  • View blog
  • Posts: 2,463
  • Joined: 04-October 09

Re: Classes and Functions in C#

Posted 17 March 2014 - 08:35 AM

It is always possible to organize methods into classes, who told you otherwise?

And yes, you should include more specific classes. Why use on OO language if you aren't going to do any OO programming?
Was This Post Helpful? 0
  • +
  • -

#12 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5105
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Classes and Functions in C#

Posted 17 March 2014 - 09:08 AM

I'd like to ask, why are you putting your code directly in the ASPX file? Why not use codebehind files (aspx.cs) to make your code more organized and readable?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1