Beispiel #1
0
        private static int HandleDate(DateOptions opts)
        {
            var datetime = new Chronic.Parser().Parse(opts.DateTime).Start;

            if (datetime == null)
            {
                Console.WriteLine("Parse failed");
            }
            else
            {
                Console.WriteLine(datetime);
            }
            return(0);
        }
        public async Task SetAlarm(IDialogContext context, LuisResult result)
        {
            EntityRecommendation title;

            if (!result.TryFindEntity(Entity_Alarm_Title, out title))
            {
                title = new EntityRecommendation(type: Entity_Alarm_Title)
                {
                    Entity = DefaultAlarmWhat
                };
            }
            EntityRecommendation date;

            if (!result.TryFindEntity(Entity_Alarm_Start_Date, out date))
            {
                date = new EntityRecommendation(type: Entity_Alarm_Start_Date)
                {
                    Entity = string.Empty
                };
            }
            EntityRecommendation time;

            if (!result.TryFindEntity(Entity_Alarm_Start_Time, out time))
            {
                time = new EntityRecommendation(type: Entity_Alarm_Start_Time)
                {
                    Entity = string.Empty
                };
            }
            var parser = new Chronic.Parser();
            var span   = parser.Parse(date.Entity + " " + time.Entity);

            if (span != null)
            {
                var when  = span.Start ?? span.End;
                var alarm = new Alarm()
                {
                    What = title.Entity, When = when.Value
                };
                this.alarmByWhat[alarm.What] = alarm;
                string reply = $"alarm {alarm} created";
                await context.PostAsync(reply);
            }
            else
            {
                await context.PostAsync("could not find time for alarm");
            }
            context.Wait(MessageReceived);
        }
Beispiel #3
0
        // This is the continuation delegate, gets invoked every time a new message comes in
        async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            WeatherLocation weatherLoc = null;
            string          theWeather = string.Empty;

            // Get the incoming activity
            var message = await argument;

            var ws = new WeatherService();

            weatherLoc = await ws.FindLocationCoordinatesAsync(message.Text);

            if (weatherLoc == null)
            {
                // Check to see if the location is already in the bot's state
                if (context.PrivateConversationData.TryGetValue("currentloc", out weatherLoc) == false)
                {
                    // We don't have the city, need to return a message saying that
                    theWeather = $"I queried Google and still didn't find anyting matching {message.Text}, mind entering a new location?";
                    await context.PostAsync(theWeather);

                    context.Wait(MessageReceivedAsync);
                }
            }

            // We have a location - save it to the conversation data
            context.PrivateConversationData.SetValue("currentloc", weatherLoc);

            // try to parse the input to see if there's a time
            var timeParser    = new Chronic.Parser();
            var chronicResult = timeParser.Parse(message.Text);

            if (chronicResult != null && chronicResult.Start.HasValue)
            {
                theWeather = await ws.GetConditionsForLocationAtTimeAsync(weatherLoc, chronicResult.Start.Value);
            }
            else
            {
                theWeather = await ws.GetCurrentConditionsAsync(weatherLoc);
            }

            // Send something back
            await context.PostAsync(theWeather);

            // Wait for everything again
            context.Wait(MessageReceivedAsync);
        }
Beispiel #4
0
        public async Task ScheduleDelivery(IDialogContext context, LuisResult result)
        {
            EntityRecommendation deliveryDate;

            if (result.TryFindEntity(EntityDateTime, out deliveryDate))
            {
                var dateparser = new Chronic.Parser();
                var datetime   = dateparser.Parse(deliveryDate.Entity).ToTime();

                var schedule = new DeliverySchedule()
                {
                    Id           = 1,
                    DeliveryDate = datetime
                };

                await UpdateDeliveryDateAsync(schedule);

                string resultMessage = $"We'll schedule a delivery date for {datetime.ToLongDateString()}";
                await context.PostAsync(resultMessage);
            }
        }
Beispiel #5
0
        private async Task AfterWhenAsync(IDialogContext context, IAwaitable <string> argument)
        {
            var departureInput = await argument;
            var parser         = new Chronic.Parser();
            var dateResult     = parser.Parse(departureInput);

            if (dateResult != null)
            {
                var parsedDate = dateResult.ToTime();
                var travelData = GetData(context);
                travelData.TravelDate = new DateTime(parsedDate.Year, parsedDate.Month, parsedDate.Day);
                SetData(context, travelData);
                await SelectNextQuestion(context);

                return;
            }

            PromptDialog.Text(
                context,
                AfterWhenAsync,
                "Sorry did not get that. When do you want to go?");
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(opts =>
            {
                if (opts.Debug && opts.Quiet)
                {
                    new Logger().Error("Cannot specify both --quiet and --debug.");
                }

                var logger = new Logger(
                    opts.Quiet ? Verbosity.Quiet :
                    opts.Debug ? Verbosity.Verbose :
                    Verbosity.Normal
                    );

                var chronic = new Chronic.Parser();
                var date    = chronic.Parse(opts.Date);

                if (date == null || date.Start == null)
                {
                    logger.Error("Could not parse date.");
                }

                int?width = null, height = null;
                if (opts.FillSize != null)
                {
                    var fill = Regex.Match(opts.FillSize, @"^(?<width>\d+)x(?<height>\d+)$");
                    if (!fill.Success)
                    {
                        logger.Error("Could not parse fillsize.");
                    }

                    width  = int.Parse(fill.Groups["width"].Value);
                    height = int.Parse(fill.Groups["height"].Value);
                }

                if (File.Exists(opts.OutDir))
                {
                    logger.Error("Output directory cannot be a file.");
                }

                if (Directory.Exists(opts.OutDir))
                {
                    logger.Debug("Output directory already exists.");
                }
                else
                {
                    try
                    {
                        logger.Debug("Output directory does not exist, creating...");
                        Directory.CreateDirectory(opts.OutDir);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Could not create output directory", ex);
                    }
                }

                logger.Log($"Retrieving {opts.Count} pictures, ending on {date.Start?.ToString("yyyy-MM-dd")}.");

                var downloader = new Downloader(logger, date.Start.Value, opts.Count, opts.OutDir, opts.Delete, width, height);

                downloader.Synchronize();
            });
        }
