EWS: How to convert Public Folder MAPI EntryID to EWS FolderID - exchangewebservices

My code works perfect if folders are private
For example if the folder belong to private message store tcFolderId="00000000C29BEF8308F4AD4188BDF6CB1517D65401008AC18FCDFD1EF64FBB5D946C26787598000000BC70750000"
Public Function mmks_ConvertMAPIFolderIdToEWSFolderId(tcFolderId As String, tcMailBox As String) As String
Dim loHexEntryID As New AlternateId(IdFormat.HexEntryId, tcFolderId, tcMailBox)
Dim loEntryId As AlternateId = _pmks_exchangeService.ConvertId(loHexEntryID, IdFormat.EntryId)
Return CType(_pmks_exchangeService.ConvertId(loEntryId, IdFormat.EwsId), AlternateId).UniqueId
End Function
But for public message store this code does not work.
When Public FolderId = "000000001A447390AA6611CD9BC800AA002FC45A0300D32A8E9A328D734A98B8E1E7D3C591F5012EE3EFFFB60000"
After conversion this code returns
"AAMkADkwZTlhMjA2LWQ1NTUtNDNkOS04N2M3LWYyZmFkZDFjMjlmNgAuAAAAAAAaRHOQqmYRzZvIAKoAL8RaAwDTKo6aMo1zSpi44efTxZH1AS7j7/+2AAA="
But this is wrong.
Because I rescan PublicFoldersRoot using FindFolders(WellKnownFolderName.PublicFoldersRoot) and this folder has UniqueId = "AQEuAAADGkRzkKpmEc2byACqAC/EWgMA0yqOmjKNc0qYuOHn08WR9QEu4+//tgAAAA=="
The questio is:
How to convert Public message store folder EntryID into EWS FolderId?

You need to use the AlternatePublicFolderId Class https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/alternatepublicfolderid for public Folders eg
Public Function mmks_ConvertMAPIFolderIdToEWSFolderId(tcFolderId As String, tcMailBox As String) As String
Dim loHexEntryID As New AlternatePublicFolderId (IdFormat.HexEntryId, tcFolderId, tcMailBox)
Dim loEntryId As AlternatePublicFolderId = _pmks_exchangeService.ConvertId(loHexEntryID, IdFormat.EntryId)
Return CType(_pmks_exchangeService.ConvertId(loEntryId, IdFormat.EwsId), AlternatePublicFolderId).UniqueId
End Function

Related

How to iterate through all keys of json node

I'm trying to scrap the key values from this website API and it seems the json format it's not an array.
I'm working with console .Net core 6.0 using System.Text.Json.Nodes
The code I'm using is :
Dim streamData As Stream = Nothing
Using http As HttpClient = New HttpClient
Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"
Dim t As Task(Of Stream) = http.GetStreamAsync(url)
streamData = t.Result
End Using
Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
Dim jsonData As JsonNode = jsonResponse("result")
Dim c As String = String.Empty
For Each jsonCurrency As JsonNode In jsonData.AsObject
c += jsonCurrency("last").ToString + " "
Next
but I get the error:
Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode
What Am I doing wrong?
Thanks
Create a class to represent your JSON, like this:
Public Class MarketStatus
Public Property IsChange As Boolean
Public Property period As Integer
Public Property open As String
Public Property last As String
Public Property high As String
Public Property low As String
Public Property volume As String
Public Property deal As String
Public Property close As String
Public Property base_volume As String
Public Property quote_volume As String
End Class
Public Class Payload
Public Property _error As Object
Public Property result As Result
Public Property id As Integer
End Class
Public Class Result
<JsonPropertyName("0xBTCBTC")>
Public Property _0xBTCBTC As MarketStatus
<JsonPropertyName("0xBTCETH")>
Public Property _0xBTCETH As MarketStatus
<JsonPropertyName("0xCASHUSDT")>
Public Property _0xCASHUSDT As MarketStatus
<JsonPropertyName("1INCH1D3LUSDT")>
Public Property _1INCH1D3LUSDT As MarketStatus
' etc...
End Class
Now you can deserialize the entire payload by using JsonSerializer.Deserialize or JsonSerializer.DeserializeAsync:
Dim payloadObject = Await JsonSerializer.DeserializeAsync(Of Payload)(streamData)
Update
Per our conversation in the comments of this answer, you want to get the last value of each MarketStatus without having to type each one manually. What you can do is:
Use reflection to get every property of the Result class
Loop over the collection
Use PropertyInfo.GetValue to get the value of the deserialized object
Here is an example using the same variable names as above:
For Each propertyInformation In GetType(Result).GetProperties()
Dim status = DirectCast(propertyInformation.GetValue(payloadObject.result), MarketStatus)
Console.WriteLine("{0}.last = {1}", propertyInformation.Name, status.last)
Next
Fiddle: https://dotnetfiddle.net/USaAgc
I solved using
Dim result As JsonObject = jsonResponse("result").AsObject
For Each kvp In result.AsEnumerable
c &= kvp.Value("last").ToString & ", "
Next

