Read Outlook messages in ASP.NET catches out of bounds error - asp.net

I am trying to integrate MS outlook in asp.net. My code(below) catches out of bounds error. What am I doing wrong? am I not getting the inbox messages properly? Thanks in advance
EDIT: based on my debugging
inbox = name.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
Returns nothing. I am not sure why
Dim ol As Outlook.Application = New Outlook.Application
Dim name As Microsoft.Office.Interop.Outlook._NameSpace
Dim inbox As Microsoft.Office.Interop.Outlook.MAPIFolder
Dim item As Microsoft.Office.Interop.Outlook.PostItem
Dim subF As Microsoft.Office.Interop.Outlook.MAPIFolder
Try
name = ol.GetNamespace("MAPI")
name.Logon(Nothing, Nothing, False, False)
inbox = name.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox)
subF = inbox.Folders(0)
Dim ctr As Integer
For ctr = 0 To subF.Items.Count
item = subF.Items(ctr)
Label1.Text += "Subject: " + item.Subject + "<br/>"
Label1.Text += "Date: " + item.SentOn.ToLongDateString() + " " + item.SentOn.ToLongTimeString() + "<br/>"
Label1.Text += "Category: " + item.Categories + "<br/>"
Label1.Text += "Body: " + item.Body + "<br/>"
Label1.Text += "HtmlBody: " + item.HTMLBody + "<br/>"
Next
Catch ex As System.Runtime.InteropServices.COMException
End Try

Check your index base
Change
For ctr = 0 To subF.Items.Count
to
For ctr = 1 To subF.Items.Count
Or possibly to
For ctr = 0 To subF.Items.Count - 1
...if Microsoft finally got rid of the base-1-indexing scheme with the Outlook objects.
Make sure there's actually a folder!
Check to ensure that the inbox contains subfolders. If not, use the inbox itself.
inbox = name.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox)
If inbox.Folders.Count > 0 Then
subf = inbox.Folders(1)
Else
subf = inbox
End If

Related

asynchronous process structuring in .net

I'm working on a process that takes an excel file, does some review of the data and adds it to a datatable to later save it in the DB. In the review that must be done, in some cases the intervention of the user is necessary, for that I need to interrupt the process, open a modal window, that the user intervenes and then continue the process, in that step is where I am stuck, no I make progress on this point. I put some of the code in case it serves as a guide, thanks in advance.
Dim oSqlBulk As SqlBulkCopy
Dim myExcelConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("DirArch").ToString() & "\" & HttpContext.Current.Session("nombrearchivo").ToString & ";Extended Properties=Excel 12.0;")
myExcelConn.Open()
Dim objOleDB As New OleDbDataAdapter("SELECT * FROM [" & nombreHoja & "$]", myExcelConn)
'data is extracted from excel
objOleDB.TableMappings.Add("Table", "DTDatos")
objOleDB.Fill(dt_datos)
Dim tmpEncaArchivo As New Encabezado_Archivo
tmpEncaArchivo.IdSubida = obtieneIdsubida()
tmpEncaArchivo.IdArchivo = "1"
tmpEncaArchivo.Usuario = " "
tmpEncaArchivo.Fecha = Fecha
tmpEncaArchivo.UbicacionArchivo = " "
tmpEncaArchivo.IdBanco = valorddlbancos '
tmpEncaArchivo.CodCuenta = valorddlcuentas '
tmpEncaArchivo.lstDetalleArchivo = New List(Of Detalle_Archivo)
' the new datatable is filled with the processed data
For i = 0 To dt_datos.Rows.Count - 1
Dim tmpDetalleArchivo As New Detalle_Archivo
tmpDetalleArchivo.IdSubida = tmpEncaArchivo.IdSubida
tmpDetalleArchivo.IdArchivo = tmpEncaArchivo.IdArchivo
tmpDetalleArchivo.Linea = i + 1
tmpDetalleArchivo.Documento = IIf(IsDBNull(dt_datos.Rows(i)("Código de Autorización")), " ", dt_datos.Rows(i)("Código de Autorización"))
tmpDetalleArchivo.Monto = CDec(Replace(dt_datos.Rows(i)("Monto"), ".", ","))
tmpDetalleArchivo.Estado = "N"
tmpDetalleArchivo.Moneda = IIf(InStr(IIf(IsDBNull(dt_datos.Rows(i)("Moneda")), " ", dt_datos.Rows(i)("Moneda")), "Colón"), "CL", "DL")
If IsDBNull(dt_datos.Rows(i)("Estado")) Then
tmpDetalleArchivo.Datos = " "
Else
tmpDetalleArchivo.Datos = "S"
End If
tmpDetalleArchivo.Fecha = Fecha
tmpDetalleArchivo.Sobrante = 0
'Depending on the result of this function, the process must be stopped
If consultaRegDuplicado(tmpDetalleArchivo.IdSubida, tmpDetalleArchivo.IdArchivo, tmpDetalleArchivo.Fecha, tmpDetalleArchivo.Moneda,
tmpDetalleArchivo.Monto, tmpDetalleArchivo.Documento, valorddlcuentas, valorddlbancos) Then
'Here the code should be executed to open the modal for user intervention
tmpEncaArchivo.lstDetalleArchivo.Add(tmpDetalleArchivo)
End If
Next

