I did a method which add a user in storage. Below is the code and the error that I'm getting.
public string addusr(string nome, string cidade, string cpf, string email, string telefone)
{
try
{
if (nome.Length == 0)
return "f:Preencha o campo nome.";
if (cidade.Length == 0)
return "f:Preencha o campo cidade.";
if (cpf.Length == 0)
return "f:Preencha o campo cpf.";
if (!Valida(cpf))
return "f:CPF Invalido.";
if (email.Length == 0)
return "f:Preencha o campo email.";
Regex rg = new Regex(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
if (!rg.IsMatch(email))
{
return "f:Email Invalido";
}
List<UserEntity> lst = new List<UserEntity>();
var _account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var _context = new CRUDUserEntities(_account.TableEndpoint.ToString(), _account.Credentials);
if (_context.Select(cpf).Count() > 0)
return "dup";
var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var context = new CRUDUserEntities(account.TableEndpoint.ToString(), account.Credentials);
UserClientEntity entity = new UserClientEntity() { nome = nome, cidade = cidade, cpf = cpf, email = email, telefone = telefone };
context.ADDUSociate(entity);
return "k";
}
catch (Exception exc)
{
string error = "f:" + exc.Message + "|" + exc.StackTrace;
// Trace.WriteLine("Erro no login: " + error , "Information");
return error;
}
}
When I try to add a user...I'm getting this error:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
f:An error occurred while processing this request.| at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait()
at Microsoft.WindowsAzure.StorageClient.CommonUtils. <LazyEnumerateSegmented>d__0`1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
at mobile.Service1.addusr(String nome, String cidade, String cpf, String email, String telefone)
</string>
I don't know what is wrong..
Not sure whats causing the error but you do miss a context.SaveChanges(); after
context.ADDUSociate(entity);
"I suggest you start with getting the emulator working for azure storage and debug this in visual studio."
I think you dont have the correct Azure sdk installed. Try to reinstall it and the emulator should work. You can follow this guide: http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/
Related
I used Google.Apis.Firestore.v1 library to create a cloud firestore for my firebase project as follows, but when running my code I am getting an error related to the database naming I guess, and it has a regular expression format as shown in the error below, and how can I fix this issue?
using Google.Apis.Firestore.v1;
private static FirestoreService _firestoreService;
public static void IntializeFirestoreAdmin() {
GoogleCredential credential = GoogleCredential.GetApplicationDefault();
if (CloudManager.Credential.IsCreateScopedRequired)
{
credential = CloudManager.Credential.CreateScoped(FirestoreService.Scope.CloudPlatform);
}
_firestoreService = new FirestoreService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = CloudManager.ApplicationName
});
}
public static void AddCloudFirestore() {
IntializeFirestoreAdmin();
var mydata = new GoogleFirestoreAdminV1Database {
LocationId = "nam5",
Type = "FIRESTORE_NATIVE",
Name = "projects/" + CloudManager.ProjectId + "/databases/(default)",
};
_firestoreService.Projects.Databases.Create(mydata, "projects/" + CloudManager.ProjectId).Execute();
}
Error :
Unhandled exception. The service firestore has thrown an exception.
HttpStatusCode is BadRequest.
Google.Apis.Requests.RequestError
database_id should be 4-63 characters, and valid characters are /[a-z][0-9]-/ [400]
Errors [
Message[database_id should be 4-63 characters, and valid characters are /[a-z][0-9]-/] Location[ - ] Reason[badRequest] Domain[global]
]
Google.GoogleApiException: The service firestore has thrown an exception. HttpStatusCode is BadRequest. database_id should be 4-63 characters, and valid characters are /[a-z][0-9]-/
at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response)
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
If you go through the given method :
FirestoreService().Projects.Databases.Create it has parent as Parameter and databaseId as a Query parameter there is also a try this method section where you can verify your parameters are correct like for example :
using Google.Apis.Firestore.v1;
private static FirestoreService _firestoreService;
public static void IntializeFirestoreAdmin() {
GoogleCredential credential = GoogleCredential.GetApplicationDefault();
if (CloudManager.Credential.IsCreateScopedRequired)
{
credential = CloudManager.Credential.CreateScoped(FirestoreService.Scope.CloudPlatform);
}
_firestoreService = new FirestoreService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = CloudManager.ApplicationName
});
}
public static void AddCloudFirestore() {
IntializeFirestoreAdmin();
var mydata = new GoogleFirestoreAdminV1Database {
LocationId = "nam5",
Type = "FIRESTORE_NATIVE",
Name = "projects/" + CloudManager.ProjectId + "/databases/my-database",
};
_firestoreService.Projects.Databases.Create(mydata, "projects/" + CloudManager.ProjectId).Execute();
}
var body = new GoogleFirestoreAdminV1Database
{
Type = "FIRESTORE_NATIVE",
LocationId = "nam5"
};
string parent = $"projects/{CloudManager.ProjectId}";
var request = _firestoreService.Projects.Databases.Create(body, parent);
request.DatabaseId = "(default)";
var response = request.Execute();
The issue was that I didn't add the databaseId as a query parameter. For more details go to this link https://groups.google.com/g/google-cloud-firestore-discuss/c/EQ-04MnPyLk
I am using wso2/gmail package to send an email notification. According to the documentation (https://central.ballerina.io/wso2/gmail) we can send an attachment with the mail through the package. However, when I try to define attachment paths as a parameter, I get an error as follows.
incompatible types: expected 'wso2/gmail:0.9.7:AttachmentPath', found 'string'
What is AttachmentPath type? Can we parse string array of attachment paths to AttachmentPath? Here is my function to send mail.
import wso2/gmail;
import ballerina/io;
import ballerina/log;
import ballerina/config;
import ballerina/http;
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
//What is the attachment path?
AttachmentPath attachmentPath = "./org/wso2/logs/loginfo.txt";
messageRequest.attachmentPaths = attachmentPath;
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
Yes. As #pasan has mentioned, AttachmentPath is a record. Following is the updated code if someone wants to refer.
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"Text/plain"
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
messageRequest.attachmentPaths = [attachmentPath];
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
AttachmentPath is defined in [wso2/gmail][1] as a record. The attachmentPaths field needs an array of such AttachmentPath objects. So following should work.
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"text/plain"
};
messageRequest.attachmentPaths = [attachmentPaths];
I have a problem using the aggregate storedproc lumenize https://github.com/lmaccherone/documentdb-lumenize with the .net client. I get error when try passing in the parameter and query into the storedproc. Below is my code
public async static void QuerySP() {
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
//Get the Database
var database = client.CreateDatabaseQuery().Where(db => db.Id == databaseId).ToArray().FirstOrDefault();
//Get the Document Collection
var collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).ToArray().FirstOrDefault();
StoredProcedure storedProc = client.CreateStoredProcedureQuery(collection.StoredProceduresLink).Where(sp => sp.Id == "cube").ToArray().FirstOrDefault();
dynamic result = await client.ExecuteStoredProcedureAsync<dynamic>(storedProc.SelfLink, "{cubeConfig: {groupBy: 'publication', field: 'pid', f: 'count'}, filterQuery: 'SELECT pid, publication FROM c'}");
Console.WriteLine("Result from script: {0}\r\n", result.Response);
}
}
I am getting the following error when execute the code
Message: {"Errors":["Encountered exception while executing Javascript. Exception = Error: cubeConfig or savedCube required\r\nStack trace: Error: cubeConfig or savedCube required\n at fn (cube.js:1803:7)\n at __docDbMain (cube.js:1844:5)\n at Unknown script code (cube.js:1:2)"]}
Not sure what I had done wrong. I would really appreciate the help. Thanks.
You almost have it. The problem is that you are sending in the cubeConfig as a string. It needs to be an object. Here is code that does that:
string cubeConfigString = #"{
cubeConfig: {
groupBy: 'publication',
field: 'pid',
f: 'count'
},
filterQuery: 'SELECT * FROM c'
}";
Object cubeConfig = JsonConvert.DeserializeObject<Object>(cubeConfigString);
Console.WriteLine(cubeConfig);
dynamic result = await client.ExecuteStoredProcedureAsync<dynamic>("dbs/dev-test-database/colls/dev-test-collection/sprocs/cube", cubeConfig);
Console.WriteLine(result.Response);
my working code
public async static Task QuerySP2()
{
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
//Get the Database
var database = client.CreateDatabaseQuery().Where(db => db.Id == databaseId).ToArray().FirstOrDefault();
//Get the Document Collection
var collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).ToArray().FirstOrDefault();
StoredProcedure storedProc = client.CreateStoredProcedureQuery(collection.StoredProceduresLink).Where(sp => sp.Id == "cube").ToArray().FirstOrDefault();
string filterQuery = string.Format(#"SELECT * from c");
string cubeConfigString = #"{
cubeConfig: {
groupBy: 'publication',
field: 'id',
f: 'count'
},
filterQuery: '" + filterQuery + "'}";
dynamic cubeConfig = JsonConvert.DeserializeObject<dynamic>(cubeConfigString);
Console.WriteLine(cubeConfig);
string continuationToken = null;
dynamic result=null;
do
{
var queryDone = false;
while (!queryDone)
{
try
{
result = await client.ExecuteStoredProcedureAsync<dynamic>(storedProc.SelfLink, cubeConfig);
cubeConfig = result.Response;
continuationToken = cubeConfig.continuation;
queryDone = true;
}
catch (DocumentClientException documentClientException)
{
var statusCode = (int)documentClientException.StatusCode;
if (statusCode == 429 || statusCode == 503)
System.Threading.Thread.Sleep(documentClientException.RetryAfter);
else
throw;
}
catch (AggregateException aggregateException)
{
if (aggregateException.InnerException.GetType() == typeof(DocumentClientException))
{
var docExcep = aggregateException.InnerException as DocumentClientException;
var statusCode = (int)docExcep.StatusCode;
if (statusCode == 429 || statusCode == 503)
System.Threading.Thread.Sleep(docExcep.RetryAfter);
else
throw;
}
}
}
} while (continuationToken != null);
Console.WriteLine("Result from script: {0}\r\n", result.Response);
}
}
I'm attempting to verify if a pdf has been digitally signed from the server side using iTextSharp, but am receiving the following error: "can't decode PKCS7SignedData object" on the code
PdfPKCS7 pk = af.VerifySignature(name);
Here is the function:
public string verifyPdfSignature(string pdfFile)
{
var parser = new X509CertificateParser();
PdfReader reader = new PdfReader(pdfFile);
AcroFields af = reader.AcroFields;
var names = af.GetSignatureNames();
if (names.Count == 0)
{
return "No Signature present in pdf file.";
}
foreach (string name in names)
{
if (!af.SignatureCoversWholeDocument(name))
{
return (string.Format("The signature: {0} does not cover the whole document.", name));
}
PdfPKCS7 pk = af.VerifySignature(name); //<--- ERROR HERE
var cal = pk.SignDate;
var pkc = pk.Certificates;
if (!pk.Verify())
{
return "The signature could not be verified.";
}
if (!pk.VerifyTimestampImprint())
{
return "The signature timestamp could not be verified.";
}
}
return "nothing";
}
I'm gonna build a webpart for creating user in active directory .
For creating user account i use method like this :
public string CreateUserAccount(string ldapPath, string userName,
string userPassword)
{
try
{
string oGUID = string.Empty;
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
DirectoryEntry newUser = dirEntry.Children.Add
("CN=" + userName, "user");
newUser.Properties["samAccountName"].Value = userName;
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { userPassword });
newUser.CommitChanges();
dirEntry.Close();
newUser.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingwith --> E.Message.ToString();
}
return oGUID;
}
When executing this method the following error occurred:
"The server is not operational"
say we have active directory installed with domain TestDomain.com and you have a OU ( Organization Unit ) called USERS and you have a user in it called TestUser
so we can saye the following
ldapDomain: the fully qualified domain as TestDomain.com or dc=contoso,dc=com
objectPath: the fully qualified path to the object: CN=TestUser, OU=USERS, DC=TestDomain, DC=com
userDn: the distinguishedName of the user: CN=TestUser, OU=USERS, DC=TestDomain, DC=com
in creating user you should determine where you want to create by determining its path ( ldap path )
In our sample we can consider it as below :
string ldapPath = "LDAP://OU=USERS, DC=TestDomain, DC=com"
For more information check the following links :
http://www.selfadsi.org/ldap-path.htm
http://www.informit.com/articles/article.aspx?p=101405&seqNum=7
http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path.aspx
Using System.DirectoryServices
To use this namespace you need to add reference System.DirectoryServices.dll
DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");
for (int i = 3; i < 6; i++)
{
try
{
DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user");
childEntry.CommitChanges();
ouEntry.CommitChanges();
childEntry.Invoke("SetPassword", new object[] { "password" });
childEntry.CommitChanges();
}
catch (Exception ex)
{
}
}
Using System.DirectoryServices.AccountManagement
To use this namespace you need to add reference System.DirectoryServices.AccountManagement.dll
PrincipalContext ouContex = new PrincipalContext(ContextType.Domain, "TestDomain.local", "OU=TestOU,DC=TestDomain,DC=local");
for (int i = 0; i < 3; i++)
{
try
{
UserPrincipal up = new UserPrincipal(ouContex);
up.SamAccountName = "TestUser" + i;
up.SetPassword("password");
up.Enabled = true;
up.ExpirePasswordNow();
up.Save();
}
catch (Exception ex)
{
}
}