Using EF model database not Updating with updateModel - vb.net

MVC 3, VB.NET, RAZOR app, using EF. I am having an issue in my post function with the database not updating at all... Using a break at db.savechanges() I look at the variable and all of the correct information is contained in the UpdateModel( ) part. But no dice the code executes and returns no errors so all looks fine but when I look at the database table it has not been changed at all, all of the old values are still present.. Function is as follows:
<AcceptVerbs(HttpVerbs.Post)>
Function EditCourse(ByVal _eCourse As cours) As ActionResult
Dim id As Integer = _eCourse.course_id
Dim _filename As String = String.Empty
Dim _guid As String = String.Empty
Dim _count As Integer = 0
Dim _courseFiles As cours = db.courses.Where(Function(f) f.course_ref = _eCourse.course_ref).First
Dim _file1 As String = _courseFiles.handoutFile1
Dim _file2 As String = _courseFiles.handoutFile2
Dim _file3 As String = _courseFiles.handoutFile3
Dim _file4 As String = _courseFiles.handoutFile4
Dim _file5 As String = _courseFiles.handoutFile5
Dim _file6 As String = _courseFiles.handoutFile6
Dim _file7 As String = _courseFiles.handoutFile7
Dim _file8 As String = _courseFiles.handoutFile8
For Each File As String In Request.Files
_count += 1
Dim hpf As HttpPostedFileBase = TryCast(Request.Files(File), HttpPostedFileBase)
If hpf.ContentLength = 0 Then
Continue For
End If
Dim savedfileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + hpf.FileName
hpf.SaveAs(savedfileName)
_filename = hpf.FileName
Select Case _count
Case Is = 1
If Not String.IsNullOrWhiteSpace(_file1) Then
If Not String.Compare(_eCourse.handoutFile1, _file1) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile1) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file1
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile1 = _filename
Case Is = 2
If Not String.IsNullOrWhiteSpace(_file2) Then
If Not String.Compare(_eCourse.handoutFile2, _file2) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile2) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file2
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile2 = _filename
Case Is = 3
If Not String.IsNullOrWhiteSpace(_file3) Then
If Not String.Compare(_eCourse.handoutFile3, _file3) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile3) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file3
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile3 = _filename
Case Is = 4
If Not String.IsNullOrWhiteSpace(_file4) Then
If Not String.Compare(_eCourse.handoutFile4, _file4) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile4) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file4
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile4 = _filename
Case Is = 5
If Not String.IsNullOrWhiteSpace(_file5) Then
If Not String.Compare(_eCourse.handoutFile5, _file5) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile5) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file5
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile5 = _filename
Case Is = 6
If Not String.IsNullOrWhiteSpace(_file6) Then
If Not String.Compare(_eCourse.handoutFile6, _file6) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile6) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file6
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile6 = _filename
Case Is = 7
If Not String.IsNullOrWhiteSpace(_file7) Then
If Not String.Compare(_eCourse.handoutFile7, _file7) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile7) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file7
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile7 = _filename
Case Is = 8
If Not String.IsNullOrWhiteSpace(_file8) Then
If Not String.Compare(_eCourse.handoutFile8, _file8) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile8) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file8
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile8 = _filename
End Select
Next
UpdateModel(_eCourse)
db.SaveChanges()
Return RedirectToAction("CourseIndex")
End Function
Any Ideas on why this is going wrong?????

You aren't attaching your _eCourse to your context so it won't update it.
UpdateModel I don't believe is required here at all as that simply takes your posted form values an assigns to your model which you already have since eCourse is a parameter. Do something like (on phone here sorry)
DB.Entry(_eCourse).State = EntityState.Modified
And then save changes

Related

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

Pictures wont become visible

