I.T. Discussion Community!
-Collapse +Expand
Bryan.V
Bryan Valencia
-Collapse +Expand Profile
Member Info
Member Narration

POSTS:
MB Posts (23)
KB Posts (27)
KB Comments (4)
Blog (2 Topics)

KBPOSTSBYTYPE:
Tech Articles
Code Snippets◄╣

Search Bryan.V:

Advanced

   ► KBProfile: Bryan.V  Print This    Code Snippet DB  
Bryan Valencia

Bryan Valencia's Code Snippets Page

9 Code Snippets (short code examples).

These Code Snippets are organized by our community groups then by our knowledge base sub-topics.

Expand All

Group: C# (Visual C# & VS.Net)


Topic: WebForms Coding Tasks

-Collapse +Expand 1. Consuming an RSS feed in ASP.NET
 

Using this quickie code snippet, you can attach an ASP:Gridview  to an external RSS Feed.

All you need to accomplish this is the URL of a usable feed.

Create a ASP AJAX webform, and drop in a GRIDVIEW control, and a button.  Double click the button control and add this code.  You'll need to add these two namespaces to your using section.

using System.Xml;
using System.Data;

This snippet will fill it with DICE ASP.NET open postings.

protected void Button1_Click(object sender, EventArgs e)
{
    XmlTextReader myReader = new
XmlTextReader("http://rss.dice.com//system/net-jobs.xml");
    DataSet myDataSet = new DataSet();
    myDataSet.ReadXml(myReader);
    GridView1.DataSource=myDataSet.Tables[3];
    GridView1.DataBind();
}
-Collapse +Expand 2. FileUpload
 

Demonstrates the code required to retreive and store a file uploaded via an ASP FileUpload object.  Assumes you have a web form with a FileUpload, a button, and a label control.  Also, this example stores the file uploaded into a folder named "Uploads" which is assumed to pre-exist.

string path=Server.MapPath(@"~\Uploads");
string SaveAsName=path+@"\"+FileUpload1.FileName;
try
{
FileUpload1.SaveAs(SaveAsName);
Label1.Text = FileUpload1.FileName + " uploaded.";
}
catch(Exception err)
{
Label1.Text = err.Message;
}
-Collapse +Expand 3. Get all components in an ASPX page recursively
 

Retrieves an array of all the components of any given type within a starter control (such as a page, table, panel, etc.)  This routine is recursive and will keep iterating down until all the embedded components are found.

This C# code can be invoked to produce an array as  follows:

CheckBox[] myCheckboxes = GetAllCheckboxes(Table1); 
public CheckBox[] GetAllCheckboxes(Control myControl)
{
  ArrayList myCheckboxes = new ArrayList();
 
  foreach (Control thisControl in myControl.Controls)
  {
    if (thisControl is CheckBox)
    {
      myCheckboxes.Add(thisControl);
    }
 
    if (thisControl.HasControls())
    {
      myCheckboxes.AddRange(GetAllCheckboxes(thisControl));
    }            
  }
 
  CheckBox[] result = (CheckBox[])myCheckboxes.ToArray(typeof(CheckBox));
  return result;
}
-Collapse +Expand 4. Getting Website Root Directory in C# ASP.NET
 

This code shows how to ask the webserver where the site's root directory is, and how to convert a relative path (like /Uploads) to the full filesystem path.  This will work across environments (i.e. Development/QA/Production).

string ServerPath2 = Server.MapPath(@"~/");

This gives the full path to the webserver's root directory. 

Example:

"C:\\Documents and Settings\\All Users\\Documents\\Visual Studio 2008\\WebSites\\MySite\\"

string ServerPath2 = Server.MapPath(@"~/Uploads");

This gives the full path to the Uploads subdirectory - even if it is a virtual directory in another location! 

...even if it is not a browsable web directory (such as APP_CODE or APP_DATA).

-Collapse +Expand 5. Sending email from C#.NET in 5 lines of code.
 

