RavenDB Document Database – Super Quickstart Guide

Raven-info0RavenDB is among the many available document databases on the market today (mongo, redis, etc.). If you‚Äôre looking to try this db and see if it‚Äôs right for your project, below is a super quick guide to start using using RavenDB on Windows with asp.net. Below are my 10 simple steps to start using. You can skip to the bottom for entire “source” code.¬† Continue reading “RavenDB Document Database – Super Quickstart Guide”

RavenDB Document Database – Super Quickstart Guide

Uploading a file via FTP in .net c#

uploadRemember when uploading a file via ftp was more a pain and took some third party components for stability? Now I have more trust in the .net method, below is a function I use for uploading a file:

You could call this function like:

ftpFile("current.jpg",@"C:\temp\some.jpg");

And the function: Continue reading “Uploading a file via FTP in .net c#”

Uploading a file via FTP in .net c#

MVC / Validating an email address with DataAnnotation

If you’re using MVC and want to capture an email address, there is a great built-in way to validate the address. When creating your model, add the¬†[EmailAddress] DataAnnotation like below.

 [Required]
 [EmailAddress]
 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
 [DataType(DataType.EmailAddress)]
 [Display(Name = "Email Address")]
 public string Email { get; set; }

Then you can add to your view:

 <li>
 <%: Html.LabelFor(m => m.Email) %>
 <%: Html.TextBoxFor(m => m.Email) %>
 </li>

And if you enter an invalid email you’ll get the error:

Invalid Email Address

MVC / Validating an email address with DataAnnotation

Adding a forgot password / reset function to MVC c#

