Example #1
1
 public void Initialize()
 {
     Session = RetsSession.Create(BaseUrl, LoginUrl, Port, UserName, Password, UserAgent, UserAgentAuth, RetsVersion, AuthMethod);
     LoginResponse = Session.Login();
 }
Example #2
0
        public async Task EndToEndProcessing()
        {
            var config      = TestHelper.GetApplicationConfiguration(Environment.CurrentDirectory);
            var retsSession = new RetsSession(config.LoginUrl);

            if (await retsSession.LoginAsync(config.Username, config.Password, config.UserAgent))
            {
                var metadata = await retsSession.GetMetadataAsync();

                foreach (var resource in metadata.Resources)
                {
                    _output.WriteLine($"Resource: {resource.StandardName} [{resource.VisibleName}]");
                    foreach (var retsClass in resource.Classes)
                    {
                        _output.WriteLine($"Class: {retsClass.StandardName} [{retsClass.VisibleName}]");
                        _output.WriteLine($"Tables:");
                        foreach (var table in retsClass.Tables)
                        {
                            _output.WriteLine("=====================================================================");
                            _output.WriteLine($"Table: Resource-{table.Resource} Class:{table.Class}");
                            _output.WriteLine("=====================================================================");
                            foreach (var field in table.Fields)
                            {
                                _output.WriteLine($"{field.StandardName,40} ({field.DataType}:{field.Precision})");
                            }
                        }
                    }
                }

                // todo: call other session methods

                await retsSession.LogoutAsync();
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            var loginUrl = "";
            var username = "";
            var password = "";
            var userAgent = "";

            using (var retsSession = new RetsSession(loginUrl))
            {
                if (!string.IsNullOrEmpty(userAgent))
                {
                    retsSession.SetUserAgent(userAgent);
                }
                retsSession.SetRetsVersion(RetsVersion.RETS_1_7_2);

                if (!retsSession.Login(username, password))
                {
                    throw new Exception("RETS login failed");
                }

                var loginResponse = retsSession.GetLoginResponse();

                // todo: inspect login response
            }
        }
Example #4
0
        public async Task Logout_WithLogin_Succeeds()
        {
            // Arrange
            var mockRetsHttpClient = new Mock <IRetsHttpClient>();

            mockRetsHttpClient
            .Setup(m => m.LoginAsync(It.IsAny <Uri>()))
            .ReturnsAsync(new LoginResponse());
            mockRetsHttpClient
            .Setup(m => m.LogoutAsync());
            var retsSession = new RetsSession("https://retsserver/login")
            {
                RetsHttpClient = mockRetsHttpClient.Object
            };

            // Act
            var response = await retsSession.LoginAsync("username", "password", "useragent");

            if (response == true)
            {
                await retsSession.LogoutAsync();
            }

            // Assert
            Assert.True(response);
            Assert.Null(retsSession.LoginResponse);
        }
Example #5
0
    static void Main(string[] args)
    {
        Options options = new Options();

        if (!options.Parse(args))
        {
            Environment.Exit(1);
        }

        RetsSession session = options.SessionFactory();

        session.SetIncrementalMetadata(options.full_metadata ? false : true);

        try
        {
            if (!session.Login(options.user_name, options.user_password))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            Environment.Exit(1);
        }

        RetsMetadata metadata = session.GetMetadata();

        dumpSystem(metadata);
        dumpForeignKeys(metadata);
        dumpAllResources(metadata);

        session.Logout();
    }
Example #6
0
        static void Main(string[] args)
        {
            var loginUrl  = "https://some.rets.server.com/rets/login";
            var username  = "";
            var password  = "";
            var userAgent = "";

            using (var retsSession = new RetsSession(loginUrl))
            {
                var uri = new Uri(loginUrl);
                if (uri.Scheme == Uri.UriSchemeHttps)
                {
                    // ssl certificate work around - https://groups.google.com/forum/#!searchin/librets/ssl%7Csort:relevance/librets/g62O8pxsAcg/AXzlKi133TUJ
                    retsSession.SetModeFlags(RetsSession.MODE_NO_SSL_VERIFY);
                }

                if (!string.IsNullOrEmpty(userAgent))
                {
                    retsSession.SetUserAgent(userAgent);
                }
                retsSession.SetRetsVersion(RetsVersion.RETS_1_8_0);

                if (!retsSession.Login(username, password))
                {
                    throw new Exception("RETS login failed");
                }

                var loginResponse = retsSession.GetLoginResponse();

                // todo: inspect login response
            }
        }
Example #7
0
        public async Task Login_WithValidCredential_ReturnsTrue()
        {
            // Arrange
            var config      = TestHelper.GetApplicationConfiguration(Environment.CurrentDirectory);
            var retsSession = new RetsSession(config.LoginUrl);

            // Act
            var result = await retsSession.LoginAsync(config.Username, config.Password, config.UserAgent);

            // Assert
            Assert.True(result);
            Assert.NotNull(retsSession.LoginResponse);
        }
Example #8
0
        public async Task Login_WithInvalidCredentials_Unsuccessful()
        {
            // Arrange
            var config      = TestHelper.GetApplicationConfiguration(Environment.CurrentDirectory);
            var retsSession = new RetsSession(config.LoginUrl);

            // Act
            var result = await retsSession.LoginAsync("invalid-username", "invalid-password", "invalid-useragent");

            // Assert
            Assert.False(result);
            Assert.Null(retsSession.LoginResponse);
        }
Example #9
0
    /**
     * Create a RetsSession and populate it with all the known options.
     */
    public RetsSession SessionFactory()
    {
        uint flags = 0;

        if (mRetsSession != null)
        {
            mRetsSession.Cleanup();
            mRetsSession = null;
        }
        mRetsSession = new RetsSession(mUrl);

        mRetsSession.SetDefaultEncoding(mEncoding);
        if (mHttpLog.Length > 0)
        {
            mRetsSession.SetHttpLogName(mHttpLog);
        }
        mRetsSession.SetLogEverything(mLogEverything);
        mRetsSession.SetRetsVersion(mRetsVersion);
        mRetsSession.SetUserAgent(mUA);
        mRetsSession.SetUserAgentAuthType(mUAAuth);
        if (mUAPass.Length > 0)
        {
            mRetsSession.SetUserAgentPassword(mUAPass);
        }

        if (mEnableCacheing)
        {
            flags |= RetsSession.MODE_CACHE;
        }

        if (mNoSSLVerify)
        {
            flags |= RetsSession.MODE_NO_SSL_VERIFY;
        }

        if (mDisableStreaming)
        {
            /*
             * Caching is required in non-streaming mode.
             */
            flags |= RetsSession.MODE_CACHE | RetsSession.MODE_NO_STREAM;
        }
        mRetsSession.SetModeFlags(flags);

        return(mRetsSession);
    }
Example #10
0
        public async Task Logout_WithLogin_Succeeds()
        {
            // Arrange
            var config      = TestHelper.GetApplicationConfiguration(Environment.CurrentDirectory);
            var retsSession = new RetsSession(config.LoginUrl);

            // Act
            var response = await retsSession.LoginAsync(config.Username, config.Password, config.UserAgent);

            if (response == true)
            {
                await retsSession.LogoutAsync();
            }

            // Assert
            Assert.True(response);
            Assert.Null(retsSession.LoginResponse);
        }
Example #11
0
        static void Main(string[] args)
        {
            bool isLoggedIn = false;

            using (RetsSession retssession = new RetsSession("http://www.eele-rets.com:6160/rets/login"))
            {
                retssession.UseHttpGet(true);
                //retssession.
                isLoggedIn = retssession.Login("corcoran", "JDXzmkGa");

                if (isLoggedIn)
                {
                    var urls = retssession.GetCapabilityUrls();
                    Console.WriteLine(urls.GetLoginUrl());

                    RetsMetadata metadata  = retssession.GetMetadata();
                    IEnumerable  resources = metadata.GetAllResources();

                    using (SearchRequest searchRequest = retssession.CreateSearchRequest(
                               "Property",
                               "CLISTINGS",
                               "(Modified=2016-12-12T00:00:00+)"))
                    {
                        searchRequest.SetQueryType(SearchRequest.QueryType.DMQL2);
                        searchRequest.SetStandardNames(false);
                        searchRequest.SetOffset(SearchRequest.OFFSET_NONE);
                        SearchResultSet results = retssession.Search(searchRequest);
                        Console.WriteLine("Record count: " + results.GetCount());
                        Console.WriteLine();
                        IEnumerable columns = results.GetColumns();
                        while (results.HasNext())
                        {
                            foreach (string column in columns)
                            {
                                Console.WriteLine(column + ": " + results.GetString(column));
                            }
                            Console.WriteLine();
                        }
                    }
                }
            }
        }
Example #12
0
    static void Main(string[] args)
    {
        RetsSession session = null;

        try
        {
            session = new RetsSession(
                "http://demo.crt.realtors.org:6103/rets/login");
            if (args.Length == 1)
            {
                session.SetHttpLogName(args[0]);
            }
            if (!session.Login("Joe", "Schmoe"))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }

            Console.WriteLine(".Net version: " + System.Environment.Version);

            LoginResponse login = session.GetLoginResponse();
            Console.WriteLine("Member name: " + login.GetMemberName());

            CapabilityUrls capabilityUrls = session.GetCapabilityUrls();
            Console.WriteLine("Search URL: " + capabilityUrls.GetSearchUrl());

            LogoutResponse logout = session.Logout();
            Console.WriteLine("Billing info: " + logout.GetBillingInfo());
            Console.WriteLine("Logout message: " + logout.GetLogoutMessage());
            Console.WriteLine("Connect time: " + logout.GetConnectTime());
        }
        finally
        {
            // Be sure to dispose RetsSession when finished, otherwise the
            // TextWriter Dispose() method may be called prior to RetsSession.
            if (session != null)
            {
                session.Dispose();
            }
        }
    }