So today in my Computer Programming Class, we created a project called CaseStudy. I saw a way to make the program have more replay value. I decided to morph the code and interface to be like a Hangman game. I've got the limbs to appear, but only after clicking Ok on the messageBox.
I'm wondering if anyone has a way to make these limbs appear in real time.
Here is the important code:
Dim SECRET_WORD As String = newSecretWord
Const FLAG As Char = "!"
Const GUESS_PROMPT As String = "Enter a letter or " & FLAG & " to guess word:"
Dim numGuesses As Integer = 0
Dim letterGuess As Char
Dim wordGuess As String
Dim tempWord As String
Dim endGame As Boolean
Dim wordGuessedSoFar As String = ""
Dim lenght As Integer = SECRET_WORD.Length
wordGuessedSoFar = wordGuessedSoFar.PadLeft(lenght, "_")
Me.lblSecretWord.Text = wordGuessedSoFar
Dim tempLetterGuess = InputBox(GUESS_PROMPT, Me.Text)
If tempLetterGuess = Nothing Then
endGame = True
Else
letterGuess = tempLetterGuess
End If
Do While letterGuess <> FLAG And wordGuessedSoFar <> SECRET_WORD And Not endGame
numGuesses += 1
For letterPos As Integer = 0 To SECRET_WORD.Length - 1
If SECRET_WORD.Chars(letterPos) = Char.ToUpper(letterGuess) Then
tempWord = wordGuessedSoFar.Remove(letterPos, 1)
wordGuessedSoFar = tempWord.Insert(letterPos, Char.ToUpper(letterGuess))
Me.lblSecretWord.Text = wordGuessedSoFar
End If
Next letterPos
If wordGuessedSoFar <> SECRET_WORD Then
tempLetterGuess = InputBox(GUESS_PROMPT, Me.Text)
If tempLetterGuess = Nothing Then
endGame = True
Else
letterGuess = tempLetterGuess
End If
End If
Loop
If wordGuessedSoFar = SECRET_WORD Then
MessageBox.Show("You guessed it in " & numGuesses & " guesses!")
ElseIf letterGuess = FLAG Then
wordGuess = InputBox("Enter a word: ", Me.Text)
If wordGuess.ToUpper = SECRET_WORD Then
MessageBox.Show("You guessed it in " & numGuesses & " guesses!")
Me.lblSecretWord.Text = SECRET_WORD
Else
MessageBox.Show("Sorry, you lose.")
End If
Else
MessageBox.Show("Game over.")
lblSecretWord.Text = Nothing
End If
Dim place As Integer = SECRET_WORD.Length - 1
If tempLetterGuess <> SECRET_WORD.Chars(place) Then
numWrong += 1
End If
If numWrong = 1 Then
picHead.Visible = True
End If
If numWrong = 2 Then
picBody.Visible = True
End If
End Sub
End Class
I can take any other pictures if you'd like.
If I'm understanding you right, you want to show your "pictures" before the user sees the message. If so, you need to move the following code to an area just before your MessageBox and just after the InputBox:
Dim place As Integer = SECRET_WORD.Length - 1
If tempLetterGuess <> SECRET_WORD.Chars(place) Then
numWrong += 1
End If
If numWrong = 1 Then
picHead.Visible = True
End If
If numWrong = 2 Then
picBody.Visible = True
End If

Using MailMessage with semi cologn seperation

