Pages

Saturday, October 5, 2013

Convert Html page to Excell of Word file

Public Sub ExportData(ByVal DataToExport As String, ByVal FileName As String, ByVal mode As String)


HttpContext.Current.Response.ClearContent()
If mode.ToUpper() = "EXCEL" Then

Dim attachment As String = "attachment; filename=" & FileName & ".xls"

HttpContext.Current.Response.AddHeader("content-disposition", attachment)

HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"

ElseIf mode.ToUpper() = "WORD" Then

Dim attachment As String = "attachment; filename=" & FileName & ".doc"

HttpContext.Current.Response.AddHeader("content-disposition", attachment)

HttpContext.Current.Response.ContentType = "application/ms-word"

End If


HttpContext.Current.Response.Write(DataToExport.ToString())

HttpContext.Current.Response.End()
End Sub

Wednesday, October 2, 2013

FaultException in WCF(Error:The creator of this fault did not specify a Reason.)

 <ServiceContract()> _
Public Interface IService
    <OperationContract()> _
    <FaultContract(GetType(MyExceptionContainer))> _
   Function div(ByVal num1 As Integer, ByVal num2 As Integer) As Integer

End Interface
<DataContract()> _
Public Class MyExceptionContainer
    Dim msg, dsc As String
    <DataMember()> _
    Public Property message() As String
        Get
            Return msg
        End Get
        Set(ByVal value As String)
            Msg = value
        End Set
    End Property
End Class

...............cs...........................
Public Class Service
    Implements IService

    Public Function div(ByVal num1 As Integer, ByVal num2 As Integer) As Integer Implements IService.div
        Try
            Return (num1 \ num2)
        Catch ex As DivideByZeroException
            Dim ec As New MyExceptionContainer
            ec.message = "Error msg"
            Throw New FaultException(Of MyExceptionContainer)(ec, New FaultReason(ec.message))
        End Try
    End Function

End Class

------------------.client Side ---------------------

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim sr As New ServiceReference1.ServiceClient
            Dim div As Integer = sr.div(10, 0)
        Catch ex As FaultException(Of ServiceReference1.MyExceptionContainer)
            Response.Write(ex.Detail.message)

        End Try
        
    End Sub
----------------------
Managing a correct error handling process in an application is a nightmare if you want to do it properly and I would say that it is not always the best exciting part, but it is absolutly needed to prevent as much as possible unhandle situation. In a normal application you simply place the code inside try-catch block with the exception type, and there are handle as normal .net exception object that you can bubble up.
With WCF service I have discover around different reading that it is a bit different, simply because WCF need to guaranty interoperability with any client application in order that they are able to catch error returned.
For that WCF need to convert the “normal .NEt exception” into a SOAP messageexception that will be understandable from client application.
To achive this you need to specify a FaultContract attrribute in your service either declaratively or imperatively way. For my case I have done it with declarative.
You specify the declarative FaultContrat as follow for your service method:

[OperationContract]
[
FaultContract (typeof(MyError))]Boolean myMethod();
MyError is here a custom type which define an error message
After having configured the service FaultContractAttribute, next you need to raise the exception from your server side service method code as follow :
Server side
catch (Exception exc){
  MyError ErrLog = new Maillefer.Nomos.Types.Common.MyError (“This is an error”,”Critical”);  FaultException<MyError> fe = new FaultException<MyError >(ErrLog, new FaultReason(ErrLog.Message));  throw fe;}
So far so good. Then from the client application side you simply need to catch the FaultException error type as you normally do and retrive the message return by the Servcie SOAP message as follow:
Client side
catch (FaultException <MyError> MyError){  string msg = Error.Detail.Message;   MessageBox.Show (msg);
  wcfclient.Close();
}
And that’s it. You then receive the error message send from your server, inside your client application.. Hmmm this is what I was expecting but it was not behaving as expected. I spend days to cross check my code and verify impementation to get the exception correctly thrown but when runnig my application my service was stoping at the time it was throwing the exception (throw fe). The error return from that execution was something strange like :
System.ServiceModel.FaultException`1 was unhandled by user code
After a lot of research I find out the solution on a post mentionning that it was due to some setting ofdebugging scenario of my VS environement, which make my code execution stop at each exception with not really logic message wich was giving a lot of confusion.
To remove this behaviour it was advise to uncheck the 2 following options from the Tools->Option menu of IDE:
 Capture
Please give the comment if the above solution save your time.

Wednesday, September 25, 2013

Delete multiple asp.net gridview rows with checkbox selection and with confirmation

First design the table in database and give name UserInformation
ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
FirstName
varchar(50)
LastName
varchar(50)
Location
varchar(50)

After completion table creation enter some dummy and design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Delete Rows in Gridview with Checkbox</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;  
}
</style>
<script type="text/javascript">
function Confirmationbox() {
var result = confirm('Are you sure you want to delete selected User(s)?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUserDetails" runat="server" DataSourceID="objUsers"
DataKeyNames="UserId" CssClass="Gridview" AutoGenerateColumns="false"
HeaderStyle-BackColor="#61A6F8" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="objUsers" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection%>"
SelectCommand="select * from UserInformation"
DeleteCommand="delete from UserInformation where UserId=@UserId" >
<DeleteParameters>
<asp:Parameter Name="UserId" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" />
</form>
</body>
</html>
.................................   .cs      ...................

protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Attributes.Add("onclick""javascript:return Confirmationbox()");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Loop through all the rows in gridview
foreach(GridViewRow gvrow in gvUserDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkdelete");
//Condition to check checkbox selected or not
if(chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);
objUsers.DeleteParameters["UserId"].DefaultValue = usrid.ToString();
objUsers.Delete();
}
}

Tuesday, September 24, 2013

How to upload a file with vb.net

        Dim file_name, agency_code, job_code As String
        '-------Building File Name and Upload Excel File to writereaddata\ExcelFiles-----------------------
        file_name = "suneel"
        file_name = file_name.Replace("/", "_")
        file_name = file_name & ".xml"
        Dim path As String = Server.MapPath(".")
        path = path.Substring(0, path.LastIndexOf("\")) & "\foldername\"
        Dim fctype As String = FileUpload1.PostedFile.ContentType
        FileUpload1.Enabled = False
        FileUpload1.PostedFile.SaveAs(path & file_name)
        Session("ffname") = file_name
        FileUpload1.Enabled = False
        Response.Write(path)