Example #13
0
        public async Task Login_WithValidCredentials_ReturnsTrue()
        {
            // Arrange
            var mockRetsHttpClient = new Mock <IRetsHttpClient>();

            mockRetsHttpClient
            .Setup(m => m.LoginAsync(It.IsAny <Uri>()))
            .ReturnsAsync(new LoginResponse());

            var retsSession = new RetsSession("http://retsserver/login")
            {
                // Use this test seam to mock the HttpClient
                RetsHttpClient = mockRetsHttpClient.Object
            };

            // Act
            var result = await retsSession.LoginAsync("username", "password", "useragent");

            // Assert
            Assert.True(result);
            Assert.NotNull(retsSession.LoginResponse);
        }
Example #14
0
        public async Task Login_WithInvalidCredentials_ReturnsFalse()
        {
            // Arrange
            var mockRetsHttpClient = new Mock <IRetsHttpClient>();

            mockRetsHttpClient
            .Setup(m => m.LoginAsync(It.IsAny <Uri>()))
            .Returns(Task.FromResult <LoginResponse>(null));

            var retsSession = new RetsSession("https://retsserver/login")
            {
                // Use this test seam to mock the HttpClient
                RetsHttpClient = mockRetsHttpClient.Object
            };

            // Act
            var result = await retsSession.LoginAsync("invalidusername", "invalidpassword", "invaliduseragent");

            // Assert
            Assert.False(result);
            Assert.Null(retsSession.LoginResponse);
        }
