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;
}
Related
I have an code implementation to read data from UA.
private readonly AnalyticsService service;
private readonly IConfiguration _config;
private ILogger<PageViewService> _logger;
public PageViewService(IConfiguration config, ILogger<PageViewService> logger)
{
try
{
_config = config;
_logger = logger;
var sercretFileLocation = _config["SecretFileLocation"];
var password = _config["Password"];
var accountEmail = _config["AccountEmail"];
X509KeyStorageFlags storageFlag = X509KeyStorageFlags.MachineKeySet;
var flag = _config["X509KeyStorageFlags"];
if (flag == "UserKeySet")
{
storageFlag = X509KeyStorageFlags.UserKeySet;
}
else if (flag == "MachineKeySet")
{
storageFlag = X509KeyStorageFlags.MachineKeySet;
}
else if (flag == "Exportable")
{
storageFlag = X509KeyStorageFlags.Exportable;
}
else if (flag == "UserProtected")
{
storageFlag = X509KeyStorageFlags.UserProtected;
}
else if (flag == "PersistKeySet")
{
storageFlag = X509KeyStorageFlags.PersistKeySet;
}
else if (flag == "EphemeralKeySet")
{
storageFlag = X509KeyStorageFlags.EphemeralKeySet;
}
else if (flag == "DefaultKeySet")
{
storageFlag = X509KeyStorageFlags.DefaultKeySet;
}
var certificate = new X509Certificate2(sercretFileLocation, password, storageFlag);
var scopes = new string[] { AnalyticsService.Scope.AnalyticsReadonly };
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(accountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
}
catch (Exception e)
{
_logger.LogError(e.ToString());
}
}
public string GetPageViews(List<string> paths)
{
string pathsString = "";
try
{
var webSiteCode = _config["WebSiteCode"];
var startDate = _config["StartDate"];
if (webSiteCode != null && startDate != null)
{
pathsString = GenerateFilter(paths);
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(
"ga:" + webSiteCode,
startDate,
"today",
"ga:uniquePageviews");
request.Filters = pathsString;
var data = request.Execute();
string uniquePageViews = data?.Rows?.FirstOrDefault()?.FirstOrDefault();
return uniquePageViews;
}
else
{
return "0";
}
}
catch (Exception e)
{
_logger.LogError($"{e.ToString()} {pathsString}");
}
return null; //null means there is an error.
}
Direct to the point questions:
Will the code above stops working on July 2023?
I already connected my UA to GA4 using GA4 Setup Assistant on April 2022 . and my GA4 already started retrieving metrics starting April 2022. Is connecting my UA to GA4 using GA4 Setup assistant still work with the above code?
Do I have to change my code to use Google.Apis.AnalyticsReporting.v4? If I use that package, is using the View ID of my UA still works on July 2023?
I tried to create this prototype but this still requires View ID. GA4 does not have View ID so I used the View ID from my UA. As mentioned my UA is connected to my GA4, will this implementation still works on July 2023? Do I have to switch to this implementation on July 2023?
static async Task Main(string[] args)
{
var dateRange = new DateRange
{
StartDate = "2020-06-01",
EndDate = "2020-06-30"
};
var dimensions = new List<Dimension>
{
new Dimension { Name = "ga:pagePath" },
new Dimension { Name = "ga:pageTitle" }
};
var metrics = new List<Metric>
{
new Metric { Expression = "ga:pageViews" },
new Metric { Expression = "ga:users" }
};
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = dimensions,
Metrics = metrics,
FiltersExpression = filtersExpression,
ViewId = "ga:12345678"
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var credential = GetGoogleCredential("C:\\Code\\PrototypeAnalytics4\\PrototypeAnalytics4\\mychuva.json");
// Create an AnalyticsReportingService object to make the Google Analytics API call
var analyticsService = new AnalyticsReportingService(new BaseClientService.Initializer
{
ApplicationName = "chuva-123",
HttpClientInitializer = credential
});
var batchGetRequest = analyticsService.Reports.BatchGet(getReportsRequest);
var getReportsResponse = await batchGetRequest.ExecuteAsync();
var analyticsData = getReportsResponse.Reports[0].Data;
}
static GoogleCredential GetGoogleCredential(string pathGAKey)
{
GoogleCredential credential;
using (FileStream stream = new FileStream(pathGAKey, FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = GoogleCredential.FromStream(stream);
}
string[] scopes = new string[]
{
AnalyticsReportingService.Scope.AnalyticsReadonly
};
credential = credential.CreateScoped(scopes);
return credential;
}
This is my RestClientService :
public class RestClientService : IRestClientService
{
protected readonly RestClient _restClient;
protected readonly RestRequest _restRequest;
public RestClientService()
{
_restClient = new RestClient();
_restRequest = new RestRequest();
}
public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
{
if (await IsPostExist(postId,website))
{
_restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
_restRequest.Method = Method.Post;
_restRequest.RequestFormat = DataFormat.Json;
_restRequest.AddJsonBody(new
{
post = postId,
author_name = comment.Author,
content = comment.Body
});
var result = await _restClient.ExecuteAsync(_restRequest);
return new MessageDTO
{
Message = result.Content,
Status = result.StatusCode.ToString()
};
}
return new MessageDTO
{
Message = "Post Not Found",
Status = "404"
};
}
}
I have a list of comments and list of products that I iterate over them and call SendComment method from RestClientService class. The problem is in first time SendComment method called _restRequest object will be get JsonBody and everything is okay but next time this method calls in loop _restRequest object has old data and won't be renewed.
In DI Container I added (Transient) RestClientService
builder.Services.AddTransient<IRestClientService,RestClientService>();
Here is where I used SendComment method in another service.
public async Task<MessageDTO> CreateSendCommentJob(SendCommentConfiguration config)
{
var updatedConfig = await _sendCommentConfigurationRepository.Get(config.Id);
var ConfigDetails = JsonConvert.DeserializeObject<SendCommentConfigurationDetailsDTO>(updatedConfig.Configuration);
var mappedWebsite = _mapper.Map<Websites>(ConfigDetails.WebsiteInfo);
if (ConfigDetails.CommentType == "blog")
{
var comments = await _uCommentService.GetCommentsByGroupId(ConfigDetails.CommentGroupId);
var commentCount = 0;
for (int postCount = 0; postCount < ConfigDetails.ProductPerSendCount; postCount++)
{
var postId = ConfigDetails.Ids[postCount];
while (commentCount < ConfigDetails.CommentsPerProductCount)
{
var random = new Random();
var index = random.Next(comments.Count);
var result = await _restClientService.SendComment(mappedWebsite, comments[index], postId);
if (result.Status == "Created")
{
Console.WriteLine($"Comment Index ({index}) at Id ({postId}) submited successfuly...");
commentCount++;
}
else
{
Console.WriteLine($"{postId} - {result.Status} - {result.Message}");
}
}
ConfigDetails.Ids.Remove(postId);
commentCount = 0;
}
}
var newConfig = new SendCommentConfiguration
{
Id = config.Id,
Configuration = JsonConvert.SerializeObject(ConfigDetails)
};
await _sendCommentConfigurationRepository.Edit(newConfig);
return new MessageDTO
{
Status = "200",
Message = "Comments Successfuly Sent "
};
}
_restClientService.SendComment is called in a loop on the same service instance. As the request instance is a field of the service instance, the same request instance is reused for each call.
As each apple performs a distinct request, each request must use a distinct instance of RestRequest, like :
public class RestClientService : IRestClientService
{
public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
{
if (await IsPostExist(postId,website))
{
//Each call, new instances
var restClient = new RestClient();
var restRequest = new RestRequest();
restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
restRequest.Method = Method.Post;
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddJsonBody(new
{
post = postId,
author_name = comment.Author,
content = comment.Body
});
var result = await restClient.ExecuteAsync(_restRequest);
return new MessageDTO
{
Message = result.Content,
Status = result.StatusCode.ToString()
};
}
return new MessageDTO
{
Message = "Post Not Found",
Status = "404"
};
}
}
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);
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.
For some reason, the 'UserManager' of 'Identity' does not store a new user when using inside my seeding class. Everything else in the seeding class works fine as expected, it is just that 'CreateAsync' method issue. Here is the code:
public class WorldContextSeedData
{
private WorldContext _context;
private UserManager<WorldUser> _userManager;
public WorldContextSeedData(WorldContext context, UserManager<WorldUser> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task EnsureSeedData()
{
if (await _userManager.FindByEmailAsync("lucas#test.com") == null)
{
//add user
var newUser = new WorldUser
{
UserName = "Lucas",
Email = "lucas#test.com"
};
await _userManager.CreateAsync(newUser, "MyP#ssword!");
}
if (!_context.Trips.Any())
{
//Add new Data
var usTrip = new Trip()
{
Name = "US Trip",
CreatedBy = "Lucas",
Timestamp = DateTime.Now,
Stops = new List<Stop>()
{
new Stop { Name= "Atlanta, GA", Order = 0},
new Stop { Name= "NYC, NY", Order = 1},
new Stop { Name= "Tempe, AZ", Order = 2}
}
};
var worldTrip = new Trip()
{
Name = "World Trip",
CreatedBy = "Lucas",
Timestamp = DateTime.Now,
Stops = new List<Stop>()
{
new Stop { Name= "Poland", Order = 0},
new Stop { Name= "France", Order = 1},
new Stop { Name= "Germany", Order = 2}
}
};
_context.Trips.Add(usTrip);
_context.Stops.AddRange(usTrip.Stops);
_context.Trips.Add(worldTrip);
_context.Stops.AddRange(worldTrip.Stops);
_context.SaveChanges();
}
}
}
As per Steve's great comment tip, I was able to verify that the password was too weak. Once I made the password stronger (digit was required), the issue was resolved.
Here, I have introduced a variable that would contain returned result of creating a new user:
IdentityResult result = await _userManager.CreateAsync(newUser, newUserPassword);
You can Use
IdentityResult result = await _userManager.CreateAsync(newUser, "MyP#ssword!");
to see what is the problem in result.
IdentityResult contains bool Succeeded for determine how the create going on. and contains Errors Property to show you what goes wrong.
add these line of codes to IdentityHostingStartup.cs:
services.Configure<IdentityOptions>(x => {
x.Password.RequireDigit = false;
x.Password.RequiredLength = 2;
x.Password.RequireUppercase = false;
x.Password.RequireLowercase = false;
x.Password.RequireNonAlphanumeric = false;
x.Password.RequiredUniqueChars = 0;
x.Lockout.AllowedForNewUsers = true;
x.Lockout.MaxFailedAccessAttempts = 5;
x.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(30);
});