Monday, June 8, 2009

PGP encrypt and sign a file with GnuPG

In order to PGP encrypt and sign a file for transfer, the following items will be needed:


  • GnuPG open source software found here


  • A private PGP Key and the corresponding public key to provide the client.


  • A clients public PGP Key.


  • A file to be encrypted.



1. Install GnuPG onto the server responsible for encrypting the file.

2. Install the keys and give proper trust level onto the server that will be encrypting the files:
gpg --import [Filename] (installs a clients public key on server)

gpg --edit [name of key] (sets trust level of client public key)
command> trust
command> 4
command> y


3. View fingerprints of keys (if needed)
gpg --fingerprint (this will show the fingerprint to the keys)


4. Execute PGP command on file gpg --passphrase-fd 0 -u %sender% -r %recipient% --yes -a --quiet --output %outfilename% --sign --encrypt %filename%

5. If the encryption will be done within an application, this key can be added to the configuration and used in a "GeneratePGPFile" function call:


6. Main Function:
protected bool GeneratePGPFile(string recipient, string filename, ref string outFilename)
{
  try
  {
    string gpgCommand = ConfigurationSettings.AppSettings["GPGCommand"];
    string gpgKeyName = ConfigurationSettings.AppSettings["GPGKeyName"];
    string gpgPassPhrase = ConfigurationSettings.AppSettings["GPGPassPhrase"]); (if needed)
    string gpgFilename = outFilename;

    gpgCommand = gpgCommand.Replace("%passphrase%", gpgPassPhrase);
    gpgCommand = gpgCommand.Replace("%sender%", string.Format("\"{0}\"", gpgKeyName));
    gpgCommand = gpgCommand.Replace("%recipient%", string.Format("\"{0}\"", recipient));
    gpgCommand = gpgCommand.Replace("%filename%", string.Format("\"{0}\"", filename));
    gpgCommand = gpgCommand.Replace("%outfilename%", string.Format("\"{0}\"", gpgFilename));

    System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("cmd.exe");

    psi.CreateNoWindow = true;
    psi.UseShellExecute = false;
    psi.RedirectStandardInput = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.WorkingDirectory = Path.GetDirectoryName(filename);

    System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
process.StandardInput.WriteLine(gpgCommand);

    process.StandardInput.Flush();
    process.StandardInput.Close();
    process.WaitForExit();
    process.Close();

    if (!File.Exists(gpgFilename)) {
      return false;
    }

  return true;
  }
  catch (Exception ex)
  {
    HandleError(ex);
    return false;
  }
}

Friday, May 29, 2009

Using onclick with ListItem within RadioButtonList Control

Below is a way to add an onclick event into the ListItems of a RadioButtonList Control:


Static RadioButtonList and ListItems within HTML
<asp:RadioButtonList id="citizenRbl" runat="server" RepeatDirection="Horizontal">
<asp:ListItem value="uscitizen" text="US Citizen"></asp:ListItem>
<asp:ListItem value="residentalien" text="Resident Alien"></asp:ListItem>
<asp:ListItem value="nonresidentalien" text="Non-Resident Alien"></asp:ListItem>
</asp:RadioButtonList>

Code Behind - add the onclick event to the parent control of the ListItems
citizenRbl.Attributes.Add("onclick", "CheckCitizenSelection('"+citizenRbl.ClientID+"')");

Javascript
<script language="Javascript">
function CheckCitizenSelection(rblID){
var rbl = document.getElementById(rblID);
var options = rbl.getElementsByTagName('input');
for(jj=0; jj<options.length; jj++)
{
  var cbox = options[jj];
  if(cbox.checked && cbox.value == "nonresidentalien"){
    alert('You choice was non-resident alien');
  }
}
}
</script>

Friday, May 8, 2009

Add client on click to asp repeater

To add a client side onclick event to buttons in a repeater, use the scenario below as a reference.


Within the web form:
<asp:Repeater ID="ItemsRpt" Runat="server">
  <ItemTemplate>
    <tr>
      <td><%#DataBinder.Eval(Container.DataItem, "ItemName")%></td>
      <td>
        <asp:Button ID="DeleteBtn" Runat="server" Visible=<%#System.Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "canDelete"))%> Text="Delete" CommandArgument=<%#DataBinder.Eval(Container.DataItem, "ItemId")%> CommandName="DeleteItem" CssClass="Btn" CausesValidation="False"></asp:Button>
      </td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