Example #15
0
    static void Main(string[] args)
    {
        RetsSession session = null;
        try
        {
            session = new RetsSession(
                "http://demo.crt.realtors.org:6103/rets/login");
        if (args.Length == 1)
            session.SetHttpLogName(args[0]);
            if (!session.Login("Joe", "Schmoe"))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }

            Console.WriteLine(".Net version: " + System.Environment.Version);

            LoginResponse login = session.GetLoginResponse();
            Console.WriteLine("Member name: " + login.GetMemberName());

            CapabilityUrls capabilityUrls = session.GetCapabilityUrls();
            Console.WriteLine("Search URL: " + capabilityUrls.GetSearchUrl());

            LogoutResponse logout = session.Logout();
            Console.WriteLine("Billing info: " + logout.GetBillingInfo());
            Console.WriteLine("Logout message: " + logout.GetLogoutMessage());
            Console.WriteLine("Connect time: " + logout.GetConnectTime());
        }
        finally
        {
            // Be sure to dispose RetsSession when finished, otherwise the
            // TextWriter Dispose() method may be called prior to RetsSession.
            if (session != null)
                session.Dispose();
        }
    }
Example #16
0
    static void Main(string[] args)
    {
        Options options = new Options();

        if (!options.Parse(args))
        {
            Environment.Exit(1);
        }

        RetsSession session = options.SessionFactory();

        try {
            if (!session.Login(options.user_name, options.user_password))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }
        } catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            Environment.Exit(1);
        }

        SearchRequest searchRequest = session.CreateSearchRequest(
            options.search_type, options.search_class, options.query);

        searchRequest.SetSelect(options.select);
        searchRequest.SetLimit(options.limit);
        searchRequest.SetOffset(options.offset);
        searchRequest.SetCountType(options.count);
        searchRequest.SetStandardNames(options.standard_names);

        try
        {
            Stream  outputStream = File.OpenWrite("rawsearch.xml");
            byte [] data         = session.SearchAsArray(searchRequest);
            outputStream.Write(data, 0, data.Length);
            outputStream.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            session.Logout();
            Environment.Exit(1);
        }

        session.Logout();

        try
        {
            // I'd rather use ReadAllBytes, but it doesn't exist in all versions.
            // byte [] data = File.ReadAllBytes("rawsearch.xml");
            //
            FileInfo   info        = new FileInfo("rawsearch.xml");
            int        len         = (int)info.Length;
            byte []    data        = new byte [len];
            FileStream inputStream = info.OpenRead();
            inputStream.Read(data, 0, len);

            SearchResultSet results = new SearchResultSet();

            results.SetEncoding(options.encoding);
            results.SetDataAsArray(data);

            Console.WriteLine("Record count: " + results.GetCount());
            Console.WriteLine();
            IEnumerable columns = null;

            while (results.HasNext())
            {
                if (columns == null)
                {
                    columns = results.GetColumns();
                }
                foreach (string column in columns)
                {
                    Console.WriteLine(column + ": " + results.GetString(column));
                }
                Console.WriteLine();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            session.Logout();
            Environment.Exit(1);
        }
    }
