/// <summary>
        /// Calculates a route, based on geocode resuls.
        /// </summary>
        private void CalculateRoute(GeocodeResult[] locations = null)
        {
            // Preparing a request for route calculation.
            var request = new RouteRequest()
            {
                Culture   = CultureInfo.CurrentUICulture.Name,
                Waypoints = new ObservableCollection <Waypoint>(),

                // Don't raise exceptions.
                ExecutionOptions = new UsingBingMaps.Bing.Route.ExecutionOptions()
                {
                    SuppressFaults = true
                },

                // Only accept results with high confidence.
                Options = new RouteOptions()
                {
                    RoutePathType = RoutePathType.Points
                }
            };

            if (from_address == false)
            {
                Waypoint w_to   = new Waypoint();
                Waypoint w_from = new Waypoint();
                w_to.Location   = x_to;
                w_from.Location = x_from;
                request.Waypoints.Add(w_from);
                request.Waypoints.Add(w_to);
            }
            else
            {
                foreach (var result in locations)
                {
                    request.Waypoints.Add(GeocodeResultToWaypoint(result));
                }
            }
            // Get credentials and only then place an async call on the route service.
            _credentialsProvider.GetCredentials(credentials =>
            {
                // Pass in credentials for web services call.
                // Replace with your own Credentials.
                request.Credentials = credentials;

                // Make asynchronous call to fetch the data.
                _routeClient.CalculateRouteAsync(request);
            });
        }
        public ConnectResult Connect()
        {
            var credentials = CredentialsProvider.GetCredentials();
            var binding     = ChannelHelper.BuildChannel(Hostname, credentials.Claim, credentials.Evidence);

            folders = new List <ChannelFolder>();

            // Try connecting
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(binding.Url);

            request.AllowAutoRedirect = false;
            request.Credentials       = new NetworkCredential(credentials.Claim, credentials.Evidence);

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Logger.Debug("Server {0} returned status-code {1}", LogSource.Channel, binding.Url, response.StatusCode);

                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Found)
                {
                    return(ConnectResult.Success);
                }

                AuthMessage = String.Format("Statuscode {0}", response.StatusCode);

                return(ConnectResult.AuthFailure);
            }
            catch (Exception ex)
            {
                AuthMessage = ex.Message;

                return(ConnectResult.AuthFailure);
            }
        }
        public ConnectResult Connect()
        {
            Pop3Connection instance;

            var credentials = CredentialsProvider.GetCredentials();

            // Get the connection for the current server and user
            bool isFree = ConnectionPool <Pop3Connection> .AcquireLock(out instance, Hostname, Port, IsSecured, credentials.Claim, credentials.Evidence);

            if (isFree == false)
            {
                return(ConnectResult.Delay);
            }

            connection = instance;

            try
            {
                connection.Open();
                connection.Authenticate();

                return(ConnectResult.Success);
            }
            catch (ChannelAuthenticationException ex)
            {
                AuthMessage = ex.Message;

                return(ConnectResult.AuthFailure);
            }
        }
예제 #4
0
        public void ReturnCredentialsFromJsonFile()
        {
            var @out = credentialsProvider.GetCredentials();

            Assert.Equal("username", @out.Username);
            Assert.Equal("password", @out.Password);
        }
예제 #5
0
        private void DoPreemptiveAuth(HttpHost host, AuthScheme authScheme, AuthState authState
                                      , CredentialsProvider credsProvider)
        {
            string schemeName = authScheme.GetSchemeName();

            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
            }
            AuthScope   authScope = new AuthScope(host, AuthScope.AnyRealm, schemeName);
            Credentials creds     = credsProvider.GetCredentials(authScope);

            if (creds != null)
            {
                if (Sharpen.Runtime.EqualsIgnoreCase("BASIC", authScheme.GetSchemeName()))
                {
                    authState.SetState(AuthProtocolState.Challenged);
                }
                else
                {
                    authState.SetState(AuthProtocolState.Success);
                }
                authState.Update(authScheme, creds);
            }
            else
            {
                this.log.Debug("No credentials for preemptive authentication");
            }
        }
        public ConnectResult Connect()
        {
            var credentials = CredentialsProvider.GetCredentials();

            Imap2Connection instance;

            // Get the connection for the current server and mailbox (username)
            bool isFree = ConnectionPool <Imap2Connection> .AcquireLock(out instance, Hostname, Port, IsSecured, credentials.Claim, credentials.Evidence);

            if (isFree == false)
            {
                return(ConnectResult.Delay);
            }

            connection = instance;

            if (instance == null)
            {
                throw new ChannelFunctionalException("Connection was null in Connect");
            }

            try
            {
                connection.Open();
                connection.Authenticate();

                return(ConnectResult.Success);
            }
            catch (ChannelAuthenticationException ex)
            {
                AuthMessage = ex.Message;

                return(ConnectResult.AuthFailure);
            }
        }