Beispiel #7
0
        // POST api/<controller>
        public IHttpActionResult Post([FromBody] PostInput data)
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
            if (data.Keywords == null)
            {
                data.Keywords = new string[0];
            }
            List <string> addkeywords = new List <string>();

            foreach (string key in data.Keywords)
            {
                string[] ks = key.Split(' ');
                if (ks.Length == 2)
                {
                    addkeywords.AddRange(ks);
                }
                if (ks.Length > 2)
                {
                    addkeywords.AddRange(ks.Zip(ks.Skip(1), (x, y) => x + " " + y));
                }
            }

            data.Keywords = data.Keywords.Concat(addkeywords).ToArray();

            (Coordinate[] coordinates, string[] cities) = ApiInterface.GetHotelLocations(data);

            var parser = new Chronic.Parser();

            if (data.ArrivalDate == null || data.ArrivalDate == "")
            {
                data.ArrivalDate = "today";
            }
            if (data.DepartureDate == null || data.DepartureDate == "")
            {
                data.DepartureDate = "next week";
            }
            if (data.Image == null)
            {
                data.Image = "";
            }

            var opt = new Chronic.Options();

            opt.EndianPrecedence = Chronic.EndianPrecedence.Little;

            DateTime arrivalDate;
            DateTime departureDate;

            if (data.ArrivalDate != null)
            {
                data.ArrivalDate.Replace('.', '/');
            }
            if (data.DepartureDate != null)
            {
                data.DepartureDate.Replace('.', '/');
            }

            try
            {
                arrivalDate = DateTime.Parse(data.ArrivalDate, null);
            }
            catch
            {
                arrivalDate = parser.Parse(data.ArrivalDate, opt).Start.Value;
            }

            try
            {
                departureDate = DateTime.Parse(data.DepartureDate, null);
            }
            catch
            {
                departureDate = parser.Parse(data.DepartureDate, opt).Start.Value;
            }

            Hotel[] hotels = coordinates.SelectMany(x => ApiInterface.Check24(x.lat, x.lng, arrivalDate, departureDate)).ToArray();

            hotels = hotels.Where((x, i) => !hotels.Take(i).Any(y => y.Id == x.Id)).ToArray();

            return(Ok(new { Hotels = hotels.Take(data.MaxOutputSize), Coordinates = coordinates, Cities = cities }));
        }
