a developer's notes – a semi-technical web development BLOG

May 15, 2015

Have Visual Studio build your MVC Views to check for errors.

Filed under: ASP.NET MVC — adevelopersnotes @ 5:41 pm
Tags: , , , ,

Step 1

Unload Project – Right click on project in solution explorer, select Unload Project.
Step 2

Edit Project – Right click and select ‘Edit Project and project XML will load in the editor window.
Step 3

Find false in Project XML file and change this to true.
Step 4

Save the Project XML file.
Step 5

Reload Project – Right click on the project and select ‘Reload Project’.

Now when Project compiles, views will also be compiled.

May 13, 2015

Javascript Namespace Function Expression Sample

Filed under: Javascript / JQuery — adevelopersnotes @ 12:05 pm
Tags: , ,

A sample of how to structure your JS file per page. This works good for organizational purposes and it will avoid name clashing.

var PageName = {

// define your functions as variables.
    bindCheckBox: function () {
        $("#mycheckbox").on("click", function () {
            PageName.checkboxClick();
        });
    },

    enableConfirmButton: function (bool) {
        if (bool)
            $("#mybutton").removeAttr("disabled");
        else
            $("#mybutton").attr("disabled", "disabled");
    },

    checkboxClick: function () {
        if ($("#mycheckbox").is(":checked"))
            this.enableConfirmButton(true);
        else
            this.enableConfirmButton(false);
    }
}

// Start of document.ready in jquery
$(function () {
    // calling the global variable you created.
    PageName.bindCheckBox();
});

If you want to use an Immediately Invoked Function Expression (IIFE)


(function() {
     // This creates a function that invokes itself with NO GLOBAL FUNCTIONS.
}());

March 20, 2015

Using a Segue with a custom cell in a UITableView

Filed under: IOS-Swift — adevelopersnotes @ 11:57 am
Tags: , , , ,

If you’re using custom cells or programmatically adding in a .xib file cell func prepareForSegue() won’t get called directly. You’ll have to use func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) to call the prepareForSegue method.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showDetailSeg" {
            
            if let indexPath = self.tableView.indexPathForSelectedRow() {
                let object = xmlParser.arrParsedData[indexPath.row]
                let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailsViewController
                controller.detailItem = object
                controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        self.performSegueWithIdentifier("showDetailSeg", sender: nil)
        
    }

February 13, 2015

The request was aborted: Could not create SSL/TLS secure channel

Filed under: ASP.NET,C# — adevelopersnotes @ 10:14 am
Tags: , , , , , ,

We had some trouble with posting data with a System.Net.WebClient request. We notice that it was sporadic and couldn’t figure it out. What we found out was that some calls had SecurityProtocolType.Ssl3 and other calls didn’t specify SecurityProtocolType.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

SecurityProtocolType is a static class, and what ended up happening was when one call changed the SSL type, it would affect other areas of the application. We had to explicitly set the protocol type in each request.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // or Ssl3

January 28, 2015

TFS 2010 Build Definition and Transform Files

Filed under: ASP.NET MVC,C# — adevelopersnotes @ 2:52 pm
Tags: , , ,

Here is a great blog that helped me with my build definition work with my transform files.

http://www.andygeldman.com/index.php/2011/10/web-and-app-config-transformations-with-tfs-build/

How do you specify multiple configurations like debug and release to get built by MS Build? See this answer.

http://stackoverflow.com/questions/14068750/changing-config-based-on-build-definition-tfs-2012

Some useful urls:
http://stackoverflow.com/questions/6346556/how-do-i-target-a-specific-net-project-within-a-solution-using-msbuild-from-vs2
https://msdn.microsoft.com/en-us/library/dd647547%28v=vs.110%29.aspx#projects

January 22, 2015

Cookie Tempdata Alerts with ASP.NET MVC

Filed under: ASP.NET MVC — adevelopersnotes @ 10:19 pm
Tags: , , ,

https://github.com/duyn9uyen/CookieTempDataProvideAlerts

A sample MVC Project using the CookieTempDataProvider and Bootstrap alerts. This project will illustrate how to add notifications on the serverside and client side via javascript.

Add the CookieTempDataProvider code We used the CookieTempDataProvider from:
https://github.com/KunleSmart/MvcExtensions/blob/master/src/CookieTempDataProvider.cs

Add a basecontroller that uses the CookieTempDataProvider
Added Bootstrap to project using NuGet for styling -(Added the reference to bootstrap.js and bootstrap.css in the _Layout.cshtml file.
Added notification icons (used http://www.famfamfam.com/lab/icons/silk/)
In _Layout.cshtml, moved the scripts into the tag (so that jquery will work) @Scripts.Render(“~/bundles/jquery”) @RenderSection(“scripts”, required: false)

December 19, 2014

Web API 2 – Sample HttpClient and Sample WebClient call

Filed under: C# — adevelopersnotes @ 11:29 am
Tags: , , , ,

Here is a sample request using the old WebClient.

//GET
using (var client = new WebClient())
{
	try
	{
		client.BaseAddress = "http://localhost/endpoint";
		// HTTP GET
		client.UseDefaultCredentials = true;
		jsonResponse = client.DownloadString(endpoint);
	}
	catch (WebException ex)
	{
		// Http Error
		if (ex.Status == WebExceptionStatus.ProtocolError)
		{
			HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
			var statusCode = (int)wrsp.StatusCode;
			var msg = wrsp.StatusDescription;
			throw new HttpException(statusCode, msg);
		}
		else
		{
			throw new HttpException(500, ex.Message);
		}
	}
}

//Post
public string PostRequest(string endpoint, NameValueCollection requestParams)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/x-www-form-urlencoded");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadValues(uri, "POST", requestParams);
			jsonResponse = Encoding.ASCII.GetString(response);
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}

// Post Json
public string PostRequestJson(string endpoint, string json)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/json");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadString(uri, "POST", json);
			jsonResponse = response;
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}


