Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, November 29, 2015

Simple Encryption and Decryption Class C#

For anyone looking for a simple encryption class using Rijndael algorithm, enjoy!
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(); }

Saturday, January 10, 2015

Maintain JQuery Tab Active Position on PostBack C#

Recent, I decided to use the JQuery tabs in one of my projects.  I noticed really quickly that when I had a click event inside the tabs, it would return to the first tab.  Typically, you can use the AJAX UpdatePanel to handle partial PostBacks but in my case,  It wasn't updating correctly with other databound controls.  The snippet below will show you how to maintain your tabs on PostBack.


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

If your running an application on your personal or company network and it's using Windows Authentication, this snippet may be of some use.  This past weekend, I was at an event where I was given the task to create an application that allowed users in the network to register for a company event.  One of the many requirements was to send a confirmation email once the registration was complete.  Since this application would be used on our company network, I decided to use WindowsIdentity and DirectoryServices in the .Net framework.

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

First, I have to say this was one of my most frustrating functions I've ever created. The biggest problem I faced was trying to get the data from the Ajax call to bind to the Gridview. As you'll see in this example, once the data returns, I loop through the xml and append a table row to the 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

I recently was working on a project where I had to use an Iframe. This Iframe would get querystring parameters and pass it to the associated page in the Iframe. Now, if your using a standard .aspx page, you won't need this tip. This tip if for people that are using Iframes in their controls. Since controls use System.Web.UI.UserControl and not the standard System.Web.UI.Page that pages use. You won't be able to use the standard Iframe tag. Instead you'll need to use the server Iframe version. Before using this server tag, you'll need to add the snippet below to your web.config in the controls section. Then add the following snippet in your control. Hope this was helpful!  
 <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#

I recently was trying to write a function that would allow me to trace an IP back to it's origin or at least return the city and state.  I didn't want to use Google API or any other type of fancy API.  After a few hours of R.N.D., I found a link to a generic site that's soul purpose is to grab your current location and return XML.  As I started to write my function to parse the XML.  I realized my typical way of parsing XML was having issues because of the way this sites XML tree was assembled.  After giving it some thought, I came to the conclusion that I needed to add a namespace manager to my XML document which is called XmlNamespaceManager.  In the example below you'll see my simple approach and how I was able to resolve this issue.  Hope this helps anyone having similar issues especially when it comes to consuming XML.  Happy Coding!!!
 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

I was looking around at some .NET forums and happened to stumble across this tutorial on how to build a custom VM with C#.  It's differently a must read if your looking to either use the code in the tutorial or creating one from scratch.  You'll find out it's must easier then you expect.  Have Fun!!

Developing a Custom VMConnect Application 

Tuesday, May 7, 2013

.NET 4.0 Routing

One of the cool features in .NET 4.0 is the RouteCollection object. If your currently using MVC then this is already built-in.  When I first tried to implement this into one of my sites, the main issue I ran across was moving it to the production server.  I made sure my site was running on .NET 4.0 and added "System.Web.Routing.dll" to my bin folder but the routing still wasn't working. As you'll see in my snippet, after creating all my routes I had to create an additional one with "Route.MapPageRoute" for it to work on production.  It seemed as if it needed a starting anchor for everything to work correctly even though it was working fine on my local machine.  I probably could have resolved this issue much easier in IIS if my server was dedicated, but that wasn't the case.  There are probably better ways to do this, but this worked for me at the time.  Anyway, hope this helps anyone having the same issues. Happy Coding!!!

public static void RegisteredRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("Home", "", "~/Default.aspx");   
        routes.Add(new Route("Contact", new ContactRouteHandler()));
    }

WPF Button Menu

I'm currently working on a WPF application that needed a button that would allow users to click and display menu options.  By default when you've got a menu associated with your button you need to right click on the button to display your 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#

In the past I've had to send multiple emails at a time with a list that ranged anywhere from 1-500.  Ideally when it comes to mass emails, you should setup a dedicated IP to prevent your site from possibly becoming blacklisted.  That said, if your needing to send multiple emails what better way to accomplish that task and not slow down your application then to do it asynchronously.  I hope this example helps to get you started.  Have Fun!!!
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

In the past I've had multiple projects where I've needed to create email templates that contained images for email blast and etc..  One of the biggest issues I've come across is that most email clients don't allow you to display images.  The reasoning behind this is because images you include are being downloaded from the web which could propose security risk to either the client and or the one receiving the email.  In this example you'll see the convention to access a linked resource is "cid:name" of the linked resource, which is the value of IMG tag SRC attribute.  There's one thing to consider when doing it this way.  The function will increase the size of the email, because the images will be embedded.  Have fun!!
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

This weather function can be created a few different ways. I created labels and plugged in the values. You can also, put this into a method or place it in your Page_Load. Have Fun!!
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();   
}