using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO;
public static class EncryptionUtils { public static byte[] GenerateKey() { RijndaelManaged provider = new RijndaelManaged(); provider.GenerateKey(); return provider.Key; } public static byte[] GenerateIV() { RijndaelManaged provider = new RijndaelManaged(); provider.GenerateIV(); return provider.IV; } public static string Decrypt(byte[] encryptedBytes, byte[] key, byte[] iv) { RijndaelManaged provider = new RijndaelManaged(); MemoryStream ms = new MemoryStream(); using (CryptoStream cryptoStream = new CryptoStream(ms, provider.CreateDecryptor(key, iv), CryptoStreamMode.Write)) { cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length); } return Encoding.UTF8.GetString(ms.ToArray()); } public static byte[] Encrypt(string value, byte[] key, byte[] iv) { RijndaelManaged provider = new RijndaelManaged(); byte[] valueBytes = Encoding.UTF8.GetBytes(value); MemoryStream ms = new MemoryStream(); using (CryptoStream cryptoStream = new CryptoStream(ms, provider.CreateEncryptor(key, iv), CryptoStreamMode.Write)) { cryptoStream.Write(valueBytes, 0, valueBytes.Length); } return ms.ToArray(); }
Sunday, November 29, 2015
Simple Encryption and Decryption Class C#
Saturday, January 10, 2015
Maintain JQuery Tab Active Position on PostBack C#
First, add your JQuery script tags in the head section.
<link href="../jquery-ui-1.11.1.custom/jquery-ui.min.css" rel="stylesheet"></link> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>Next, add this script inside the header to initiate your tabs.
<script>
$(function () {
$("#tabs").tabs();
});
</script>
Next, add this script function to the bottom of the page. This script will get the value from the hiddenfield control after PostBack.
<script type="text/javascript">
$(function () {
$("#tabs").tabs({
activate: function () {
var selectedTab = $('#tabs').tabs('option', 'active');
$("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
},
active: <%= hdnSelectedTab.Value %> + ""
});
});
</script>
Next, add this hiddenfield control. This will be used to set the active tab when the PostBack occurs.
<asp:hiddenfield id="hdnSelectedTab" runat="server"> </asp:hiddenfield>Finally, set the value of the hiddenfield control to the appropriate tab. To reset the value, set the value to 0 when the page is not a PostBack.
protected void btnCalShipping_Click(object sender, EventArgs e)
{
hdnSelectedTab.Value = "1";
}
Monday, August 18, 2014
Accessing Network Users Email With LDAP
In the snippet below, I will show you how to access the current users email address. As you begin to explore the Active Directory, remember that "mail" is only one of many attributes that you can accessed through LDAP. For more, go here. Happy Coding!! :)
You'll need to reference DirectoryServices in your project.
using System.DirectoryServices; using System.Security.Principal;
public static string DisplayEmail(IIdentity id)
{
string email = string.Empty;
var winId = id as WindowsIdentity;
if (id == null)
{
return "Identity is not a windows identity";
}
var userInQuestion = winId.Name.Split('\\')[1];
var myDomain = winId.Name.Split('\\')[0];
var entry = new DirectoryEntry("LDAP://" + myDomain);
var adSearcher = new DirectorySearcher(entry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))"
};
var userObject = adSearcher.FindOne();
if (userObject != null)
{
email = string.Format("{0}", userObject.Properties["mail"][0]);
}
return email;
}
Typically, I put functions like this in my Utility class but you can put it where ever you see fit. Below is an example of how to execute this function.
var email = Utility.DisplayUser(WindowsIdentity.GetCurrent());
Saturday, February 1, 2014
Binding returned data from an Ajax call to a Gridview
You'll need the JQuery reference in the head section.
<script src ="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type ="text/javascript">
For this first function you'll need to change the url in the ajax call to either the page your creating the Ajax call or the page your getting the post from which can also be a web service or handler. Then don't forget to set the method name after the page or web service your calling.
function Button1_onclick() {
$.ajax({
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
url: "AjaxTest.aspx/GetTransactionData",
dataType: "xml",
success: OnSuccess,
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#errmsg").ajaxError(function (event, request, settings) {
$(this).append("<li>Error requesting page " + settings.url + "</li>");
});
}
});
return false;
}
The next function will loop through the returned xml and append a table row for each row found in the xml to the Gridview.
function OnSuccess(xml) {
debugger;
try {
$(xml).find('Table1').each(function () {
var id_text = $(this).find('ID').text();
var name_text = $(this).find('Description').text();
$('#<%=GridView1.ClientID %>').append("<tr><td>" + id_text + "</td><td>" + id_text + "</td</tr>");
});
}
catch (err) {
var txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.description + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
Below is the form example used to initiate the ajax call.
<input id="Button1" type="button" value="Get XML" onclick="return Button1_onclick()" />
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
Finally, this is where you'll fill the data that gets returned to the client side. You'll need to add a WebMethod to your ".CS" page then create your data table and fill it from either a direct database call or web service to return the xml. In the example below, I'm creating my initial data table columns in the Page_Load so that when the Ajax call returns, it knows what columns are mapped to the Gridview.
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Script.Services; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls;
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID");
table.Columns.Add("Description");
table.Rows.Add();
GridView1.DataSource = table;
GridView1.DataBind();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static string GetTransactionData()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Description");
dt.Rows.Add("1", "Description 1");
dt.Rows.Add("2", "Description 2");
dt.Rows.Add("3", "Description 3");
dt.Rows.Add("4", "Description 4");
dt.Rows.Add("5", "Description 5");
DataSet m_dsDataSet = new DataSet("pageDataSet");
m_dsDataSet.Tables.Add(dt);
string strXml = m_dsDataSet.GetXml();
return strXml;
}
Monday, January 27, 2014
Binding Nested Detailsview in Gridview
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
// Make sure we aren't in header/footer rows
if (row.DataItem == null)
{
return;
}
DetailsView dv = (DetailsView)row.FindControl("DetailsView1");
List<[object]> aList = List<[object]>();
if (e.Row.RowType == DataControlRowType.DataRow)
{
aList[e.Row.RowIndex].Name = aList[e.Row.RowIndex].Name;
dv.DataSource = aList.Where(u => u.ID == Convert.ToInt32(aList[e.Row.RowIndex].Address)).ToList();
dv.DataBind();
}
}
Wednesday, December 25, 2013
Using Htmlframe tag instead of Iframe tag
<controls> <add assembly="System.Web" namespace="System.Web.UI.HtmlControls"
tagprefix="asp"/> </controls>
<asp:HtmlIframe frameborder="0" height="650" id="myiframe" name="myiframe" runat="server" src="prefcontent.aspx" width="400"> </asp:HtmlIframe>
Friday, May 10, 2013
Locating IP Original Origin C#
private const string _hostIPUrl = "http://api.hostip.info/";
public string GetLocation()
{
WebClient client = new WebClient();
Uri uri = new Uri(String.Format("{0}", _hostIPUrl));
List location = new List();
string xmlString = client.DownloadString(uri).ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("gml", "http://www.opengis.net/gml");
XmlNode cityLocation = doc.SelectSingleNode("//HostipLookupResultSet/" +
"gml:featureMember/Hostip/gml:name/text()", manager);
return cityLocation.Value;
}
Wednesday, May 8, 2013
Developing a Custom VMConnect Application
Developing a Custom VMConnect Application
Tuesday, May 7, 2013
.NET 4.0 Routing
public static void RegisteredRoutes(RouteCollection routes)
{
routes.MapPageRoute("Home", "", "~/Default.aspx");
routes.Add(new Route("Contact", new ContactRouteHandler()));
}
WPF Button Menu
By setting "ContextMenuService.IsEnabled=False" in your button and adding the code below to your button click this should resolve that issue. In the example below you'll see how to setup your button to display a menu when clicked. Have Fun ☺
< Button x:Name="btnMenu" Content="Menu" HorizontalAlignment="Left" Height="30" ContextMenuService.IsEnabled="False" Width="100" Click="btnMenu_Click">
< Button.ContextMenu>
< ContextMenu>
< MenuItem Header="Menu 1" />
< MenuItem Header="Menu 1" />
< MenuItem Header="Menu 1" />
< MenuItem Header="Menu 1" />
< Separator />
< MenuItem Header="Second Menu">
< MenuItem Header="Menu 2" />
< MenuItem Header="Menu 2" />
< MenuItem Header="Menu 2" />
< MenuItem Header="Menu 2" />
< Separator />
< MenuItem Header="Third Menu" />
< / MenuItem>
< / ContextMenu>
< / Button.ContextMenu>
< / Button>
private void btnMenu_Click(object sender, RoutedEventArgs e)
{
(sender as Button).ContextMenu.IsEnabled = true;
(sender as Button).ContextMenu.PlacementTarget = (sender as Button);
(sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
(sender as Button).ContextMenu.IsOpen = true;
}
Sunday, May 5, 2013
Async Emails C#
protected void Page_Load(object sender, EventArgs e)
{
MailMessage msg = new MailMessage();
MailAddress from = new MailAddress("[YOUR EMAIL]");
msg.Subject = "[SUBJECT]";
msg.Body = "[BODY]";
List emailList = new List();
emailList.Add("email@email1.com");
emailList.Add("email@email2.com");
foreach (string str in emailList)
{
SendEmail(msg, str, from, true);
}
}
public static void SendEmail(MailMessage m, string to, MailAddress from, Boolean Async)
{
SmtpClient smtpClient = null;
NetworkCredential SMTPUserInfo = new NetworkCredential("[YOUR EMAIL]", "[YOUR PASSWORD]");
smtpClient = new SmtpClient("[SMTP SERVER]", 587);
smtpClient.Credentials = SMTPUserInfo;
smtpClient.EnableSsl = true;
m.To.Clear();
m.To.Add(to);
m.From = from;
if (Async)
{
SendEmailDelegate sd = new SendEmailDelegate(smtpClient.Send);
AsyncCallback cb = new AsyncCallback(SendEmailResponse);
sd.BeginInvoke(m, cb, sd);
}
else
{
smtpClient.Send(m);
}
}
private delegate void SendEmailDelegate(System.Net.Mail.MailMessage m);
private static void SendEmailResponse(IAsyncResult ar)
{
SendEmailDelegate sd = (SendEmailDelegate)(ar.AsyncState);
sd.EndInvoke(ar);
}
Saturday, May 4, 2013
Email messages with embedded images
public void SendImbeddedEmail()
{
var logo = new LinkedResource(@"C:\logo.jpg");
string from = "[EMAIL ADDRESS]";
string to = "[EMAIL ADDRESS]";
var subjust = "[EMAIL SUBJECT LINE]";
logo.ContentId = Guid.NewGuid().ToString();
var body = string.Format(@"< html >< body >< h1 >
Image< /h1 >
< img cid:="" src="" />< /body >< /html >", logo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(logo);
SmtpClient client = new SmtpClient("[SMTP SERVER]");
using (var message = new MailMessage(from, to)
{
Subject = subjust,
Body = body,
IsBodyHtml = true
})
{
message.AlternateViews.Add(view);
client.Send(message);
}
}
Google Weather
HttpWebRequest theGoogleRequest = null;
HttpWebResponse theGoogleResponse = null;
XmlDocument theGoogleXMLdoc = null;
StringBuilder theStringBuilder = new StringBuilder();
try{
theGoogleRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api?weather="
+ "Lenexa, KS");
theGoogleResponse = (HttpWebResponse)theGoogleRequest.GetResponse();
theGoogleXMLdoc = new XmlDocument();
theGoogleXMLdoc.Load(theGoogleResponse.GetResponseStream());
XmlNode root = theGoogleXMLdoc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("weather/current_conditions");
XmlNodeList nodeList1 = root.SelectNodes("weather/forecast_conditions");
current_temp.Text = nodeList.Item(0).SelectSingleNode("temp_f").Attributes["data"].InnerText;
hi_temp.Text = nodeList1.Item(0).SelectSingleNode("high").Attributes["data"].InnerText;
lo_temp.Text = nodeList1.Item(0).SelectSingleNode("low").Attributes["data"].InnerText;
condition_icon.Text = "< img src=" + "'" + "http://google.com" +
nodeList.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText + "'" + " alt='' /> ";
condition.Text = nodeList.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText;
string theWindSpeed = nodeList.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerXml;
Match theMatch = Regex.Match(theWindSpeed, "(?:\\d+)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (theMatch.Success)
{
condition_wind.Text = theMatch.Value;
}
}
catch (System.Exception ex)
{
ErrorHelper.LogError("weather:Page_Load", ex);
}
finally
{
theGoogleResponse.Close();
}