Parse Dynamic Json Object into VB Classes

I have this nested structure
and want to parse it into classes.
I have this code to get the json file and to deserialize it
Public Function getData(ByVal _token As String, ByVal _identifier As String) As Results_FullData
Dim client = New RestClient(_baseURI)
Dim request = New RestRequest("/datasource/{id}/data", Method.GET)
request.AddParameter("id", _identifier)
request.AddUrlSegment("id", _identifier)
request.AddHeader("Authorization", "Bearer " + _token)
request.AddHeader("environment", _environment)
Dim jstr = client.Execute(request).Content
Dim allData As Results_FullData = JsonConvert.DeserializeObject(Of Results_FullData)(jstr)
Return allDATA
End Function
And build this class structure
Public Class Results_FullData
Public Property results As List(Of DSContent)
End Class
Public Class DSContent
Public Property userRunId As Long
Public Property metaColumnValues As List(Of String)
Public Property dataColumnValues As List(Of String)
End Class
But running the code the object datasourceInfo is empty and I do not know why. I thought I could just adopt the solution of this answer but it does not work. I guess the List(Of String) part is wrong. The problem mibht be that the length of metaColumnValues und dataColumnValues differs within each object {}. The idea is to get it into a string and seperate it later, since the values are , seperated within the object
Anyone who can help me here?
Edit:
Dataexample:
{"result":[{"userRunId":"xxxxxxx","metaColumnValues":["9006409","20073"],"dataColumnValues":["","superior"]},{"userRunId":"xxxxxxx","metaColumnValues":["2345","235","1"],"dataColumnValues":["","superior", "test"]}]}
In Results_FullData, the property is called results, but in the example JSON, it's called result. Also, DSContent.userRunId is declared as a Long, even though in the JSON, that property contains String values. If you fix those two things in your data classes, it properly deserializes your example data:
Public Sub Main()
Dim json As String = "{""result"":[{""userRunId"":""xxxxxxx"",""metaColumnValues"":[""9006409"",""20073""],""dataColumnValues"":["""",""superior""]},{""userRunId"":""xxxxxxx"",""metaColumnValues"":[""2345"",""235"",""1""],""dataColumnValues"":["""",""superior"", ""test""]}]}"
Dim allData As Results_FullData = JsonConvert.DeserializeObject(Of Results_FullData)(json)
End Sub
Public Class Results_FullData
Public Property result As List(Of DSContent)
End Class
Public Class DSContent
Public Property userRunId As String
Public Property metaColumnValues As List(Of String)
Public Property dataColumnValues As List(Of String)
End Class

Writing and Reading JSON in VB.net using Newtonsoft