Example #17
0
    static void Main(string[] args)
    {
        Options options = new Options();

        if (!options.Parse(args))
        {
            Environment.Exit(1);
        }

        RetsSession session = options.SessionFactory();

        try
        {
            if (!session.Login(options.user_name, options.user_password))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }

            /*
             * Create an update request.
             */
            UpdateRequest updateRequest = session.CreateUpdateRequest(
                options.update_resource,
                options.update_class);
            updateRequest.SetDelimiter("|");
            updateRequest.SetValidateFlag(options.validation_code);
            updateRequest.SetUpdateType(options.update_type);

            /*
             * Pull apart the Record.
             */
            string[] lines = options.update_record.Split(",".ToCharArray());

            /*
             * We should now have key/value pairs in lines.
             * Process them.
             */
            foreach (string line in lines)
            {
                string[] keyValue = line.Split("=".ToCharArray());
                string   key      = keyValue[0].Trim();
                string   value    = keyValue[1].Trim();
                updateRequest.SetField(key, value);
            }

            /*
             * Perform the update.
             */
            UpdateResponse results = session.Update(updateRequest);

            IEnumerable columns = null;
            while (results.HasNext())
            {
                if (columns == null)
                {
                    columns = results.GetColumns();
                }
                foreach (string column in columns)
                {
                    Console.WriteLine(column + ": " + results.GetString(column));
                }
                Console.WriteLine();
            }

            /*
             * See if there are errors. If so, show them.
             */
            bool seen = false;
            while (results.HasNextError())
            {
                if (!seen)
                {
                    seen = true;
                    Console.WriteLine("Errors:");
                }

                Console.WriteLine(results.GetErrorFieldName() +
                                  ", Error: " +
                                  results.GetErrorNumber() +
                                  " at offset " +
                                  results.GetErrorOffset() +
                                  ", Message: " +
                                  results.GetErrorText());
            }

            /*
             * See if there are warnings. If so, show them.
             */

            seen = false;
            while (results.HasNextWarning())
            {
                if (!seen)
                {
                    seen = true;
                    Console.WriteLine("Warnings:");
                }

                Console.WriteLine(results.GetWarningFieldName() +
                                  ", Error: " +
                                  results.GetWarningNumber() +
                                  " at offset " +
                                  results.GetWarningOffset() +
                                  ", Message: " +
                                  results.GetWarningText() +
                                  ", Response Required: " +
                                  results.GetWarningResponseRequired());
            }

            LogoutResponse logout = session.Logout();
            Console.WriteLine("Billing info: " + logout.GetBillingInfo());
            Console.WriteLine("Logout message: " + logout.GetLogoutMessage());
            Console.WriteLine("Connect time: " + logout.GetConnectTime());
        }
        catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            Environment.Exit(1);
        }
    }
