using System;
using System.Data;
using System.Globalization;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Sensor.Gateway.DataXfer;
public partial class GatewayFileSubmit : System.Web.UI.Page
{
// Keys used in the Xfer service
string secretKey = "Secret";
string storeKey = "SensorStore";
string dbKey = "DBConnection";
string absPath = "AbsStorePath";
// Params used
string sigParam = "signature";
string stageName = "Stage";
// variables used
string fileSHA1;
string connString;
string path, storePath;
protected void Page_Load(object sender, EventArgs e)
{
try
{
// Get the params needed
fileSHA1 = Request[sigParam];
if (fileSHA1 == null) { throw new ArgumentNullException("fileSHA1"); }
}
catch
{
Response.Write("Incorrect parameters. Check signature");
return;
}
HttpFileCollection uploadFiles = Request.Files;
// Build HTML listing the files received.
string summary = "";
// Loop over the uploaded files and save to disk.
int i;
for (i = 0; i < uploadFiles.Count; i++)
{
HttpPostedFile postedFile = uploadFiles[i];
SetEnvironment(postedFile.FileName);
// Access the uploaded file's content in-memory:
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
// Check the SHA-1 of the file
if (fileSHA1 == null)
{
Response.Write("SHA-1 absent ... aborting");
return;
}
// append date to the filename
string fname = AppendDateToFilename(postedFile.FileName);
// bool fileIntegrity = CheckFileSha1(fileData, fileSHA1, postedFile.FileName);
//Test
bool fileIntegrity = true;
if (fileIntegrity)
{
// Process File
int bytes = postedFile.ContentLength;
if (CheckEmptyFile(bytes))
{
Response.Write(fname + " file is empty. Nothing to do ...");
return;
}
// Save the posted file in our "data" virtual directory.
// if the file passes the check.
//TODO: uncomment
postedFile.SaveAs(Server.MapPath(storePath) + fname);
//connString = "Data Source=LEMON\\LEMON;Initial Catalog=BrazilStage;User Id=koala;Password=koala123;";
GatewayFileProcessor fp = new GatewayFileProcessor(path, fname, bytes, connString);
summary += fp.ProcessFile();
}
else
{
Response.Write("SHA-1 does not match ... aborting");
return;
}
}
Response.Write(summary);
}
#region Helper Functions
///
/// compares the SHA-1 of the file recieved
/// with the signature sent by the sender
///
///
///
///
public bool CheckFileSha1 (byte[] fileData, string fileSHA1, string filename)
{
byte[] secretPhrase = AppendSecretPhrase (fileData, filename);
string shaResult;
SHA1 sha = new SHA1CryptoServiceProvider();
shaResult = Bytes2String(sha.ComputeHash(secretPhrase));
return ShaCompare(shaResult, fileSHA1);
}
///
/// Compares the SHA-1 strings
///
///
///
///
public bool ShaCompare(string shaResult, string fileSHA)
{
if (shaResult.CompareTo(fileSHA) == 0)
{
return true;
}
return false;
}
///
/// The secret phrase is appended to the data file
/// using the BlockCopy function. The resulting
/// array is returned
///
///
///
public byte[] AppendSecretPhrase (byte[] fileData, string filename)
{
byte[] concat;
// Get the secret phrase
string secret = filename + System.Configuration.ConfigurationManager.AppSettings[secretKey];
byte[] secretBytes = new System.Text.ASCIIEncoding().GetBytes(secret);
// append the secret phrase
concat = new byte[fileData.Length + secretBytes.Length];
System.Buffer.BlockCopy(fileData, 0, concat, 0, fileData.Length);
System.Buffer.BlockCopy(secretBytes, 0, concat, fileData.Length, secretBytes.Length);
return concat;
}
///
/// Helper function that converts Bytes to String
/// and prints it in hex format
///
///
///
public string Bytes2String(byte[] input)
{
string hex = BitConverter.ToString(input);
hex = hex.Replace("-", "");
return hex;
}
///
/// Appends the system date to the name of the file.
///
///
///
public string AppendDateToFilename(string fname)
{
// Get the current time from the system.
DateTime dt = DateTime.Now;
string currDt = dt.ToString("s", DateTimeFormatInfo.InvariantInfo);
currDt = currDt.Replace(":", "-");
string storeName = fname + "." + currDt;
return storeName;
}
public bool CheckEmptyFile(int numBytes)
{
if (numBytes < 8)
return true;
else
return false;
}
public void SetEnvironment(string fname)
{
string[] tmp = fname.Split('.');
string dbName = tmp[0];
string stage = dbName + stageName;
// Build up the key for the required DB
connString = System.Configuration.ConfigurationManager.AppSettings[dbKey];
// Replace DB name in connString
connString = connString.Replace("XXX", stage);
// obtain the store location
path = System.Configuration.ConfigurationManager.AppSettings[absPath] + dbName;
storePath = System.Configuration.ConfigurationManager.AppSettings[storeKey] + dbName + "/";
}
#endregion Helper functions
}