Beispiel #1
0
            private static void initFromFrame(OutlookData data, Outlook outlook, Location location)
            {
                DateTime
                    locationTime  = location.LocationTime,
                    locationToday = new DateTime(locationTime.Year, locationTime.Month, locationTime.Day),
                    windowBeg     = locationToday, //locationTime,
                    windowEnd     = locationToday.AddDays(1).AddMilliseconds(-1)
                ;

                // EWS: create connection point
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

                ExchangeService service = new ExchangeService(outlook.EwsVersion)
                {
                    Credentials = new WebCredentials(
                        outlook.Account,
                        RsaUtil.Decrypt(outlook.Password)
                        ),
                };

                // EWS: get URL
                if (!string.IsNullOrWhiteSpace(outlook.URL))
                {
                    service.Url = new Uri(outlook.URL);
                }
                else
                {
                    service.Url = HttpRuntime.Cache.GetOrAddSliding(
                        string.Format("exchange_account_{0}", outlook.Account),
                        () =>
                    {
                        service.AutodiscoverUrl(outlook.Account, RedirectionUrlValidationCallback);
                        return(service.Url);
                    },
                        TimeSpan.FromMinutes(60)
                        );
                }

                // mailbox: get display name
                data.DisplayName = outlook.Name;
                if (string.IsNullOrWhiteSpace(data.DisplayName))
                {
                    var match = service.ResolveName(outlook.Mailbox);
                    if (match.Count > 0)
                    {
                        if (match[0].Contact != null)
                        {
                            data.DisplayName =
                                match[0].Contact.CompleteName.FullName
                                ?? match[0].Contact.DisplayName
                                ?? data.DisplayName
                            ;
                        }

                        else if (match[0].Mailbox != null)
                        {
                            data.DisplayName =
                                match[0].Mailbox.Name
                                ?? data.DisplayName
                            ;
                        }
                    }
                    //else
                    //    throw new ApplicationException(string.Format("Mailbox {0} not found", mailbox));
                }

                // mailbox: get availability
                GetUserAvailabilityResults uars = service.GetUserAvailability(
                    new AttendeeInfo[] { new AttendeeInfo(outlook.Mailbox, MeetingAttendeeType.Required, true) },
                    new TimeWindow(locationToday, locationToday.AddDays(1)),
                    AvailabilityData.FreeBusy
                    );
                var u = uars.AttendeesAvailability[0];

                if (u.WorkingHours != null)
                {
                    data.startTime = u.WorkingHours.StartTime;
                    data.endTime   = u.WorkingHours.EndTime;
                    data.timeZone  = u.WorkingHours.TimeZone;
                }

                // events: prep filter
                FolderId       folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(outlook.Mailbox));
                CalendarFolder calendar = CalendarFolder.Bind(service, folderId, new PropertySet());
                CalendarView   cView    = new CalendarView(windowBeg, windowEnd)
                {
                    PropertySet = new PropertySet(
                        AppointmentSchema.Subject,
                        AppointmentSchema.DateTimeCreated,
                        AppointmentSchema.Start,
                        AppointmentSchema.End,
                        AppointmentSchema.Duration
                        )
                };

                // events: get list
                data.events = calendar
                              .FindAppointments(cView)
                              .OrderBy(i => i.Start)
                              .ThenBy(i => i.DateTimeCreated)
                              .ThenBy(i => i.Subject)
                              //.Take(Math.Max(1, outlook.ShowEvents))
                              .Select(a => new EventEntry
                {
                    Subject   = a.Subject,
                    CreatedOn = a.DateTimeCreated,
                    Starts    = a.Start,
                    Ends      = a.End,
                    Duration  = a.Duration,
                    Today     = locationToday,
                })
                              //.ToList()
                ;
            }
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            HttpRequest  Request  = context.Request;
            HttpResponse Response = context.Response;

            try
            {
                // set headers, prevent client caching, return PNG
                Response.Clear();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetSlidingExpiration(true);
                Response.Cache.SetNoStore();
                Response.ContentType = "image/png";

                int frameId = Request.IntOrZero("frame");

                byte[]      data = null;
                int         panelHeight = -1, panelWidth = -1;
                RenderModes mode = RenderModes.RenderMode_Crop;

                Report report = new Report(frameId);

                if (report.FrameId != 0)
                {
                    Panel panel = new Panel(report.PanelId);
                    if (panel.PanelId != 0)
                    {
                        panelWidth  = panel.Width;
                        panelHeight = panel.Height;
                    }

                    mode = report.Mode;

                    //TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    //BitmapSource bitmapSource = decoder.Frames[0];

                    data = await HttpRuntime.Cache.GetOrAddAbsoluteAsync(
                        report.CacheKey,
                        async (expire) =>
                    {
                        expire.When = DateTime.Now.AddMinutes(report.CacheInterval);

                        // get response from report server
                        WebClient client = new WebClient();
                        if (!string.IsNullOrWhiteSpace(report.User))
                        {
                            client.Credentials = new NetworkCredential(
                                report.User.Trim(),
                                RsaUtil.Decrypt(report.Password),
                                report.Domain.Trim()
                                );
                        }

                        byte[] repBytes = await client.DownloadDataTaskAsync(report.Url);

                        if (repBytes == null)
                        {
                            return(null);
                        }

                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(repBytes))
                            {
                                await Task.Run(() => Picture.WriteImage(src, trg, panelWidth, panelHeight, mode));
                                return(trg.GetBuffer());
                            }
                    });
                }

                if (data != null)
                {
                    await Response.OutputStream.WriteAsync(data, 0, data.Length);
                }

                else
                {
                    Content missingContent = await Content.GetMissingContentAsync();

                    using (MemoryStream ms = new MemoryStream(missingContent.Data))
                    {
                        await Task.Run(() => Picture.WriteImage(ms, Response.OutputStream, -1, -1, RenderModes.RenderMode_Crop));
                    }
                }

                await Response.OutputStream.FlushAsync();
            }

            catch (Exception ex)
            {
                Debug.Print(string.Format("getReport error: {0}", ex.Message));
                Response.Write(ex.Message);
            }

            /*finally
             * {
             *  Response.OutputStream.Flush();
             * }*/
        }
        public static async Task <string> GetAccessTokenAsync(int accountId)
        {
            string accessToken = null;

            await DataAccess.ExecuteTransactionAsync(async (cnn, trn) => {
                using (SqlCommand cmd = new SqlCommand()
                {
                    CommandType = CommandType.Text,
                    CommandText = "select top 1 * from AzureAccount with(updlock,rowlock) where AccountId=@accountId",
                    Connection = cnn,
                    Transaction = trn,
                })
                {
                    cmd.Parameters.AddWithValue("@accountId", accountId);

                    DateTime?expiresOn             = null;
                    string clientId                = null, clientSecret = null, user = null, password = null, tenantId = null;
                    Models.AzureResources resource = Models.AzureResources.AzureResource_PowerBi;
                    await cmd.ExecuteReaderExtAsync((reader) =>
                    {
                        expiresOn    = reader.AsNullable <DateTime>("ExpiresOn");
                        accessToken  = reader.StringOrBlank("AccessToken").Trim();
                        resource     = reader.ValueOrDefault <Models.AzureResources>("Resource", Models.AzureResources.AzureResource_PowerBi);
                        clientId     = reader.StringOrBlank("ClientId");
                        clientSecret = reader.StringOrBlank("ClientSecret");
                        user         = reader.StringOrBlank("User");
                        password     = RsaUtil.Decrypt(reader.BytesOrNull("Password"));
                        tenantId     = reader.StringOrDefault("TenantId", null);
                        return(false);
                    });

                    if (string.IsNullOrWhiteSpace(accessToken) || !expiresOn.HasValue || expiresOn.Value < DateTime.UtcNow)
                    {
                        TokenInfo token = await Token.GetGrantTypePasswordAsync(
                            resource,
                            clientId,
                            clientSecret,
                            user,
                            password,
                            tenantId
                            );
                        using (SqlCommand cmdu = new SqlCommand()
                        {
                            CommandType = CommandType.Text,
                            CommandText = "update AzureAccount set AccessToken=@accessToken, ExpiresOn=@expiresOn where AccountId=@accountId",
                            Connection = cnn,
                            Transaction = trn,
                        })
                        {
                            cmdu.Parameters.AddWithValue("@accountId", accountId);
                            cmdu.Parameters.AddWithValue("@accessToken", token.AccessToken);
                            cmdu.Parameters.AddWithValue("@expiresOn", token.ExpiresOn.AddMinutes(-1)); // allow 1 minute to avoid issues
                            cmdu.ExecuteNonQuery();
                        }
                        accessToken = token.AccessToken;
                    }
                }
            });

            return(accessToken);
        }