Example #18
0
    /**
     * Create a RetsSession and populate it with all the known options.
     */
    public RetsSession SessionFactory()
    {
        uint flags = 0;

        if (mRetsSession != null)
        {
            mRetsSession.Cleanup();
            mRetsSession = null;
        }
        mRetsSession = new RetsSession(mUrl);

        mRetsSession.SetDefaultEncoding(mEncoding);
        if (mHttpLog.Length > 0)
            mRetsSession.SetHttpLogName(mHttpLog);
        mRetsSession.SetLogEverything(mLogEverything);
        mRetsSession.SetRetsVersion(mRetsVersion);
        mRetsSession.SetUserAgent(mUA);
        mRetsSession.SetUserAgentAuthType(mUAAuth);
        if (mUAPass.Length > 0)
            mRetsSession.SetUserAgentPassword(mUAPass);

        if (mEnableCacheing)
          flags |= RetsSession.MODE_CACHE;

        if (mNoSSLVerify)
          flags |= RetsSession.MODE_NO_SSL_VERIFY;

        if (mDisableStreaming)
        {
            /*
             * Caching is required in non-streaming mode.
             */
            flags |= RetsSession.MODE_CACHE | RetsSession.MODE_NO_STREAM;
        }
        mRetsSession.SetModeFlags(flags);

        return mRetsSession;
    }
Example #19
0
    static void Main(string[] args)
    {
        Options options = new Options();

        if (!options.Parse(args))
        {
            Environment.Exit(1);
        }

        RetsSession session = options.SessionFactory();

        try {
            if (!session.Login(options.user_name, options.user_password))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }
        } catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            Environment.Exit(1);
        }

        Console.WriteLine("Action: " + session.GetAction());
        RetsVersion version = session.GetDetectedRetsVersion();

        Console.WriteLine("RETS Version: " +
                          ((version == RetsVersion.RETS_1_5) ? "1.5" :
                           ((version == RetsVersion.RETS_1_7) ? "1.7" : "1.0")));

        SearchRequest searchRequest = session.CreateSearchRequest(
            options.search_type, options.search_class, options.query);

        searchRequest.SetSelect(options.select);
        searchRequest.SetLimit(options.limit);
        searchRequest.SetOffset(options.offset);
        searchRequest.SetCountType(options.count);
        searchRequest.SetStandardNames(options.standard_names);
        searchRequest.SetRestrictedIndicator("XXXX");
        searchRequest.SetFormatType(SearchRequest.FormatType.COMPACT);
        SearchResultSet results = session.Search(searchRequest);

        Console.WriteLine("Record count: " + results.GetCount());
        Console.WriteLine();
        IEnumerable columns = null;

        while (results.HasNext())
        {
            if (columns == null)
            {
                columns = results.GetColumns();
            }
            foreach (string column in columns)
            {
                Console.WriteLine(column + ": " + results.GetString(column));
            }
            Console.WriteLine();
        }

        LogoutResponse logout = session.Logout();

        Console.WriteLine("Billing info: " + logout.GetBillingInfo());
        Console.WriteLine("Logout message: " + logout.GetLogoutMessage());
        Console.WriteLine("Connect time: " + logout.GetConnectTime());
    }