If you’re using any of the out-of-the-box mvc template projects (Visual Studio 2012 / c#), they do a great job with including functionality for user membership including log in, register and change password. However it does seem to be missing a ‘forgot password’ or ‘reset password’ function. Below is how you can quickly add this functionality by modifying the existing controllers and views:

1. Add a new view (I’m calling mine ResetPass) under the Views > Account folder:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ledme2.Models.LoginModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Reset Pass
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <hgroup class="title">
        <h1>Reset Your Password</h1>
    </hgroup>

    <section id="loginForm">
        <h2>Enter the username you wish to reset. An email will be sent with your password and the new password will expire in 3 hours.</h2>
        <% using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
           { %>
        <%: Html.AntiForgeryToken() %>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Enter the username you wish to reset. An email will be sent with your password and the new password will expire in 3 hours.</legend>
            <ol>
                <li>
                    <%: Html.LabelFor(m => m.UserName) %>
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </li>
            </ol>
            <input type="submit" value="Reset" />
        </fieldset>

        <% } %>

        <% if (ViewData["msg"] != null)
           { %>
        <%: ViewData["msg"] %>
        <% } %>
    </section>
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>

<asp:Content ID="Content4" ContentPlaceHolderID="ScriptsSection" runat="server">
</asp:Content>

2. Add these two methods to the AccountController.cs (I’ve left out the code w/ the email function, feel free to add your own):

 [AllowAnonymous]
        public ActionResult ResetPass(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPass(LoginModel model, string returnUrl)
        {
            if (WebSecurity.UserExists(model.UserName))
            {
                string ptoken = WebSecurity.GeneratePasswordResetToken(model.UserName, 190);
                //change to be as secure as you choose
                string tmpPass = Membership.GeneratePassword(10, 4);
                WebSecurity.ResetPassword(ptoken, tmpPass);
                //add your own email logic here
                ViewData["msg"] = "Your new password is: " + tmpPass;
                return View(model);
            }
            else
            {
                ModelState.AddModelError("", "The user name wasn't found.");
            }

            return View(model);
        }

3. Add this code to the Login.aspx view:

<p>
            <%: Html.ActionLink("Reset", "ResetPass") %> your forgotten passord?

</p>

4. Now you should get this result on the login page:

forgot1

And when clicked:
forgot2

Adding a forgot password / reset function to MVC c#

c# Get Email Address from Active Directory (using Username) in Asp.net

dirSometimes it’s handy to grab either a username or email address (why not both?) from active directory. Below are the steps I believe you’ll need to get going quickly. In my example, I’m using VS2012 and .net 4.5.

1. Set your app to use¬†windows authentication, you’ll need to set these to debug in VS:

Your web.config:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Windows" />
    <identity impersonate="true" />

    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
</configuration>

Your project settings:

vs_winauth

2. Now in your application, add a reference to System.DirectoryServices:

dirservices

3. And in your code file:

using System.DirectoryServices;

4. A little function to search through active directory:

 private string uEmail(string uid)
        {
            DirectorySearcher dirSearcher = new DirectorySearcher();
            DirectoryEntry entry = new DirectoryEntry(dirSearcher.SearchRoot.Path);
            dirSearcher.Filter = "(&(objectClass=user)(objectcategory=person)(mail=" + uid + "*))";

            SearchResult srEmail = dirSearcher.FindOne();

            string propName = "mail";
            ResultPropertyValueCollection valColl = srEmail.Properties[propName];
            try
            {
                return valColl[0].ToString();
            }
            catch
            {
                return "";
            }

        }

5. And finally, how you can use:

string uName = "";
uName = uEmail(HttpContext.Current.User.Identity.Name.Replace(@"yourdomain\", ""));

Hope you enjoy! You can also use this method to retrieve other AD details (groups, full name, etc.).

c# Get Email Address from Active Directory (using Username) in Asp.net

c# Whole Word Matching (RegEx)

metal-detector-shmarkiiIf you’ve ever wanted to test a string to see if a word exists, but can’t use “.contains” because it doesn’t respect whole words (not that I would expect it to), below is a fast, simple way using Regex:

Of course you’ll need:¬†using System.Text.RegularExpressions;

Now setup your pattern and Regex object:

string pattern = @"\bteam\b";
Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);

Now create a match:

Match m = rx.Match("Teamwork is working together.");

Does the word exist:

if (m.Success) {
//no
}

Try again using a string with the whole word:

Match m = rx.Match("I am just part of the team.");

Does the word exist now?:

if (m.Success) {
//yes!
}

Of course, this is just a tiny portion of the power of Regex. Happy matching!

c# Whole Word Matching (RegEx)

Disable ‘Compatibility Mode’ in Internet Explorer (IE) 8 / 9

compatibilty-modeOver the past few months you put tons of time and effort into your awesome new site. However, your roll it live and find out that someone¬†accidentally¬†has¬†Compatibility Mode mode in IE turned on. Now your scripts don’t function exactly how you imagined and your layout is acting funky. There are some Meta tags that apparently take care of this if you add them to your page (<meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″ />) but personally I haven’t had great success with these. Below is the way I found best in .net to disable and turn off¬†Compatibility Mode in IE:

On your page (preferably master page in web forms or mvc) add this line:

<% Response.AddHeader(“X-UA-Compatible”, “IE=edge,chrome=1”); %>

In my case I’m adding it below the¬†<%@ Master Language=”C#” … line before the start of content (doctype).

Update: You can also easily add the header in IIS (no need to update your code) by going to ‘http response headers’ and choosing ‘add’:

iis_comp-view

 

 

 

Disable ‘Compatibility Mode’ in Internet Explorer (IE) 8 / 9

Twilio SMS Messages In Non-web .net Application with Twilio REST API (c#)

cell-phoneTwilio is a great SMS (text message) gateway to use for sending and receiving SMS messages. The process is super simple and flexible to get started using (the Twilio REST API helper library is great). However, in my case, I wanted to access the API through a “windows form” application, but the API needs a little something extra to get this to function. In my¬†experience,¬†a proxy. Below are the steps from start to finish to retrieve messages from your Twilio account: Continue reading “Twilio SMS Messages In Non-web .net Application with Twilio REST API (c#)”

Twilio SMS Messages In Non-web .net Application with Twilio REST API (c#)

Update – More Details: Retrieving Email using Exchange Web Services Managed API 2.0 (c#)

email-orange-512x512So maybe you have started to use the¬†Exchange Web Services Managed API to get email from inboxes and wanted to get a few additional details. Below are two of the most popular issues: Continue reading “Update – More Details: Retrieving Email using Exchange Web Services Managed API 2.0 (c#)”

Update – More Details: Retrieving Email using Exchange Web Services Managed API 2.0 (c#)

Retrieving and Sending Email using Exchange Web Services Managed API 2.0 (c#)

exlogoIf you haven’t already had the need, I’m sure you will at some point, to either retrieve email or send email through Exchange (not just relay or connect to Outlook) using .net. Since Microsoft introduced the Microsoft Exchange Web Services Managed API 2.0 this task has become much more¬†efficient No more clunky 2.0 type web service references etc. Below is a complete chuck of code with a few samples. One sample function sends an email, the other retrieves email messages from an inbox with the option of filters.

Continue reading “Retrieving and Sending Email using Exchange Web Services Managed API 2.0 (c#)”

Retrieving and Sending Email using Exchange Web Services Managed API 2.0 (c#)