Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Category: ASP.NET Page 4 of 7

Category for ASP.NET

webform_dopostbackwithoptions is undefined

A few days back I’ve got the error message “webform_dopostbackwithoptions is undefined” on the project that i’m working on.
The strange thing it happened only when I activated the securepagemodule, when i deactivated the module it works perfectly. I tried to debug it with HTTP debugger (fiddler tool) and i found that on that particular page, there is a request from webresources.axd but the request is not into https but into http and what i believe since the page is on secure mode therefore it discards the “webresources.axd” since it’s not secure. The workaround for this issue is by adding entry of “webresources.axd” under securepage and the problem is solved.

This is the sample of web.config for it

 
        
         
   </secureWebPages

NOTE:This is resolved in the new version of securepage module

Using Transaction Scope on .NET

Basic Requirements:

1. Have the MSDTC(Distributed Transaction Coordinator) windows service running on your machine
2. Be talking to a SQL 2000 or 2005 Database configured likewise
3. Run this registry script to fix the windows XP SP2 that was causing MSDTC to fail (save as “.reg”)

Registry Script

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\RPC]
"RestrictRemoteClients"=dword:00000000

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Rpc\Internet]
"Ports"=hex(7):31,00,30,00,32,00,35,00,2d,00,31,00,30,00,35,00,35,00,00,00,00,\
  00
"PortsInternetAvailable"="Y"
"UseInternetPorts"="Y"

You can create a class/library to wrap the transaction code
Code:

using System;
using System.Data;
using System.Transactions;

namespace BusinessLayer
{
    public class TransactionScopeWrapper : IDisposable
    {
        private TransactionScope _scope = null;

        public TransactionScopeWrapper()
        {
            if (ConfigHelper.UseTransactionScope)
            {
                int timeout = ConfigHelper.TransactionTimeoutMinutes;

                if (timeout == int.MinValue)
                {
                    timeout = 10;
                }

                _scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, timeout, 0));
            }
        }

        public void Complete()
        {
            if (_scope != null)
            {
                _scope.Complete();
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_scope != null)
            {
                _scope.Dispose();
            }
        }

        #endregion
    }
}

Usage of the wrapper:

public void CancelAuction(int auctionid)
        {
            using (TransactionScopeWrapper scope = new TransactionScopeWrapper())
            {
                tdsAuction.AuctionDataTable auctionTable = AuctionAdapter.AuctionSelect(auctionid);

                if (auctionTable.Rows.Count > 0)
                {
                    tdsAuction.AuctionRow auctionRow = auctionTable.Rows[0] as tdsAuction.AuctionRow;

                    auctionRow.AuctionStatusID = (int)AuctionStatusEnum.Cancelled;
                    AuctionAdapter.Update(auctionRow);

                    // return the Stock to inventory
                    if (auctionRow.IsAuction)
                    {
                        InventoryData.InventoryReturnLotsCancelAuction(auctionid);
                    }
                    else
                    {
                        InventoryData.InventoryReturnLotsForDeal(auctionid);
                    }
                }

                scope.Complete();
            }
        }

the server committed a protocol violation section= responsestatusline

I’ve got this error and try to spend almost an hour to resolve this:

“the server committed a protocol violation section= responsestatusline” when I tried to get the response back from the payment gateway. It happens when you send HTTP Request one after another on the same page. The solution is to add unsafeheaderparsing to true in web.config and to seet keepAlive property to false from the http request it self

Web.Config


		
			
		
		
			
		
    
      
        
      
    
  