Example #20
0
    static void Main(string[] args)
    {
        bool useStream = true;
        if ((args.Length == 1) && args[0].Equals("bytes"))
        {
            Console.WriteLine("Using GetDataAsBytes()");
            useStream = false;
        }

        RetsSession session = new RetsSession(
            "http://demo.crt.realtors.org:6103/rets/login");
        if (!session.Login("Joe", "Schmoe"))
        {
            Console.WriteLine("Invalid login");
            Environment.Exit(1);
        }

        GetObjectRequest request = new GetObjectRequest("Property", "Photo");
        request.AddAllObjects("LN000001");

        GetObjectResponse response = session.GetObject(request);
        foreach(ObjectDescriptor objectDescriptor in response)
        {
            string objectKey = objectDescriptor.GetObjectKey();
            int objectId = objectDescriptor.GetObjectId();
            string contentType = objectDescriptor.GetContentType();
            string description = objectDescriptor.GetDescription();
            string location = objectDescriptor.GetLocationUrl();

            Console.Write(objectKey + " object #" + objectId);
            if (description.Length != 0)
                Console.Write(", desription: " + description);
            if (location.Length != 0)
                Console.Write(", location: " + location);
            if (objectDescriptor.GetRetsReplyCode() != 0)
              Console.Write (", ***** " + objectDescriptor.GetRetsReplyCode() +
                                      ": " + objectDescriptor.GetRetsReplyText());
            Console.WriteLine();

            Hashtable extensions = new Hashtable();
            extensions["image/jpeg"] = "jpg";
            extensions["image/gif"] = "gif";
            extensions["text/xml"] = "xml";

            string extension = (string) extensions[contentType];
            string outputFileName = objectKey + "-" + objectId + "." +
                extension;
        /*
         * Only save the object if there was no error and we're not using the
         * location=1 option.
         */
            if (objectDescriptor.GetRetsReplyCode() == 0 && location.Length == 0)
            {
                Stream outputStream = File.OpenWrite(outputFileName);
                if (useStream)
                {
                    const int BUFFER_SIZE =  1024;
                    Stream stream = objectDescriptor.GetDataStream();
                    byte[] buffer = new Byte[BUFFER_SIZE];
                    int bytesRead;
                    while ((bytesRead = stream.Read(buffer, 0, BUFFER_SIZE)) > 0)
                    {
                        outputStream.Write(buffer, 0, bytesRead);
                    }
                }
                else
                {
                    byte[] data = objectDescriptor.GetDataAsBytes();
                    BinaryWriter w = new BinaryWriter(outputStream);
                    w.Write(data);
                    w.Close();
                }

                outputStream.Close();
            }
        }

        session.Logout();
    }
Example #21
0
    static void Main(string[] args)
    {
        bool useStream = true;

        if ((args.Length == 1) && args[0].Equals("bytes"))
        {
            Console.WriteLine("Using GetDataAsBytes()");
            useStream = false;
        }

        RetsSession session = new RetsSession(
            "http://demo.crt.realtors.org:6103/rets/login");

        if (!session.Login("Joe", "Schmoe"))
        {
            Console.WriteLine("Invalid login");
            Environment.Exit(1);
        }

        GetObjectRequest request = new GetObjectRequest("Property", "Photo");

        request.AddAllObjects("LN000001");

        GetObjectResponse response = session.GetObject(request);

        foreach (ObjectDescriptor objectDescriptor in response)
        {
            string objectKey   = objectDescriptor.GetObjectKey();
            int    objectId    = objectDescriptor.GetObjectId();
            string contentType = objectDescriptor.GetContentType();
            string description = objectDescriptor.GetDescription();
            string location    = objectDescriptor.GetLocationUrl();

            Console.Write(objectKey + " object #" + objectId);
            if (description.Length != 0)
            {
                Console.Write(", desription: " + description);
            }
            if (location.Length != 0)
            {
                Console.Write(", location: " + location);
            }
            if (objectDescriptor.GetRetsReplyCode() != 0)
            {
                Console.Write(", ***** " + objectDescriptor.GetRetsReplyCode() +
                              ": " + objectDescriptor.GetRetsReplyText());
            }
            Console.WriteLine();


            Hashtable extensions = new Hashtable();
            extensions["image/jpeg"] = "jpg";
            extensions["image/gif"]  = "gif";
            extensions["text/xml"]   = "xml";

            string extension      = (string)extensions[contentType];
            string outputFileName = objectKey + "-" + objectId + "." +
                                    extension;

            /*
             * Only save the object if there was no error and we're not using the
             * location=1 option.
             */
            if (objectDescriptor.GetRetsReplyCode() == 0 && location.Length == 0)
            {
                Stream outputStream = File.OpenWrite(outputFileName);
                if (useStream)
                {
                    const int BUFFER_SIZE = 1024;
                    Stream    stream      = objectDescriptor.GetDataStream();
                    byte[]    buffer      = new Byte[BUFFER_SIZE];
                    int       bytesRead;
                    while ((bytesRead = stream.Read(buffer, 0, BUFFER_SIZE)) > 0)
                    {
                        outputStream.Write(buffer, 0, bytesRead);
                    }
                }
                else
                {
                    byte[]       data = objectDescriptor.GetDataAsBytes();
                    BinaryWriter w    = new BinaryWriter(outputStream);
                    w.Write(data);
                    w.Close();
                }

                outputStream.Close();
            }
        }

        session.Logout();
    }