Here is a sample request using the new HttpClient.


HttpClientHandler handler = new HttpClientHandler()
{
	PreAuthenticate = true,
	UseDefaultCredentials = true
};


string reasonPhrase = "";
using (var client = new HttpClient(handler))
{
	client.BaseAddress = new Uri("http://localhost/endpoint");
	client.DefaultRequestHeaders.Accept.Clear();
	client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
	
	// GET
	var response = client.GetAsync(endpoint).Result;
	// Post
	// var response = client.PostAsJsonAsync("http://localhost/endpoint", obj).Result;
	
	if (response.IsSuccessStatusCode)
	{
		var result = response.Content.ReadAsStringAsync().Result;
		return result;
	}
	else
	{
		reasonPhrase = response.ReasonPhrase;
		if (reasonPhrase.ToUpper() == "UNAUTHORIZED")
		{
			throw new KeyNotFoundException("Not authorized");
		}
		var apps = response.Content.ReadAsAsync<ResponseHeader>().Result;
		if (apps.ReturnCode.ToUpper() == "NOTFOUND" )
		{		
			throw new KeyNotFoundException(apps.Result);
		}
		else
		{
			throw new SystemException(apps.Result);
		}
	}
}

December 17, 2014

Expire All Cookies in C#

Filed under: C# — adevelopersnotes @ 11:27 am
Tags: , ,
public static class CookieUtility
{
	public static void ExpireAllCookies(HttpRequestBase request, HttpResponseBase response)
	{
		// Get all cookies associated with MYA
		List<HttpCookie> cookies = new List<HttpCookie>();

		var cookieKeysArray = request.Cookies.AllKeys;

		for (int i = 0; i < cookieKeysArray.Length; i++)
		{
			HttpCookie cookie = request.Cookies[cookieKeysArray[i]];
			cookies.Add(cookie);
		}

		// Expire all cookies
		foreach (var cookie in cookies)
		{
			if (cookie != null)
				CookieUtility.ExpireCookie(response, cookie);
		}
	}
}

// From a controller
public virtual ActionResult LogOut(string logOutUrl)
{
	CookieUtility.ExpireAllCookies(Request, Response);

	return Redirect(logOutUrl);
}

// From Global.asax
var requestWrapper = new HttpRequestWrapper(Request);
var responseWrapper = new HttpResponseWrapper(Response);
CookieUtility.ExpireAllCookies(requestWrapper, responseWrapper);

TripleDes Encryption/Decryption in C#

Filed under: C# — adevelopersnotes @ 10:15 am
Tags: , , ,
public static class TripleDESUtility
{
    /// <summary>
    /// Encrypt using Triple DES.
    /// </summary>
    public static string EncryptTripleDES(string PlainText)
    {
        TripleDES des = CreateDES();
        ICryptoTransform ct = des.CreateEncryptor();
        byte[] input = Encoding.UTF8.GetBytes(PlainText);
        var output = ct.TransformFinalBlock(input, 0, input.Length);

        return Convert.ToBase64String(output);
    }

    /// <summary>
    /// Decrypt using Triple DES.
    /// </summary>
    public static string DecryptTripleDES(string CypherText)
    {
        byte[] b = Convert.FromBase64String(CypherText);
        TripleDES des = CreateDES();
        ICryptoTransform ct = des.CreateDecryptor();
        byte[] output = ct.TransformFinalBlock(b, 0, b.Length);

        return Encoding.UTF8.GetString(output);
    }

    // This is not used in the TripleDESUtility
    public static string SHA1Hash(string text)
    {
        var temp = Encoding.ASCII.GetBytes(text);
        using (SHA1Managed sha1 = new SHA1Managed())
        {
            var hash = sha1.ComputeHash(temp);

            return Convert.ToBase64String(hash);
        }
    }

    /// <summary>
    /// Create the Tripel DES encryption object instance.
    /// </summary>
    private static TripleDES CreateDES()
    {
        TripleDES des = new TripleDESCryptoServiceProvider();

        // MD5 Hashing Key
        MD5 md5 = new MD5CryptoServiceProvider();
        des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(GetKeyString()));

        des.Key = TripleDESUtility.GetKeyBytes();
        des.Mode = CipherMode.CBC;
        des.Padding = PaddingMode.PKCS7; // PKCS7 and PKCS5 algorthims are the same.

        des.IV = GetIVBytes();
        return des;
    }
    
    private static byte[] GetKeyBytes()
    {
        string encodedKey = ConfigurationManager.AppSettings["AppKeyThatContainsTheEncryptionKey"];
        
        byte[] data = Convert.FromBase64String(encodedKey);
        return data;
    }

    // Decode a base64 encoded string to a readable string
    private static string GetKeyString()
    {
        string encodedKey = ConfigurationManager.AppSettings["AppKeyThatContainsTheEncryptionKey"];

        byte[] data = Convert.FromBase64String(encodedKey);
        return Encoding.UTF8.GetString(data);
    }

    private static byte[] GetIVBytes()
    {
        string IV = ConfigurationManager.AppSettings["AppKeyThatContainsTheEncryptionKey"];

        return Convert.FromBase64String(IV);
    }
}

Simple Encryption/Decryption example in C#

Filed under: C# — adevelopersnotes @ 10:03 am
Tags: , , ,

Here are some sample code projects that I have used in the past that have worked great.

http://www.codeproject.com/Articles/33350/Encrypting-Query-Strings
http://www.codeproject.com/Tips/306620/Encryption-Decryption-Function-in-Net-using-MD-Cry
http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt

Next Page »

The Rubric Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 28 other followers