How to upload xls file's data to SQL Server in devexpress popup control?

I have enquiry on how to insert xls file data into SQL Server. The upload button, and gridview control are placed inside the devexpress popup control and the code works without the popup control but doesn't work with popup control. When I inserted the xls file and clicked the upload button, the label display showed "Please select a file to upload!" although I have did this.
ASP.NET markup:
<dx:ASPxPopupControl ID="popupControl" ClientInstanceName="popupControl"
AllowDragging="true" ShowOnPageLoad="false" runat="server" AllowResize="true" >
<ContentCollection>
<dx:PopupControlContentControl runat="server">
<div class="flexs">
<dx:ASPxUploadControl ID="XXUpload" runat="server" UploadMode="Auto" ValidationSettings-AllowedFileExtensions=".xls" width="500px" >
</dx:ASPxUploadControl>
<dx:ASPxLabel ID="Label2" runat="server" Text=""></dx:ASPxLabel>
<dx:ASPxButton ID="DataUpload" runat="server" Text="UPLOAD" OnClick="DataUpload_Click ">
</dx:ASPxButton>
<dx:ASPxGridView ID="UpdateSplitGrid" ClientIDMode="Static" ClientInstanceName="UpdateSplitGrid" runat="server" Width="200%" DataSourceID="dtSource2" Theme="DevEx" >
.....
</dx:ASPxGridView>
</div>
</dx:PopupControlContentControl>
</ContentCollection>
</dx:ASPxPopupControl>
Vb.net code:
Function uploadExcel1(filePath As String) As String
Dim str As String = ""
Dim namestr1 As String = XXUpload.UploadedFiles.ToArray(0).FileName.ToString
If namestr1 <> "" Then
If Not XXUpload.UploadedFiles.ToArray(0).IsValid Then
str = "Fail to Upload " + namestr1
Else
XXUpload.UploadedFiles.ToArray(0).SaveAs(filePath)
str = " Successfully Uploaded!"
End If
Else
str = "Please select a File to upload!"
End If
Return str
End Function
Function getDTe(filename As String, ByVal sql As String) As DataTable
Dim dt As New DataTable()
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';"
Dim connection As New OleDbConnection(connectionString)
Dim adapter As New OleDbDataAdapter(sql, connection)
adapter.Fill(dt)
Return dt
End Function
Protected Sub DataUpload_Click(sender As Object, e As EventArgs)
Dim filepath As String = "C:\New folder\" + XXUpload.UploadedFiles.ToArray(0).FileName.ToString + ".xls"
Dim msg As String = uploadExcel1(filepath)
Label2.Text = msg
If msg.Contains("Successfully") Then
Dim sql As String = "select * from [Sheet1$]"
Dim dt As New DataTable
dt = getDTe(filepath, sql)
If dt.Rows.Count > 0 Then
Dim i As Integer = 0
Dim colname() As String = {"LotID", "Split_Cat", "Engr_Time", "PLANDESC", "STEPSEQ", "EQPTYPE", "PPID", "STEPDESC", "Split", "Recipe", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22"}
For Each dc As DataColumn In dt.Columns
If dc.ColumnName.ToString <> colname(i) Then
Label2.Text = " File is not in correct format - Details: " + dc.ColumnName.ToString
Return
End If
i = i + 1
Next
For Each dr In dt.Rows
Try
Dim LotID As String = dr("LotID").ToString
Dim Split_Cat As String = dr("Split_Cat").ToString
Dim Engr_Time As String = dr("Engr_Time").ToString
Dim PLANDESC As String = dr("PLANDESC").ToString
Dim STEPSEQ As String = dr("STEPSEQ").ToString
Dim EQPTYPE As String = dr("EQPTYPE").ToString
Dim PPID As String = dr("PPID").ToString
Dim STEPDESC As String = dr("STEPDESC").ToString
Dim Split As String = dr("Split").ToString
Dim Recipe As String = dr("Recipe").ToString
Dim a As String = dr("F11").ToString
Dim b As String = dr("F12").ToString
Dim c As String = dr("F13").ToString
.............
Dim insertsql2 As String = ""
insertsql2 += "insert into PTHOME.dbo.SplitTable (LotID,Split_Cat,Engr_Time,PLANDESC,STEPSEQ,EQPTYPE,PPID,STEPDESC,Split,Recipe,[1],[2],[3]) values "
insertsql2 += "('" + LotID + "','" + Split_Cat + "','" + Engr_Time + "','" + PLANDESC + "','" + STEPSEQ + "','" + EQPTYPE + "','" + PPID + "','" + STEPDESC + "','" + Split + "','" + Recipe + "', "
insertsql2 += " '" + a + "','" + b + "','" + c + "') "
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(insertsql2, conn)
conn.Open()
Dim res As Integer = cmd.ExecuteNonQuery
conn.Close()
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Else
Label2.Text = " NO Records Uploaded! "
End If
Catch ex As Exception
Label2.Text = " Failed to Upload, pls check your data or file format ! "
End Try
Next
End If
End If
End Sub
When i upload the xls file, the label displayed
"Please select a File to upload!", anything i missed out in the popup control? Please guide me on this, thanks in advance.
EDIT*
I have changed the upload control to this and it no longer showed the "Please select a File to upload!" now there is another error showed "File is not in correct format - Details: F11", the error seems to lie on the column [1]-[12], but the excel column is 1-12 and the column in database is [1]-[12].how can i achieve this? ( Solved by changing the number to F11 and so on.)
<dx:ASPxUploadControl runat="server" ClientInstanceName="XXUpload" ID="XXUpload" Width="600px" >
<ValidationSettings AllowedFileExtensions=".xls"></ValidationSettings>
</dx:ASPxUploadControl>
Edit 2*
The data has uploaded successfully to sql server and now another problem occurred, the data uploaded to sql server wont show in the UpdateSplitGrid gridview although i have declared this in my code.
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Your ASPxUploadControl, the XXUpload, doesn't have any function to execute when upload is complete. I suggest you use OnFileUploadComplete event with FileUploadMode="OnPageLoad".

Attatch Gridview to email body VB.NET

I am currently sending emails programatically in my web page, the emails work fine but i would also like to attach a gridview into the email body.
this is my VB code I have for sending the email so far...
Dim Uname As String = Page.User.Identity.Name.Substring(Page.User.Identity.Name.IndexOf("\") + 1)
strFm = Uname + "#Inscapepeople.co.uk"
If strTo <> "" Then
Dim insMail As New System.Net.Mail.MailMessage(New MailAddress(strFm), New MailAddress(strTo))
With insMail
For Each y As String In strToREST.Split(";")
If y = "" Then
Else
.CC.Add(y)
End If
Next
.Subject = subject
.Body = Greet + "<br />" + "<br />" + bodyTxt.Text + "<br />" + PName + "- " + PNum + "<br />" + "<br />" + "The Required Date was: " + ReqDateNow.Text + " ,The Required Date is now: " + ReqDateAfter.Text + "<br />" + "Regards," + "<br />" + "<br />"
.IsBodyHtml = True
Sig = Uname
If Sig.ToLower = "djones" Then Sig = "GBennett"
Dim source As String = Path + Sig + ".jpg"
If System.IO.File.Exists(source) = False Then
Msgbox.ShowAlertMessage("Signature not found, but the email was still sent.")
Else
Dim lr As New LinkedResource(source)
lr.ContentId = "Signature"
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(insMail.Body + "<img width=""500"" height=""400"" src=cid:Signature>", Nothing, "text/html")
htmlView.LinkedResources.Add(lr)
.AlternateViews.Add(htmlView)
End If
End With
Dim smtp As New System.Net.Mail.SmtpClient
smtp.EnableSsl = False
smtp.Host = "192.168.50.2"
smtp.Port = 25
smtp.UseDefaultCredentials = True
smtp.Send(insMail)
I have searched around online and i cannot find anything to help me, I was wondering if i could get some assistance with this, thank you in advance.
Any help at all would be appreciated.
I would suggest converting the gridview to Html using a function such as:
Private Function GridViewToHtml(ByVal gv As GridView) As String
Dim sb As New StringBuilder
Dim sw As New StringWriter
Dim hw As New HtmlTextWriter(sw)
gv.RenderControl(hw)
Return sb.ToString()
End Function
Then you could call this function and add it to the body of your email.

sending email in from asp.net page

I want to add this to my email body and i want it to look like this but it doesnt work.
Tour: lotour.text
Date: loddate.text
Party: lolnumparty.text
first name: locfname.text
last name: loclname.text
as you see i want them right after another and it doesnt work when i use a </br>
this is my email body.
objEmail.Body = "There was a booking rquest made by " & Request.QueryString("comp") & " to see more details click the link " + x
this is my full code
If Page.IsValid And ValidateCCNumber(cardnumber.Text) = True Then
SqlDataSource1.Insert()
Dim x As String
x = "http://www.clubabc.com/bookingrequest/confirm.aspx?date=" & HttpUtility.UrlEncode(now.Text) & "&tfname=" & HttpUtility.UrlEncode(p1fname.Text) & "&tlname=" & HttpUtility.UrlEncode(p1lname.Text) & "&comp=" & HttpUtility.UrlEncode(Request.QueryString("comp") & "&land=" & HttpUtility.UrlEncode(land.Text))
Dim objEmail As New MailMessage()
objEmail.To = "cnna#BC.com"
objEmail.From = "page#bc.com"
objEmail.Cc = memail.Text
objEmail.Subject = "Booking for " + p1fname.Text + " " + p1lname.Text + " made by " & Request.QueryString("comp")
objEmail.Body = "There was a booking rquest made by " & Request.QueryString("comp") & " to see more details click the link " + x
SmtpMail.SmtpServer = "mail.bc.com"
Try
SmtpMail.Send(objEmail)
Catch exc As Exception
Response.Write("Send failure: " + exc.ToString())
End Try
Response.Redirect("http://www.clubabc.com/bookingrequest/confirm.aspx?date=" + now.Text + "&tfname=" + p1fname.Text + "&tlname=" + p1lname.Text + "&comp=" + Request.QueryString("comp") & "&land=" & HttpUtility.UrlEncode(land.Text))
ElseIf ValidateCCNumber(cardnumber.Text) = False Then
invalidcard.Visible = True
End If
I guess you are searching for (MSDN):
Environment.NewLine
The <br> tag will only work in HTML Emails.
Update
This would be a very simple example, how you could use Environment.NewLine:
Imports System
Class Sample
Public Shared Sub Main()
Dim firstName As String = "John"
Dim lastName As String = "Doe"
Dim city As String = "Brooklyn"
Console.WriteLine("First name: " + firstName + Environment.NewLine + "Last name: " + lastName + Environment.NewLine + "City: " + city + Environment.NewLine)
End Sub
End Class
Try to set IsHtml property for objEmail variable to get some more formatting possibilities.
Do not use Enviornment.NewLine, instead use vbCrLf
Environment.NewLine may only output Cr or Lf, which may cause your email to either:
a)Be blocked because it's not RFC complient
or
b)Be marked as spammy
To have new lines in email, always use CrLf.
--Dave

VS Macro/Add-in to convert string concatenations to string.format style

I have project in development where string operations like "Hi " + variable + ", welcome to Project" are used at many places (given example is very minor one).
One of the requirement is to convert it to string.format style.
It is very long and tedious job, where I would not like to break earlier working code due to any human error might happen while converting it.
I would like to if any Macro or VS command which I can create to handle it. Just like we mark block of code and do Extract function in Re-factor options.
I felt the code was a little long to post here, but I posted an answer at my blog:
http://www.brianschmitt.com/2010/08/converting-concatenated-string-into.html
-- EDIT --
Per comment here is the relevant Macro - not sure why you cannot access...
Public Sub ConvertToStringFormat()
DTE.UndoContext.Open("ConvertToStringFormat")
Dim textSelection As TextSelection = DTE.ActiveDocument.Selection
Dim output As String = "string.Format(""{0}"", {1})"
Dim delimt As String = ", "
Dim fmtdTostring As String = ".tostring("""
Dim txtSelection As String() = System.Text.RegularExpressions.Regex.Split(textSelection.Text.Trim, "\+\s_[+\n\r\t]|&\s_[+\n\r\t]|\+|&")
Dim hardStrings As String = String.Empty
Dim valueStrings As String = String.Empty
Dim counter As Int16 = 0
For Each str As String In txtSelection
Dim tmpString As String = str.Trim
If tmpString.StartsWith("""") Then
hardStrings &= tmpString.Substring(1, tmpString.Length - 2)
Else
Dim fmt As String = String.Empty
Dim indxToString As Int32 = 0
If tmpString.ToLower.Contains(fmtdTostring) Then
indxToString = tmpString.ToLower.IndexOf(fmtdTostring)
fmt = tmpString.Substring(indxToString + 11, tmpString.Length - tmpString.ToLower.IndexOf(""")", indxToString) - 1)
End If
If fmt <> String.Empty Then
hardStrings &= "{" & counter.ToString & ":" & fmt & "}"
valueStrings &= tmpString.Substring(0, indxToString) & delimt
Else
hardStrings &= "{" & counter.ToString & "}"
valueStrings &= tmpString & delimt
End If
counter += 1
End If
Next
If valueStrings <> String.Empty Then valueStrings = valueStrings.Substring(0, valueStrings.Length - delimt.Length)
textSelection.Text = String.Format(output, hardStrings, valueStrings)
DTE.UndoContext.Close()
End Sub

Resources