예제 #7
0
        private void GetPasswords(bool getGroups)
        {
            if (getGroups)
            {
                passwordManagerGroupsProvider.GetGroups(cbGroup);
            }

            var group = cbGroup.SelectedIndex == 0 ? String.Empty : (string)cbGroup.SelectedItem;

            credentialsProvider.GetCredentials(lvCredentials, tb_Search.Text, group);
        }
예제 #8
0
        private static bool HandleCredentials(CredentialsProvider credentialProvider, PostMethod postMethod)
        {
            var credentials = (UsernamePasswordCredentials)credentialProvider.GetCredentials();

            if (credentials != null)
            {
                postMethod.UserName = credentials.GetUsername();
                postMethod.Password = credentials.GetPassword();
            }

            return(credentials != null);
        }
예제 #9
0
        public static void ReverseGeocodeAddress(Dispatcher uiDispatcher, CredentialsProvider credentialsProvider, Location location, Action <GeocodeResult> completed = null, Action <GeocodeError> error = null)
        {
            completed = completed ?? (r => { });
            error     = error ?? (e => { });

            // Get credentials and only then place an async call on the geocode service.
            credentialsProvider.GetCredentials(credentials =>
            {
                var request = new ReverseGeocodeRequest()
                {
                    // Pass in credentials for web services call.
                    Credentials = credentials,

                    Culture  = CultureInfo.CurrentUICulture.Name,
                    Location = location,

                    // Don't raise exceptions.
                    ExecutionOptions = new ExecutionOptions
                    {
                        SuppressFaults = true
                    },
                };

                EventHandler <ReverseGeocodeCompletedEventArgs> reverseGeocodeCompleted = (s, e) =>
                {
                    try
                    {
                        if (e.Result.ResponseSummary.StatusCode != Bing.Geocode.ResponseStatusCode.Success ||
                            e.Result.Results.Count == 0)
                        {
                            // Report geocode error.
                            uiDispatcher.BeginInvoke(() => error(new GeocodeError(e)));
                        }
                        else
                        {
                            // Only report on first result.
                            var firstResult = e.Result.Results.First();
                            uiDispatcher.BeginInvoke(() => completed(firstResult));
                        }
                    }
                    catch (Exception ex)
                    {
                        uiDispatcher.BeginInvoke(() => error(new GeocodeError(ex.Message, ex)));
                    }
                };

                var geocodeClient = new GeocodeServiceClient();
                geocodeClient.ReverseGeocodeCompleted += reverseGeocodeCompleted;
                geocodeClient.ReverseGeocodeAsync(request);
            });
        }
        public void Initialize()
        {
            if (Credentials == null && CredentialsProvider != null)
            {
                var authenticationResult = CredentialsProvider.GetCredentials();
                Credentials = authenticationResult.AgentCredentials;

                Logger.Logger.Log.Info("Inside Initialize() authenticationResult.AgentCredentials.Name :->" + authenticationResult.AgentCredentials.Name);
                Logger.Logger.Log.Info("Inside Initialize() authenticationResult.AgentCredentials.Password :->" + authenticationResult.AgentCredentials.Password);
                Logger.Logger.Log.Info("Inside Initialize() authenticationResult.AgentCredentials.Id :->" + authenticationResult.AgentCredentials.Id);
                Logger.Logger.Log.Info("Inside Initialize() authenticationResult.AgentCredentials.AgentID :->" + authenticationResult.AgentCredentials.AgentID);


                ScreenPop      = ((CtiServiceAgent)Agent).InteractionManager.AgentScreenPop;
                Device.Address = authenticationResult.LocationInfo.DeviceAddress;
                ((CtiServiceAgent)Agent).Name = authenticationResult.AgentCredentials.Name;
            }
        }
        /// <exception cref="Apache.Http.Auth.MalformedChallengeException"></exception>
        public virtual Queue <AuthOption> Select(IDictionary <string, Header> challenges, HttpHost
                                                 authhost, HttpResponse response, HttpContext context)
        {
            Args.NotNull(challenges, "Map of auth challenges");
            Args.NotNull(authhost, "Host");
            Args.NotNull(response, "HTTP response");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            Queue <AuthOption>          options  = new List <AuthOption>();
            Lookup <AuthSchemeProvider> registry = clientContext.GetAuthSchemeRegistry();

            if (registry == null)
            {
                this.log.Debug("Auth scheme registry not set in the context");
                return(options);
            }
            CredentialsProvider credsProvider = clientContext.GetCredentialsProvider();

            if (credsProvider == null)
            {
                this.log.Debug("Credentials provider not set in the context");
                return(options);
            }
            RequestConfig        config    = clientContext.GetRequestConfig();
            ICollection <string> authPrefs = GetPreferredAuthSchemes(config);

            if (authPrefs == null)
            {
                authPrefs = DefaultSchemePriority;
            }
            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Authentication schemes in the order of preference: " + authPrefs);
            }
            foreach (string id in authPrefs)
            {
                Header challenge = challenges.Get(id.ToLower(CultureInfo.InvariantCulture));
                if (challenge != null)
                {
                    AuthSchemeProvider authSchemeProvider = registry.Lookup(id);
                    if (authSchemeProvider == null)
                    {
                        if (this.log.IsWarnEnabled())
                        {
                            this.log.Warn("Authentication scheme " + id + " not supported");
                        }
                        // Try again
                        continue;
                    }
                    AuthScheme authScheme = authSchemeProvider.Create(context);
                    authScheme.ProcessChallenge(challenge);
                    AuthScope authScope = new AuthScope(authhost.GetHostName(), authhost.GetPort(), authScheme
                                                        .GetRealm(), authScheme.GetSchemeName());
                    Credentials credentials = credsProvider.GetCredentials(authScope);
                    if (credentials != null)
                    {
                        options.AddItem(new AuthOption(authScheme, credentials));
                    }
                }
                else
                {
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Challenge for " + id + " authentication scheme not available");
                    }
                }
            }
            // Try again
            return(options);
        }
