Bellow is my code
public async void TestLoops(long device, double date1, double date2)
{
var connectionString = "mongodb://localhost.:27017";//Connection string
MongoClientSettings settings1 = MongoClientSettings.FromUrl(new MongoUrl(connectionString));// Set Url to the MongoClient
//MongoS
// MongoClient mongoClient = new MongoClient(settings1);
var client = new MongoClient(new MongoClientSettings
{
Server = new MongoServerAddress("connectionString"),
ClusterConfigurator = builder =>
{
builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(1000)));
}
});
//Server s = new MongoServerAddress(connectionString);
var db = client.GetDatabase("tracking");//Specifing the Database name
var user = db.GetCollection<BsonDocument>("location");//Specifing t
var builder1 = Builders<BsonDocument>.Filter;
// var builder1 = Builders<BsonDocument>.Filter;
//int
var filt = builder1.Eq("device", device) & builder1.Gte("timestamp", date1) & builder1.Lte("timestamp", date2);
//var filter = builder1.Eq("device", 358740050124519);
var data = user.Find(filt).Count();
lblmsg.Text = data.ToString();
}
when i write the var data = user.Find(filt); it works fine
You can do
var collection = database.GetCollection<Type>("DBName");
var cursor = collection.Find(Query.EQ("FieldToMatch" : "ValueToMatch"));
var count = cursor.Count();
another approach
db.collection.CountAsync(); // you can pass new BsonDocument() or a condition to countAsync based on your requirement.
Related
i have been searching for a good solution where I copied code used in an API from postman and tried to use it in Xamarin forms. Problem is that there is a method in the API that generates "signatures", which they do in JS. I have tried various solutions but it does not generate the same message.
In JS =
(function () {
var timestamp = getTime();
pm.environment.set("timestamp",timestamp);
var clientId = pm.environment.get("client_id");
var secret = pm.environment.get("secret");
var sign = calcSign(clientId,secret,timestamp);
pm.environment.set('easy_sign', sign);
})();
function getTime(){
var timestamp = new Date().getTime();
return timestamp;
}
function calcSign(clientId,secret,timestamp){
var str = clientId + timestamp;
var hash = CryptoJS.HmacSHA256(str, secret);
var hashInBase64 = hash.toString();
var signUp = hashInBase64.toUpperCase();
return signUp;
}
In C# =
public void timeStamp()
{
/*
* var str = clientId + timestamp;
var hash = CryptoJS.HmacSHA256(str, secret);
var hashInBase64 = hash.toString();
var signUp = hashInBase64.toUpperCase();
return signUp;
*/
var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var t = (DateTime.Now.ToUniversalTime() - timestamp);
time = t.ToString();
//CalcSign
var str = clientID + t;
var key = Convert.FromBase64String(secret);
//var key = Convert.FromBase64String(str);
Console.Write("key:");
prtByte(key);
var provider = new System.Security.Cryptography.HMACSHA256(key);
var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
Console.Write("hash:");
prtByte(hash);
var signature = Convert.ToBase64String(hash);
Console.WriteLine("signature:" + signature);
var signUp = signature.ToUpper();
sign = signUp;
}
public static void prtByte(byte[] b)
{
for (var i = 0; i < b.Length; i++)
{
Console.Write(b[i].ToString("x2"));
}
Console.WriteLine();
}
The message i get back is =
"The request time is invalid".
After a lot of troubleshooting and help from #Jason and #Jack Hua the problem was solved by using DateTime.UtcNow, formatting with String.Format, converting the values first to double and then to int, shown below.
var timestamp = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Console.WriteLine("Timestamp = "+timestamp.ToString());
var t2 = String.Format("{0}",timestamp.TotalMilliseconds);
var t = Double.Parse(t2);
var t3 = Convert.ToInt64(t);
time =""+ t3;
Now I only need to solve my other issue "sign invalid", but that is another question. Cheers!!
I have little problem with using Cloudinary, I can upload the images it works fine but I guess i cant get any response from Cloudinary. Suggestion? about required parameters
Handler
public async Task<Photo> Handle(Command request, CancellationToken cancellationToken)
{
var photoUploadResult = _photoAccessor.AddPhoto(request.File);
var photo = new Photo
{
Url = photoUploadResult.Url,
Id = photoUploadResult.PublicId
};
var success = await _context.SaveChangesAsync() > 0;
if (success) return photo;
throw new Exception("Problem saving changes");
}
Accessor
public PhotoUploadResult AddPhoto(IFormFile file)
{
var uploadResult = new ImageUploadResult();
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams
{
File = new FileDescription(file.FileName, stream)
};
uploadResult = _cloudinary.Upload(uploadParams);
}
}
if (uploadResult.Error != null)
throw new Exception(uploadResult.Error.Message);
return new PhotoUploadResult
{
PublicId = uploadResult.PublicId,
Url = uploadResult.SecureUri.AbsoluteUri
};
}
What do you get in response? Can you try:
string cloud_name = "<Cloud Name>";
string ApiKey = "<Api-Key>";
string ApiSecret = "<Api-Secret>";
Account account = new Account(cloud_name,ApiKey,ApiSecret);
Cloudinary cloudinary = new Cloudinary(account);
cloudinary.Api.Timeout = int.MaxValue;
var ImguploadParams = new ImageUploadParams()
{
File = new FileDescription(#"http://res.cloudinary.com/demo/image/upload/couple.jpg"),
PublicId = "sample",
Invalidate = true,
Overwrite = true
};
var ImguploadResult = cloudinary.Upload(ImguploadParams);
Console.WriteLine(ImguploadResult.SecureUri);
On a Solr instance I can get the status with this command: bin/solr status
Is there a way to get the status using SolrNet? Sometimes I need to import a lot of data and I would like halt the import if the heap size is >= 80%
Example query to get the status
http://my-solr.bigboss.com/solr/admin/collections?_=1573650195955&action=CLUSTERSTATUS&wt=json
http://my-solr.bigboss.com/solr/admin/info/system?_=1573650195955&nodes=10.0.1.138:8983_solr,10.0.1.232:8983_solr,10.0.5.244:8983_solr&wt=json
I am now using httpClient but are still interested if this can be done with SolrNet
private List<string> GetSolrNodes()
{
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromSeconds(20);
var url = _solrBaseUrl + "admin/collections?action=CLUSTERSTATUS&wt=json";
var json = httpClient.GetStringAsync(url).Result;
var obj = JObject.Parse(json);
var liveNodes = (JArray)obj["cluster"]["live_nodes"];
return liveNodes.HasValues ? liveNodes.Select(liveNode => liveNode.ToString()).ToList() : new List<string>();
}
}
private int GetSolrNodeWithMaxHeapSize()
{
var nodes = GetSolrNodes();
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromSeconds(20);
var stringNodes = nodes.Join(",");
var url = _solrBaseUrl + $"admin/info/system?nodes={stringNodes}&wt=json";
var json = httpClient.GetStringAsync(url).Result;
var obj = JObject.Parse(json);
return nodes.Select(node => (int) obj[node]["jvm"]["memory"]["raw"]["used%"]).Concat(new[] {0}).Max();
}
}
I started with ASP.Net Core 2.0, I'm trying to rewrite a method GetAll by search use stored procedure. Here is method search:
public async Task<List<DepartmentTypeDto>> SearchDepartmentType()
{
EnsureConnectionOpen();
using (var command = CreateCommand("CM_DEPT_GROUP_Search", CommandType.StoredProcedure))
{
using (var dataReader = await command.ExecuteReaderAsync())
{
List<DepartmentTypeDto> result = new List<DepartmentTypeDto>();
while (dataReader.Read())
{
DepartmentTypeDto departmentTypeDto = new DepartmentTypeDto
{
GROUP_ID = dataReader["GROUP_ID"].ToString(),
GROUP_CODE = dataReader["GROUP_CODE"].ToString(),
GROUP_NAME = dataReader["GROUP_NAME"].ToString(),
NOTES = dataReader["NOTES"].ToString(),
RECORD_STATUS = dataReader["RECORD_STATUS"].ToString(),
MAKER_ID = dataReader["MAKER_ID"].ToString(),
CREATE_DT = Convert.ToDateTime(dataReader["CREATE_DT"]),
AUTH_STATUS = dataReader["AUTH_STATUS"].ToString(),
CHECKER_ID = dataReader["CHECKER_ID"].ToString(),
APPROVE_DT = Convert.ToDateTime(dataReader["APPROVE_DT"]),
AUTH_STATUS_NAME = dataReader["AUTH_STATUS_NAME"].ToString(),
RECORD_STATUS_NAME = dataReader["RECORD_STATUS_NAME"].ToString()
};
}
return result;
}
}
}
Here is the service:
public async Task<PagedResultDto<GetDepartmentTypeForView>> GetAll(GetAllDepartmentTypesInput input)
{
var filteredDepartmentTypes = _departmentTypeRepository.SearchDepartmentType();
var query = (from o in filteredDepartmentTypes
select new GetDepartmentTypeForView() { DepartmentType = ObjectMapper.Map<DepartmentTypeDto>(o) });
var totalCount = await query.CountAsync();
var departmentTypes = await query
.OrderBy(input.Sorting ?? "departmentType.id asc")
.PageBy(input)
.ToListAsync();
return new PagedResultDto<GetDepartmentTypeForView>(totalCount, departmentTypes);
}
But I get an error:
Task<List<DepartmentTypeDto>> does not contain a definition for Select
Does anyone know what I should do? I work on Asp.Net Zero.
I changed my search method
public IQueryable<DepartmentTypeView> SearchDepartmentType(GetAllDepartmentTypesInput input, int top)
{
try
{
var GROUP_FILTER = input.Filter;
var GROUP_CODE = input.GROUP_CODEFilter;
var GROUP_NAME = input.GROUP_NAMEFilter;
var AUTH_STATUS = input.AUTH_STATUSFilter;
var result = Context.Query<DepartmentTypeView>().FromSql($"EXEC CM_DEPT_GROUP_Search #p_GROUP_FILTER = {GROUP_FILTER}, #p_GROUP_CODE={GROUP_CODE}, #p_GROUP_NAME={GROUP_NAME}, #p_AUTH_STATUS={AUTH_STATUS}, #p_TOP={top}");
return result;
}
catch
{
return null;
}
}
and in the service, I call that function
var filteredDepartmentTypes = _departmentTypeRepository.SearchDepartmentType(input,100);
I also create new class to keep the result and don't forget to map that class with DTO class
configuration.CreateMap<DepartmentTypeView, DepartmentTypeDto>();
It works for me.
im trying to add my contacts in telegram-cli by using vcard. but when i use this command:
import_card <card>
nothing happen! it just goes to next line without any error and no contact added.
my vcard is VERSION:2.1
how can i improt my contacts to my telegram account by using vcard?
Install-Package TLSharp
client = new TelegramClient(apiId, apiHash);
await client.ConnectAsync();
var phoneContact = new TLInputPhoneContact() { phone = "", first_name = "", last_name = "" };
var contacts = new List<TLInputPhoneContact>() { phoneContact };
var req = new TeleSharp.TL.Contacts.TLRequestImportContacts() { contacts = new TLVector<TLInputPhoneContact>() { lists = contacts } };
var rrr= await client.SendRequestAsync<TeleSharp.TL.Contacts.TLImportedContacts>(req);
private async Task<bool> ImportContact(string _phone , string _first_name , string _last_name)
{
//https://github.com/sochix/TLSharp/issues/243
var phoneContact = new TLInputPhoneContact() { phone = _phone, first_name = _first_name, last_name = _last_name };
var contacts = new List<TLInputPhoneContact>() { phoneContact };
var req = new TLRequestImportContacts() { contacts = new TLVector<TLInputPhoneContact>() { lists = contacts } };
TLImportedContacts result = await client.SendRequestAsync<TLImportedContacts>(req);
if (result.users.lists.Count > 0)
return true;
else return false;
}