Tuesday, January 29, 2013

Page_Load executing twice

Correct Page_Load from loading twice
Check to make sure that the .aspx page and .cs page are not both wiring up Page_Load.

.aspx page:

<%@ Page Language="C#" AutoEventWireup="false"...

.aspx.cs code behind:

private void InitializeComponent()

{
     this.Load += new System.EventHandler(this.Page_Load);
}  

If AutoEventWireup="true" and this.Load wires up the Page_Load method, either remove the manual wireup or set AutoEventWireup="false".

Thursday, January 17, 2013

WCF Adding HttpHeaders to ChannelFactory request

To add credentials to WCF ChannelFactory request:
Create Set up ChannelFactory with desired binding:
ChannelFacotry<ITest>factory = new ChannelFactory<ITest>(new BasicHttpBinding(BasicHttpSecurityMode.None));

Create proxy using EndpointAddress:
ITest proxy = factory.CreateChannel(new EndpointAddress(TheEndpointAddress));
Create OperationContextScope with the proxy:
OperationContextScope contextScope = new OperationContextScope(proxy)
Create HttpRequestMessageProperty and configure credentials:
HttpRequestMessageProperty httpHeaders = new HttpRequestMessageProperty();
httpHeaders.Headers[USERNAME_HTTP_HEADER] = Username;

httpHeaders.Headers[PASSWORD_HTTP_HEADER] = Password;

Add HttpRequestMessageProperty to the OperationContexts outgoing message properties:
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpHeaders;

Wednesday, December 5, 2012

Preserve TextBox value on PostBack when disabled

In ASP.NET, the TextBox text is not transferred back to the server when the TextBox is disabled.  If you want the TextBox to post back the text, you can add a readonly attribute to the TextBox in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
     TB1.Attributes.Add("readonly", "readonly");
}

You could also add some style to the TextBox so it appears disabled:
.disabled
{
     color:#ACA899;
}   <asp:textbox id="TB1" Runat="server" CssClass="disabled"></asp:textbox>

Wednesday, October 31, 2012

Add header variables to WCF service request using ChannelFactory

This is a way to add a specific soap header to a service request:

using (ChannelFactory factory = new ChannelFactory<ITest>(new BasicHttpBinding(BasicHttpSecurityMode.None), http://localhost/service.svc)){
 
  using(ITest proxy = factory.CreateChannel())  {
    //Sets up OperationContext so that the header can be added to soap request
    using (OperationContextScope contextScope = new OperationContextScope(proxy))
    { 
      var appHeader = new MessageHeader<string>("appID1");
          string HeaderAppString = "application";          

      OperationContext.Current.OutgoingMessageHeaders.Add(appHeader.GetUntypedHeader  (HeaderAppString, ns));
      TestCandidateResponse retVal = proxy.Print(details);   
     }
  }
}   

This action will add an "application" node in the soap header packet with the value of appID1 as seen below:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <application xmlns="ns"> appID1 </application>
  <s:Header>

<s:Body>

  .........
</s:Body>

</s:Envelope>







Tuesday, October 2, 2012

Navigate back a page instead of the last PostBack

To go back a page in history instead of the last postback, this concept can be used.
  In the code behind

1.) Preferably, in a base page, create a counter:
private int postBackCount = 0;

2.) Create a HyperLink:
protected HyperLink previousPageLink;

3.) Override ViewState management and store the counter:
protected override void LoadViewState(object savedState)
{
object[] data = (object[])savedState;   
base.LoadViewState(data[0]);   
this.postBackCount = (int)data[1];
}

protected override object SaveViewState()
{
object [] data = new object[2];   
data[0] = base.SaveViewState();   
data[1] = this.postBackCount;   
return data;
}

4.) In either Page_Load or OnPreRender, increment the counter appropriately and set the HyperLink value:
postBackCount = (IsPostBack) ? (postBackCount + 1) : 0;
previousPageLink.Attributes.Add("onclick", string.Format("Backward('{0}')", postBackCount.ToString()));



In the .aspx page
1.) Add the HyperLink
HyperLink
ID="previousPageLink" Runatimg src="/img/back.png" border="0" align="absmiddle">BackHyperLink>

2.) Add the javascript:
script type= text/javascript

function Backward(backCnt)
{
//Total number of post-backs
var refreshes = new Number(0);
//Allows the actual previous page to be selected
var offset = new Number(1);
refreshes = new Number(backCnt) + offset;
//Redirects to the actual previous page
history.go(-refreshes);
}





Thursday, August 30, 2012

Cannot evaluate expression because the code of the current method is optimized

To fix problems with debugging due to optimized code:
1.) Pull up the project Properties under the "Project" menu

2.) Select the "Build" tab

3.) Uncheck "Optimize code" under the General area

Friday, August 10, 2012

Attach a client certificate to web service request


Attach an X509 client certificate to a web service request based on the certificates FriendlyName
1.)
//using

using System.Security.Cryptography.X509Certificates;

2.)
//Create web service
WS_Service service = new WS_Service();
//Add certificate
service.ClientCertificates.Add(GetCertificate(certificateName));
service.ExecuteServiceRequest();

3.)
//Adding Certificate
private X509Certificate GetCertificate(string certName)
{
    // Look in the local machine store.
    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    X509CertificateCollection col = (X509CertificateCollection)store.Certificates;
    X509Certificate cert = null;

    for (int i = 0; i < col.Count; i++)
    {
        string friendlyName = ((X509Certificate2)col[i]).FriendlyName;
        if (friendlyName.ToLower().Trim() == certName.ToLower().Trim())
        {
            cert = col[i];
            break;
        }
    }
    return cert;
}