System.ComponentModel.Win32Exception: 'An error occurred trying to start process' - wpf

I am showing this notification to the user when I finish doing some work.
I manage to send the notification to the user, but it doesn't open the document that I am sending it
What I am trying to do, is open the document in word on your local compuuter
speechRecognizer.SessionStopped += (sender, e) => {
const string ext = ".docx";
var pathToSave = CreateFolderService.CreateFolder(ConstantsHelpers.TRANSCRIPTIONS);
var filename = Path.Combine(pathToSave, $"{Path.GetFileNameWithoutExtension(FilePath)}{ext}");
var sb = new StringBuilder();
foreach (var item in Characers) {
sb.Append(item);
}
using var document = new WordDocument();
document.EnsureMinimal();
document.LastParagraph.AppendText(sb.ToString());
// Find all the text which start with capital letters next to period (.) in the Word document.
//For example . Text or .Text
TextSelection[] textSelections = document.FindAll(new Regex(#"[.]\s+[A-Z]|[.][A-Z]"));
for (int i = 0; i < textSelections.Length; i++) {
WTextRange textToFind = textSelections[i].GetAsOneRange();
//Replace the period (.) with enter(\n).
string replacementText = textToFind.Text.Replace(".", ".\n\n");
textToFind.Text = replacementText;
}
document.Save(filename);
ToastService.LaunchToastNotification(filename);
tiles![Id].IsTileActive = true;
public static void LaunchToastNotification(string FilePath) {
ToastNotificationManagerCompat.OnActivated += toastArgs => {
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
Process.Start(FilePath, args["doc"]);
};
new ToastContentBuilder()
.AddText(Lang.ToastMsg1)
.AddText(Lang.ToastMsg2)
.AddAppLogoOverride(new Uri("file:///" + Path.GetFullPath(#"Images\Word.png"), UriKind.Absolute), ToastGenericAppLogoCrop.Circle)
.AddButton(new ToastButton()
.SetContent("Open document")
.AddArgument("action", "openDec")
.AddArgument("doc", FilePath))
.Show();
I get an exception
System.ComponentModel.Win32Exception:
'An error occurred trying to start process 'C:\Users\xxx\OneDrive - Universidad Politécnica de Madrid\Documents\TreanscribeMe\Transcriptions\Why French Makes No Sense pt 120 Accents.docx' with working directory
'C:\Users\xxx\source\repos\TranscribeMe\bin\Debug\net6.0-windows10.0.19041.0'. The specified executable is not a valid application for this OS platform.'
Witch makes no sense to me, because, I am sending the file path
C:\Users\xxx\OneDrive - Universidad Politécnica de Madrid\Documents\TreanscribeMe\Transcriptions\Why French Makes No Sense pt 120 Accents.docx
Also for some reason, the notification is triggered twice
This is my Toast Service
public class ToastService {
public static void LaunchToastNotification(string FilePath) {
ToastNotificationManagerCompat.OnActivated += toastArgs => {
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
Process.Start(FilePath, args["doc"]);
};
new ToastContentBuilder()
.AddText(Lang.ToastMsg1)
.AddText(Lang.ToastMsg2)
.AddAppLogoOverride(new Uri("file:///" + Path.GetFullPath(#"Images\Word.png"), UriKind.Absolute), ToastGenericAppLogoCrop.Circle)
.AddButton(new ToastButton()
.SetContent("Open document")
.AddArgument("action", "openDec")
.AddArgument("doc", FilePath))
.Show();
}
}
}
Update
I am doing this now
ToastNotificationManagerCompat.OnActivated += toastArgs => {
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
Process.Start("WINWORD.EXE", args["doc"]);
};
new ToastContentBuilder()
.AddText(Lang.ToastMsg1)
.AddText(Lang.ToastMsg2)
.AddAppLogoOverride(new Uri("file:///" + Path.GetFullPath(#"Images\Word.png"), UriKind.Absolute), ToastGenericAppLogoCrop.Circle)
.AddButton(new ToastButton()
.SetContent("Open document")
.AddArgument("action", "openDec")
.AddArgument("doc", FilePath))
.Show();
and get
System.Collections.Generic.KeyNotFoundException: 'A key with name 'doc' could not be found.'
Second update
I change a little to
ToastNotificationManagerCompat.OnActivated += toastArgs => {
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
var startInfo = new ProcessStartInfo();
startInfo.FileName = "WINWORD.EXE";
startInfo.Arguments = FilePath;
startInfo.Arguments = "doc";
Process.Start(startInfo);
System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'WINWORD.EXE' with working directory 'C:\Users\egome\source\repos\TranscribeMe\bin\Debug\net6.0-windows10.0.19041.0'. The system cannot find the file specified.'

Related

Tenant to tenant user migration in Azure Active Directory using Graph API

Is it possible to migrate users using the MS Graph API in Azure AD?
If so, please explain how to migrate users from one tenant to the other using the MS Graph API.
You can export the users with MS Graph. Note, you can't export the passwords. This means that you have to create a new password and share it with the users. Or choose a random password and let the users reset their password using the self-service password rest feature.
Here is an example how to export the users from a directly
public static async Task ListUsers(GraphServiceClient graphClient)
{
Console.WriteLine("Getting list of users...");
DateTime startTime = DateTime.Now;
Dictionary<string, string> usersCollection = new Dictionary<string, string>();
int page = 0;
try
{
// Get all users
var users = await graphClient.Users
.Request()
.Select(e => new
{
e.DisplayName,
e.Id
}).OrderBy("DisplayName")
.GetAsync();
// Iterate over all the users in the directory
var pageIterator = PageIterator<User>
.CreatePageIterator(
graphClient,
users,
// Callback executed for each user in the collection
(user) =>
{
usersCollection.Add(user.DisplayName, user.Id);
return true;
},
// Used to configure subsequent page requests
(req) =>
{
var d = DateTime.Now - startTime;
Console.WriteLine($"{string.Format(TIME_FORMAT, d.Days, d.Hours, d.Minutes, d.Seconds)} users: {usersCollection.Count}");
// Set a variable to the Documents path.
string filePrefix = "0";
if (usersCollection.Count >= 1000000)
{
filePrefix = usersCollection.Count.ToString()[0].ToString();
}
page++;
if (page >= 50)
{
page = 0;
string docPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"users_{filePrefix}.json");
System.IO.File.WriteAllTextAsync(docPath, JsonSerializer.Serialize(usersCollection));
}
Thread.Sleep(200);
return req;
}
);
await pageIterator.IterateAsync();
// Write last page
string docPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"users_all.json");
System.IO.File.WriteAllTextAsync(docPath, JsonSerializer.Serialize(usersCollection));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
After you export the users, you can import them back to the other tenant. The following example creates test users. Change the code to set the values from the files you exported earlier. Also, this code uses batch with 20 users in single operation.
public static async Task CreateTestUsers(GraphServiceClient graphClient, AppSettings appSettings, bool addMissingUsers)
{
Console.Write("Enter the from value: ");
int from = int.Parse(Console.ReadLine()!);
Console.Write("Enter the to value: ");
int to = int.Parse(Console.ReadLine()!);
int count = 0;
Console.WriteLine("Starting create test users operation...");
DateTime startTime = DateTime.Now;
Dictionary<string, string> existingUsers = new Dictionary<string, string>();
// Add the missing users
if (addMissingUsers)
{
// Set a variable to the Documents path.
string docPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "users.json");
if (!System.IO.File.Exists(docPath))
{
Console.WriteLine("Can't find the '{docPath}' file.");
}
string usersFile = System.IO.File.ReadAllText(docPath);
existingUsers = JsonSerializer.Deserialize<Dictionary<string, string>>(usersFile);
if (existingUsers == null)
{
Console.WriteLine("Can't deserialize users");
return;
}
Console.WriteLine($"There are {existingUsers.Count} in the directory");
}
List<User> users = new List<User>();
// The batch object
var batchRequestContent = new BatchRequestContent();
for (int i = from; i < to; i++)
{
// 1,000,000
string ID = TEST_USER_PREFIX + i.ToString().PadLeft(7, '0');
if (addMissingUsers)
{
if (existingUsers.ContainsKey(ID))
continue;
}
count++;
try
{
var user = new User
{
DisplayName = ID,
JobTitle = ID.Substring(ID.Length - 1),
Identities = new List<ObjectIdentity>()
{
new ObjectIdentity
{
SignInType = "userName",
Issuer = appSettings.TenantName,
IssuerAssignedId = ID
},
new ObjectIdentity
{
SignInType = "emailAddress",
Issuer = appSettings.TenantName,
IssuerAssignedId = $"{ID}#{TEST_USER_SUFFIX}"
}
},
PasswordProfile = new PasswordProfile
{
Password = "1",
ForceChangePasswordNextSignIn = false
},
PasswordPolicies = "DisablePasswordExpiration,DisableStrongPassword"
};
users.Add(user);
if (addMissingUsers)
{
Console.WriteLine($"Adding missing {ID} user");
}
// POST requests are handled a bit differently
// The SDK request builders generate GET requests, so
// you must get the HttpRequestMessage and convert to a POST
var jsonEvent = graphClient.HttpProvider.Serializer.SerializeAsJsonContent(user);
HttpRequestMessage addUserRequest = graphClient.Users.Request().GetHttpRequestMessage();
addUserRequest.Method = HttpMethod.Post;
addUserRequest.Content = jsonEvent;
if (batchRequestContent.BatchRequestSteps.Count >= BATCH_SIZE)
{
var d = DateTime.Now - startTime;
Console.WriteLine($"{string.Format(TIME_FORMAT, d.Days, d.Hours, d.Minutes, d.Seconds)}, count: {count}, user: {ID}");
// Run sent the batch requests
var returnedResponse = await graphClient.Batch.Request().PostAsync(batchRequestContent);
// Dispose the HTTP request and empty the batch collection
foreach (var step in batchRequestContent.BatchRequestSteps) ((BatchRequestStep)step.Value).Request.Dispose();
batchRequestContent = new BatchRequestContent();
}
// Add the event to the batch operations
batchRequestContent.AddBatchRequestStep(addUserRequest);
// Console.WriteLine($"User '{user.DisplayName}' successfully created.");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

An unexpected null key in HashSet, the first be added not the rest

I'm learning Activiti 7, I drew a BPMN diagram as below:
When the highlight1 UserTask has been completed but the highlight2 UserTask is still pending, I ran the following code to highlight the completed flow element.
private AjaxResponse highlightHistoricProcess(#RequestParam("instanceId") String instanceId,
#AuthenticationPrincipal UserInfo userInfo) {
try {
// Get the instance from the history table
HistoricProcessInstance instance = historyService
.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
BpmnModel bpmnModel = repositoryService.getBpmnModel(instance.getProcessDefinitionId());
Process process = bpmnModel.getProcesses().get(0);
// Get all process elements, including sequences, events, activities, etc.
Collection<FlowElement> flowElements = process.getFlowElements();
Map<String, String> sequenceFlowMap = Maps.newHashMap();
flowElements.forEach(e -> {
if (e instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) e;
String sourceRef = sequenceFlow.getSourceRef();
String targetRef = sequenceFlow.getTargetRef();
sequenceFlowMap.put(sourceRef + targetRef, sequenceFlow.getId());
}
});
// Get all historical Activities, i.e. those that have been executed and those that are currently being executed
List<HistoricActivityInstance> actList = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.list();
// Each history Activity is combined two by two
Set<String> actPairSet = new HashSet<>();
for (HistoricActivityInstance actA : actList) {
for (HistoricActivityInstance actB : actList) {
if (actA != actB) {
actPairSet.add(actA.getActivityId() + actB.getActivityId());
}
}
}
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
// Get the completed Activity
List<HistoricActivityInstance> finishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.finished()
.list();
// Highlight the completed Activity
Set<String> highActSet = Sets.newHashSet();
finishedActList.forEach(point -> highActSet.add(point.getActivityId()));
// Get the pending highlighted node, i.e. the currently executing node
List<HistoricActivityInstance> unfinishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.unfinished()
.list();
Set<String> unfinishedPointSet = Sets.newHashSet();
unfinishedActList.forEach(point -> unfinishedPointSet.add(point.getActivityId()));
...
return AjaxResponse.ajax(ResponseCode.SUCCESS.getCode(),
ResponseCode.SUCCESS.getDesc(),
null);
} catch (Exception e) {
e.printStackTrace();
return AjaxResponse.ajax(ResponseCode.ERROR.getCode(),
"highlight failure",
e.toString());
}
}
Please see this piece of code:
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
It was expected to get 2 elements in the highSequenceSet, but it got 3, with a unexpected null.
The log printed in the console was:
Why is the first null added to the HashSet but not the rest?
Why is the first null added to the HashSet but not the rest?
HashSet implements the Set interface, duplicate values are not allowed.

Excel corrupted generated with Apache POI returned fronm API REST spring boot

EDIT :
If I hit directly the endpoint from the browser, the file is dowloaded correctly.
So I guess the problem is in the front and the way to create and save the file with the data received.
I have a java/spring boot application where I want to build an API endpoint that creates and returns a downloadable excel file. Here is my controller endpoint:
#GetMapping(path = "/informe/{informeDTO}")
public ResponseEntity<InputStreamResource> generarInforme(#PathVariable(value = "informeDTO") String informeDTOString) throws JsonParseException, JsonMappingException, IOException {
final InformeDTO informeDTO =
new ObjectMapper().readValue(informeDTOString, InformeDTO.class);
List<InformeDTO> listDatosinformeDTO = utilsService.getDatosInformeDTO(informeDTO);
for (InformeDTO informeDTO2 : listDatosinformeDTO) {
logger.debug(informeDTO2);
}
ByteArrayInputStream in = createReport(listDatosinformeDTO);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=IOPreport.xlsx");
return ResponseEntity.ok().headers(headers)
.contentType(
MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(new InputStreamResource(in));
}
This is the angular controller :
function generarInformeIOP(){
InformesService.generarInformeIOP($scope.informeView.sociedad, $scope.informeView.area, $scope.informeView.epigrafe,
$scope.informeView.cuenta, $scope.informeView.status, $scope.informeView.organizationalUnit,
$scope.informeView.societyGL, $scope.informeView.calculationType, $scope.informeView.provincia, $scope.informeView.financialSegment,
$scope.informeView.loadDateFrom, $scope.informeView.loadDateTo, $scope.informeView.incomeDateFrom, $scope.informeView.incomeDateTo)
.then(
function(response)
{
var blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "IOPreport.xlsx");
$scope.informeFunctionality.errorMessage = '';
},
function(errResponse)
{
console.log("ERROR: " + errResponse.data);
$scope.informeFunctionality.errorMessage = "Ha ocurrido un error inesperado: " + errResponse.data.error +
": " + errResponse.data.message;
}
)
}
And the service :
....
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO)).then(
function(response) {
console.log("GenerarInformeIOP - success");
deferred.resolve(response);
}, function(errResponse) {
console.log("GenerarInformeIOP - error");
deferred.reject(errResponse);
});
...
The generation is successfull, the file is downloaded but I think it is corrupted because Excel can't open it.
Are there anything wrong?
EDIT (adding createReport) :
private ByteArrayInputStream createReport(List<InformeDTO> datosInforme) {
ByteArrayInputStream result =null;
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
Set<String> columns = new LinkedHashSet<String>();
// Coumnas fijas
columns.add("Cuenta");
columns.add("Epigrafe");
columns.add("Descripcion");
columns.add("Total_Importe");
// Columnas dinamicas
/*
* Tedremos que recorrer todas las filas puesto que no sabremos si una traera
* menos periodos que otra de esta manera obtendremos todos los periodos
*/
for (InformeDTO informeDTO : datosInforme) {
for (Map.Entry<String, Double> entry : informeDTO.getTotalByPeriodoContable().entrySet()) {
columns.add(entry.getKey());
}
}
/*
* CreationHelper helps us create instances for various things like DataFormat,
* Hyperlink, RichTextString etc in a format (HSSF, XSSF) independent way
*/
// CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("IOPReport");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Creating cells
int i = 0;
for (String value : columns) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(value);
cell.setCellStyle(headerCellStyle);
i++;
}
// Create Other rows and cells with employees data
int rowNum = 1;
int cellDynamicNum = 0;
for (InformeDTO informeDTO : datosInforme) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(informeDTO.getCuenta());
row.createCell(1).setCellValue(informeDTO.getEpigrafe());
row.createCell(2).setCellValue(informeDTO.getDescripcion_epigrafe());
row.createCell(3).setCellValue("No Data");
cellDynamicNum = 4;
for (Map.Entry<String, Double> entry : informeDTO.getTotalByPeriodoContable().entrySet()) {
row.createCell(cellDynamicNum).setCellValue(entry.getValue());
cellDynamicNum++;
}
}
// Resize all columns to fit the content size
for (i = 0; i < columns.size(); i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
workbook.write(out);
result = new ByteArrayInputStream(out.toByteArray());
out.close();
workbook.close();
} catch (Exception e) {
logger.debug("Excepcion en la creacion del report " + e);
}
return result;
}
Regards
When building the output here:
result = new ByteArrayInputStream(out.toByteArray());
The workbook is not saved into out until it is closed. So you need to change the order to:
workbook.close()
result = new ByteArrayInputStream(out.toByteArray());
Closing a ByteArrayOutputStream is not necessary but it's fine if you leave it.
I'm not sure why ResponseEntity<InputStreamResource> is used. I've another working solution which use byte-array ResponseEntity<byte[]>. Some of the code snippet are attached below:
After creating the workbook, write it to outputstream:
private final MediaType mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
...
...
// at the end
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.write(stream);
return getDownload(stream.toByteArray(), filename, mediaType);
....
Download method:
public static ResponseEntity<byte[]> getDownload(byte[] content, String filename, MediaType mediaType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(content.length);
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
headers.set(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
headers.setContentType(mediaType);
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
Let me know if this works.
I resolved it adding the reponse type in the front call:
var config = { responseType: 'blob' };
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO), config).then(
....
)

How to access Spans with a SpanNearQuery in solr 6.3

I am trying to build a query parser by ranking the passages containing the terms.
I understand that I need to use SpanNearQuery, but I can't find a way to access Spans even after going through the documentation. The method I got returns null.
I have read https://lucidworks.com/blog/2009/07/18/the-spanquery/ which explains in a good way about the query. This explains how to access spans, but it is for solr 4.0 and unfortunately solr 6.3 doesn't have atomic reader any more.
How can I get the actual spans?
public void process(ResponseBuilder rb) throws IOException {
SolrParams params = rb.req.getParams();
log.warn("in Process");
if (!params.getBool(COMPONENT_NAME, false)) {
return;
}
Query origQuery = rb.getQuery();
// TODO: longer term, we don't have to be a span query, we could re-analyze the document
if (origQuery != null) {
if (origQuery instanceof SpanNearQuery == false) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Illegal query type. The incoming query must be a Lucene SpanNearQuery and it was a " + origQuery.getClass().getName());
}
SpanNearQuery sQuery = (SpanNearQuery) origQuery;
SolrIndexSearcher searcher = rb.req.getSearcher();
IndexReader reader = searcher.getIndexReader();
log.warn("before leaf reader context");
List<LeafReaderContext> ctxs = (List<LeafReaderContext>) reader.leaves();
log.warn("after leaf reader context");
LeafReaderContext ctx = ctxs.get(0);
SpanWeight spanWeight = sQuery.createWeight(searcher, true);
Spans spans = spanWeight.getSpans(ctx, SpanWeight.Postings.POSITIONS);
AtomicReader wrapper = SlowCompositeReaderWrapper.wrap(reader);
Map<Term, TermContext> termContexts = new HashMap<Term, TermContext>();
Spans spans = fleeceQ.getSpans(wrapper.getContext(), new Bits.MatchAllBits(reader.numDocs()), termContexts);
// SpanWeight.Postings[] postings= SpanWeight.Postings.values();
// Spans spans = sQuery.getSpans();
// Assumes the query is a SpanQuery
// Build up the query term weight map and the bi-gram
Map<String, Float> termWeights = new HashMap<String, Float>();
Map<String, Float> bigramWeights = new HashMap<String, Float>();
createWeights(params.get(CommonParams.Q), sQuery, termWeights, bigramWeights, reader);
float adjWeight = params.getFloat(ADJACENT_WEIGHT, DEFAULT_ADJACENT_WEIGHT);
float secondAdjWeight = params.getFloat(SECOND_ADJ_WEIGHT, DEFAULT_SECOND_ADJACENT_WEIGHT);
float bigramWeight = params.getFloat(BIGRAM_WEIGHT, DEFAULT_BIGRAM_WEIGHT);
// get the passages
int primaryWindowSize = params.getInt(OWLParams.PRIMARY_WINDOW_SIZE, DEFAULT_PRIMARY_WINDOW_SIZE);
int adjacentWindowSize = params.getInt(OWLParams.ADJACENT_WINDOW_SIZE, DEFAULT_ADJACENT_WINDOW_SIZE);
int secondaryWindowSize = params.getInt(OWLParams.SECONDARY_WINDOW_SIZE, DEFAULT_SECONDARY_WINDOW_SIZE);
WindowBuildingTVM tvm = new WindowBuildingTVM(primaryWindowSize, adjacentWindowSize, secondaryWindowSize);
PassagePriorityQueue rankedPassages = new PassagePriorityQueue();
// intersect w/ doclist
DocList docList = rb.getResults().docList;
log.warn("Before Spans");
while (spans.nextDoc() != Spans.NO_MORE_DOCS) {
// build up the window
log.warn("Iterating through spans");
if (docList.exists(spans.docID())) {
tvm.spanStart = spans.startPosition();
tvm.spanEnd = spans.endPosition();
// tvm.terms
Terms terms = reader.getTermVector(spans.docID(), sQuery.getField());
tvm.map(terms, spans);
// The entries map contains the window, do some ranking of it
if (tvm.passage.terms.isEmpty() == false) {
log.debug("Candidate: Doc: {} Start: {} End: {} ", new Object[] { spans.docID(), spans.startPosition(), spans.endPosition() });
}
tvm.passage.lDocId = spans.docID();
tvm.passage.field = sQuery.getField();
// score this window
try {
addPassage(tvm.passage, rankedPassages, termWeights, bigramWeights, adjWeight, secondAdjWeight, bigramWeight);
} catch (CloneNotSupportedException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Internal error cloning Passage", e);
}
// clear out the entries for the next round
tvm.passage.clear();
}
}
}
}

Get appointments from all Outlook calendars

I'm trying to read appointments from Outlook calendar using ExchangeServiceBinding but my solution takes appointments only from "default" outlook calendar and don't read from "sub calendars/custom calendars". Do you know how to define rest of the calendars or do you know better solution which contains all calendars?
Critical part is that solution shouldn't contain MAPI because of next use in web service.
My current code:
private static List<List<string>> ReadCalendarEvents(string email)
{
List<List<string>> calendarEvents = new List<List<string>>();
// Specify the request version.
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007;
// Form the FindItem request.
FindItemType findItemRequest = new FindItemType();
CalendarViewType calendarView = new CalendarViewType();
calendarView.StartDate = DateTime.Now.AddDays(-7);
calendarView.EndDate = DateTime.Now.AddDays(200);
calendarView.MaxEntriesReturned = 1000;
calendarView.MaxEntriesReturnedSpecified = true;
findItemRequest.Item = calendarView;
// Define which item properties are returned in the response.
ItemResponseShapeType itemProperties = new ItemResponseShapeType();
// Use the Default shape for the response.
//itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
findItemRequest.ItemShape = itemProperties;
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;
//
folderIDArray[0].Mailbox = new EmailAddressType();
folderIDArray[0].Mailbox.EmailAddress = email;
findItemRequest.ParentFolderIds = folderIDArray;
// Define the traversal type.
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
try
{
// Send the FindItem request and get the response.
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
// Access the response message.
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType[] rmta = responseMessages.Items;
int folderNumber = 0;
foreach (ResponseMessageType rmt in rmta)
{
// One FindItemResponseMessageType per folder searched.
FindItemResponseMessageType firmt = rmt as FindItemResponseMessageType;
if (firmt.RootFolder == null)
continue;
FindItemParentType fipt = firmt.RootFolder;
object obj = fipt.Item;
// FindItem contains an array of items.
if (obj is ArrayOfRealItemsType)
{
ArrayOfRealItemsType items =
(obj as ArrayOfRealItemsType);
if (items.Items == null)
{
folderNumber++;
}
else
{
foreach (ItemType it in items.Items)
{
if (it is CalendarItemType)
{
CalendarItemType cal = (CalendarItemType)it;
List<string> ce = new List<string>();
ce.Add(cal.Location);
ce.Add(cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString());
ce.Add(cal.End.ToShortDateString() + " " + cal.End.ToShortTimeString());
ce.Add(cal.Subject);
if (cal.Organizer != null)
{
ce.Add(cal.Organizer.Item.Name);
}
calendarEvents.Add(ce);
Console.WriteLine(cal.Subject + " " + cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString() + " " + cal.Location);
}
}
folderNumber++;
}
}
}
}
catch (Exception e)
{
throw;
}
finally
{
}
return calendarEvents;
}
In EWS you need to query one folder at a time, for non default folders you will first need to find the FolderId before you can then query the appointments (or items) within a Folder. To find all the Calendar folders in a Mailbox you need to use the FindFolder operation and create a restriction to limit the result to folder with a FolderClass of IPF.Appointment eg
// Create the request and specify the travesal type.
FindFolderType findFolderRequest = new FindFolderType();
findFolderRequest.Traversal = FolderQueryTraversalType.Deep;
// Define the properties that are returned in the response.
FolderResponseShapeType responseShape = new FolderResponseShapeType();
responseShape.BaseShape = DefaultShapeNamesType.Default;
findFolderRequest.FolderShape = responseShape;
// Identify which folders to search.
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.msgfolderroot;
IsEqualToType iet = new IsEqualToType();
PathToUnindexedFieldType FolderClass = new PathToUnindexedFieldType();
FolderClass.FieldURI = UnindexedFieldURIType.folderFolderClass;
iet.Item = FolderClass;
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "IPF.Appointment";
constantType.Item = constantValueType;
iet.FieldURIOrConstant = constantType;
// Add the folders to search to the request.
RestrictionType restriction = new RestrictionType();
restriction.Item = iet;
findFolderRequest.Restriction = restriction;
findFolderRequest.ParentFolderIds = folderIDArray;
try
{
// Send the request and get the response.
FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest);
// Get the response messages.
ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items;
foreach (ResponseMessageType rmt in rmta)
{
// Cast to the correct response message type.
if (((FindFolderResponseMessageType)rmt).ResponseClass == ResponseClassType.Success) {
foreach (FolderType folder in ((FindFolderResponseMessageType)rmt).RootFolder.Folders) {
Console.WriteLine(folder.DisplayName);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
You also might want to look at using the EWS Managed API which will save you greatly time and the amount of code you need to write
Cheers
Glen

Resources