Beispiel #8
0
        public async static Task <Matchup> ScrapeSchedule(String firstTeamString, String secondTeamString, IMatchupRepository matchupRepository)
        {
            Matchup         matchup     = null;
            var             parser      = new Chronic.Parser();
            String          currentDate = String.Empty;
            String          startTime   = String.Empty;
            DateTime        when        = DateTime.MinValue;
            List <HtmlNode> statusNodes = null;

            Teams firstTeam  = Teams.None;
            Teams secondTeam = Teams.None;

            if (!firstTeamString.FindTeamByNameVariation(out firstTeam) || !secondTeamString.FindTeamByNameVariation(out secondTeam))
            {
                return(matchup);
            }

            Matchup existing = matchupRepository.GetByTeams(firstTeam, secondTeam);

            if (existing != null)
            {
                matchup = existing;
                return(matchup);
            }

            Teams    awayTeam = Teams.None;
            Teams    homeTeam = Teams.None;
            Networks network  = Networks.None;

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(await Methods.DownloadPageStringAsync("http://www.foxsports.com/nfl/schedule"));

            HtmlNode scheduleTable = doc.DocumentNode.QuerySelector("table.wisbb_scheduleTable");

            foreach (HtmlNode el in scheduleTable.ChildNodes)
            {
                if (el.Name == "thead")
                {
                    currentDate = el.QuerySelector("th").InnerText;
                }
                else if (el.Name == "tbody")
                {
                    foreach (HtmlNode row in el.ChildNodes.Where(x => x.Name == "tr"))
                    {
                        try
                        {
                            Matchup temp = new Matchup();

                            statusNodes = row.QuerySelectorAll("td.wisbb_gameInfo .wisbb_status").ToList();
                            if (statusNodes.Count == 0)
                            {
                                continue;
                            }

                            if (row.QuerySelector(".wisbb_firstTeam .wisfb_logoImage").Attributes["alt"].Value.FindTeamByNameVariation(out awayTeam) &&
                                row.QuerySelector(".wisbb_secondTeam .wisfb_logoImage").Attributes["alt"].Value.FindTeamByNameVariation(out homeTeam))
                            {
                                temp.AwayTeamEnum = awayTeam;
                                temp.HomeTeamEnum = homeTeam;

                                startTime = statusNodes.LastOrDefault(x => !String.IsNullOrEmpty(x.InnerText)).InnerText;
                                startTime = startTime.Replace("a", " AM").Replace("p", " PM").Replace(" ET", String.Empty);

                                temp.WhenDate = DateTime.ParseExact($"{currentDate} {startTime}", "dddd, MMMM d h:mm tt", CultureInfo.InvariantCulture);


                                temp.Where = row.QuerySelector(".wisbb_location").InnerText.Replace("&amp;", "&").Trim();

                                row.QuerySelector(".wisbb_network").InnerText.Trim().FindNetworkByNameVariation(out network);
                                temp.NetworkEnum = network;

                                matchupRepository.AddOrUpdate(temp);

                                if ((firstTeam == awayTeam && secondTeam == homeTeam) || (secondTeam == awayTeam && firstTeam == homeTeam))
                                {
                                    matchup = temp;
                                    return(matchup);
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            return(matchup);
        }
Beispiel #9
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <Message> argument)
        {
            var message = await argument;

            string    resp  = "";
            LUISModel model = await GetEntityFromLUIS(message.Text);


            if (model.intents.Count() > 0)
            {
                switch (model.intents[0].intent)
                {
                case intent_hi:


                    await context.PostAsync("Hallo! Versuchen Sie: \"Wann kommt mein Paket?\"\n\noder: \"Liefere mein Paket zur nähesten Abholstation\"");

                    context.Wait(MessageReceivedAsync);
                    break;

                case intent_deliveryState:
                    var               start = "Graz";
                    var               dest  = "Am Europlatz 3, Vienna";
                    Message           msg   = new Message();
                    string            query = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Routes?wp.0=" + start + ";64;1&wp.1=" + dest + ";66;2&key=AgArU18mPZIHjbt9F0l5_StVXlcXITxAbGRYl07EEUzOLiXIRYLBzWAiBTeTYNcQ";
                    List <Attachment> a     = new List <Attachment>();
                    a.Add(new Attachment(contentUrl: query, contentType: "image/jpeg"));

                    msg.Attachments = a;

                    string   metaquery   = "http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0=" + start + "&wp.1=" + dest + "&key=AgArU18mPZIHjbt9F0l5_StVXlcXITxAbGRYl07EEUzOLiXIRYLBzWAiBTeTYNcQ";
                    string   s           = new WebClient().DownloadString(metaquery);
                    dynamic  meta        = JsonConvert.DeserializeObject(s);
                    string   seconds     = meta.resourceSets[0].resources[0].travelDuration;
                    TimeSpan time        = TimeSpan.FromSeconds(Double.Parse(seconds));
                    var      arrivalTime = DateTime.Now.Add(time);
                    msg.Text = "Ihr Paket befindet sich im Moment in " + start + " und \nwird um " + arrivalTime.ToString(@"HH\:mm") + " ankommen.";


                    PostAndWait(context, msg);
                    break;

                case intent_changeDelivery:
                    DateTime?when    = DateTime.Now;
                    var      hasDate = model.entities.Where(e => e.type == "builtin.datetime.time").FirstOrDefault();
                    if (hasDate != null)
                    {
                        var parser = new Chronic.Parser();

                        var span = parser.Parse(hasDate.entity);
                        if (span != null)
                        {
                            if (when.Value.Hour < 18)
                            {
                                PostAndWait(context, "Okay, Zustellung geändert auf " + when.Value.ToString(@"HH\:mm"));
                            }
                            else
                            {
                                PostAndWait(context, MakeMessage("http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/Am%20Europlatz%20Vienna?mapLayer=TrafficFlow&key=AgArU18mPZIHjbt9F0l5_StVXlcXITxAbGRYl07EEUzOLiXIRYLBzWAiBTeTYNcQ",
                                                                 "Das ist leider nicht möglich. Ihr Paket wird zu ihrer nähesten Abholstation geliefert. Am Europlatz 3, Vienna"));
                            }


                            break;
                        }
                    }


                    PostAndWait(context, MakeMessage("http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/Am%20Europlatz%20Vienna?mapLayer=TrafficFlow&key=AgArU18mPZIHjbt9F0l5_StVXlcXITxAbGRYl07EEUzOLiXIRYLBzWAiBTeTYNcQ",
                                                     "Ihr Paket wird zu ihrer nähesten Abholstation \ngelifiert. Am Europlatz 3, Vienna"));

                    break;

                case intent_findStation:
                    Message           m           = new Message();
                    string            q           = "http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/Am%20Europlatz%20Vienna?mapLayer=TrafficFlow&key=AgArU18mPZIHjbt9F0l5_StVXlcXITxAbGRYl07EEUzOLiXIRYLBzWAiBTeTYNcQ";
                    List <Attachment> attachments = new List <Attachment>();
                    attachments.Add(new Attachment(contentUrl: q, contentType: "image/jpeg"));

                    m.Attachments = attachments;
                    m.Text        = "Die näheste Abholstation ist Am Europlatz 3, Vienna";

                    PostAndWait(context, m);
                    break;

                case intent_paketTarif:

                    List <EntityRecommendation> entities = new List <EntityRecommendation>();
                    //get land

                    IFormDialog <PaketTarif> tmp = MakeRootDialog(new PaketTarif(), entities: entities);
                    context.Call(tmp, PaketTarifComplete);
                    break;

                default:
                    PostAndWait(context, "Didn't get that");
                    break;
                }
            }
            else
            {
                PostAndWait(context, "Leider nicht verstanden");
            }
        }
Beispiel #10
0
        public async Task StartPollAsync(CommandContext ctx)
        {
            var pollMessageUpdater = await PollMessageUpdater.Create(ctx);

            var setupMessageUpdater = await SetupMessageUpdater.Create(ctx);

            var interactivity = ctx.Client.GetInteractivity();

            var questionReponse =
                await interactivity.WaitForMessageAsync(
                    msg => msg.Author == ctx.Member && msg.ChannelId == ctx.Channel.Id,
                    _timeOut);

            if (questionReponse.TimedOut)
            {
                await ctx.ErrorAsync("You didn't respond in time. Please start over", "Timed out");

                await ctx.Channel.DeleteMessagesAsync(new[] { setupMessageUpdater.Message, pollMessageUpdater.Message });

                return;
            }

            string pollQuestion = questionReponse.Result.Content.Trim();

            if (pollQuestion.IsEmptyOrWhiteSpace())
            {
                await ctx.ErrorAsync("You didn't provide a proper poll question. Please start over", "Empty question");

                await ctx.Channel.DeleteMessagesAsync(new[] { setupMessageUpdater.Message, pollMessageUpdater.Message });

                return;
            }

            await pollMessageUpdater.SetPollTitle(pollQuestion);

            await ctx.Channel.DeleteMessageAsync(questionReponse.Result);

            await setupMessageUpdater.SetSecondInstruction();

            var timeResponse =
                await interactivity.WaitForMessageAsync(
                    msg => msg.Author == ctx.Member && msg.ChannelId == ctx.Channel.Id,
                    _timeOut);

            if (timeResponse.TimedOut)
            {
                await ctx.ErrorAsync("You didn't respond in time. Please start over", "Timed out");

                await ctx.Channel.DeleteMessagesAsync(new[] { setupMessageUpdater.Message, pollMessageUpdater.Message });

                return;
            }

            var timeParser = new Chronic.Parser(new Chronic.Options()
            {
                Context          = Chronic.Pointer.Type.Future,
                EndianPrecedence = Chronic.EndianPrecedence.Little,
                FirstDayOfWeek   = DayOfWeek.Monday
            });

            Chronic.Span parsedTime = timeParser.Parse(timeResponse.Result.Content);
            if (parsedTime == null)
            {
                await ctx.ErrorAsync("I couldn't understand this Date/Time. Please start over", "Invalid Time");

                await ctx.Channel.DeleteMessagesAsync(new[] { setupMessageUpdater.Message, pollMessageUpdater.Message });

                return;
            }

            DateTime endTime = parsedTime.ToTime();

            if (endTime < DateTime.Now)
            {
                await ctx.ErrorAsync("The provided time is in the past. Please start over", "Invalid Time");

                await ctx.Channel.DeleteMessagesAsync(new[] { setupMessageUpdater.Message, pollMessageUpdater.Message });

                return;
            }

            await pollMessageUpdater.SetEndTime(endTime);

            await ctx.Channel.DeleteMessageAsync(timeResponse.Result);

            await setupMessageUpdater.SetThirdInstruction();

            await setupMessageUpdater.AddOkButton();

            var pollAnswers = new List <PollAnswer>();

            while (true)
            {
                var addAnswerTask = interactivity.WaitForMessageAsync(
                    msg => msg.Author == ctx.Member && msg.ChannelId == ctx.Channel.Id,
                    _timeOut);
                var okTask = interactivity.WaitForButtonAsync(setupMessageUpdater.Message, ctx.Member, _timeOut);
                var result = await Task.WhenAny(addAnswerTask, okTask);

                if (result == addAnswerTask)
                {
                    var pollOptionResponse = addAnswerTask.Result;
                    if (pollOptionResponse.TimedOut)
                    {
                        if (pollAnswers.Count >= 2)
                        {
                            break;
                        }

                        await ctx.ErrorAsync("You didn't provide enough answers in time. Please start over",
                                             "Timed out");

                        await ctx.Channel.DeleteMessagesAsync(new[]
                        {
                            setupMessageUpdater.Message, pollMessageUpdater.Message
                        });

                        return;
                    }

                    var order       = pollAnswers.Count;
                    var answerValue = pollOptionResponse.Result.Content;
                    pollAnswers.Add(new PollAnswer(order, answerValue));

                    await ctx.Channel.DeleteMessageAsync(pollOptionResponse.Result);

                    await pollMessageUpdater.UpdateAnswers(pollAnswers);

                    await pollMessageUpdater.UpdateAnswersButtons(pollAnswers);
                }
                else
                {
                    if (!okTask.Result.TimedOut)
                    {
                        await okTask.Result.Result.Interaction.CreateResponseAsync(InteractionResponseType
                                                                                   .UpdateMessage);

                        if (pollAnswers.Count < 2)
                        {
                            await ctx.ErrorAsync("Not enough answer options! Please add more first!");
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (pollAnswers.Count >= 2)
                        {
                            break;
                        }

                        await ctx.ErrorAsync("You didn't provide enough answers in time. Please start over",
                                             "Timed out");

                        await ctx.Channel.DeleteMessagesAsync(new[]
                        {
                            setupMessageUpdater.Message, pollMessageUpdater.Message
                        });

                        return;
                    }
                }
            }

            await ctx.Channel.DeleteMessageAsync(setupMessageUpdater.Message);

            var poll = new Poll(ctx.Guild.Id, ctx.Channel.Id, pollMessageUpdater.Message.Id, ctx.Member.Id,
                                pollQuestion, pollAnswers,
                                endTime.ToUniversalTime());

            await _pollService.AddAndStartPollAsync(poll);
        }
        public async Task XDBSessions(IDialogContext context, LuisResult result)
        {
            var isAuthenticated = await context.IsAuthenticated();

            if (!isAuthenticated)
            {
                context.SetUnauthorizedMessageText(result.Query);
                await context.Forward(new AuthenticationDialog(), this.ResumeAfterAuth, context.MakeMessage(), CancellationToken.None);
            }
            else if (context.IsAdministrator() || context.IsInRole(RoleNames.BotAnalytics))
            {
                EntityRecommendation period;
                Chronic.Span         span = null;

                if (result.TryFindEntity(Constants.Entities.BuiltIn_DateTime, out period))
                {
                    var parser = new Chronic.Parser();
                    foreach (var resolution in period.Resolution)
                    {
                        if (new Regex(@"^(201[0-9])$").IsMatch(resolution.Value))
                        {
                            try
                            {
                                var year = int.Parse(resolution.Value.Substring(0, 4));
                                span = new Chronic.Span(new DateTime(year, 1, 1), new DateTime(year, 1, 1).AddYears(1));
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            span = parser.Parse(resolution.Value);
                        }
                    }

                    if (span == null && period.Resolution.Count > 0)
                    {
                        var resolution = period.Resolution.FirstOrDefault();
                        if (new Regex(@"^(201[0-9]\-W([0-5][0-9]))$").IsMatch(resolution.Value))
                        {
                            try
                            {
                                var year = int.Parse(resolution.Value.Substring(0, 4));
                                var week = int.Parse(resolution.Value.Substring(6));
                                span = new Chronic.Span(DateHelpers.FirstDateOfWeek(year, week), DateHelpers.LastDateOfWeek(year, week));
                            }
                            catch
                            {
                            }
                        }
                        else if (new Regex(@"^(201[0-9]\-([0-1][0-9]))$").IsMatch(resolution.Value))
                        {
                            try
                            {
                                var year  = int.Parse(resolution.Value.Substring(0, 4));
                                var month = int.Parse(resolution.Value.Substring(5));
                                span = new Chronic.Span(new DateTime(year, month, 1), new DateTime(year, month, 1).AddMonths(1));
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                if (span == null)
                {
                    span = new Chronic.Span(DateTime.Now, DateTime.Now.AddDays(1));
                }

                var response = await SitecoreXdbAPI.Instance(context.AccessToken()).Interactions(span.Start, span.End);

                if (response.Count > 0)
                {
                    var contacts = response.Select(i => i.ContactId).Distinct();

                    await context.PostAsync($"Between {span.Start.Value.ToString("dd-MM-yyyy")} and {span.End.Value.ToString("dd-MM-yyyy")} we've had a total of {contacts.Count()} unique contacts in {response.Count} interactions. Let's look at some facts.");

                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine($"The average value was {Math.Round((double)response.Sum(i => i.Value) / response.Count, 1, MidpointRounding.ToEven)}  \n");
                    sb.AppendLine($"The average number of pages visited was {Math.Round((double)response.Sum(i => i.VisitPageCount) / response.Count, 1, MidpointRounding.ToEven)}  \n");

                    if (response.Any(i => i.CampaignId.HasValue))
                    {
                        sb.AppendLine($"{response.Count(i => i.CampaignId.HasValue)} triggered a campaign.  \n");
                    }
                    else
                    {
                        sb.AppendLine($"None of them triggered a campaign.  \n");
                    }

                    await context.PostAsync(sb.ToString());
                }
                else
                {
                    await context.PostAsync($"I'm very sorry to say that you haven't had any interactions between {span.Start} and {span.End}");
                }
            }
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            Amazon.EC2.AmazonEC2Client ec2 = new Amazon.EC2.AmazonEC2Client(RegionEndpoint.APSoutheast2);
            var securityGroups             = ec2.DescribeSecurityGroupsAsync().Result.SecurityGroups;

            foreach (var securityGroup in securityGroups)
            {
                var dict    = securityGroup.IpPermissions.ToList();
                var newDict = dict.ToList();

                foreach (var rule in dict)
                {
                    if (rule.Ipv4Ranges != null)
                    {
                        foreach (var ipv4rule in rule.Ipv4Ranges.ToList())
                        {
                            var rulesRegex = new Regex(@"\[(?:\[[^\[\]]*\]|[^\[\]])*\]", RegexOptions.None);

                            if (ipv4rule.Description == null)
                            {
                                continue;
                            }

                            var m = rulesRegex.Matches(ipv4rule.Description).ToList();

                            if (m == null)
                            {
                                continue;
                            }

                            foreach (Group g in m)
                            {
                                var extension = g.Value.Split(new[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries).ToDictionary(s => s.Split('=')[0], s => s.Split('=')[1]).FirstOrDefault();

                                if (extension.Key == "fqdn")
                                {
                                    //get ip from DNS
                                    var newIP = Dns.GetHostEntry(extension.Value).AddressList.FirstOrDefault().ToString() + "/32";

                                    if (ipv4rule.CidrIp == newIP)
                                    {
                                        Console.WriteLine("Didn't update security group. Cidr Still matches");
                                    }
                                    else
                                    {
                                        IpPermission oldPermission = new IpPermission
                                        {
                                            FromPort   = rule.FromPort,
                                            IpProtocol = rule.IpProtocol,
                                            ToPort     = rule.ToPort
                                        };
                                        oldPermission.Ipv4Ranges.Add(ipv4rule);
                                        var oldlistofpermissions = new List <IpPermission>();
                                        oldlistofpermissions.Add(oldPermission);
                                        //revoke that one rule.
                                        ec2.RevokeSecurityGroupIngressAsync(new Amazon.EC2.Model.RevokeSecurityGroupIngressRequest {
                                            GroupId = securityGroup.GroupId, IpPermissions = oldlistofpermissions
                                        }).Wait();

                                        //add the new one.

                                        IpPermission newPermission = new IpPermission
                                        {
                                            FromPort   = rule.FromPort,
                                            IpProtocol = rule.IpProtocol,
                                            ToPort     = rule.ToPort
                                        };
                                        var newiprange = new IpRange();
                                        newiprange.CidrIp      = newIP;
                                        newiprange.Description = ipv4rule.Description;
                                        newPermission.Ipv4Ranges.Add(newiprange);
                                        var newlistofpermissions = new List <IpPermission>();
                                        newlistofpermissions.Add(newPermission);

                                        //ipv4rule.CidrIp = Dns.GetHostEntry(extension.Value).AddressList.FirstOrDefault().ToString() + "/32";
                                        ec2.AuthorizeSecurityGroupIngressAsync(new Amazon.EC2.Model.AuthorizeSecurityGroupIngressRequest {
                                            GroupId = securityGroup.GroupId, IpPermissions = newlistofpermissions
                                        }).Wait();
                                    }
                                }

                                if (extension.Key == "expiry")
                                {
                                    var isDate = DateTime.TryParse(extension.Value, out DateTime expiry);

                                    if (!isDate)
                                    {
                                        var chronic = new Chronic.Parser();
                                        expiry = chronic.Parse(extension.Value, new Chronic.Options {
                                            EndianPrecedence = Chronic.EndianPrecedence.Little
                                        }).ToTime();
                                        ipv4rule.Description = ipv4rule.Description.Replace(g.Value, $"[expiry={expiry.ToString("yyyy-MM-dd HH:mm")}]");

                                        IpPermission newPermission = new IpPermission
                                        {
                                            FromPort   = rule.FromPort,
                                            IpProtocol = rule.IpProtocol,
                                            ToPort     = rule.ToPort
                                        };
                                        var newiprange = new IpRange();
                                        newiprange.Description = ipv4rule.Description;
                                        newiprange.CidrIp      = ipv4rule.CidrIp;
                                        newPermission.Ipv4Ranges.Add(newiprange);
                                        var newlistofpermissions = new List <IpPermission>();
                                        newlistofpermissions.Add(newPermission);


                                        ec2.UpdateSecurityGroupRuleDescriptionsIngressAsync(new Amazon.EC2.Model.UpdateSecurityGroupRuleDescriptionsIngressRequest {
                                            GroupId = securityGroup.GroupId, IpPermissions = newlistofpermissions
                                        }).Wait();
                                        //ec2.RevokeSecurityGroupIngressAsync(new Amazon.EC2.Model.RevokeSecurityGroupIngressRequest { GroupId = securityGroup.GroupId, IpPermissions = listofpermissions }).Wait();
                                    }
                                    else
                                    {
                                        if (expiry < DateTime.Now)
                                        {
                                            IpPermission permission = new IpPermission
                                            {
                                                FromPort   = rule.FromPort,
                                                IpProtocol = rule.IpProtocol,
                                                ToPort     = rule.ToPort
                                            };
                                            permission.Ipv4Ranges.Add(ipv4rule);
                                            var listofpermissions = new List <IpPermission>();
                                            listofpermissions.Add(permission);

                                            ec2.RevokeSecurityGroupIngressAsync(new Amazon.EC2.Model.RevokeSecurityGroupIngressRequest {
                                                GroupId = securityGroup.GroupId, IpPermissions = listofpermissions
                                            }).Wait();
                                            //newDict.Where(x => x == rule).Where(y => y.Ipv4Ranges == rule.Ipv4Ranges).First().Ipv4Ranges.Add()
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public static DateTime? FindStartDate(this LuisResult result, UserState userState)
        {
            //
            // We special-case "now" since it most likely overrules anything else we might see.
            //
            if (result.IsStartTimeNow())
            {
                var localNow = userState.ConvertToLocalTime(DateTime.UtcNow);

                return localNow.Date;
            }

            TimeSpan maxDaysInFuture = TimeSpan.FromDays(30);   // Limit how far in the future we can recognize

            EntityRecommendation builtinDate = null;
            result.TryFindEntity(EntityBuiltinDate, out builtinDate);

            var parser = new Chronic.Parser(
                new Chronic.Options
                {
                    Context = Chronic.Pointer.Type.Future,
                    Clock = () =>
                    {
                        var utcNow = DateTime.UtcNow;
                        var tzOffset = userState.LocalOffsetForDate(utcNow);

                        return new DateTime((utcNow + tzOffset).Ticks, DateTimeKind.Unspecified);
                    }
                });

            if (builtinDate != null && builtinDate.Resolution.ContainsKey("date"))
            {
                //
                // Give DateTime a crack at parsing it first. This handles cases like MM/DD which Chronic
                // can't handle, for some reason.
                //
                DateTime date;

                if (DateTime.TryParse(builtinDate.Entity, out date))
                {
                    date = date.Date;
                    // Only accept dates in the reasonably near future.
                    if (date >= DateTime.Now.Date && date <= DateTime.Now.Date + maxDaysInFuture)
                    {
                        return date;
                    }
                }

                var span = parser.Parse(builtinDate.Entity);

                if (span != null)
                {
                    var when = span.Start ?? span.End;
                    return when.Value.Date;
                }
            }

            foreach (var startDate in result.Entities.Where(e => e.Type == EntityStart))
            {
                var span = parser.Parse(startDate.Entity);

                if (span != null)
                {
                    var when = span.Start ?? span.End;

                    if (when.Value.HasDate())
                    {
                        return when.Value.Date;
                    }
                }
            }

            return null;
        }
        public static DateTime? FindStartTime(this LuisResult result, UserState userState)
        {
            //
            // We special-case "now" since it most likely overrules anything else we might see.
            // We snap the time to the "best" nearby time-slot (15-minute intervals).
            //
            if (result.IsStartTimeNow())
            {
                return userState.LocalTime().ToNearestTimeSlot();
            }

            EntityRecommendation builtinTime = null;
            result.TryFindEntity(EntityBuiltinTime, out builtinTime);

            var parser = new Chronic.Parser(
                new Chronic.Options
                {
                    Context = Chronic.Pointer.Type.Future,
                    Clock = () =>
                    {
                        var utcNow = DateTime.UtcNow;
                        var tzOffset = userState.LocalOffsetForDate(utcNow);

                        return new DateTime((utcNow + tzOffset).Ticks, DateTimeKind.Unspecified);
                    }
                });

            if (builtinTime != null && builtinTime.Resolution.ContainsKey("time"))
            {
                var span = parser.Parse(builtinTime.Entity);

                if (span != null)
                {
                    var when = span.Start ?? span.End;

                    if (when.Value.HasTime())
                    {
                        return when.Value;
                    }
                }
            }

            foreach (var startDate in result.Entities.Where(e => e.Type == EntityStart))
            {
                var span = parser.Parse(startDate.Entity.Replace("at ", string.Empty));

                if (span != null)
                {
                    var when = span.Start ?? span.End;

                    if (when.Value.HasTime())
                    {
                        return DateTime.MinValue + when.Value.TimeOfDay;
                    }
                }
            }

            return null;
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            //string findCityNameUrl = string.Format("http://partners.api.skyscanner.net/apiservices/browsequotes/v1.0/UK/CNY/en-GB/BJSA-sky/CSHA-sky/2017-04-19/?apiKey=ma452197785131011345379685638992", "beijing");
            //HttpWebRequest request = WebRequest.Create(findCityNameUrl) as HttpWebRequest;
            //using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            //{
            //    StreamReader reader = new StreamReader(response.GetResponseStream());
            //    //Console.WriteLine(reader.ReadToEnd());
            //    //Console.ReadKey();
            //    //List<Places> p = new List<Places>();

            //    string jsonContent = reader.ReadToEnd();


            //    List<Currencies> currency = new List<Currencies>();
            //    List<Quotes> quote = new List<Quotes>();
            //    List<AirPlaces> places = new List<AirPlaces>();
            //    List<Carriers> carriers = new List<Carriers>();



            //    //string resultQeruy = getData(query.fromLocation, query.toLocation, query.dateTime, query.dateTime);
            //    JObject o = JObject.Parse(jsonContent);

            //    currency = JsonConvert.DeserializeObject<List<Currencies>>(o["Currencies"].ToString());



            //    quote = JsonConvert.DeserializeObject<List<Quotes>>(o["Quotes"].ToString());
            //    JArray ja = JArray.Parse(o["Quotes"].ToString());

            //    for(int i = 0;i<ja.Count;i++)
            //    {
            //        JObject j = JObject.Parse(ja[i].ToString());

            //        OutboundLeg ob = new OutboundLeg();
            //        ob = JsonConvert.DeserializeObject<OutboundLeg>(j["OutboundLeg"].ToString());
            //        quote[i].Outboudleg=ob;


            //       string ji = ob.CarrierIds[0].ToString();
            //        //JArray jarry1 = JArray.Parse(j["OutboundLeg"].ToString());
            //    }


            //    places = JsonConvert.DeserializeObject<List<AirPlaces>>(o["Places"].ToString());

            //    carriers = JsonConvert.DeserializeObject<List<Carriers>>(o["Carriers"].ToString());



            //DateTime t = DateTime.Today;
            //Console.WriteLine(t.Year.ToString());
            //Console.WriteLine(t.Month.ToString());
            //Console.WriteLine(t.Day.ToString());
            //Console.WriteLine(t.DayOfYear);
            //Console.WriteLine(t.AddDays(1).Day);
            Chronic.Parser  p  = new Chronic.Parser();
            Chronic.Options op = new Chronic.Options();
            var             r  = p.Parse("today");
            var             t  = DateTime.Now.ToString("yyyy-MM-dd");


            Console.WriteLine(r.ToTime().ToString("yyyy-MM-dd"));
            Console.ReadKey();



            //JObject o = JObject.Parse(jsonContent);
            //p =JsonConvert.DeserializeObject<List<Places>>(o["Places"].ToString());

            //p[0].CityId.ToString();



            //XmlReader xr = XmlReader.Create(reader);


            //DataSet objDataSet = new DataSet();
            //objDataSet.ReadXml(reader.ReadToEnd());
            //}
        }
        public async Task AuthenticateIntent(IDialogContext context, LuisResult result)
        {
            object formattedValues = null;
            var    entity          = result.Entities.FirstOrDefault(x =>
                                                                    x.Type == "builtin.datetimeV2.date" ||
                                                                    x.Type == "builtin.datetimeV2.daterange" ||
                                                                    x.Type == "builtin.datetimeV2.timerange" ||
                                                                    x.Type == "builtin.datetimeV2.time" ||
                                                                    x.Type == "builtin.datetimeV2.datetime" ||
                                                                    x.Type == "builtin.datetimeV2.datetimerange");

            entity?
            .Resolution?
            .TryGetValue("values", out formattedValues);

            // If no date indication, please ask for a date.
            if (entity == null)
            {
                await context.PostAsync($"When are you home to receive a mechanic?");

                context.Wait(MessageReceived);
                return;
            }

            // Als date time --> plan dan afspraak in in dynamics.
            // Als date time in verleden, zeg dan dat het lastig wordt om langs te komen.
            // Als geen date time en wel vraag gesteld, stel dan zelf een datum voor (random).

            Chronic.Parser       parser = new Chronic.Parser();
            EntityRecommendation date   = new EntityRecommendation();

            Chronic.Span resultSpan = null;

            if (entity.Type == "builtin.datetimeV2.daterange")
            {
                result.TryFindEntity("builtin.datetimeV2.daterange", out date);
                resultSpan = parser.Parse(date.Entity);
            }
            else if (entity.Type == "builtin.datetimeV2.date")
            {
                result.TryFindEntity("builtin.datetimeV2.date", out date);
                resultSpan = parser.Parse(date.Entity);
            }
            else if (entity.Type == "builtin.datetimeV2.timerange")
            {
                result.TryFindEntity("builtin.datetimeV2.timerange", out date);
                resultSpan = parser.Parse(date.Entity);
            }
            else if (entity.Type == "builtin.datetimeV2.time")
            {
                result.TryFindEntity("builtin.datetimeV2.time", out date);
                resultSpan = parser.Parse(date.Entity);
            }
            else if (entity.Type == "builtin.datetimeV2.datetime")
            {
                result.TryFindEntity("builtin.datetimeV2.datetime", out date);
                resultSpan = parser.Parse(date.Entity);
            }

            // If we would have used a scheduling service, we could just feed it the dates and it would come up with a suggestion...
            if (!resultSpan.Start.HasValue && !resultSpan.End.HasValue)
            {
                await context.PostAsync($"When are you home to receive a mechanic?");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value <= DateTime.Now && resultSpan.End.Value <= DateTime.Now)
            {
                await context.PostAsync($"I understand you want this issue to be resolved already, but we can't go back in time to send a mechanic.");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value.Date != resultSpan.End.Value.Date)
            {
                // We got a date range, let's pick a random date (and time).
                await context.PostAsync($"Date range, let's pick a random date");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value.TimeOfDay.Hours == 0)
            {
                // Midnight, assume that we didn't recieve a time frame and suggest some random times a day.
                // GIVE TWO OPTIONS
                await context.PostAsync($"Single time on a day.");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value.TimeOfDay.Hours == resultSpan.Start.Value.TimeOfDay.Hours)
            {
                // We got a single time on that day
                await context.PostAsync($"Sorry, there is no mechanic available at " + resultSpan.Start.Value.TimeOfDay.Hours + ".");

                this.suggestedDate = resultSpan.Start.Value.AddHours(1);
                PromptDialog.Confirm(context, this.ConfirmMechanicDateTime, $"There is one available at " + (resultSpan.Start.Value.TimeOfDay.Hours + 1) + ", should I schedule that for you?");
                return;
            }
            else if (resultSpan.Start.Value.TimeOfDay.Hours != resultSpan.Start.Value.TimeOfDay.Hours)
            {
                // Just have some fun, pick a random time on this day
                await context.PostAsync($"Timeframe on a day, pick a random time");

                context.Wait(MessageReceived);
                return;
            }
            else
            {
                // Yeah, what else?
                await context.PostAsync($"Yeah, what else? =(");

                context.Wait(MessageReceived);
                return;
            }
        }
Beispiel #17
0
        public async Task FindQuery(IDialogContext context, LuisResult result)
        {
            Query query;

            TryFindQuery(context, result, out query);

            Chronic.Parser parser     = new Chronic.Parser();
            var            dateResult = parser.Parse(query.dateTime);


            List <Currencies> currency = new List <Currencies>();
            List <Quotes>     quote    = new List <Quotes>();
            List <AirPlaces>  places   = new List <AirPlaces>();
            List <Carriers>   carriers = new List <Carriers>();

            string resultQeruy = getData(query.fromLocation, query.toLocation, dateResult.ToTime().ToString("yyyy-MM-dd"), context);


            //await context.PostAsync(resultQeruy);


            string re_Url = getRedirect(query.fromLocation, query.toLocation, dateResult.ToTime().ToString("yyyy-MM-dd"));

            JObject o = JObject.Parse(resultQeruy);

            currency = JsonConvert.DeserializeObject <List <Currencies> >(o["Currencies"].ToString());

            quote = JsonConvert.DeserializeObject <List <Quotes> >(o["Quotes"].ToString());

            JArray ja = JArray.Parse(o["Quotes"].ToString());

            for (int i = 0; i < ja.Count; i++)
            {
                JObject j = JObject.Parse(ja[i].ToString());

                OutboundLeg ob = new OutboundLeg();
                ob = JsonConvert.DeserializeObject <OutboundLeg>(j["OutboundLeg"].ToString());
                quote[i].Outboudleg = ob;
                //JArray jarry1 = JArray.Parse(j["OutboundLeg"].ToString());
            }


            places = JsonConvert.DeserializeObject <List <AirPlaces> >(o["Places"].ToString());

            carriers = JsonConvert.DeserializeObject <List <Carriers> >(o["Carriers"].ToString());


            var incomingMessage = context.MakeMessage();


            incomingMessage.Attachments = new List <Attachment>();

            List <CardImage> cardimages = new List <CardImage>();

            cardimages.Add(new CardImage(url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490980048159&di=104c5ef2ae24b270e1976fd06577a3e8&imgtype=0&src=http%3A%2F%2Fimgm.ph.126.net%2FYy3TW3UU8mlOj8jodUuq9A%3D%3D%2F6597605228821133585.png"));

            List <CardAction> cardButtons = new List <CardAction>();



            CardAction plButton = new CardAction()
            {
                Value = re_Url,
                Type  = "openUrl",
                Title = "More information"
            };

            cardButtons.Add(plButton);
            List <ReceiptItem> receiptList = new List <ReceiptItem>();

            foreach (Quotes q in quote)
            {
                string title = "";
                foreach (AirPlaces i in places)
                {
                    if (q.Outboudleg.OriginId == i.PlaceId)
                    {
                        title = i.Name;
                    }
                }

                foreach (AirPlaces i in places)
                {
                    if (q.Outboudleg.DestinationId == i.PlaceId)
                    {
                        title = title + "  --  " + i.Name;
                    }
                }

                string subtitle = "";

                foreach (Carriers i in carriers)
                {
                    if (q.Outboudleg.CarrierIds[0].ToString() == i.CarrierId)
                    {
                        subtitle = i.Name;
                    }
                }

                subtitle = subtitle + " " + Convert.ToDateTime(q.Outboudleg.DepartureDate).ToString("yyyy-MM-dd");

                ReceiptItem lineItem = new ReceiptItem()
                {
                    Title    = title,
                    Subtitle = subtitle,
                    Price    = q.MinPrice + currency[0].Symbol,
                    Image    = new CardImage(url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1492622273490&di=d35bdd3145d751c386540cf90798cea0&imgtype=0&src=http%3A%2F%2Fimg01.taopic.com%2F150630%2F240402-1506300U40237.jpg")
                };
                receiptList.Add(lineItem);
            }

            ReceiptCard plCard = new ReceiptCard()
            {
                Title   = "Booking Details",
                Buttons = cardButtons,
                Items   = receiptList
            };

            Attachment plAttachment = plCard.ToAttachment();

            //incomingMessage.Attachments.Add(receiptCard.ToAttachment());
            incomingMessage.Attachments.Add(plAttachment);
            await(context.PostAsync(incomingMessage));

            //else
            //{
            //    await context.PostAsync("did not find alarm");
            //}
            //context.Wait(MessageReceived);
        }