If I manually put my address in for EmailMessage.To.Add(GetDelimitedField(x, strEmailRep, ";")) It sends me the message just fine. However If I use the code as is below which is using a list that looks like ;email1#mail.com;email2.mail.com
Then it gives an error that email address cannot be blank
Somewhere in GetDelimitedField is erasing addresses. I'm not sure where the problem is actually occurring. Here is all the code involved with this.
strmsg = "LOW STOCK ALERT: Component (" & rsMPCS("MTI_PART_NO") & ") has reached or fallen below it's minimum quantity(" & rsMPCS("MIN_QTY") & ")."
Dim EmailMessage As MailMessage = New MailMessage
EmailMessage.From = New MailAddress("noreply#mail.com")
For x = 1 To GetCommaCount(strEmailRep) + 1
EmailMessage.To.Add(GetDelimitedField(x, strEmailRep, ";"))
Next
EmailMessage.Subject = ("LOW STOCK ALERT!")
EmailMessage.Body = strmsg
EmailMessage.Priority = MailPriority.High
EmailMessage.IsBodyHtml = True
Dim smtp As New SmtpClient("smtp.mycompany.com")
smtp.UseDefaultCredentials = True
smtp.Send(EmailMessage)
Public Function GetCommaCount(ByVal sText As String)
Dim X As Integer
Dim Count As Integer
Dim Look As String
For X = 1 To Len(sText)
Look = Microsoft.VisualBasic.Left(sText, X)
If InStr(X, Look, ";", 1) > 0 Then
Count = Count + 1
End If
Next
GetCommaCount = Count
End Function
Public Function GetDelimitedField(ByRef FieldNum As Short, ByRef DelimitedString As String, ByRef Delimiter As String) As String
Dim NewPos As Short
Dim FieldCounter As Short
Dim FieldData As String
Dim RightLength As Short
Dim NextDelimiter As Short
If (DelimitedString = "") Or (Delimiter = "") Or (FieldNum = 0) Then
GetDelimitedField = ""
Exit Function
End If
NewPos = 1
FieldCounter = 1
While (FieldCounter < FieldNum) And (NewPos <> 0)
NewPos = InStr(NewPos, DelimitedString, Delimiter, CompareMethod.Text)
If NewPos <> 0 Then
FieldCounter = FieldCounter + 1
NewPos = NewPos + 1
End If
End While
RightLength = Len(DelimitedString) - NewPos + 1
FieldData = Microsoft.VisualBasic.Right(DelimitedString, RightLength)
NextDelimiter = InStr(1, FieldData, Delimiter, CompareMethod.Text)
If NextDelimiter <> 0 Then
FieldData = Microsoft.VisualBasic.Left(FieldData, NextDelimiter - 1)
End If
GetDelimitedField = FieldData
End Function
You can split the list easier using string.Split:
Dim strEmails = "a#test.com;b#test.com;c#test.com;"
Dim lstEmails = strEmails.Split(";").ToList()
'In case the last one had a semicolon:
If (lstEmails(lstEmails.Count - 1).Trim() = String.Empty) Then
lstEmails.RemoveAt(lstEmails.Count - 1)
End If
If (lstEmails.Count > 0) Then
lstEmails.AddRange(lstEmails)
End If

Mailenable API AJAX Calls