Calling Code:

   Private Function SendXML(ByVal strSend As String) As Boolean
        Dim blnSuccess As Boolean = False
        Dim objSendXML As XmlDocument
        Dim objRequest As HttpWebRequest
        Dim mywriter As StreamWriter
        Dim objResponse As HttpWebResponse
        Dim objReturnedXML As XmlDataDocument
        Dim objElementRoot As XmlElement
        Dim objElementTransaction As XmlNode
        Dim objElementCreditCardInfo As XmlNode
        Dim x As XmlNode

        Dim strApproved As String = String.Empty
        Dim blnCreditCardInfo As Boolean = False

        ' Must reset the variable incase of error
        Me._Paid = False

        objSendXML = New XmlDocument
        objRequest = WebRequest.Create(strPaymentURL)


        'if it is using proxy/behind proxy
        If (UseProxy And Not (String.IsNullOrEmpty(ProxyServer))) Then
            objRequest.Proxy = New System.Net.WebProxy(ProxyServer, True)

            'if there is credential
            If (UseDefaultCredential) Then
                objRequest.Proxy.Credentials = CredentialCache.DefaultCredentials
            Else
                objRequest.Proxy.Credentials = New NetworkCredential(UserName, Password)
            End If

        End If

        objRequest.Method = "POST"
        objRequest.ContentLength = strSend.Length
        objRequest.ContentType = "text/xml"

        'to solve protocol violation problem
        objRequest.KeepAlive = False

Invalid postback or call argument

It’s quite often I have this error because of the content has been changed during postback or because of the control id. I’ve read most of the article suggested to disable the event validation by putting this on the page which is loosen up the security of that particular page. I found the other method without need to change the EnableEventValidation to false. What i found is that you can reregister your control on the render method
VB.NET

Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)

Register(Me)
MyBase.Render(writer) End Sub

Private Sub Register(ByVal ctrl As Control)
For Each c As Control In ctrl.Controls

Register(c)

Next

Page.ClientScript.RegisterForEventValidation(ctrl.UniqueID)

End Sub

C#

protected override void Render(HtmlTextWriter writer)

{
Register(this);base.Render(writer);

}
private void Register(Control ctrl)

{
foreach (Control c in ctrl.Controls)

Register(c);

Page.ClientScript.RegisterForEventValidation(ctrl.UniqueID);

}

Create hyperlink column in gridview or datagrid

Sometimes when you display the data on the datagrid or gridview , you want to create some link. let’s say when you displaying your user detail data in the grid. you want the user to be able to click the link in email column that automatically open microsoft outlook for you. You also would like to avoid writing some string replacement or creating a function in rowbound event. This is the easiest way to do it. Edit the column and add this into DataFormatString

{0:G}

this can be used to pass some variable from the fields(query string) to some address.

Error code 0x8013134b when debugging ASP.NET

Auto-attach to process ‘[2440] w3wp.exe’ on machine ‘…’ failed. Error code 0x8013134b. This problem is most likely occurred because I have two .NET framework installed in my PC (v1.14322 and v2.0).

To fix this problem:

• Open IIS (inetmgr)
• Right click on the web site with the problem
• Click the ASP.NET tab
• Change the ASP.NET version from 2.something to 1.14322 in the dropdown(or vice versa) and debugging works again

Enums with description in c#

Sometime when we have Enum , we want to use it /bind it on the list as well with a better description/ word. With this method you can bind enum to a list which display its description but store its value as well.This is very useful function.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.ComponentModel;