Within the code behind "InitializeComponent"
this.ItemsRpt.ItemCreated += new RepeaterItemEventHandler(ItemsRpt_ItemCreated);

and then...
private void PositionsRpt_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  if (e.Item.DataItem != null)
  {
    Button btn = e.Item.FindControl("DeleteBtn") as Button;
    if (btn != null) {
      btn.Attributes.Add("onclick", "return confirm('Confirm the deletion of this item');");
    }
  }
}

Monday, April 6, 2009

SSRS check for blank parameters

Within an SSRS .rdl file you may want to check to see if a Parameter is null before you try to filter results, below are a couple solutions:

=IIf((LEN(Parameters!range.Value)>0), Parameters!range.Value, Fields!range.Value)

=IIf(IsNothing(Parameters!range.Value), Fields!range.Value, Parameters!range.Value)

Sunday, April 5, 2009

DataBinder if else solution

Below is an example that will allow two different images to be displayed in an image control based on the DataBinder.Eval result.

<img src="<%# (Convert.ToInt32(DataBinder.Eval(Container.DataItem, "availabilityId")) == 1) ? "/images/available.gif" : "/images/scheduled.gif"%>" alt="schedule" id="scheduleImg" style="border:none"/>

Monday, December 8, 2008

Use ICallbackEventHandler interface for asynchronous calls to the server

A simple way to perform asynchronous calls to the server from the client is by using the ICallbackEventHandler interface in .NET 2.0.

1.) Create a class and specify ICallbackEventHandler interface:
public partial class TestClass : System.Web.UI.UserControl, ICallbackEventHandler

2.) Implement ICallbackEventHandler.RaiseCallbackEvent and ICallbackEventHandler.GetCallbackResult()
private string results;
void ICallbackEventHandler.RaiseCallbackEvent(string argument)
{
string[] list;
int i=0;
string id= argument.ToLower();
DataView dv = RetrieveData(argument);
list = new string[dv.Table.Rows.Count];

foreach (DataRow row in dv.Table.Rows)
{
list[i] = row[1].ToString() + "," + row[2].ToString();
i++;
}
results = String.Join("-", list);

return;
}

string ICallbackEventHandler.GetCallbackResult()
{
return results;
}


3.) Create async call-back function for use on client side.
private string GetDataRefreshScript()
{
StringBuilder sb = new StringBuilder("function RefreshResults(data){");
sb.AppendLine(Page.ClientScript.GetCallbackEventReference(this, "data", "UpdateData","null", "UpdateData_Error", true));
sb.AppendLine("}");
sb.AppendLine(GetUpdateDataScript());

return sb.ToString();
}


4.) Create client script to handle data retreived from server through async call.
private string GetUpdateDataScript()
{
StringBuilder sb = new StringBuilder("function UpdateData(response, context) {");
sb.AppendLine("var id = document.getElementById(\"" + ResultsGrid.ClientID + "\");");
sb.AppendLine("if(id != null){");
sb.AppendLine("var rows = new Array();");
sb.AppendLine("rows = response.split(\"-\");");
sb.AppendLine("for(j=0; j sb.AppendLine("var tmpRow = rows[j];");
sb.AppendLine("addResultGridRow(id, tmpRow);\r\n}}}");

//Error
sb.AppendLine("function UpdateData_Error(response, context) {");
sb.AppendLine("var err = document.getElementById(\"" + errorMessage.ClientID +"\");");
sb.AppendLine("if(err != null){");
sb.AppendLine("err.innerHTML = 'Error processing data.';");
sb.AppendLine("err.style.visibility = 'visible';\r\n}}");

return sb.ToString();
}


5.) The last thing that needs done is triggering the async call from client
btn.Attributes.Add("onmousedown", "RefreshResults('" + data + "')");

Communicate data between two browser windows

To communicate data between two browser windows "window.opener" can be of assistance. window.opener returns a reference to the window that opened the current window. So this mock function below should be inserted into the opened window.
Make note that "__datatarget" and "__datawindow" are two variables that were defined in the parent window.

function SetData(data)
{
  if ((window.opener != null)
  && (!window.opener.closed)
  && (window.opener.__datatarget != null))
  {
    var changed = (window.opener.__datatarget.value != data);
    window.opener.__dataetarget.value = employee;
    window.opener.__datawindow.value = null;
    if (changed)
      window.opener.__datatarget.fireEvent("onchange");
  }
window.close();
}