Beispiel #4
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = context.Request;
            HttpResponse Response = context.Response;

            try
            {
                // set headers, prevent client caching, return PNG
                Response.Clear();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetSlidingExpiration(true);
                Response.Cache.SetNoStore();
                Response.ContentType = "image/png";

                int frameId = Convert.ToInt32(Request.QueryString["frame"]);

                byte[]      data = null;
                int         panelHeight = -1, panelWidth = -1;
                RenderModes mode = RenderModes.RenderMode_Crop;

                Report report = new Report(frameId);

                if (report.FrameId != 0)
                {
                    Panel panel = new Panel(report.PanelId);
                    if (panel.PanelId != 0)
                    {
                        panelWidth  = panel.Width;
                        panelHeight = panel.Height;
                    }

                    mode = report.Mode;

                    //TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    //BitmapSource bitmapSource = decoder.Frames[0];

                    data = HttpRuntime.Cache.GetOrAddAbsolute(
                        report.CacheKey,
                        () =>
                    {
                        // get response from report server
                        WebClient client = new WebClient();
                        if (!string.IsNullOrWhiteSpace(report.User))
                        {
                            client.Credentials = new NetworkCredential(
                                report.User.Trim(),
                                RsaUtil.Decrypt(report.Password),
                                report.Domain.Trim()
                                );
                        }

                        byte[] repBytes = client.DownloadData(report.Url);

                        if (repBytes == null)
                        {
                            return(null);
                        }

                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(repBytes))
                            {
                                Picture.WriteImage(src, trg, panelWidth, panelHeight, mode);
                                return(trg.GetBuffer());
                            }
                    },
                        DateTime.Now.AddMinutes(report.CacheInterval)
                        );
                }

                if (data != null)
                {
                    Response.OutputStream.Write(data, 0, data.Length);
                }

                else
                {
                    data = File.ReadAllBytes("~/files/404.png");
                    using (MemoryStream ms = new MemoryStream(data))
                    {
                        Picture.WriteImage(ms, Response.OutputStream, panelWidth, panelHeight, mode);
                    }
                }
            }

            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

            finally
            {
                Response.OutputStream.Flush();
            }
        }
            public static async System.Threading.Tasks.Task <OutlookData> FromFrameAsync(Outlook outlook, Location location, int reserveMinutes)
            {
                OutlookData data = new OutlookData();
                DateTime
                    locationTime  = location.LocationTime,
                    locationToday = new DateTime(locationTime.Year, locationTime.Month, locationTime.Day),
                    windowBeg     = locationToday, //locationTime,
                    windowEnd     = locationToday.AddDays(1).AddMilliseconds(-1)
                ;

                // EWS: create connection point
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

                ExchangeService service = new ExchangeService(outlook.EwsVersion)
                {
                    Credentials = new WebCredentials(
                        outlook.Account,
                        RsaUtil.Decrypt(outlook.Password)
                        ),
                };

                // EWS: get URL
                if (!string.IsNullOrWhiteSpace(outlook.URL))
                {
                    service.Url = new Uri(outlook.URL);
                }
                else
                {
                    service.Url = await HttpRuntime.Cache.GetOrAddSlidingAsync(
                        string.Format("exchange_account_{0}", outlook.Account),
                        async (expire) =>
                    {
                        expire.After = TimeSpan.FromMinutes(60);
                        await System.Threading.Tasks.Task.Run(() => service.AutodiscoverUrl(outlook.Account, RedirectionUrlValidationCallback));
                        return(service.Url);
                    });
                }

                // mailbox: get display name
                data.DisplayName = outlook.Name;
                if (string.IsNullOrWhiteSpace(data.DisplayName))
                {
                    var match = await System.Threading.Tasks.Task.Run(() => service.ResolveName(outlook.Mailbox));

                    if (match.Count > 0)
                    {
                        if (match[0].Contact != null)
                        {
                            data.DisplayName =
                                match[0].Contact.CompleteName.FullName
                                ?? match[0].Contact.DisplayName
                                ?? data.DisplayName
                            ;
                        }

                        else if (match[0].Mailbox != null)
                        {
                            data.DisplayName =
                                match[0].Mailbox.Name
                                ?? data.DisplayName
                            ;
                        }
                    }
                    //else
                    //    throw new ApplicationException(string.Format("Mailbox {0} not found", mailbox));
                }

                // mailbox: get availability
                GetUserAvailabilityResults uars = await System.Threading.Tasks.Task.Run(() => service.GetUserAvailability(
                                                                                            new AttendeeInfo[] { new AttendeeInfo(outlook.Mailbox, MeetingAttendeeType.Required, true) },
                                                                                            new TimeWindow(locationToday, locationToday.AddDays(1)),
                                                                                            AvailabilityData.FreeBusy
                                                                                            ));

                var u = uars.AttendeesAvailability[0];

                if (u.WorkingHours != null)
                {
                    data.startTime = u.WorkingHours.StartTime;
                    data.endTime   = u.WorkingHours.EndTime;
                    data.timeZone  = u.WorkingHours.TimeZone;
                }

                if (reserveMinutes > 0)
                {
                    Appointment appointment = new Appointment(service)
                    {
                        Body    = "Test",
                        Subject = "Test",
                        Start   = DateTime.Now,
                        End     = DateTime.Now.AddMinutes(reserveMinutes),
                    };

                    if (outlook.Mailbox == outlook.Account)
                    {
                        await System.Threading.Tasks.Task.Run(() => appointment.Save(SendInvitationsMode.SendToNone));
                    }
                    else
                    {
                        appointment.Resources.Add(outlook.Mailbox);
                        await System.Threading.Tasks.Task.Run(() => appointment.Save(SendInvitationsMode.SendOnlyToAll));
                    }
                }

                // events: prep filter
                FolderId       folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(outlook.Mailbox));
                CalendarFolder calendar = await System.Threading.Tasks.Task.Run(() => CalendarFolder.Bind(service, folderId, new PropertySet()));

                CalendarView cView = new CalendarView(windowBeg, windowEnd)
                {
                    PropertySet = new PropertySet(
                        //BasePropertySet.FirstClassProperties,
                        AppointmentSchema.Subject,
                        AppointmentSchema.DateTimeCreated,
                        AppointmentSchema.Start,
                        AppointmentSchema.End,
                        AppointmentSchema.Duration,
                        AppointmentSchema.Sensitivity,
                        AppointmentSchema.LegacyFreeBusyStatus
                        )
                };

                // events: get list
                var appointments = await System.Threading.Tasks.Task.Run(() => calendar.FindAppointments(cView));

                data.events = appointments
                              //.FindAppointments(cView)
                              .Where(a =>
                                     (outlook.Privacy != Models.OutlookPrivacy.OutlookPrivacy_NoClassified || a.Sensitivity == Sensitivity.Normal) &&
                                     (outlook.IsShowAsAllowed(a.LegacyFreeBusyStatus))
                                     )
                              .OrderBy(i => i.Start)
                              .ThenBy(i => i.DateTimeCreated)
                              .ThenBy(i => i.Subject)
                              //.Take(Math.Max(1, outlook.ShowEvents))
                              .Select(a => new EventEntry
                {
                    Subject =
                        outlook.Privacy == Models.OutlookPrivacy.OutlookPrivacy_All || a.Sensitivity == Sensitivity.Normal ? a.Subject :
                        DataAccess.StringResource(string.Format("EWS_Sensitivity_{0}", a.Sensitivity.ToString())),
                    CreatedOn   = a.DateTimeCreated,
                    Starts      = a.Start,
                    Ends        = a.End,
                    Duration    = a.Duration,
                    Sensitivity = a.Sensitivity,
                    Today       = locationToday,
                    ShowAs      = a.LegacyFreeBusyStatus,
                })
                              .ToList()
                ;

                return(data);
            }