public class Enums
    {
        #region helpers
        public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
              (DescriptionAttribute[])fi.GetCustomAttributes
              (typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        public static T Parse(string input)
        {
            return (T)Enum.Parse(typeof(T), input);
        }
        #endregion

        #region enums
        public enum ResultsType
        {
            [Description("Featured Products")]
            FeaturedProducts,
            [Description("New Products")]
            NewStock,
            CategoryResults,
            [Description("Specials")]
            Specials,
            Brand,
            Row1,
            Row2,
            Row3,
            [Description("This Weeks Specials")]
            ThisWeeksSpecials,
            [Description("Top 10 Best Sellers")]
            Top10BestSellers,
            [Description("Special Offers")]
            SpecialOffers,
            [Description("Buy 1 Get 1 Free")]
            Buy1Get1Free,
            [Description("Half Price Bargains")]
            HalfPriceBargains,
            [Description("Top Sellers")]
            TopSellers,
            [Description("Summer Specials")]
            SummerSpecials,
            [Description("CUSTOMERS WHO BOUGHT THIS ALSO BOUGHT")]
            AlsoBought,
            [Description("Related Products")]
            Upsell
        }

          public enum ReportType
         {
            [Description("Monthly Sales Report")]
            MonthySalesReport = 1,
            [Description("Dispatched Orders Report")]
            DispatchedOrdersReport = 2,
            [Description("Order Report")]
            OrderReport = 3
         }

#endregion

}

This is how you bind it

Private Sub PopulateReportType()

        ddlReportType.Items.Clear()
        ddlReportType.Items.Add(New ListItem(Enums.GetEnumDescription(Enums.ReportType.MonthySalesReport), Convert.ToInt32(Enums.ReportType.MonthySalesReport)))
        ddlReportType.Items.Add(New ListItem(Enums.GetEnumDescription(Enums.ReportType.DispatchedOrdersReport), Convert.ToInt32(Enums.ReportType.DispatchedOrdersReport)))
        ddlReportType.Items.Add(New ListItem(Enums.GetEnumDescription(Enums.ReportType.OrderReport), Convert.ToInt32(Enums.ReportType.OrderReport)))

    End Sub

Raise Event in User Control

I need to create a payment gateway user control that will be used accross all of the modules. This user control should be as simple as doing the transaction ONLY. So what I need to do is to let the host/page container knows whether the transaction is succeeded or not, if it is succeeded then the rest of the logic will be handled on ASPX page.

In order to do so I need to create an event on the user control that will be bubbled up to the page container/host. This sample might not be the best solution but it works perfectly for my needs and only requires several lines of code.

Write this in your user control including declaration(signature) of parameter that you want to pass

Partial Class usercontrols_MyPaymentGateway
    Inherits System.Web.UI.UserControl

#Region "Property"

    ''' 
    ''' this is an event for process status
    ''' 
    ''' 
    Public Event getProcessStatus(ByVal isPaid As Boolean)

Write this in your user control where you want to raise the event and pass the parameter

     RaiseEvent getProcessStatus(True)

Write this in your page container(Create an Event handler to handle your user control events) (NOTE: paymentGateway is the name of your user control)

 ''' 
    ''' event handler to the payment gateway controls
    ''' 
    ''' 
    ''' 
    Private Sub paymentProcessed(ByVal isPaid as boolean) Handles paymentGateway.getProcessStatus

        If (paymentGateway.IsPaid) Then
            ltMessage.Text = "Payment Successful " + paymentGateway.ResponseMessage

            'if it is paid then we need to clear the remaining text boxes
            paymentGateway.ClearFields()
        Else
            ltMessage.Text = "Payment Failed " + paymentGateway.ResponseMessage
        End If

    End Sub

Reference to user control in web.config

I’ve seen that most of people put their user control declaration in individual aspx page, and they declare it on the top of that page. What will happen if you are going to use it on multiple number of pages and i believe most of you would like to have a kind of tag that you can simply use on your web page to add your user control. In here, we declare all the user controls in web.config which I believe is more clean and manageable.

Web.Config


      
        
		
	  
    
	  
		  
		  
		  
		  
		  
		  
    

How to use it in ASPX Page






    Untitled Page


    
        
    


Find a control in ContentPlaceHolder

I have a user control and I would like to hide a control on the page container that host this user control. I try to use

Page.FindControl("litContent")

But It throws an error of object not found. The solution is you need to find the contentplaceholder first on the master page then you find the control that you want from that placeholder. It’s a bit tricky since i thought once you get a Page instance then you can get all control hosted on the Page instance itself.

1. Place this tag on your asp.net page where it hosts your control


2. go to the page behind of the user control/page where you want to place your logic to hide/show it

'hide the dynamic page from the parent page
Dim mainContent As ContentPlaceHolder = CType(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)

If Not (mainContent Is Nothing) Then
   Dim contentPlaceHolder As Literal = CType(mainContent.FindControl("litContent"),Literal)
   If Not (contentPlaceHolder Is Nothing) Then
       contentPlaceHolder.Visible = False
   End If
End If

Page 4 of 7

Powered by WordPress & Theme by Anders Norén