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);
}