예제 #12
0
        public void Send(ChannelMessage message)
        {
            var creds = CredentialsProvider.GetCredentials().ToNetworkCredential();

            Mail_Message msg = new Mail_Message();

            msg.MimeVersion = "1.0";
            msg.MessageID   = MIME_Utils.CreateMessageID();
            msg.Subject     = message.Context;
            msg.From        = message.From.ToMailBoxList();
            msg.ReplyTo     = message.ReturnTo == null?
                              message.From.ToAddressList() : message.ReturnTo.ToAddressList();

            if (String.IsNullOrEmpty(message.InReplyTo) == false)
            {
                msg.InReplyTo = message.InReplyTo;
            }

            msg.To = new Mail_t_AddressList();
            foreach (var address in message.To)
            {
                msg.To.Add(address.ToMailBox());
            }

            msg.Cc = new Mail_t_AddressList();
            foreach (var address in message.CC)
            {
                msg.Cc.Add(address.ToMailBox());
            }

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);

            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);

            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------------------------------------------------------------------
            MIME_Entity        entity_multipartAlternative      = new MIME_Entity();
            MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);

            contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);

            entity_multipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entity_multipartAlternative);

            //--- text/plain ----------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_plain = new MIME_Entity();
            MIME_b_Text text_plain        = new MIME_b_Text(MIME_MediaTypes.Text.plain);

            entity_text_plain.Body = text_plain;
            // Add text body if there is any
            if (message.BodyText != null && message.BodyText.Length > 0)
            {
                var bodyText = message.BodyText.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyText.EndsWith(Environment.NewLine))
                {
                    bodyText = bodyText + Environment.NewLine;
                }

                text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText);
            }

            multipartAlternative.BodyParts.Add(entity_text_plain);

            //--- text/html ------------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_html = new MIME_Entity();
            MIME_b_Text text_html        = new MIME_b_Text(MIME_MediaTypes.Text.html);

            entity_text_html.Body = text_html;
            if (message.BodyHtml != null && message.BodyHtml.Length > 0)
            {
                var bodyHtml = message.BodyHtml.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyHtml.EndsWith(Environment.NewLine))
                {
                    bodyHtml = bodyHtml + Environment.NewLine;
                }

                text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml);
            }

            multipartAlternative.BodyParts.Add(entity_text_html);

            foreach (var channelAttachment in message.Attachments)
            {
                MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream);
                MIME_Entity        attachment     = new MIME_Entity();
                attachment.Body = attachmentBody;

                // Has to happen before the following lines of code
                multipartMixed.BodyParts.Add(attachment);

                attachment.ContentType            = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename));
                attachment.ContentType.Param_Name = channelAttachment.Filename;

                MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment);
                contentDisposition.Param_FileName = channelAttachment.Filename;

                attachment.ContentDisposition      = contentDisposition;
                attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString();

                attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64);
            }

            // Inject headers
            if (!String.IsNullOrEmpty(message.MessageIdentifier))
            {
                msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier));
            }

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow))
            //    msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow));

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference))
            //    mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence))
            //    mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation))
            //    mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId))
            //    mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId);


            // Send message
            try
            {
                SMTP_Client client = new SMTP_Client();

                if ("/Settings/Channels/LoggerEnabled".AsKey(false))
                {
                    client.Logger = new LumiSoft.Net.Log.Logger();
                }

                // todo push this logic into the smtp client implementation itself
                if (Hostname == "smtp.live.com")
                {
                    // Hack for hotmail, first do a connect with no secured channel,
                    // then a STARTTLS
                    client.Connect(Hostname, Port, false);
                    client.StartTLS();
                }
                else
                {
                    client.Connect(Hostname, Port, IsSecured);
                }

                client.Authenticate(creds.UserName, creds.Password);

                using (MemoryStream ms = new MemoryStream())
                {
                    client.MailFrom(msg.From[0].Address, -1);

                    msg.ToStream(ms,
                                 new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    // Reset stream
                    ms.Seek(0, SeekOrigin.Begin);

                    foreach (var address in message.To)
                    {
                        client.RcptTo(address.Address);
                    }

                    foreach (var address in message.CC)
                    {
                        client.RcptTo(address.Address);
                    }

                    foreach (var address in message.BCC)
                    {
                        client.RcptTo(address.Address);
                    }

                    try
                    {
                        client.SendMessage(ms);
                    }
                    finally
                    {
                        client.Dispose();
                    }
                }
            }
            catch (SmtpFailedRecipientsException e)
            {
                throw new ChannelFunctionalException(e.Message, e)
                      {
                          DoNotRetry = true
                      };
            }
            catch (SmtpException e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
        }
예제 #13
0
        public static void ReverseGeocodeAddress(Dispatcher uiDispatcher, CredentialsProvider credentialsProvider, Location location, Action <GeocodeResult> completed = null, Action <GeocodeError> error = null)
        {
            Debug.WriteLine("inside ReverseGeocodeAddress");
            completed = completed ?? (r => { });
            error     = error ?? (e => { });

            // Get credentials and only then place an async call on the geocode service.
            credentialsProvider.GetCredentials(credentials =>
            {
                Debug.WriteLine("inside GetCredentials");
                var request = new ReverseGeocodeRequest()
                {
                    // Pass in credentials for web services call.
                    Credentials = credentials,

                    Culture  = CultureInfo.CurrentUICulture.Name,
                    Location = location,

                    // Don't raise exceptions.
                    ExecutionOptions = new ScheduledTaskAgent1.Bing.Geocode.ExecutionOptions
                    {
                        SuppressFaults = true
                    },
                };



                EventHandler <ReverseGeocodeCompletedEventArgs> reverseGeocodeCompleted = (s, e) =>
                {
                    try
                    {
                        if (e.Result.ResponseSummary.StatusCode != ScheduledTaskAgent1.Bing.Geocode.ResponseStatusCode.Success ||
                            e.Result.Results.Count == 0)
                        {
                            // Report geocode error.
                            uiDispatcher.BeginInvoke(() => error(new GeocodeError(e)));
                        }
                        else
                        {
                            // Only report on first result.
                            var firstResult = e.Result.Results[0];
                            uiDispatcher.BeginInvoke(() => completed(firstResult));
                            //Debug.WriteLine("street=" + firstResult.Address.AddressLine.ToString());
                            //Debug.WriteLine("admin district=" + firstResult.Address.AdminDistrict.ToString());
                            //Debug.WriteLine("country region=" + firstResult.Address.CountryRegion.ToString());
                            //Debug.WriteLine("district=" + firstResult.Address.District.ToString());
                            Debug.WriteLine("formatted addres=" + firstResult.Address.FormattedAddress.ToString());
                            //Debug.WriteLine("locality=" + firstResult.Address.Locality.ToString());
                            //Debug.WriteLine("postal code=" + firstResult.Address.PostalCode.ToString());
                            //Debug.WriteLine("postal town=" + firstResult.Address.PostalTown.ToString());
                            CurrentAddress = firstResult.Address.FormattedAddress.ToString();
                            //CurrentAddress_AdminDistrict = firstResult.Address.AdminDistrict.ToString();
                            //CurrentAddress_CountryRegion = firstResult.Address.CountryRegion.ToString();
                            //CurrentAddress_Locality = firstResult.Address.Locality.ToString();
                            //CurrentAddress_PostalCode = firstResult.Address.PostalCode.ToString();
                            //CurrentAddress_AddressLine = firstResult.Address.AddressLine.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        uiDispatcher.BeginInvoke(() => error(new GeocodeError(ex.Message, ex)));
                    }
                };

                var geocodeClient = new GeocodeServiceClient();
                geocodeClient.ReverseGeocodeCompleted += reverseGeocodeCompleted;
                geocodeClient.ReverseGeocodeAsync(request);
            });
        }
예제 #14
0
        public void Update()
        {
            //Get SVN respository credentials
            List <Repository> tfsRepositories = _data.GetRepositories("tfs");

            foreach (var tfsRepository in tfsRepositories)
            {
                //invokeEvent: Libs.WriteLine("Initializing: " + tfsRepository.Name);

                //credentials
                CredentialsProvider connect = new CredentialsProvider();
                ICredentials        iCred   = new NetworkCredential(tfsRepository.RootUsername, tfsRepository.RootPassword, "*");
                connect.GetCredentials(new Uri(tfsRepository.BaseUrl), iCred);

                //var tfsCreds = new TfsClientCredentials(new WindowsCredential(), true);
                //var configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(tfsRepository.BaseUrl), connect);
                //configurationServer.EnsureAuthenticated();
                //var projects = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsRepository.BaseUrl), tfsCreds);

                var projects = new TfsTeamProjectCollection(new Uri(tfsRepository.BaseUrl), connect);
                var vcs      = projects.GetService <VersionControlServer>();

                var tmpFile = System.IO.Path.GetTempPath() + Path.DirectorySeparatorChar + "ProMan.tmp";

                long maxRevision  = tfsRepository.LastRevision;
                var  lastRevision = vcs.GetLatestChangesetId();

                //invokeEvent: Libs.WriteLine("Scanning: " + tfsRepository.Name);
                //get projects in this repository

                for (var iRevision = maxRevision; iRevision < lastRevision; iRevision++)
                {
                    //invokeEvent: Libs.WriteLine("        r" + iRevision);

                    long totalBoc   = 0;
                    var  newestDate = DateTime.MinValue;

                    if (maxRevision >= lastRevision)
                    {
                        continue;
                    }

                    var changeset = vcs.GetChangeset((int)iRevision, true, true);

                    //check and find dev in this project
                    var developer = _data.GetDevelopers().Where(o => o.TfsUser == changeset.Committer).FirstOrDefault();
                    if (developer == null)
                    {
                        developer = _data.InsertDeveloper(changeset.Committer);
                    }

                    foreach (var w in changeset.Changes)
                    {
                        //get file url
                        var fileUrl = tfsRepository.BaseUrl + w.Item.ServerItem;
                        ProjectRepository projectRepository = null;
                        foreach (var pr in _data.GetProjectRepositories())
                        {
                            if (fileUrl.Replace("//", "/").ToLower().Contains(pr.Path.Replace("//", "/").ToLower()))
                            {
                                projectRepository = pr;
                                break;
                            }
                        }
                        if (projectRepository == null)
                        {
                            continue;
                        }
                        var rgxExclude = new Regex(projectRepository.Project.ExcludeRegExp);
                        if (rgxExclude.IsMatch(fileUrl))
                        {
                            continue;
                        }

                        if (!w.Item.ServerItem.StartsWith(projectRepository.Path, true, System.Globalization.CultureInfo.InvariantCulture))
                        {
                            continue;
                        }

                        var changeType       = TfsChangeType(w.ChangeType);
                        var changeTypeString = "add";

                        if (w.Item.ItemType != ItemType.File)
                        {
                            continue;
                        }

                        if (rgxExclude.IsMatch(w.Item.ServerItem))
                        {
                            continue;
                        }

                        //get filetype
                        var ext      = Path.GetExtension(w.Item.ServerItem);
                        var fileType = _data.GetFileTypes().Where(o => o.Type == ext).FirstOrDefault();
                        if (fileType == null)
                        {
                            continue;
                        }

                        //Get file BOC
                        long bocs     = 0;
                        var  revision = w.ChangeType == ChangeType.Delete ? iRevision - 1 : iRevision;

                        w.Item.DownloadFile(tmpFile);
                        var str = System.IO.File.ReadAllText(tmpFile);
                        bocs = GetCodeBytes(str, fileType.RemovesRegExp);

                        if (changeType == ChangeType.Delete)
                        {
                            changeTypeString = "del";
                            bocs            *= -1;
                        }

                        if (changeType == ChangeType.Edit || changeType == ChangeType.Merge || changeType == ChangeType.Rollback)
                        {
                            try
                            {
                                Item previousItem = vcs.GetItem(w.Item.ItemId, Convert.ToInt32(iRevision - 1), true);

                                previousItem.DownloadFile(tmpFile);
                                var str2 = System.IO.File.ReadAllText(tmpFile);
                                bocs             = bocs - GetCodeBytes(str2, fileType.RemovesRegExp);
                                changeTypeString = "mod";
                            }
                            catch
                            {
                                bocs = w.Item.ContentLength;
                            }
                        }

                        totalBoc += bocs;

                        if (bocs == 0)
                        {
                            continue;
                        }

                        //find file in db or create one
                        var file = _data.GetFile(w.Item.ServerItem);

                        if (file == null)
                        {
                            file = _data.InsertFile(w.Item.ServerItem);
                        }


                        _data.InsertBOC(projectRepository == null ? null : (int?)projectRepository.ProjectID,
                                        projectRepository == null ? null : (int?)projectRepository.ID,
                                        developer.ID,
                                        file.ID,
                                        fileType == null ? null : (int?)fileType.ID,
                                        w.Item.ServerItem,
                                        bocs,
                                        iRevision,
                                        changeTypeString,
                                        w.Item.CheckinDate);
                    }

                    _data.UpdateRepositoryRevision(iRevision, tfsRepository.ID);
                }
            }
        }
예제 #15
0
        public IEnumerable <ChannelContact> GetContacts()
        {
            var cred = CredentialsProvider.GetCredentials();
            var rs   = new RequestSettings("Tabdeelee-Inbox2-1", cred.Claim, cred.Evidence)
            {
                AutoPaging = true
            };
            var cr = new ContactsRequest(rs);

            var feed = cr.GetContacts();

            foreach (Contact entry in feed.Entries)
            {
                ChannelContact contact = new ChannelContact();

                contact.Person.Name = entry.Title;
                contact.Profile.ChannelProfileKey = entry.Id;

                if (entry.Phonenumbers.Count > 0)
                {
                    var phone = entry.Phonenumbers.First();
                    contact.Profile.PhoneNr = phone.Value;
                }

                if (entry.PrimaryEmail != null)
                {
                    contact.Profile.SourceAddress = new SourceAddress(entry.PrimaryEmail.Address, contact.Person.Name);
                }

                try
                {
                    // Check for 404 with custom httpclient on photourl since regular HttpWebClient keeps throwing exceptions
                    //var token = cr.Service.QueryAuthenticationToken();
                    //var code = HttpStatusClient.GetStatusCode(entry.PhotoUri.ToString(),
                    //    new Dictionary<string, string> { { "Authorization", "GoogleLogin auth=" + token }});

                    //if (code.HasValue && code == 200)
                    //{
                    IGDataRequest request = cr.Service.RequestFactory.CreateRequest(GDataRequestType.Query, entry.PhotoUri);
                    request.Execute();

                    using (var avatarstream = request.GetResponseStream())
                    {
                        if (avatarstream != null)
                        {
                            ChannelAvatar avatar = new ChannelAvatar();

                            // Copy avatarstream to a new memorystream because the source
                            // stream does not support seek operations.
                            MemoryStream ms = new MemoryStream();
                            avatarstream.CopyTo(ms);

                            avatar.Url           = entry.PhotoUri.ToString();
                            avatar.ContentStream = ms;

                            contact.Profile.ChannelAvatar = avatar;
                        }
                    }
                    //}
                }
                catch (CaptchaRequiredException)
                {
                    // Since GMail will keep on raising CaptchaRequiredException, break out here
                    // todo let the user know in some way or another?
                    yield break;
                }
                catch (Exception)
                {
                }

                yield return(contact);
            }
        }
        public IEnumerable <ChannelEvent> GetEvents(ChannelCalendar calendar)
        {
            var creds = CredentialsProvider.GetCredentials();

            service.setUserCredentials(creds.Claim, creds.Evidence);
            string url = String.Format("http://www.google.com/calendar/feeds/{0}/private/full", creds.Claim);

            // Check for 404 with custom httpclient on photourl since regular HttpWebClient keeps throwing exceptions
            var token = service.QueryAuthenticationToken();
            var code  = HttpStatusClient.GetStatusCode(url,
                                                       new Dictionary <string, string> {
                { "Authorization", "GoogleLogin auth=" + token }
            });

            if (!(code == 200 || code == 302))
            {
                Logger.Warn("Not downloading calendar events because of un expected HttpStatusCode. Code = [0}", LogSource.Sync, code);

                yield break;
            }

            EventQuery query = new EventQuery {
                Uri = new Uri(url)
            };
            EventFeed feed = service.Query(query);

            foreach (EventEntry item in feed.Entries)
            {
                // Create a new channelevent
                ChannelEvent evt = new ChannelEvent();

                // Get the event key
                evt.ChannelEventKey = item.Id.Uri.ToString();

                // Get subject, description and location
                evt.Subject     = item.Title.Text;
                evt.Description = item.Content.Content;
                evt.Location    = item.Locations[0].ValueString;

                // Get the start, end date and date modified
                evt.StartDate = item.Times[0].StartTime;
                evt.EndDate   = item.Times[0].EndTime;
                evt.Modified  = item.Updated;

                // Get the date of the event when it was initially created
                evt.Stamp = item.Published;

                // Set the date of the event when it was created by Inbox2
                evt.DateCreated = DateTime.Now;

                // Get the status
                if (item.Status == EventEntry.EventStatus.CONFIRMED)
                {
                    evt.State = EventState.Confirmed;
                }
                else if (item.Status == EventEntry.EventStatus.TENTATIVE)
                {
                    evt.State = EventState.Tentative;
                }
                else if (item.Status == EventEntry.EventStatus.CANCELED)
                {
                    evt.State = EventState.Cancelled;
                }
                else
                {
                    evt.State = EventState.Confirmed;
                }

                // Get the visability (/class)
                if (item.EventVisibility.Value == EventEntry.Visibility.PUBLIC_VALUE)
                {
                    evt.Class = EventClassType.Public;
                }
                else if (item.EventVisibility.Value == EventEntry.Visibility.PRIVATE_VALUE)
                {
                    evt.Class = EventClassType.Private;
                }
                else if (item.EventVisibility.Value == EventEntry.Visibility.CONFIDENTIAL_VALUE)
                {
                    evt.Class = EventClassType.Confidential;
                }
                else if (item.EventVisibility.Value == EventEntry.Visibility.DEFAULT_VALUE)
                {
                    evt.Class = EventClassType.Public;
                }
                else
                {
                    evt.Class = EventClassType.Public;
                }

                // Gmail hasn't a priority status, so set it to None
                evt.Priority = EventPriority.None;

                // Return the event
                yield return(evt);
            }
        }
        public static void ReverseGeocodeAddress(Dispatcher uiDispatcher, CredentialsProvider credentialsProvider, Location location, Action<GeocodeResult> completed = null, Action<GeocodeError> error = null)
        {
            completed = completed ?? (r => { });
            error = error ?? (e => { });

            // Get credentials and only then place an async call on the geocode service.
            credentialsProvider.GetCredentials(credentials =>
            {
                var request = new ReverseGeocodeRequest()
                {
                    // Pass in credentials for web services call.
                    Credentials = credentials,

                    Culture = CultureInfo.CurrentUICulture.Name,
                    Location = location,

                    // Don't raise exceptions.
                    ExecutionOptions = new UsingBingMaps.Bing.Geocode.ExecutionOptions
                    {
                        SuppressFaults = true
                    },
                };

 

                EventHandler<ReverseGeocodeCompletedEventArgs> reverseGeocodeCompleted = (s, e) =>
                {
                    try
                    {
                        if (e.Result.ResponseSummary.StatusCode != UsingBingMaps.Bing.Geocode.ResponseStatusCode.Success ||
                            e.Result.Results.Count == 0)
                        {
                            // Report geocode error.
                            uiDispatcher.BeginInvoke(() => error(new GeocodeError(e)));
                        }
                        else
                        {
                            // Only report on first result.
                            var firstResult = e.Result.Results.First();
                            uiDispatcher.BeginInvoke(() => completed(firstResult));
                            Debug.WriteLine("street=" + firstResult.Address.AddressLine.ToString());
                            Debug.WriteLine("admin district=" + firstResult.Address.AdminDistrict.ToString());
                            Debug.WriteLine("country region=" + firstResult.Address.CountryRegion.ToString());
                            Debug.WriteLine("district=" + firstResult.Address.District.ToString());
                            Debug.WriteLine("formatted addres=" + firstResult.Address.FormattedAddress.ToString());
                            Debug.WriteLine("locality=" + firstResult.Address.Locality.ToString());
                            Debug.WriteLine("postal code=" + firstResult.Address.PostalCode.ToString());
                            Debug.WriteLine("postal town=" + firstResult.Address.PostalTown.ToString());
                            CurrentAddress = firstResult.Address.FormattedAddress.ToString();
                            CurrentAddress_AdminDistrict = firstResult.Address.AdminDistrict.ToString();
                            CurrentAddress_CountryRegion = firstResult.Address.CountryRegion.ToString();
                            CurrentAddress_Locality = firstResult.Address.Locality.ToString();
                            CurrentAddress_PostalCode = firstResult.Address.PostalCode.ToString();
                            CurrentAddress_AddressLine = firstResult.Address.AddressLine.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        uiDispatcher.BeginInvoke(() => error(new GeocodeError(ex.Message, ex)));
                    }
                };

                var geocodeClient = new GeocodeServiceClient();
                geocodeClient.ReverseGeocodeCompleted += reverseGeocodeCompleted;
                geocodeClient.ReverseGeocodeAsync(request);
            });
        }