I am trying to understand how the MailEnable API works.
So far, I could only look at the AJAX documentation and got the LOGIN command work. It's like:
AJAXRequest('LOGIN','Username='user'&Password='pass', false);
That command returns an xml string like
<BASEELEMENT SCHEMA="VALUE" METHOD="LOGIN"><RETURNVALUE>1</RETURNVALUE></BASEELEMENT>
That working well, anything else than the LOGIN command (For example LOG-OFF or LIST-MESSAGES) gives me a timeout error like
<BASEELEMENT SCHEMA="TIMEOUT" METHOD="LOGOUT"></BASEELEMENT>
The commands I am using for LOG-OFF and LIST-MESSAGES are these and they both give me the below error.
AJAXRequest('LIST-MESSAGES','Folder=/Inbox', false);
AJAXRequest('LOG-OFF','ID=', false);
I am using the example files from that link. I just can't understand if I am missing something, or these examples and documentations are not up to date or has issues or smth?
Thanks!
(I couldn't find "mailenable" tag to tag this question. It's a pity that noone has tagged mailenable before in stackoverflow, mailenable forum is like a grave :S)
Ok as per comments I am posting a self written Mail Api for MailEnable
Imports System
Imports System.Web
Imports MailEnable.Administration
Imports QueryStringModule
Imports System.Xml
Public Class MailApi : Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim doc As XmlDocument = GetXmlToShow(context)
context.Response.ContentType = "test/xml"
context.Response.ContentEncoding = System.Text.Encoding.UTF32
context.Response.Expires = -1
context.Response.Cache.SetAllowResponseInBrowserHistory(True)
doc.Save(context.Response.Output)
End Sub
Private Function GetXmlToShow(context As HttpContext) As XmlDocument
Dim Result As String = ""
Dim doc As New XmlDocument
Try
Dim query As String = QueryStringModule.Decrypt(context.Request.QueryString("val").Replace(" ", "+"))
Dim PostOffice As String = HttpUtility.ParseQueryString(query).Get("PostOffice")
Dim Domain As String = HttpUtility.ParseQueryString(query).Get("Domain")
Dim Username As String = HttpUtility.ParseQueryString(query).Get("Username")
Dim Password As String = HttpUtility.ParseQueryString(query).Get("Password")
Dim MailBoxQuota As Integer = CInt(Val(HttpUtility.ParseQueryString(query).Get("MailBoxQuota")))
If MailBoxQuota = 0 Then
MailBoxQuota = 102400
End If
Dim act As String = HttpUtility.ParseQueryString(query).Get("Action")
Select Case act
Case "Create"
Result = fnCreateMailAccount(Username, PostOffice)
Case "Delete"
Case "Update"
Case "GetAll"
Result = fnGetAll(Username, PostOffice)
Case "GetToday"
Case "GetFromTo"
Case "GetUnread"
Result=fnGetUnread(Username,PostOffice)
Case "GetRead"
Case "GetUnreadCount"
Result = fnGetUnreadCount(Username, PostOffice)
Case "GetTotalCount"
Result = fnGetTotalCount(Username, PostOffice)
Case Else
Result = "<result status=""Err""><reason>Invaid action!</reason></result>"
End Select
doc.LoadXml(Result)
Catch ex As Exception
Result = "<result status=""Err""><reason>" + ex.Message + "</reason></result>"
doc.LoadXml(Result)
End Try
Return doc
End Function
Private Function fnGetUnread(Username As String, Postoffice As String) As String
Dim XMLFile As String = ""
Try
If Len(Username) <= 0 Or Len(Postoffice) <= 0 Then
Throw New ArgumentException("Invalid Parameters!")
Else
Dim oMailbox As New MailEnable.Administration.Mailbox
oMailbox.Postoffice = Postoffice
oMailbox.MailboxName = Username
oMailbox.Status = 1
If oMailbox.GetMailbox() = 1 Then
Dim APIResult As Long
Dim oStore As New MailEnable.Store
APIResult = oStore.StoreFolder_Open(Postoffice, Username, "\Inbox", 0, 1)
If oStore.StoreFolder_FindFirstItem() = 1 Then
Do
If oStore.StoreItem_GetProperty("PR_ME_READ").ToString = "0" Or oStore.StoreItem_GetProperty("PR_ME_READ").ToString = "" Then
Dim WrapperStart As String = "<message>"
Dim ItemId As String = "<itemid>" + oStore.StoreItem_GetProperty("ME_ITEM_ID").ToString + "</itemid>"
Dim MessageDate As String = "<dated>" + Left(oStore.StoreItem_GetProperty("PR_ME_MESSAGEDATE").ToString, 10) + " " + Right(oStore.StoreItem_GetProperty("PR_ME_MESSAGEDATE").ToString, 8) + "</dated>"
Dim Attachments As String = "<attachments>" + oStore.StoreItem_GetProperty("PR_ME_ATTACHMENTS").ToString + "</attachments>"
Dim From As String = "<from>" + oStore.StoreItem_GetProperty("PR_ME_FROM").ToString.Replace("<", """").Replace(">", """") + "</from>"
Dim Subject As String = "<subject>" + oStore.StoreItem_GetProperty("PR_SUBJECT").Replace("<", """").Replace(">", """").ToString + "</subject>"
Dim Size As String = "<size>" + oStore.StoreItem_GetProperty("PR_ME_SIZE").ToString + "</size>"
Dim Status As String = "<status>" + oStore.StoreItem_GetProperty("PR_ME_FLAGSTATUS").ToString + "</status>"
Dim WrapperEnd As String = "</message>"
XMLFile = XMLFile + WrapperStart +ItemId + MessageDate + Attachments + From + Subject + Size + Status + WrapperEnd
End If
Loop While (oStore.StoreFolder_FindNextItem() = 1)
XMLFile = "<messages>" + XMLFile + "</messages>"
End If
APIResult = oStore.StoreFolder_FindClose()
APIResult = oStore.StoreFolder_Close()
Else
Throw New ArgumentException("Invalid Mailbox!")
End If
End If
XMLFile = "<result status=""Success"">" + XMLFile + "</result>"
Catch ex As Exception
XMLFile = "<result status=""Err""><reason>" + ex.Message + "</reason></result>"
End Try
Return XMLFile
End Function
Private Function fnGetAll(Username As String, Postoffice As String) As String
Dim XMLFile As String = ""
Try
If Len(Username) <= 0 Or Len(Postoffice) <= 0 Then
Throw New ArgumentException("Invalid Parameters!")
Else
Dim oMailbox As New MailEnable.Administration.Mailbox
oMailbox.Postoffice = Postoffice
oMailbox.MailboxName = Username
oMailbox.Status = 1
If oMailbox.GetMailbox() = 1 Then
Dim APIResult As Long
Dim oStore As New MailEnable.Store
APIResult = oStore.StoreFolder_Open(Postoffice, Username, "\Sent Items", 0, 1)
If oStore.StoreFolder_FindFirstItem() = 1 Then
Do
Dim WrapperStart As String = "<message>"
Dim ItemId As String="<itemid>"+oStore.StoreItem_GetProperty("ME_ITEM_ID").ToString +"</itemid>"
Dim MessageDate As String = "<dated>" + Left(oStore.StoreItem_GetProperty("PR_ME_MESSAGEDATE").ToString, 10) + " " + Right(oStore.StoreItem_GetProperty("PR_ME_MESSAGEDATE").ToString, 8) + "</dated>"
Dim Attachments As String = "<attachments>" + oStore.StoreItem_GetProperty("PR_ME_ATTACHMENTS").ToString + "</attachments>"
Dim From As String = "<from>" + oStore.StoreItem_GetProperty("PR_ME_FROM").ToString.Replace("<", """").Replace(">", """") + "</from>"
Dim Subject As String = "<subject>" + oStore.StoreItem_GetProperty("PR_SUBJECT").Replace("<", """").Replace(">", """").ToString + "</subject>"
Dim Size As String = "<size>" + oStore.StoreItem_GetProperty("PR_ME_SIZE").ToString + "</size>"
Dim Status As String = "<status>" + oStore.StoreItem_GetProperty("PR_ME_FLAGSTATUS").ToString + "</status>"
Dim WrapperEnd As String = "</message>"
XMLFile = XMLFile + WrapperStart + ItemId + MessageDate + Attachments + From + Subject + Size + Status + WrapperEnd
Loop While (oStore.StoreFolder_FindNextItem() = 1)
XMLFile = "<messages>" + XMLFile + "</messages>"
End If
APIResult = oStore.StoreFolder_FindClose()
APIResult = oStore.StoreFolder_Close()
Else
Throw New ArgumentException("Invalid Mailbox!")
End If
End If
XMLFile = "<result status=""Success"">" + XMLFile + "</result>"
Catch ex As Exception
XMLFile = "<result status=""Err""><reason>" + ex.Message + "</reason></result>"
End Try
Return XMLFile
End Function
Private Function fnGetTotalCount(Username As String, Postoffice As String) As String
Dim XMLFile As String = ""
Dim c As Integer = 0
Try
If Len(Username) <= 0 Or Len(Postoffice) <= 0 Then
Throw New ArgumentException("Invalid Parameters!")
Else
Dim oMailbox As New MailEnable.Administration.Mailbox
oMailbox.Postoffice = Postoffice
oMailbox.MailboxName = Username
oMailbox.Status = 1
If oMailbox.GetMailbox() = 1 Then
Dim APIResult As Long
Dim oStore As New MailEnable.Store
APIResult = oStore.StoreFolder_Open(Postoffice, Username, "\Inbox", 0, 1)
If oStore.StoreFolder_FindFirstItem() = 1 Then
Do
c = c + 1
Loop While (oStore.StoreFolder_FindNextItem() = 1)
XMLFile = "<count>" + c.ToString + "</count>"
End If
APIResult = oStore.StoreFolder_FindClose()
APIResult = oStore.StoreFolder_Close()
Else
Throw New ArgumentException("Invalid Mailbox!")
End If
End If
XMLFile = "<result status=""Success"">" + XMLFile + "</result>"
Catch ex As Exception
XMLFile = "<result status=""Err""><reason>" + ex.Message + "</reason></result>"
End Try
Return XMLFile
End Function
Private Function fnGetUnreadCount(Username As String, Postoffice As String) As String
Dim XMLFile As String = ""
Dim c As Integer = 0
Try
If Len(Username) <= 0 Or Len(Postoffice) <= 0 Then
Throw New ArgumentException("Invalid Parameters!")
Else
Dim oMailbox As New MailEnable.Administration.Mailbox
oMailbox.Postoffice = Postoffice
oMailbox.MailboxName = Username
oMailbox.Status = 1
If oMailbox.GetMailbox() = 1 Then
Dim APIResult As Long
Dim oStore As New MailEnable.Store
APIResult = oStore.StoreFolder_Open(Postoffice, Username, "\Inbox", 0, 1)
If oStore.StoreFolder_FindFirstItem() = 1 Then
Do
If oStore.StoreItem_GetProperty("PR_ME_READ").ToString = "0" Or oStore.StoreItem_GetProperty("PR_ME_READ").ToString = "" Then
c = c + 1
End If
Loop While (oStore.StoreFolder_FindNextItem() = 1)
XMLFile = "<count>" + c.ToString + "</count>"
End If
APIResult = oStore.StoreFolder_FindClose()
APIResult = oStore.StoreFolder_Close()
Else
Throw New ArgumentException("Invalid Mailbox!")
End If
End If
XMLFile = "<result status=""Success"">" + XMLFile + "</result>"
Catch ex As Exception
XMLFile = "<result status=""Err""><reason>" + ex.Message + "</reason></result>"
End Try
Return XMLFile
End Function
Private Function fnCreateMailAccount(Username As String, Postoffice As String) As String
Dim XMLFile As String = ""
Dim MailBoxQuota As Long = 102400
Try
If Len(Username) > 0 And Len(Postoffice) > 0 Then
Dim oPostoffice As New MailEnable.Administration.Postoffice
Dim oDomain As New MailEnable.Administration.Domain
oPostoffice.Account = Postoffice
oPostoffice.Name = Postoffice
oPostoffice.Host = Postoffice
oPostoffice.Status = 1
If oPostoffice.GetPostoffice <> 1 Then
CreatePostoffice(Postoffice, New Guid().ToString.Substring(20))
End If
Dim oLogin As New MailEnable.Administration.Login
oLogin.Account = Postoffice
oLogin.LastAttempt = -1
oLogin.LastSuccessfulLogin = -1
oLogin.LoginAttempts = -1
oLogin.Password = ""
oLogin.Rights = ""
oLogin.Status = -1
oLogin.UserName = Username & "#" & Postoffice
If oLogin.GetLogin <> 1 Then
oLogin.LastAttempt = 0
oLogin.LastSuccessfulLogin = 0
oLogin.LoginAttempts = 0
oLogin.Password = Right(Guid.NewGuid().ToString, 16)
oLogin.Rights = "USER"
oLogin.Status = 1
'Create Login
If oLogin.AddLogin = 1 Then
End If
oLogin = Nothing
Dim oMailbox As New MailEnable.Administration.Mailbox
oMailbox.Postoffice = Postoffice
oMailbox.MailboxName = Username
oMailbox.RedirectAddress = ""
oMailbox.RedirectStatus = 0
oMailbox.Size = 0
oMailbox.Limit = MailBoxQuota
oMailbox.Status = 1
'Create Mailbox
If oMailbox.AddMailbox = 1 Then
'
' Mailbox was added - What could go wrong!
'
End If
oMailbox = Nothing
' Finally, we need to assign address map(s) for the mailbox
Dim oAddressMap As New MailEnable.Administration.AddressMap
oAddressMap.Account = Postoffice
oAddressMap.DestinationAddress = "[SF:" & Postoffice & "/" & Username & "]"
oAddressMap.SourceAddress = "[SMTP:" & Username & "#" & Postoffice & "]"
oAddressMap.Scope = 0
If oAddressMap.AddAddressMap = 1 Then
'
' Address Map was added too - What could go wrong!
'
End If
oAddressMap = Nothing
XMLFile = "<result status=""Success""></result>"
Else
Throw New ArgumentException("Account already exists!")
End If
Else
Throw New ArgumentException("Invalid Parameters!")
End If
Catch ex As Exception
XMLFile = "<result status=""Err""><reason>" + ex.Message + "</reason></result>"
End Try
Return XMLFile
End Function
Function CreatePostoffice(sPostoffice As String, sPassword As String) As String
Dim oPostOffice As New MailEnable.Administration.Postoffice
Dim oMailbox As New MailEnable.Administration.Mailbox
Dim oLogin As New MailEnable.Administration.Login
Dim lResult As Long
CreatePostoffice = False
If Len(sPostoffice) > 0 And Len(sPassword) > 0 Then
oPostOffice.Account = sPostoffice
oPostOffice.Name = sPostoffice
oPostOffice.Status = 1
lResult = oPostOffice.AddPostoffice
If (lResult = 1) Then
oMailbox.Postoffice = sPostoffice
oMailbox.Limit = -1
oMailbox.MailboxName = "Postmaster"
oMailbox.RedirectAddress = ""
oMailbox.RedirectStatus = 0
oMailbox.Status = 1
lResult = oMailbox.AddMailbox
If (lResult = 1) Then
oLogin.Account = sPostoffice
oLogin.Description = "Postmaster Mailbox"
oLogin.Password = sPassword
oLogin.Rights = "ADMIN"
oLogin.Status = 1
oLogin.UserName = "Postmaster#" & sPostoffice
lResult = oLogin.AddLogin
If (lResult = 1) Then
CreatePostoffice = True
End If
End If
End If
End If
oPostoffice = Nothing
oMailbox = Nothing
oLogin = Nothing
End Function
End Class
Though this is not the complete answer, you can start working on it. This way.
Place this ashx code in your MailEnable webmail folder and request from your application.
QueryStringModule is a available to download here
QueryStringModule is used in your application to encrypt http requests and decrypt at MailEnable application.
Allow only your application IP at MailEnable web application for security reasons.

Name Proper Casing

Can you help me in having a proper casing,
I have this code...
Private Function NameCsing(ByVal sValue As String) As String
Dim toConvert As String() = sValue.Split(" ")
Dim lst As New List(Of String)
For i As Integer = 0 To toConvert.Length - 1
Dim converted As String = ""
If toConvert(i).Contains("~") Then
Dim toName As String() = toConvert(i).Split("~")
Dim sName As String = ""
For n As Integer = 0 To toName.Length - 1
Dim sconvert As String = ""
If n = 0 Then
sName = StrConv(toName(n), VbStrConv.ProperCase)
Else
sName += StrConv(toName(n), VbStrConv.ProperCase)
End If
Next
converted = sName
Else
converted = toConvert(i)
End If
lst.Add(converted)
Next
Dim ret As String = ""
For i As Integer = 0 To lst.Count - 1
If i = 0 Then
ret = lst(0)
Else
ret += " " + lst(i)
End If
Next
Return ret
End Function
My codes will just output like this "McDonalds" is you input "mc~donalds"
now my problem is eh I input "evalue", my output must be "eValue"
The only way to know how to treat a special string is to code it yourself from a list of rules:
Private Function NameCsing(ByVal sValue As String) As String
If sValue.Trim.ToLower = "evalue" Then Return "eValue"
'Then process any other special cases
End Function