Blog Archives
asp .net could not establish trust relationship for the SSL/TLS secure channel
A quick google search revealed multiple reported resolutions, however, after following the steps in the MSDN blog reference listed below, the issue was still unresolved in my situation.
Additional details in the stack trace will reveal another similar message: “The remote certificate is invalid according to the validation procedure.”
In this specific scenario, the site in question is either not configured with a wildcard certificate for a subdomain of the parent site or the operation system I am working on does not support SNI. In the meantime, a workaround is needed to continue testing and development.
Additional reading on google revealed another solution which was more suitable and utilized a code based approach, as opposed to a server configuration based solution.
To make it more dynamic, I added a key into the app/web config to control if SSL errors should be ignored. Please note that it is also possible to replace the code based approach solely with an app/web config entry listed in the west-wind blog referenced below, but I personally prefer to go with code whenever possible.
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=servername;Initial Catalog=databasename;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ignoresslerrors" value="true"/>
</appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
public class ConfigValues
{
public static string IgnoreSSLErrors { get { return getval("ignoresslerrors"); } }
}
public function main() {
connect("https://sitename.com",ConfigValues.IgnoreSSLErrors);
}
public function connect(string url, string ignoresslerrors) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
if (Convert.ToBoolean(ignoresslerrors))
{
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; //will always accept the cert and ignore errors. this is not good common practice unless you are sure of the destination you are connecting to. needed in this scenario to continue development until issue with cert is resolved.
};
}
}
catch (Exception ex)
{
Shared.HandleError(ex);
}
}
References
http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors
c# .net split strings with math divrem using lambda linq
Recently I came across a nice alternative to loops using linq for evenly splitting a string using Math.DivRem.
The following example illustrates how this can be used to parse a sequence of numbers based on a time series which may give variable results in a custom messaging protocol.
(inspired by R. Prestol)
//not the complete classes but satisfies the below example
class message {
string series {get;set;}
}
string[] series = message.series.Split(' '); //will NOT throw an exception if series string is empty
int Rem = 0;
int d = Math.DivRem(name.Length, 2, out Rem); //hardcoded two for simplicity in this example
//valueB will contain the same value as valueA if there is no second value in the sequence
string valueA = string.Join(" ", sentence.Take(Math.Max(d, 1)).ToArray());
string valueB = string.Join(" ", sentence.Skip(d).Take(d + Rem).ToArray());
int average = (Convert.ToInt32(valueA) + Convert.ToInt32(valueB)) / 2; //2 would also need to be dynamic here
Console.WriteLine(average.ToString());
//potential input
//100 101
//100
//output for average
//first input: 100
//second input: 100
A significant figure is lost (.5) on first input since valueA and valueB are converted to int. Conversion to decimal, double etc would of course maintain this detail depending on the rounding you are looking for.
lastChild is null in FireFox works in IE invalid nodeType javascript c# asp .net
This issue alluded me at first as it works in IE but not in FF. See code below.
//pass in table, last cell number and style to apply to it. call this on hover and blur for cell highlight effects. alternatively you can determine last cell number as well and this function could be rewritten to work solely for the purpose of modifying specific cells rather than last cell
function ChangeTableCellStyle(tableid,cellnumber,mystyle) {
if (document.getElementById)
{
var selectedElement = document.getElementById(tableid);
selectedElement.className = style;
//change style on end cell by drilling into table. this will become deprecated by css3.
if (selectedElement.tagName.toLowerCase()=="table")
{
var tbody = selectedElement.lastChild;
if (tbody!=null)
{
var tr = tbody.lastChild;
if (tbody !=null)
{
var tr = tbody.lastChild; //BUGGED IN FF!
//nodetype should be 1 for element type. in FF it is 3. see reference link at bottom for list of types.
if (tr.nodeType!=1) {
tr.tbody.getElementsByTagName("td");
tr[cellnumber].className+= ' ' + mystyle;
} else {
tr.lastChild.className+=' ' + mystyle;
}
}
}
}
}
}
//example usage
ChangeTableCellStyle("table1",3,"cellend"); //will append the class cellend to the last cell in table1 if table1 only has 4 cells per row
In you’re interested in reviewing other approaches to styling your table cells, see my similar article here.
system.windows.resourcedictionary. source threw an exception wpf c#
In general this issue is caused when a referenced resource cannot be found.
<Application x:Class="AppName.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
In my specific circumstance, as the xaml above details, this issue was caused by a reference to PresentationFramework.Aero DLL that was not contained in the output bin folder of the compiled project. Under references, setting Copy Local to true did the trick for me.
.NET Map Drive in C# (WPF)
Complete class reference updated for WPF (not yet tested). For backwards compatibility, previous Win32 code maintained in code comments (and just replace ‘Window’ with ‘Form’).
/// <summary>
/// Network drive interface from original application slightly modified to handle WPF windows.
/// </summary>
public class NetworkDrive
{
#region API
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2A(ref structNetResource pstNetRes, string psPassword, string psUsername, int piFlags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);
[DllImport("mpr.dll")]
private static extern int WNetConnectionDialog(int phWnd, int piType);
[DllImport("mpr.dll")]
private static extern int WNetDisconnectDialog(int phWnd, int piType);
[DllImport("mpr.dll")]
private static extern int WNetRestoreConnectionW(int phWnd, string psLocalDrive);
[StructLayout(LayoutKind.Sequential)]
private struct structNetResource
{
public int iScope;
public int iType;
public int iDisplayType;
public int iUsage;
public string sLocalName;
public string sRemoteName;
public string sComment;
public string sProvider;
}
private const int RESOURCETYPE_DISK = 0x1;
//Standard
private const int CONNECT_INTERACTIVE = 0x00000008;
private const int CONNECT_PROMPT = 0x00000010;
private const int CONNECT_UPDATE_PROFILE = 0x00000001;
//IE4+
private const int CONNECT_REDIRECT = 0x00000080;
//NT5 only
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_CMD_SAVECRED = 0x00001000;
#endregion
#region Propertys and options
private bool lf_SaveCredentials = false;
/// <summary>
/// Option to save credentials are reconnection...
/// </summary>
public bool SaveCredentials
{
get { return (lf_SaveCredentials); }
set { lf_SaveCredentials = value; }
}
private bool lf_Persistent = false;
/// <summary>
/// Option to reconnect drive after log off / reboot ...
/// </summary>
public bool Persistent
{
get { return (lf_Persistent); }
set { lf_Persistent = value; }
}
private bool lf_Force = false;
/// <summary>
/// Option to force connection if drive is already mapped...
/// or force disconnection if network path is not responding...
/// </summary>
public bool Force
{
get { return (lf_Force); }
set { lf_Force = value; }
}
private bool ls_PromptForCredentials = false;
/// <summary>
/// Option to prompt for user credintals when mapping a drive
/// </summary>
public bool PromptForCredentials
{
get { return (ls_PromptForCredentials); }
set { ls_PromptForCredentials = value; }
}
private string ls_Drive = "s:";
/// <summary>
/// Drive to be used in mapping / unmapping...
/// </summary>
public string LocalDrive
{
get { return (ls_Drive); }
set
{
if (value.Length >= 1)
{
ls_Drive = value.Substring(0, 1) + ":";
}
else
{
ls_Drive = "";
}
}
}
private string ls_ShareName = "\\\\Computer\\C$";
/// <summary>
/// Share address to map drive to.
/// </summary>
public string ShareName
{
get { return (ls_ShareName); }
set { ls_ShareName = value; }
}
#endregion
#region Function mapping
/// <summary>
/// Map network drive
/// </summary>
public void MapDrive() { zMapDrive(null, null); }
/// <summary>
/// Map network drive (using supplied Password)
/// </summary>
public void MapDrive(string Password) { zMapDrive(null, Password); }
/// <summary>
/// Map network drive (using supplied Username and Password)
/// </summary>
public void MapDrive(string Username, string Password) { zMapDrive(Username, Password); }
/// <summary>
/// Unmap network drive
/// </summary>
public void UnMapDrive() { zUnMapDrive(this.lf_Force); }
/// <summary>
/// Check / restore persistent network drive
/// </summary>
public void RestoreDrives() { zRestoreDrive(); }
/// <summary>
/// Display windows dialog for mapping a network drive
/// </summary>
public void ShowConnectDialog(Window ParentForm) { zDisplayDialog(ParentForm, 1); }
/// <summary>
/// Display windows dialog for disconnecting a network drive
/// </summary>
public void ShowDisconnectDialog(Window ParentForm) { zDisplayDialog(ParentForm, 2); }
#endregion
#region Core functions
// Map network drive
private void zMapDrive(string psUsername, string psPassword)
{
//create struct data
structNetResource stNetRes = new structNetResource();
stNetRes.iScope = 2;
stNetRes.iType = RESOURCETYPE_DISK;
stNetRes.iDisplayType = 3;
stNetRes.iUsage = 1;
stNetRes.sRemoteName = ls_ShareName;
stNetRes.sLocalName = ls_Drive;
//prepare params
int iFlags = 0;
if (lf_SaveCredentials) { iFlags += CONNECT_CMD_SAVECRED; }
if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
if (ls_PromptForCredentials) { iFlags += CONNECT_INTERACTIVE + CONNECT_PROMPT; }
if (psUsername == "") { psUsername = null; }
if (psPassword == "") { psPassword = null; }
//if force, unmap ready for new connection
if (lf_Force)
{
try { zUnMapDrive(true); }
catch { }
}
//call and return
int i = WNetAddConnection2A(ref stNetRes, psPassword, psUsername, iFlags);
if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
}
// Unmap network drive
private void zUnMapDrive(bool pfForce)
{
//call unmap and return
int iFlags = 0;
if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
int i = WNetCancelConnection2A(ls_Drive, iFlags, Convert.ToInt32(pfForce));
if (i != 0) i = WNetCancelConnection2A(ls_ShareName, iFlags, Convert.ToInt32(pfForce)); //disconnect if localname was null
if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
}
// Check / Restore a network drive
private void zRestoreDrive()
{
//call restore and return
int i = WNetRestoreConnectionW(0, null);
if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
}
// Display windows dialog
private void zDisplayDialog(Window poParentForm, int piDialog)
{
int i = -1;
int iHandle = 0;
//get parent handle
if (poParentForm != null)
{
IntPtr hwnd = (new WindowInteropHelper(poParentForm)).Handle;
iHandle = hwnd.ToInt32(); //poParentForm.Handle.ToInt32();
}
//show dialog
if (piDialog == 1)
{
i = WNetConnectionDialog(iHandle, RESOURCETYPE_DISK);
}
else if (piDialog == 2)
{
i = WNetDisconnectDialog(iHandle, RESOURCETYPE_DISK);
}
if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
//set focus on parent form
//poParentForm.BringToFront();
poParentForm.Activate();
poParentForm.Topmost = true;
}
#endregion
}
References
StackOverflow (blog), http://stackoverflow.com/questions/3465182/how-to-map-a-drive-using-c
PINVOKE (code references and snippets), http://pinvoke.net/default.aspx/Structures/NETRESOURCE.html
MSDN (info on class types and structures), http://msdn.microsoft.com/en-us/library/windows/desktop/aa385341%28v=vs.85%29.aspx
Common WPF Resource Dictionaries
Skinning a WPF application is as simple as adding an assembly reference (PresentationFramework.Aero) and xml config change. See below.
<Application.Resources>
<Application.Resources>
<ResourceDictionary>
<!-- -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application.Resources>
Other sources:
<ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/> <ResourceDictionary Source="/PresentationFramework.Classic;component/themes/Classic.xaml"/> <ResourceDictionary Source="/PresentationFramework.Royale;component/themes/Royale.NormalColor.xaml"/> <ResourceDictionary Source="/PresentationFramework.Luna.Homestead;component/themes/Luna.Homestead.xaml"/> <ResourceDictionary Source="/PresentationFramework.Luna.Metallic;component/themes/Luna.Metallic.xaml"/> <ResourceDictionary Source="/PresentationFramework.Zune;component/themes/Zune.NormalColor.xaml"/>
References
StackOverflow, http://stackoverflow.com/questions/2075720/windows-7-theme-for-wpf
Serialize C# object to JSON JavaScriptSerializer .Net
//declare data you want to send as an object type
public class MyType {
//may simply contain properties mapping to your database rows or be more complex objects
//use [Serializable] attributes to mark props or methods as non-serialized
}
public void Page_Load(object sender, EventArgs e) {
MyType o1 = new MyType {p1="",p2=""};
Response.Write(JSONSerialize(o1));
Response.Write("<br /><br />");
MyType o2 = new MyType {p1="",p2=""};
List<MyType> olist = new List<MyType> {o1, o2};
Response.Write(JSONSerialize(olist));
}
public string JSONSerialize(MyType o) {
System.Web.Script.Serialization.JavaScriptSerializer sz =
new System.Web.Script.Serialization.JavaScriptSerializer();
return sz.Serialize(o);
}
//additional signature to handle lists of object
public string JSONSerialize(List<MyType> o) {
System.Web.Script.Serialization.JavaScriptSerializer sz =
new System.Web.Script.Serialization.JavaScriptSerializer();
return sz.Serialize(o);
}
References
MS Blogs, http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx
JSON.org, http://www.json.org/js.html
C# Cross-Site Page Access, http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method
PHP Cross-Site Page Access, http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
JS Eval string to JSON Object, http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
WCF Service Library in Windows Service
References
CodeProject (WCF Service in Windows Service), http://www.codeproject.com/KB/WCF/WCF_windows_hosting.aspx
MSDN (Debug Windows Service Applications), http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.80).aspx
MSDN (Host WCF Service in Managed Windows Service), http://msdn.microsoft.com/en-us/library/ms733069.aspx