Example #22
0
    /*
     * This class demonstrates the interleaving of search transactions.
     */
    static void Main(string[] args)
    {
        Options options = new Options();

        if (!options.Parse(args))
        {
            Environment.Exit(1);
        }

        RetsSession session = options.SessionFactory();

        try {
            if (!session.Login(options.user_name, options.user_password))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }
        } catch (Exception e)
        {
            Console.WriteLine("RetsException: " + e);
            Environment.Exit(1);
        }

        RetsVersion version = session.GetDetectedRetsVersion();

        Console.WriteLine("RETS Version: " +
                          ((version == RetsVersion.RETS_1_5) ? "1.5" :
                           ((version == RetsVersion.RETS_1_7) ? "1.7" : "1.0")));

        /*
         * Find the key field for the resource.
         */
        RetsMetadata     metadata         = session.GetMetadata();
        MetadataResource metadataResource = metadata.GetResource(options.search_type);

        if (metadataResource == null)
        {
            Console.WriteLine("Invalid resource: " + options.search_type);
            session.Logout();
            Environment.Exit(1);
        }

        string keyField = metadataResource.GetKeyField();

        /*
         * Find the timestamp field if it is known (RETS 1.7 and later). If
         * not known, then the user must provide it.
         */
        MetadataClass metadataClass = metadata.GetClass(options.search_type, options.search_class);

        if (metadataClass == null)
        {
            Console.WriteLine("Invalid resource:class: " + options.search_type + ":" + options.search_class);
            session.Logout();
            Environment.Exit(2);
        }

        if (options.classTimeStamp != null && options.classTimeStamp.Length == 0)
        {
            options.classTimeStamp = metadataClass.GetStringAttribute("ClassTimeStamp");
        }

        if (options.classTimeStamp == null || options.classTimeStamp.Length == 0)
        {
            Console.WriteLine("Class " + options.search_type +
                              ":" + options.search_class +
                              " has no ClassTimeStamp specified in the metadata.");
            Console.WriteLine("Please manually provide one using the --timetsamp switch.");
            session.Logout();
            Environment.Exit(2);
        }

        /*
         * See if the last modified timestamp has been provided. If not, use yesterday.
         */
        if (options.lastModified == null || options.lastModified.Length == 0)
        {
            DateTime ts = DateTime.Now;

            options.lastModified = ts.AddDays(-1).ToString("yyyy-MM-dd");
        }

        /*
         * OK - let's find all listings that have changed since the lastModified date.
         */

        SearchRequest searchRequest = session.CreateSearchRequest(
            options.search_type,
            options.search_class,
            "(" +
            options.classTimeStamp.ToString() +
            "=" +
            options.lastModified.ToString() +
            "+)");

        searchRequest.SetSelect(keyField);
        searchRequest.SetLimit(SearchRequest.LIMIT_NONE);
        searchRequest.SetOffset(SearchRequest.OFFSET_NONE);
        searchRequest.SetCountType(SearchRequest.CountType.RECORD_COUNT_AND_RESULTS);
        searchRequest.SetStandardNames(false);

        /*
         * This starts the outer search.
         */
        SearchResultSet results = session.Search(searchRequest);

        Console.WriteLine("Record count: " + results.GetCount());
        Console.WriteLine();

        while (results.HasNext())
        {
            /*
             * Fetch the listing detail and media. This will cause a separate search transaction
             * to be open within the outer search transaction.
             */
            SearchRequest listingRequest = session.CreateSearchRequest(
                options.search_type,
                options.search_class,
                "(" +
                keyField +
                "=" +
                results.GetString(keyField) +
                ")");
            listingRequest.SetStandardNames(false);
            listingRequest.SetLimit(SearchRequest.LIMIT_DEFAULT);
            listingRequest.SetOffset(SearchRequest.OFFSET_NONE);
            listingRequest.SetCountType(SearchRequest.CountType.NO_RECORD_COUNT);
            listingRequest.SetFormatType(SearchRequest.FormatType.COMPACT);

            SearchResultSet listingResult = session.Search(listingRequest);
            IEnumerable     columns       = null;

            while (listingResult.HasNext())
            {
                if (columns == null)
                {
                    columns = listingResult.GetColumns();
                }

                /*
                 * Show the listing detail.
                 */
                foreach (string column in columns)
                {
                    Console.WriteLine("{0,15}: {1}", column, listingResult.GetString(column));
                }
                Console.WriteLine();

                /*
                 * Now set up to fetch the objects associated with this listing.
                 */
                GetObjectRequest getObjectRequest = new GetObjectRequest(options.search_type, "Photo");
                getObjectRequest.AddAllObjects(listingResult.GetString(keyField));

                GetObjectResponse getObjectResponse = session.GetObject(getObjectRequest);

                foreach (ObjectDescriptor objectDescriptor in getObjectResponse)
                {
                    /*
                     * Report the object details.
                     */
                    string objectKey = objectDescriptor.GetObjectKey();
                    int    objectId  = objectDescriptor.GetObjectId();
                    //string  contentType = objectDescriptor.GetContentType();
                    string description = objectDescriptor.GetDescription();

                    Console.Write("Object " + objectKey + ":" + objectId.ToString());
                    if (description.Length > 0)
                    {
                        Console.Write(", description: " + description);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("=================");
            }
        }

        session.Logout();
    }
Example #23
0
    static void Main(string[] args)
    {
        /*
         * Logging may be performed two different ways. The first is legacy
         * and uses a logging delegate. This can give more control to the user
         * and remains to support older .NET implementations that already implemented
         * logging. The second is simply makes use of the existing logging classes
         * within libRETS and only requires specifying the log file name.
         */
        RetsSession session   = null;
        TextWriter  logWriter = null;

        /*
         * Legacy method:
         */
        try
        {
            session = new RetsSession(
                "http://demo.crt.realtors.org:6103/rets/login");
            if (args.Length == 1)
            {
                logWriter = new StreamWriter(args[0]);
            }
            else
            {
                logWriter = TextWriter.Null;
            }

            session.LoggerDelegate =
                TextWriterLogger.CreateDelegate(logWriter);
            if (!session.Login("Joe", "Schmoe"))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }

            Console.WriteLine(".Net version: " + System.Environment.Version);

            LoginResponse login = session.GetLoginResponse();
            Console.WriteLine("Member name: " + login.GetMemberName());

            CapabilityUrls capabilityUrls = session.GetCapabilityUrls();
            Console.WriteLine("Search URL: " + capabilityUrls.GetSearchUrl());

            LogoutResponse logout = session.Logout();
            Console.WriteLine("Billing info: " + logout.GetBillingInfo());
            Console.WriteLine("Logout message: " + logout.GetLogoutMessage());
            Console.WriteLine("Connect time: " + logout.GetConnectTime());
        }
        finally
        {
            // Be sure to dispose RetsSession when finished, otherwise the
            // TextWriter Dispose() method may be called prior to RetsSession.
            if (session != null)
            {
                session.Dispose();
            }
            logWriter.Close();
        }

        /*
         * Preferred method.
         */
        session = null;
        try
        {
            session = new RetsSession(
                "http://demo.crt.realtors.org:6103/rets/login");

            if (args.Length == 1)
            {
                session.SetHttpLogName(args[0] + ".1");
            }
            if (!session.Login("Joe", "Schmoe"))
            {
                Console.WriteLine("Invalid login");
                Environment.Exit(1);
            }

            Console.WriteLine(".Net version: " + System.Environment.Version);

            LoginResponse login = session.GetLoginResponse();
            Console.WriteLine("Member name: " + login.GetMemberName());

            CapabilityUrls capabilityUrls = session.GetCapabilityUrls();
            Console.WriteLine("Search URL: " + capabilityUrls.GetSearchUrl());

            LogoutResponse logout = session.Logout();
            Console.WriteLine("Billing info: " + logout.GetBillingInfo());
            Console.WriteLine("Logout message: " + logout.GetLogoutMessage());
            Console.WriteLine("Connect time: " + logout.GetConnectTime());
        }
        finally
        {
            // Be sure to dispose RetsSession when finished, otherwise the
            // TextWriter Dispose() method may be called prior to RetsSession.
            if (session != null)
            {
                session.Dispose();
            }
        }
    }