This is my first time using JSON and I'm stuck. I'm trying to send a test SMS via http://sms.roamtech.com/smsapi/. The format is:
Send message format(json).
{
"result":{
"account":"xxxx",
"user":"xxxx",
"password":"xxxxxxxx",
"requestType":"BULK",
"alphanumeric":"xxxxxxxx",
"data":{
"linkid":"xxxxxxx",
"msisdn":"xxxxxxxxxxx",
"networkid":"1",
"message":"xxxxxxxxxxxx",
"callback":"http//test"
}
}
}
So, this is what I've come up with after reviewing various posts on this and other sites:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.IO
Imports System.Net
Imports System.Text
Module modJSON
Public Class clsResult
Public account As String
Public user As String
Public password As String
Public requestType As String
Public alphanumeric As String
Public data As New clsData
End Class
Public Class clsData
Public linkid As String
Public msisdn As String
Public networkid As String
Public message As String
Public callback As String
End Class
Public Class clsPOST
Public result As New clsResult
End Class
Public Sub chkJSON()
Dim r As New clsResult
Dim d As New clsData
Dim x As New clsPOST
r.account = "8852"
r.user = "username"
r.password = "password"
r.requestType = "BULK"
r.alphanumeric = "SMSLEO"
d.linkid = "1001"
d.msisdn = "2547xxxxxxxx"
d.networkid = "1"
d.message = "Just a test"
d.callback = "http://infiniti-africa.com/json"
r.data = d
x.result = r
Dim uriRoam As New Uri("http://sms.roamtech.com/smsapi")
Dim strJSON = JsonConvert.SerializeObject(x, Formatting.Indented)
Dim bytJSON = Encoding.UTF8.GetBytes(strJSON)
Dim result_post = SendRequest(uriRoam, bytJSON, "application/json", "POST")
MsgBox(result_post)
End Sub
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
End Module
The string strJSONseems to contain the correct key:value combinations. However, the code doesn't send the test SMS and I don't get any response. 'SendRequest' returns an empty string.
Also, I'm not sure what to use for the "callback" url, which is where the delivery report is forwarded.
Note:
1. "linkid" is a unique message ID
2. "msidn" is the recipient phone number
Any help is appreciated.
I have also tried using the following class:
Public Class JsonPost
Private urlToPost As String = ""
Public Sub New(ByVal urlToPost As String)
Me.urlToPost = urlToPost
End Sub
Public Function postData(pstData As Byte()) As Boolean
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Try
webClient.Headers("content-type") = "application/json"
resByte = webClient.UploadData(Me.urlToPost, "post", pstData)
resString = Encoding.Default.GetString(resByte)
Console.WriteLine(resString)
webClient.Dispose()
Return True
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return False
End Function
End Class
Then calling:
Dim strJSON = JsonConvert.SerializeObject(x)
Dim bytJSON = Encoding.UTF8.GetBytes(strJSON)
Dim jsonPost As New JsonPost("http://sms.roamtech.com/smsapi")
jsonPost.postData(bytJSON)
I'm still getting nothing. Been struggling with this for three days now. Any ideas anyone?
Turns out I've been stressing for four days over a trailing slash (/). The API URL is:
http://sms.roamtech.com/smsapi/
While I've been using:
http://sms.roamtech.com/smsapi
Lesson learnt.

Getting Error Invalid cast from 'System.String' to 'System.Guid'

I am Importing Data in Student Record from excel sheet with .xls as it's file extension when i am calling the function to upload Excel that is
public ActionResult Importexcel()
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-UserInfo-20140318063343.mdf;Initial Catalog=aspnet-UserInfo-20140318063343;Integrated Security=True";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [Id],[Name],[StudentId] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
//Give your Destination table name
sqlBulk.DestinationTableName = "StudentRecords";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
// SQL Server Connection String
}
return RedirectToAction("Import");
}
I am getting the following Error
Invalid cast from 'System.String' to 'System.Guid'.
My model is below and i cant change Guid as it is necessary need of mine
public class StudentRecord
{
public long Id { get; set; }
public string Name { get; set; }
public Guid StudentId { get; set; }
}
studentRecord.Guid = new Guid("Mystring");
Maybe, you have to itarate trough the objects what sou got from db, and parse on by one for reach the statement above.
You could also look at using a TypeConverter.
Parse string to system Guid as below. it may help you
System.Guid.Parse(yourStringVariable);

POST using the uploadstring method to call a web service and pass a json array

I am attempting to do a POST to a web service. I am using the WebClient class and calling the uploadstring method. This works fine until the web service I call expects some data, particularly a json array. I am trying to find out what format the data needs to be in, in order for the web service to accept and consume it properly. Example:
WebClient myWebClient = new WebClient();
string resp = myWebClient.UploadString("www.myUrl.com", "POST", "someDataToSend");
Any help here would be appreciated!
the web service (vb.net) being called takes a keyvaluepair:
<OperationContract(), WebInvoke(BodyStyle:=WebMessageBodyStyle.WrappedRequest, Method:="POST", RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)> _
Public Function DoSomething(ByVal myKeyValuePair() As KeyValuePair(Of String, String)) As String
I found a solution for this. The data has to be in json format literally:
"{"Type":[{"key":"cType","value":"Age"}]}"
I created a class serialized it and then finagled the square brackets in.
Public Class cType
Private _key As String
Public Property Key() As String
Get
Return _key
End Get
Set(ByVal value As String)
value = "cType"
_key = value
End Set
End Property
Public value As String
End Class
Dim objType As cType = New cType
objType.value = "Age"
Dim myData As String = deserializer.Serialize(New With {.cType = objType})
myData = myData.Insert(12, "[")
myData = myData.Insert(myData.Length - 1, "]")