GithubHelp home page GithubHelp logo

loveseat's Introduction

LoveSeat

Love Seat is a simply architected CouchDB C# client with the intent to abstract away just enough so that it's easy to use, but not enough so that you don't know what's going on. LoveSeat will not introduce unneeded dependancies and will attempt to remove programmer burden while leaving you close enough to the metal that you are able to utilize the full featureset of CouchDb.

Tested compatibility

  • CouchDB 1.0.1
  • .NET Framework 3.5, 4.0 or Mono 2.9 (compiled master branch from Nov 20 2010), and MonoDroid

LoveSeat usage

Basics

// assumes localhost:5984 with no credentials if constructor is left blank
var client = new CouchClient();
var db= client.GetDatabase("Northwind");

// set default design doc (not required)
db.SetDefaultDesignDoc("docs"); 

// get document by ID
Document myDoc = db.GetDocument("12345");

// get document by ID (strongly typed POCO version)
MyObject myObj = db.GetDocument<MyObject>("12345"); 

Simple view results

// get view results
var results = db.View<MyObject>("view_name");

// get view results with parameters
var options = new ViewOptions();
options.StartKey.Add("Atlanta");
options.EndKey.Add("Washington");

var results = db.View<MyObject>("view_name", options);

// loop through strongly typed results
foreach (var item in results.Items){ 
    // do something 

}

Generating more complex view parameters

var options = new ViewOptions();
// generate ["foo"] startkey parameter
options.StartKey.Add("foo");
// generate ["foo",{},{}] endkey parameter
options.EndKey.Add("foo", CouchValue.Empty, CouchValue.Empty);

var results = db.View<MyObject>("view_name", options);

// loop through strongly typed results
foreach (var item in results.Items){ 
    // do something 

}

Customized view key parameters

Assuming that view keys have complex structure, for example:

["johny", ["work", "programming"]]

["joe", ["programming"]]

["johny", ["work"]]

using Newtonsoft.Json.Linq;

...

var options = new ViewOptions(); 
options.StartKey.Add(new JRaw("[\"johny\",[\"work\"]"));
options.EndKey.Add(new JRaw("[\"johny\",[\"work\",{}]]"));  

var results = db.View<MyObject>("view_name", options);

foreach (var item in results.Items){ 
    // do something 

}

This example will return only rows where first key contains "johny" and second key contains "work".

Get the results of a List

var results = db.List("list_name")

LoveSeat supports replication and user management off of the CouchClient as well. Enjoy!

loveseat's People

Contributors

chriswoerz avatar deadok22 avatar ido-ran avatar jzablocki avatar mccow002 avatar northnick avatar nsainaney avatar pagebrooks avatar willholley avatar yojimbo87 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

loveseat's Issues

Admin Party mode does not work

CouchClient alwasy throws error unauthorized. I have ensured that local.ini has no admins defined. But CouchClient.DeleteDatabase() errors with message unauthorized. can you help!

CouchClient.HasDatabase Method

Hi there,

I had to make a modification to the CouchDatabase.HasDatabase method, as it was it was causing strange timeout issues to occur with subsequent calls. I believe the reason for this is that it was always returning "True" as it was due to CouchDB returning a 200 status code and some error JSON even if it doesn't exist, the method was only checking for a 200 status code.

    public bool HasDatabase(string databaseName)
    {
        var request = GetRequest(baseUri + databaseName);
        request.Timeout = -1;

        HttpWebResponse response = request.GetResponse();
        Document pDocResult = new Document(response.GetResponseString());

        if (pDocResult["error"] == null)
        {
            return (true);
        }
        else if (pDocResult["error"].Value<String>() == "not_found")
        {
            return (false);
        }
        else
            throw new Exception(pDocResult["error"].Value<String>());
    }

Feature request: Support Silverlight, WP7 and Metro

The silverlight, WP7 and Metro apps only allow asynchronized operations. E.g. HttpWebResponse.GetResponse() needs to be replaced by HttpWebResponse.BeginGetResponse() and EndGetResponse().

It would be a cool to port LoveSeat to asynchronize to support the future of Windows Metro apps.

I am not aware of any existing async C# couch library. If you know any, please also let me know.

Thanks!

Portability .NET Core

Hi @soitgoes !

Congratulations for LoveSeat project,
It's easy and intuitive project.
I need support to .NET Core.

We already solved it in a fork and I would like to know if it's open to a PR.

Thanks!

Authentication Issue

Hi there,

I'm not entirely sure if this is down to the way we have our server setup or not, but in order to get cookie authentication to work I had to modify the CouchBase GetSession method, even after reading the documentation I'm still confused as to why I had to add this, but it seems to work great now...

(I added the line to include the Authorization header to the web request, it seems to require that and also the form data)

    public Cookie GetSession()
    {
        var authCookie = cookiestore["authcookie"];

        if (authCookie != null)
            return authCookie;

        if (string.IsNullOrEmpty(username)) return null;
        var request = new CouchRequest(baseUri + "_session");
        request.GetRequest().Headers.Add("Authorization:Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password)));
        var response = request.Post()
            .Form()
            .Data("name=" + username + "&password=" + password)
            .GetResponse();

        var header = response.Headers.Get("Set-Cookie");
        if (header != null)
        {
            var parts = header.Split(';')[0].Split('=');
            authCookie = new Cookie(parts[0], parts[1]);
            authCookie.Domain = response.Server;
            cookiestore.Add("authcookie", authCookie, TimeSpan.FromMinutes(9));
        }
        return authCookie;
    }

Nuget update

Hi,
I was wondering if you are planning on releasing the library as a nuget package. I saw in a previous post that the original author would not release the nuget.org project to the new owner, but you would consider releasing it under a separate id/name? It does seem like the original author abandoned it anyway.

As a workaround, I could certainly build it myself and consume it, but I would also like to be notified of any updates/fixes (assuming this project is still being maintained).

Thanks,
Cristian

NullReferenceException on conection loss

LoveSeat.Support.CouchRequest.GetResponse() returns null on connection interruption.

The way to handle this is at least to add a check response for null at LoveSeat.CouchDatabase.AddAttachment and throw some exception just to make user able to handle this situation. That is where I faced the issue, actually, I guess it's the way all requests should be processed. Or may be we need to try to reestablish connection.

Mocking IDocumentDatabase/CouchDatabase

I have an application where I would like to mock out the CouchDatabase class.

I have two options:

  • Add the CouchDatabase.Compact function to the IDocumentDatabase interface which is the only function that I require that is not implemented by the interface
  • Allow a constructor on the CouchDatabase class to be accessible from outside this assembly so that I can inherit the CouchDatabase class

There might be other solutions, and I would love to hear them.

.NET 4.5 upgrade

I'm having a little trouble upgrading the VS project to .NET 4.5. It seems to build ok but when I reference it from another project and run it, i run into a TypeLoadException.

Normally, I would associate this to a framework mismatch, but LoveSeat, and my other project are both .NET 4.5. Is it possible that the issue lies with libcurl.dll and the other LoveSeat dependencies?

Thanks

CouchRequest.Timeout issues

I'm not sure that the CouchRequest.Timeout property behaves as intended. It is only applied to the HttpWebRequest in one of the CouchRequest constructors, which means that setting it has no effect, as setting can only occur after the constructor has executed. It's also only applied in the cookie constructor and not the basic auth one.

An option would be to make it a fluent method like Put/Get/etc. That would ensure that it is applied regardless of the constructor used, and would be consistent with the other methods on this class. (And it could be an int rather than an int? in this case.)

The other issue, which led me to this, is that it is impossible for a LoveSeat library user to set the CouchRequest Timeout when using the CouchClient. I'd like to set a long timeout for some view reindexing requests and i think there is no way to get to the CouchRequest object to do this. I'm not sure of the best solution, otherwise I would have submitted some code to implement it. My only idea so far is to have a Timeout property on CouchBase (and hence on CouchDatabase), which would be passed through to the CouchRequest in CouchBase.GetRequest. A LoveSeat user who wanted to change the timeout would set it on the CouchDatabase object before making a call; it would then retain that value until reset. This is not ideal, but the alternative would seem to be adding it as an optional parameter on all the CouchDatabase calls, which feels like overkill.

I'd be happy to put together some code to implement whatever solution seems best, but if you have a view on what that solution should be.

Non-strongly-typed view results

Is there a better way to retrieve non-strongly-typed view results? This is what I'm currently doing to have results as LoveSeat.Document:

        var options = new ViewOptions();
        options.IncludeDocs = true;
        var results = db.View<JObject>("docs", options);
        return View(results.RawDocs.Select(x => new Document(x)));

CouchClient.cs - HTTPS

Trying to use Cloudant for my CouchDB and modified the code below to allow HTTPS traffic:

///

    /// Constructs the CouchClient and gets an authentication cookie (10 min)
    /// </summary>


    /// <param name="host">The hostname of the CouchDB instance</param>
    /// <param name="port">The port of the CouchDB instance</param>
    /// <param name="username">The username of the CouchDB instance</param>
    /// <param name="password">The password of the CouchDB instance</param>
    public CouchClient(string host, int port, string username, string password,bool isHttps = false)
        : base(username, password)
    {
        if (isHttps == false)
        {
            baseUri = "http://" + host + ":" + port + "/";
        }
        else
        {
            baseUri = "https://" + host + ":" + port + "/";
        }
    }

In addition, I got a null reference exception on line 47 of Couchbase.cs when the request wasn't over https.

I added this below line 47 of Couchbase.cs

if (response == null)
{
throw new NullReferenceException("Response from authentication post yielded a null reference exception.");
}

Working example for pagination

I need an working example for pagination using loveseat.. whereas i am not able to understand clearly in the document and i tried it but ended up with faliure.. Pls help me in doing this.. its urgent..
Thanks in advance.

Special characters not working in update function.

I am trying to insert special characters from UI into couchdb. but while returning response it produces Server Error:500 .Please help me to fix this issue. Thanks in advance. See following code for reference.

public ReVO Update(ReVO atvo)
{
ReVO response = new ReVO ();
Stream newStream = null;
WebResponse webResponse = null;
try
{
string data = string.Empty;

            //data = JsonConvert.SerializeObject(atvo);

            data = "Obj=" + JsonConvert.SerializeObject(atvo);
            byte[] dataStream = Encoding.UTF8.GetBytes(data);

            request = ConfigSettings.GetEnvConfigValue("CouchDBUrl") + "/_design/At/_update/updateAtDetail/" + atvo.AtDocId;

            Uri requestUri = new Uri(request);
            WebRequest webRequest = WebRequest.Create(requestUri);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = dataStream.Length;

            newStream = webRequest.GetRequestStream();
            // Send the data. 
            newStream.Write(dataStream, 0, dataStream.Length);
            webResponse = webRequest.GetResponse();
            response.StatusCode = "1";
            response.StatusMessage = "Updated Successfully";
            response.AtId = atvo.AtDocId;

}
}

Having issues using generics

Here's the code snippet I'm using:

ViewResult<CouchUserDocument> result = db.View<CouchUserDocument>("testing_users");

The 'Items' property of result has a null result. It seems the data did not deserialize into the CouchUserDocument object.

Here is result.RawString:

{
   "total_rows":1,
   "offset":0,
   "rows":[
      {
         "id":"org.couchdb.user:[email protected]",
         "key":{
            "_id":"org.couchdb.user:[email protected]",
            "_rev":"2-b1259ad3584f2ae18aced7cdddc7b8c2",
            "name":"[email protected]",
            "type":"user",
            "Content-Type":"application/json",
            "roles":[
               "role1",
               "role2"
            ],
            "datecreated":null,
            "datemodified":null,
            "user_type":"testing",
            "user_name":"Joe",
            "testing_password":"HASHEDPASSWORD"
         },
         "value":null
      }
   ]
}

Can't get an update to take on the users table.

For some reason I cannot get an update to take on the users table in couch. Here's some code

CouchClient _client = CouchClientProvider.GetClient();
CouchDatabase _db = _client.GetDatabase("_users");
_db.SetDefaultDesignDoc("test_users");

Document<CouchUserDocument> doc = new Document<CouchUserDocument>(
  new CouchUserDocument()
    {
        name = user.Email,
        user_name = user.Name,
        testing_password = user.Password,
        datecreated = user.DateCreated,
        datemodified = user.DateModified,
        roles = user.Roles.Select(x => x.Name).ToList(),
        user_type = "testing",
        type = "user"
    });
doc.Id = "org.couchdb.user:" + user.Email;
 _db.SaveDocument(doc);

var result = _db.GetDocument<CouchUserDocument>(doc.Id);

I'm getting the doc back, but nothing is updating. I'm specifically trying to update the 'roles' property.
Any thoughts?

Mutual SSL Auth Support with self issued certs

I used LoveSeat recently as part of code I wrote for an open source project I work on called Thali. Thali's goal is to figure out what it would take to make the web peer to peer. As part of this I wrote a Chrome extension that lets a web page using PouchDB talk to the Thali Device Hub. The back end of the Chrome Extension is a C# program which uses LoveSeat for some of the behind the scenes configuration of the Thali Device Hub.

The reason I'm bothering you is that Thali's data model is just CouchDB. But its security model involves mutual SSL auth using self-signed certs. To make this work in C# land I need to get my hands on the HttpWebRequest object in order to set both the client certs and to take over the server cert validation.

Unfortunately LoveSeat does not currently seem to expose the interfaces I need.

So in my fork of LoveSeat I added an extra argument to let me submit a class that any Web Requests created by LoveSeat get passed to. This gives me a 'hook' to make the changes I need.

I can't say I'm in love with the API I created. Instead of a class with one method I could have passed a method directly. I also looked at CouchConfiguration. One could imagine having an optional method there that set either a class or method that implemented the functionality I need.

In any case I submitted a pull request so you could easily see the changes I made and decide if you are interested. I also found a few bugs that I fixed and updated json.net to a more recent version via nuget.

I have no expectation that you will accept the pull request. It's just meant to make the discussion more concrete about how LoveSeat could support the functionality if you are interested in seeing it supported.

Nuget package

Being a huge fan of Nuget, I thought it would be great to have LoveSeat available on the nuget gallery.
I can create and maintain the package myself, but I'd like to know if it's okay before I do it.

isAtKeysSizeLimit never returns true

It seems that in the method Keys.ToString() returns the name of the type and so the length ends up being 21

       internal bool isAtKeysSizeLimit
        {
            get { return Keys != null && Keys.Any() && Keys.ToString().Length > KeysLengthLimit; }
        }

CouchDatabase.CreateDocument()

Hi!
Why won't CreateDocument() methods check for existence of "_id" and "_rev" properties?
It is discouraging when you create a Document, set it's "_id" property, then call CouchDatabase.CreateDocument(...) and loose the property.
I suggest checking these properties, or at least adding an overload as follows:

    public JObject CreateDocument(Document doc)
    {
        var documentId = doc.Id;
        if (string.IsNullOrEmpty(documentId))
        {
            return CreateDocument<Document>(doc);
        } 
        return CreateDocument(documentId, ObjectSerializer.Serialize(doc));
    }

PS thank you for LoveSeat. enjoying it =)

Getting request failed to receive a response while doing load testing of my application.

I am calling my view such as
ViewOptions voStats = new ViewOptions();
voStats.GroupLevel = 2;
ViewResult results = oCouchDB.View("viewName", voStats);

and i am getting following error.

Request failed to receive a response/n at LoveSeat.Support.CouchRequest.GetResponse()
at LoveSeat.CouchDatabase.ProcessGenericResults[T](String uri, ViewOptions options)
at LoveSeat.CouchDatabase.View[T](String viewName, ViewOptions options, String designDoc)
at LoveSeat.CouchDatabase.View[T](String viewName, ViewOptions options)

Kindly help me in sorting out this issue.

Need tutorial for saving POCO objects

I don't see any document or test to create POCO objects. I have a hard time saving them. It only saves the id and rev and no other properties. I am sure I am doing something wrong but it would be nice to have a simple tutorial or document to do this kind of basic operation. Thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LoveSeat;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    public class Row:Document
    {
        [JsonProperty("Type")]
        public string Type;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var client = new CouchClient("somedomain.iriscouch.com", 80, "username", "password");
            var db = client.GetDatabase("database");

            Row r = new Row();
            r.Type = "222";
            r.Id = Guid.NewGuid().ToString();
            db.CreateDocument(r);  // Type isn't saved.  only id and rev is saved.
        }
    }
}

Views with rows containing more keys

I have a view which returns rows with two keys. Key examples with three returned rows:
["johny", ["work", "programming"]]

["joe", ["programming"]]

["johny", ["work"]]

When I want to get rows which contains only "johny" as a first key and "work" as a second key, I need to construct request to my view with start and end key like this:
http://.../_design/docs/_view/myview?startkey=[%22johny%22,[%22work%22]]&endkey=[%22johny%22,[%22work%22,{}]]

Is it possible to construct these kind of view parameters with LoveSeat? I wasn't able to do it, because it looks like that only single string values are supported for SetStartKey and SetEndKey methods within ViewOptions. Brackets and other characters are encoded before sending request, so I also wasn't able to "abuse" this methods.

Problems with handling _id, _rev

The following POCO object:

public class Objective : CDBObject
{
    public Guid Guid { get; set; }

    public Int32[] Capacities { get; set; }
}

is serialized as:

{
"_id": "d7e064bd9fb27f47d0e9a72fbc006687",
"_rev": "1-cf6ff74d37157f430bbf0e40cee4be8e",
"gu_id": "2b47b251-e00f-41ad-9327-11322edaae22",
"capacities": [
256,
128
],
"type": "Objective"
}

note that the field name is not "guid" , but "gu_id", i've also found it impossible to have a property named "Id" in my POCO object, wouldn't it be better to have these special fields to be named exactly as they are written inside document?

The field Type in document does not seem to work

Hi,
I'm just starting with LoveSeat. I saw the Document class has Type field but it does not seem to be working. I've add a field to my document name type and Type but neither of them was parsed into the Type property.

Nuget package

Not an issue to the code, but if someone knows the author/account owner of the original NuGet package, please contact him to update the package.

Also please use versioning in AssemblyInfo.cs

Thanks!

KeyOptions::ToString(). Problem with Httputility

I was trying LoveSeat, and in mono, in a console proyect HttpUtitly fails.

This is a suggestion to it: (Basicaly change it for System.Uri.EscapeDataString ).

In other hand. Thanks, it's a great job!

---- Code ---

public override string ToString()
{
if (objects.Count == 0)
{
return "";
}
if (objects.Count == 1)
{
return System.Uri.EscapeDataString(objects[0].ToString(Formatting.None, new IsoDateTimeConverter()) );
}

        string result = "[";
        bool first = true;
        foreach (var item in objects)
        {
            if (!first)
                result += ",";
            first = false;
            if(item.ToString().Equals("{}"))
                result += item.ToString(Formatting.None, new IsoDateTimeConverter());
            else
                result += System.Uri.EscapeDataString( item.ToString(Formatting.None, new IsoDateTimeConverter()));
        }
        result += "]";
        return result;
    }

List exception thrown

This is how I am trying to connect to couchdb instance and fetch a list -

CouchClient cl = new CouchClient("localhost", 5984, "uname", "pwd", false, AuthenticationType.Basic);
IListResult ilr = cl.GetDatabase("db").List("l", "v", null, "d");

This throws a null reference exception. There is also not much to debug to know what is the issue here.

Instead when I execute the list via Browser, I get proper response. Is this the issue with LoveSeat or do I need to do anything else here to call a list.

http://localhost:5984/db/_design/d/_list/l/v

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.