blue cosmosdb – Cosmos SQL DAO (data access object) in C #

In my IoT project, I have DB cosmos to store telemetric data and other commercial data.

I am implementing the DAO pattern for the first time, looking for a better and reusable code suggestion.

The DAO pattern and the repository solve the same problem, I do not have any entity (which is directly assigned with the collection of DB cosmos), the unique collection of Cosmos DB that stores multiple types of data, so I implemented the DAO pattern.

BaseDAO

public abstract class BaseDAO: IBaseDAO
{
DocumentClient read-only public client;

BaseDAO protected (IAppConfiguration appConfiguration)
{
this.client = new DocumentClient (appConfiguration.DatabaseEndPoint, appConfiguration.DatabaseKey,
new ConnectionPolicy
{
//ConnectionMode.Direct is faster, but it is not recommended in the consumption plan
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp,
// Customize retry options for accelerated requests
RetryOptions = new RetryOptions ()
{
MaxRetryAttemptsOnThrottledRequests = 10,
MaxRetryWaitTimeInSeconds = 30
}
});
}

/// 
    /// Create document in the database
/// 
    /// database name
    /// name of the collection
    /// document object
    /// 
    
    
    
    Public virtual asynchronous task CreateAsync (string DatabaseId, string collectionId, JObject document)
{
Document response = await this.client.CreateDocumentAsync (UriFactory.CreateDocumentCollectionUri (databaseId, collectionId), document);
return response.Id;
}

/// 
    /// Delete document from the database
/// 
    /// database name
    /// name of the collection
    /// unique id document
    /// 
    
    
    
    Public virtual asynchronous task DeleteAsync (string databaseId, string collectionId, string id)
{
await this.client.DeleteDocumentAsync (UriFactory.CreateDocumentUri (databaseId, collectionId, id));
true returns
}

/// 
    /// Delete document from the database
/// 
    /// database name
    /// name of the collection
    /// unique id document
    /// ///  document partition key
    /// 
    
    
    
    Public virtual asynchronous task DeleteWithPartitionKeyAsync (string DatabaseId, string collectionId, string id, string partitionKey)
{
wait for this.client.DeleteDocumentAsync (UriFactory.CreateDocumentUri (databaseId, collectionId, id), new RequestOptions {PartitionKey = new PartitionKey (partitionKey)});
true returns
}

/// 
    /// Get document by ID
/// 
    /// database name
    /// name of the collection
    /// unique id document
    /// 
    
    
    
    public virtual string GetDocumentById (string database ID, string identification string, string ID)
{
var query = new SqlQuerySpec (
"SELECT * FROM c where c.id = @id",
new SqlParameterCollection (new SqlParameter[] {new SqlParameter {Name = "@id", Value = id}
}));
Document document = this.client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri (databaseId, collectionId), query)
.AsEnumerable (). FirstOrDefault ();
back Serialize (document);
}

/// 
    /// Get list of documents with filter criteria
/// 
    /// database name
    /// name of the collection
    /// filter condition
    /// 
    
    
    
    JArray virtual GetDocuments (string DatabaseId, string collectionId, Dictionary terms)
{
if (conditions.Count == 0)
throw new ArgumentException ("The condition can not be blank");

Parameters of SqlParameterCollection = new SqlParameterCollection ();
StringBuilder whereCondition = new StringBuilder ();

foreach (condition var in conditions)
{
parameters.Add (new SqlParameter {Name = $ "@ {condition.Key}", Value = condition.Value});
whereCondition.Append ($ "c. {condition.Key} = @ {condition.Key} and");
}
string where = whereCondition.ToString (). Remove (whereCondition.ToString (). LastIndexOf ("and"));

var query = new SqlQuerySpec (
$ "SELECT * FROM c where {where}", parameters);

List documents = this.client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri (databaseId, collectionId), query)
.AsEnumerable (). ToList ();
return JArray.Parse (Serialize (documents));
}