First, you must add the System.Net.Mail namespace to your project. There are 2 objects we use to send the email, a MailMessage, and an SMTPClient.

This code works from C# projects or from ASP.NET projects. Make sure your mail server is set to relay messages for whoever might be sending the message. In my case my webserver is sending through my exchange server so I had to tell exchange to relay for my webserver.

using System.Net.Mail;
--
MailMessage thisMessage = new MailMessage("from@here.com","to@there.com");
thisMessage.Subject = "Sending a quick email.";
thisMessage.Body = "A rolling stone gathers no moss.";

SmtpClient thisMailer = new SmtpClient("mailserver.com");
thisMailer.Send(thisMessage);
--



Group: Website Design & Hosting





Topic: Website Design

-Collapse +Expand 6. SHORTCUT ICON
 

Get rid of the boring default icon on your website.  Add a custom icon!  Most browsers support .ico and the most popular ones will show any standard web image. 

Follow this easy step by step to add one to your web page or site.

Example: This is Prestwood.com's icon. 

Images must be 16x16 pixels.  I use GIMP to create mine.

Normally, save as a .ico file in the root of your site or in any unsecured folder.  I usually put them in "/images", and I usually name it favicon.ico or favicon.gif.

Add this to the header section of your AJAX Master page or any aspx/htm/html/shtml page.

<link REL="SHORTCUT ICON" HREF="/images/favicon.gif">

Some browsers even support ANIMATED gifs.




Group: Coding & OO





Topic: General .Net Concepts

-Collapse +Expand 7. Send Email Using C#
 

This code snippet will send a very quick email. Note that this code will not work as-is. You need to have valid email accounts and a valid email server to send a real email.

You need to add: using System.Net.Mail;

 

MailMessage myMessage = new MailMessage(
"fromaddress@somewhere.com", "toaddress@somewhere.com",
"Subject", "Message Body.");
 
SmtpClient mySMTPClient = new SmtpClient("mailserver.somewhere.com"); 
mySMTPClient.Send(myMessage);



Group: DBA, Databases, & Data





Topic: Microsoft SQL Server

-Collapse +Expand 8. Easy SQL Server Backup Script
 

Learn how to make an easy SQL Server Script that will automatically back up all your databases in a simple way.

-- Back Up All Databases
-- by Bryan Valencia

--create temp table
declare @temp table(commands varchar(500), completed bit)

--load it with backup commands
insert into @temp (commands, completed)
(select
    'BACKUP DATABASE ['+name+
    '] TO  DISK = N''J:\Backups\'+name+
    '.bak'' WITH  COPY_ONLY, NOFORMAT, NOINIT,  NAME = N'''+name+
    '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD,  STATS = 10',
    0
from
    master.sys.databases
where
    owner_sid <> 0x01 and state_desc='ONLINE'
)

--variable for the current command
declare @thisCommand varchar(500);

--loop through the table
while (select count(1) from @temp where completed=0)>0
begin
    --find the first row that has not already been executed
    select top 1 @thisCommand = commands from @temp where completed=0

    --show the command in the "mesage" output window.
    print @thisCommand

    --execute the command
    EXEC (@thisCommand);

    --flag this row as completed.
    update @temp set completed=1 where commands=@thisCommand
end

--show the user the rows that have been found.
select * from @temp




Topic: MS SQL 2005

-Collapse +Expand 9. MSSQL Update Trigger Example
 

This tutorial shows how you would create a trigger in Microsoft SQL Server 2005/2008 that will date/timestamp a column named last_updated everytime any data in the row is updated.

This example assumes a primary key that includes 3 fields.

CREATE TRIGGER MyTableUpdate
ON dbo.MyTable
FOR update
AS
UPDATE
MyTable
SET last_updated = GetDate()
From MyTable Inner Join Inserted On
MyTable.KeyField1 = Inserted.KeyField1
and MyTable.KeyField2 = Inserted.KeyField2
and MyTable.KeyField3 = Inserted.KeyField3

Follow PrestwoodBoards on: 


©1995-2019 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech