C# — Imap via Telnet

So, connecting to Telnet via C#, most especially when the point of the whole thing is to connect to an IMAP server, is kind of a pain in the butt.  Many things I read in forums suggested giving up and paying for a library.  But finally, got this working.

using System.Net.Sockets;
using System.IO;
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace ImapMain
{
class Program
{
static void Main(String[] args)
{
TcpClient oClient = new TcpClient();
try{
NetworkStream ns = TelnetOps.GetImapServer(ref oClient);
Console.WriteLine(TelnetOps.read(ns));
TelnetOps.write(ns, @”A2 LIST “””” “”*”””);
TelnetOps.write(ns, @”A3 SELECT “”INBOX”””);
TelnetOps.write(ns, @”A4 FETCH 1 ALL”);
//TelnetOps.write(ns, @”A4 FETCH 1 BODY[Header.FIELDS (Subject)]”);
//TelnetOps.write(ns, @”A4 FETCH 1 BODY[Text]”);
TelnetOps.write(ns, @”A4 FETCH 1 BODY[]”);
ProcessEmail(TelnetOps.read(ns));
TelnetOps.write(ns, Environment.NewLine);
TelnetOps.write(ns, “A5 LOGOUT”);
ns.Close();
oClient.Close();
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(Environment.NewLine + ex.Message);
if (oClient.Connected)
oClient.Close();
}
}

public static void ProcessEmail(String rawEmail)
{
String EmailBody = GetBody(rawEmail);
String SubjectOfEmail = GetSubject(rawEmail);
}

private static String GetSubject(String rawEmail)
{
int StartOfHeader = rawEmail.IndexOf(“Subject:”) + “Subject:”.Length;
String subjectOfEmail = rawEmail.Substring(StartOfHeader);
return subjectOfEmail.Substring(0, subjectOfEmail.IndexOf(“\r”)).Trim();
}

private static String GetBody(String rawEmail)
{
int StartOfBody = rawEmail.IndexOf(“Content-Type: text/plain;”);
int EndOfBody = rawEmail.IndexOf(“Content-Type: text/html;”);
String bodyOfEmail = rawEmail.Substring(StartOfBody, EndOfBody – StartOfBody);
StartOfBody = bodyOfEmail.IndexOf(“\n”);
EndOfBody = bodyOfEmail.IndexOf(“–“);
return bodyOfEmail.Substring(StartOfBody, EndOfBody – StartOfBody);
}
}
}

namespace ImapMain
{
public static class TelnetOps
{
public static NetworkStream GetImapServer(ref TcpClient oClient)
{
try
{
AppSettingsReader apps = new AppSettingsReader();
String TelnetServer = apps.GetValue(“TelnetServer”, typeof(System.String)).ToString();
String TelnetUsername = apps.GetValue(“TelnetUsername”, typeof(System.String)).ToString();
String TelnetPassword = apps.GetValue(“TelnetPassword”, typeof(System.String)).ToString();
oClient.Connect(TelnetServer, 143);
NetworkStream ns = oClient.GetStream();
TelnetOps.write(ns, String.Format(“A1 LOGIN {0} {1}”, TelnetUsername, TelnetPassword));
return ns;
}
catch (Exception exc)
{
throw exc;
}
}

public static string read(NetworkStream ns)
{
StringBuilder sb = new StringBuilder();
if (ns.CanRead)
{
byte[] readBuffer = new byte[1024];

int someBytes = 0;

do
{
someBytes = ns.Read(readBuffer, 0, readBuffer.Length);
sb.AppendFormat(“{0}”, Encoding.ASCII.GetString(readBuffer, 0, someBytes));
}
while (ns.DataAvailable);

}

return sb.ToString();
}

public static void write(NetworkStream ns, string message)
{
byte[] msg = Encoding.ASCII.GetBytes(message + Environment.NewLine);
ns.Write(msg, 0, msg.Length);
Console.WriteLine(Environment.NewLine + read(ns));
}
}
}

Advertisement
Posted in .NET, Uncategorized | Leave a comment

Blue Border in Safari on Mac

If you’ve been cross-browser-izing your site you may have noticed that Safari (especially on a Mac) tends to add it’s own little flair.   However, when working with larger clients you tend to have incredibly picky graphic designers and computer non-literates looking over your shoulder asking “Why did you make that blue, that doesn’t look good, Stop trying to ruin my site!!”.

 

So, in case you’ve come across this particular issue, here’s how you get rid of it…

It’s a simple override, reference the closest CSS class or ID and then override the styling that Safari adds.

.CSSClassName:focus {
outline-width:0;
}

Posted in Uncategorized | Leave a comment

Automating SQL Server Backups

These instructions are assuming you have already created the database
-this is using SqlServer 2008, there will be modifications added later for SqlServer 2003 changes