Public Virtual T GetDocument(string databaseId, string collectionId, Dictionary terms)
{
JArray documents = GetDocuments (databaseId, collectionId, conditions);
if (documents.Count> 0)
{
return JsonConvert.DeserializeObject(documents.First (). ToString ());
}
plus
{
default return (T);
}
}

/// 
    /// Update the document in the collection by ID
/// 
    /// database name
    /// name of the collection
    /// unique id document
    /// New document object
    /// 
    
    
    
    Public virtual asynchronous task UpdateAsync (string databaseId, string collectionId, string id, JObject newDocument)
{
wait for this.client.ReplaceDocumentAsync (UriFactory.CreateDocumentUri (databaseId, collectionId, id), newDocument);
true returns
}

Serialize public virtual series (object obj)
{
return JsonConvert.SerializeObject (obj);
}

virtual public deserialize(serialized string)
{
return JsonConvert.DeserializeObject(serialized);
}

}

MasterData DAO Collection

public class MasterDAO: BaseDAO, IMasterDAO
{
private read-only IAppConfiguration appConfiguration;

Public MasterDAO (IAppConfiguration appConfiguration)
: base (appConfiguration)
{
this.appConfiguration = appConfiguration;
}

Public task CreateAsync (JObject document)
{
return base.CreateAsync (appConfiguration.DatabaseId, AMSConstraints.MasterData, document);
}

Public asynchronous task DeleteAsset (string assetId, string assetType)
{
var parameters = new dictionary();
parameters.Add ("assetid", assetId);
parameters.Add ("assetType", assetType);
JArray documents = base.GetDocuments (appConfiguration.DatabaseId, AMSConstraints.MasterData, parameters);
if (documents.Count> 0)
{
string id = documents.First ()["id"].Chain();
return awaits base.DeleteAsync (appConfiguration.DatabaseId, AMSConstraints.MasterData, id);
}
plus
{
false return;
}
}

JArray público GetAssetBySerialNumber (IEnumerable serial number)
{
// ALL: you need to use the parameter query (the previous parameterization query does not work)
dynamic result = client.CreateDocumentoQuería(
UriFactory.CreateDocumentCollectionUri (appConfiguration.DatabaseId, AMSConstraints.MasterData),
"select * FROM c where c.ApplicationName = & # 39; Eroutes & # 39; and c.Device[0].SerialNumber IN ("+ serialNumber.ListToString () +") ")
.AsEnumerable (). ToList ();
if (result! = null && result.Count> 0)
return JArray.Parse (Serialize (result));
plus
returns JArray.Parse ("[]");
}

public string GetAssetType (chain mark, serial number string)
{
var query = new SqlQuerySpec ("select c.AssetType FROM c where c.ApplicationName = & # 39; Eroutes & # 39; and c.Device[0].SerialNumber = @ SerialNumber and c.Device[0].Make = @ Make ",
new SqlParameterCollection (new SqlParameter[] {
new SqlParameter {Name = "@SerialNumber", Value = serialNumber},
new SqlParameter {Name = "@Make", Value = make}
}));

dynamic result = client.CreateDocumentoQuería(
UriFactory.CreateDocumentCollectionUri (appConfiguration.DatabaseId, AMSConstraints.MasterData), query)
.AsEnumerable (). FirstOrDefault ();
yes (result! = null)
{
var json = JObject.Parse (Serialize (result));
back json["AssetType"].Chain();
}
plus
{
Return chain. Empty;
}
}

Public asynchronous task UpdateDocumentByAsset (string assetId, string assetType, JObject newDocument)
{
var parameters = new dictionary();
parameters.Add ("assetid", assetId);
parameters.Add ("assetType", assetType);
JArray document = base.GetDocuments (appConfiguration.DatabaseId, AMSConstraints.MasterData, parameters);
string id = document[0]["id"].Chain();
return await base.UpdateAsync (appConfiguration.DatabaseId, AMSConstraints.MasterData, id, newDocument);
}
}