Step 1 – Set up Folders
a. Add a folder called ‘DBBackupFTP’ in the ftp root
Add a folder called ‘DBBackupPublic’ in the webroot
b. Give both folders either universal priviliges or specify the sql client and a windows user that you’ll remember the login credentials to.
c. Make sure to disable directory viewing on ‘DBBackupPublic’
-if you do take the step to share this folder with sql and one user (b.), then when you attempt to download from a link in the email, you’ll have to enter that users credentials before you’ll be given access to the file.

Step 2 – Prep Sql Server
Open SSMS
a. Run the following on the server, to toggle the Sql Mail property to enabled

sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Database Mail XPs', 1; GO RECONFIGURE GO

b. Run the following to add the main stored procedure to the database
-configure the values at (a.) and (b.)(c.) and (d.) if necessary
-put your email address at (e.)

USE [ServerName] -- a. Replace with relevant Database Name (any database we have created)
GO
/****** Object: StoredProcedure [dbo].[BackUpDB] Script Date: 03/09/2010 10:29:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
CREATE PROCEDURE [BackUpDB]
-- Add the parameters for the stored procedure here
AS
BEGIN

SET NOCOUNT ON;
DECLARE @name VARCHAR(50) -- database name
DECLARE @ftppath VARCHAR(256) -- path for backup files that can be retrieved via ftp
DECLARE @dloadpath VARCHAR(256) -- path for backup files that can be downloaded
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name

SET @name = ''
SET @ftppath = 'C:\inetpub\ftproot\DBBackupFTP\' -- b. Path to the FTP root folder
SET @dloadpath = 'C:\inetpub\wwwroot\DBBackupPublic\' -- c. Path to the website root where you created that folder

SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb','ReportServer$MSSQLSERVER2008','ReportServer$MSSQLSERVER2008TempDB') -- d. Specify any databases not listed here that you do not wished to be backed up. You won't have permission to backup system databases anyway, so this will avoid bugs.

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @ftppath + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
SET @fileName = @dloadpath + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName

FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor;
DECLARE @bodyText AS varchar(255)
SET @bodyText = 'Winsvr DB Back-up'
SEt @bodyText = @bodyText + '
'
SET @bodyText = @bodyText + 'Download a Copy Here'
EXECUTE msdb.dbo.sp_send_dbmail
@profile_name = 'Sql2008Profile',
@recipients = 'sendto@gmail.com',
@body = @bodyText,
@subject = 'Winsvr DB Back-up',
@file_attachments = @fileName;

END

Step 3 – Set up Mail Profile with Database Mail
In the Object Explorer in SSMS, click on ‘Management’
The right click on Database Mail and Configure
a. Set up a new profile
-Create An Account
-Click Next, then Finish, Then go back and right click on Database Mail and go back to configure, this time you’ll create a new Profile
-Make the Profile name = Sql2008Profile
-Click Add…
-Click Next, then Finish.

b. Right Click on Database Mail, Click on Configure, Select ‘View or Change System Parameters’. Change the ‘Maximum File Size’ to 1000000000.
Click Next, Click Finish.
c. Right Click on Database Mail, Test Email, Enter your email, if this fails to send you an email, talk to your Server Admin.

** It’s now set up so you can email yourself a backup with an extra download link just by executing a stored procedure. The next step is just to automate that.

Step 4. Automate (this python script below is an option, or you can build your own script into your project)
a. Python Script, includes the need to add python and pymssql to the server

import pymssql
conn = pymssql.connect(host='SERVER2008\\MSSQLSERVER2008', user='Username', 'Password', 'DatabaseName')
cur = conn.cursor()
cur.execute('EXECUTE BackUpDB;')
conn.commit()
conn.close()

-add this script to your DBBackupPublic folder, call it dbBackup.ps. -if .bak files are protect by login, then specify that this script has full access from the http user, then add a cron job to call this script, http://webaddress/DBBackupPublic/dbBackup.ps however often you wish to receive a db backup, and your finished.

Posted in Sql Server | Leave a comment

Truncating SQL Server Log Files

It has been frequently seen in SQL Server, that despite the efforts of the DBAs, the Log Files will refuse to be truncated. However, the following snippet of T-SQL is most effective on it’s own.

USE DatabaseName
GO
DBCC SHRINKFILE(TransactionLogName, 1)
BACKUP LOG DatabaseName WITH TRUNCATE_ONLY
DBCC SHRINKFILE(TransactionLogName, 1)
GO

These are just a few of the sites I went to doing my research:
http://ss64.com/sql/dbcc_shrinkfile.html
http://msdn.microsoft.com/en-us/library/aa258824%28SQL.80%29.aspx
http://blog.sqlauthority.com/2010/05/03/sql-server-shrinkfile-and-truncate-log-file-in-sql-server-2008/

Posted in Sql Server | Leave a comment