Adding subscribers to a list using Mailchimp's API v3 using .net - asp.net

I am trying add a subscriber to a list but I'm struggling to implement it without any example code.
can anybody help me with the example?

Inspired by this video:
MailChimp.NET Tutorial: Create, Edit And Delete List Members - here my test code to add a subscriber to a 'given list'.
The subscriber will receive an email asking to confirm the subscription. After that confirmation the new subscriber
will be listed in mailchimp campaign list.
(used version mailchimp.net wrapper v:3 with newtonsoft.json version 10.0.3) - this worked for me.
private static readonly IMailChimpManager Manager = new MailChimpManager(ApiKey);
public async Task AddSubscriberToCampaignList(string emailAddress, string listName, string fname, string lname)
{
try
{
var listsAwaitable = Manager.Lists.GetAllAsync().ConfigureAwait(false);
var list = listsAwaitable.GetAwaiter().GetResult().FirstOrDefault(l =>
l.Name.Equals(listName, StringComparison.CurrentCultureIgnoreCase));
if (list != null)
{
//the subscriber
var member = new Member
{
EmailAddress = emailAddress,
StatusIfNew = Status.Pending,
EmailType = "html",
TimestampSignup = DateTime.UtcNow.ToString("s"),
};
if (fname != null && lname != null)
{
var subscriberName = new Dictionary<string, object>
{
{"FNAME", fname},
{"LNAME", lname}
};
member.MergeFields = subscriberName;
}
string campaignListKey = list.Id;
await Manager.Members.AddOrUpdateAsync(campaignListKey, member);
}
}
catch (MailChimpException e)
{
throw;
}

Related

Google.Apis.Requests.RequestError Not Found when deleting event

I have below method to delete event in calendar:
public async Task<string> DeleteEventInCalendarAsync(TokenResponse token, string googleUserId, string calendarId, string eventId)
{
string result = null;
try
{
if (_calService == null)
{
_calService = GetCalService(token, googleUserId);
}
// Check if event exist
var eventResource = new EventsResource(_calService);
var erListRequest = eventResource.List(calendarId);
var eventsResponse = await erListRequest.ExecuteAsync().ConfigureAwait(false);
var existingEvent = eventsResponse.Items.FirstOrDefault(e => e.Id == eventId);
if (existingEvent != null)
{
var deleteRequest = new EventsResource.DeleteRequest(_calService, calendarId, eventId);
result = await deleteRequest.ExecuteAsync().ConfigureAwait(false);
}
}
catch (Exception exc)
{
result = null;
_logService.LogException(exc);
}
return result;
}
And I am getting error as follow -
Google.GoogleApiException Google.Apis.Requests.RequestError Not Found [404] Errors [ Message[Not Found] Location[ - ] Reason[notFound] Domain[global] ]
Can you help me understand why this error? Or where I can find the details about these error?
The error you are getting is due to the event's id you are passing doesn't exist or you are passing it in the wrong way. Following the .Net Quickstart I made a simple code example on how to pass the event's id to the Delete(string calendarId, string eventId) method from the Class Events
namespace CalendarQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-dotnet-quickstart.json
static string[] Scopes = { CalendarService.Scope.Calendar };
static string ApplicationName = "Google Calendar API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define request.
EventsResource.ListRequest request = service.Events.List("primary");
// List events.
Events events = request.Execute();
Event existingEvent = events.Items.FirstOrDefault(e => e.Id == "your event id you want to get");
Console.WriteLine("Upcoming events:");
if (existingEvent != null)
{
Console.WriteLine("{0} {1}", existingEvent.Summary, existingEvent.Id);
string deleteEvent = service.Events.Delete("primary", existingEvent.Id).Execute();
}
else
{
Console.WriteLine("No upcoming events found.");
}
Console.Read();
}
}
}
Notice
I made this example in a synchronous syntax way for testing purposes in the console. After you test it and see how it works, you could adapt it to your code. Remember, make your you are passing the correct Id.
Docs
For more info check this doc:
Namespace Google.Apis.Calendar.v3

ASP.Net Core : get members of Active Directory group

I'm wondering how I could get a list of members of an AD group.
Checking if an entered password of a user is correct works perfectly fine. For this I'm using Novell's Ldap.NetStandard:
private bool IsUserValid(string userName,string userPassword)
{
try{
using (var connection = new LdapConnection { SecureSocketLayer = false })
{
connection.Connect("test.local", LdapConnection.DEFAULT_PORT);
connection.Bind(userDn, userPassword);
if (connection.Bound)
{
return true;
}
}
}
catch (LdapException ex)
{
Console.WriteLine(ex.Massage);
}
return false;
}
What I want now is something like this:
bool isUserInGroup("testUser","testGroup");
The problem is I can't get my method working:
public bool IsUserMemberOfGroup(string userName,string groupName)
{
var ldapConn = GetConnection();
var searchBase = "";
var filter = $"(&(objectClass=group)(cn={groupName}))";
var search = ldapConn.Search(searchBase, LdapConnection.SCOPE_BASE, filter, null, false);
while (search.hasMore())
{
var nextEntry = search.next();
if (nextEntry.DN == userName)
return true;
}
return false;
}
What ever I'm doing, I'm not getting back any value from my Ldap.Search()...
Now there is an implementation of System.DirectoryServices.AccountManagement for .NET Core 2. It is available via nuget.
With this package you are able to things like that:
using (var principalContext = new PrincipalContext(ContextType.Domain, "YOUR AD DOMAIN"))
{
var domainUsers = new List<string>();
var userPrinciple = new UserPrincipal(principalContext);
// Performe search for Domain users
using (var searchResult = new PrincipalSearcher(userPrinciple))
{
foreach (var domainUser in searchResult.FindAll())
{
if (domainUser.DisplayName != null)
{
domainUsers.Add(domainUser.DisplayName);
}
}
}
}
This performs a search for the user in your domain.Nearly the same is possible for searching your group. The way I used to search my AD (description in my question) is now obsolet:
Checking if an entered password of a user is correct works perfectly
fine. For this I'm using Novell's Ldap.NetStandard:
How about:
HttpContext.User.IsInRole("nameOfYourAdGroup");
(namespace System.Security.Claims)

Invalid object name 'AspNetRoleClaims' exception when logging in

So I implemented Identity for my core project. I have successfully completed my Registration. So while trying to login using the _signInManager.PasswordSignInAsync I am getting the exception Invalid object name 'AspNetRoleClaims'.
I know this is because the AspNetRoleClaims table is not present in my database. But idont know the structure of this table nor do I know how to create it automatically like in mvc.
Can somebody enlighten me why this table is used. Or at least what is the expected structure.
public async Task<IActionResult> RegisterSubmit(Registermodel rm)
{
if (rm.role == "" || rm.role.Trim() == "-1")
{
return View();
}
else
{
var user = new ApplicationUser { UserName = rm.username, Email = rm.username, DeptName = rm.role };
var result = await _userManager.CreateAsync(user, rm.Password);
if (result.Succeeded)
{
_userManager.GenerateEmailConfirmationTokenAsync(user);
await _signInManager.SignInAsync(user, isPersistent: false);
var roleexists = await _roleManager.RoleExistsAsync(rm.role);
if (!roleexists)
{
var role = new IdentityRole();
role.Name = rm.role;
await _roleManager.CreateAsync(role);
}
await _userManager.AddToRoleAsync(user, rm.role);
user.Claims.Add(new IdentityUserClaim<string>
{
ClaimType = "ProductUploadRequest",
ClaimValue = "Allow"
});
}
return View("Login");
}
}
This is my login method.
public async Task<IActionResult> Login(LoginIdentityModel lim)
{
var result = await _signInManager.PasswordSignInAsync(lim.username, lim.password,false, lockoutOnFailure: false); //exception comes here
if (result.Succeeded)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
UserProfileInfo userProfileInfo = new UserProfileInfo();
userProfileInfo.UserId = new Guid(user.Id);
userProfileInfo.FirstName = "test";
userProfileInfo.UserName = lim.username;
userProfileInfo.LastVisit = DateTime.Now;
string query2 = "select ud.UserId,dp.Id DeptId,dp.Name DeptName,rd.Id RoleId,rd.Name RoleName,ud.[ReadWrite] from UserInDepartment ud inner join Department dp on ud.DeptId=dp.Id inner join RolesInDepartment rd on dp.Id=rd.DeptId and ud.RoleId=rd.Id where ud.UserId='" + user.Id + "' and dp.IsEnable=1 and rd.IsEnable=1 and ud.IsEnable=1";
var userProfile = await _departMentalContext.UserProfiles.FromSql(query2).SingleOrDefaultAsync();
if (userProfile != null)
{
Dictionary<int, string> deptValues = new Dictionary<int, string>() { { userProfile.DeptId, userProfile.DeptName } };
userProfileInfo.Dept = deptValues;
Dictionary<int, string> roleValues = new Dictionary<int, string>() { { userProfile.RoleId, userProfile.RoleName } };
userProfileInfo.Role = roleValues;
userProfileInfo.ReadOrWrite = userProfile.ReadWrite;
HttpContext.Session.SetObject(UserProfileSessionName, userProfileInfo);
}
return View("/Home/DashBoard");
}
return View();
}
As you are using EF, you should be able to update your model database.
You can use CLI command (learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet).
Or if you are using Visual Studio, in the package manager console, you can execute those commands :
Add-Migration "init"
Update-Database
Commands allows you tu update table in your database. Also, it will create migrations files, which are a "picture" of your models. When the command Update-Database is executed, it loads the last migration file.

In Skype bot framework Attachments Content null

I'm trying to access the list of attachments sent by the user to the skype bot that I'm developing.
Here is how I access the attachment details ,
public async Task<HttpResponseMessage> Post([FromBody]Activity message)
{
if (message.Attachments != null)
{
if (message.Attachments.Count > 0)
{
List<Attachment> attachmentList = message.Attachments.ToList();
foreach (var item in attachmentList)
{
var name = item.Name;
var content = item.Content;
}
}
}
}
But I get null for the following even though the attachment count is greater than zero,
var name = item.Name;
var content = item.Content;
Am I doing this right?
Maybe do something like this...
List<Attachment> attachmentList = message?.Attachments?.Where(x => x != null)?.ToList() ?? new List<Attachment>();
This would hopefully always set attachmentList to an empty list or a list containing non null items?

Login users at the same time problems in signalr

I'm working on a social network with ASP.NET and signalr. I have a simple login page, if it finds the user in the database it creates an Application variable and redirect the user to the profile page and in this page i invoke my Connect method declared in my hub class, this method takes the userid in the session and it give the friend list of this user. That works great when two or many users logged in at different time. The thing is, when two or several users logged in at the same time, the connect method declared in my hub takes the last user id stored in the Application variable and it give the friend list of this last user id and it send it to all user connected.
I can't find the correct approach.
Loggin Page code:
protected void btn_login_Click(object sender, EventArgs e)
{
Tbl_User user = new Tbl_User();
user = FonctionCommun.Login(txt_UserName.Text , txt_PassWord.Text);
if (user != null)
{
Application["UserID"] = user.UserID.ToString();
Response.Redirect("Profile.aspx");
}
else {
Label1.Visible = true;
}
}
My connect method code:
public void connect()
{
UserID = Guid.Parse(HttpContext.Current.Application["UserID"].ToString());
string OutPut = "";
if (ListOnlineUser.Count(x => x.UserID == UserID) == 0)
{
ListOnlineUser.Add(new OnlineUsers { UserID = UserID, ConnetionID = Guid.Parse(Context.ConnectionId) });
objchat.SetOnline(UserID);
ListFriends = objchat.GetFriendLoginStatus(UserID);
}
foreach (Tbl_User item in ListFriends)
{
if (item.Status == "1")
{
OnlineUsers onlineFriend = ListOnlineUser.FirstOrDefault(x => x.UserID == Guid.Parse(item.UserID.ToString()));
if (onlineFriend != null)
{
using (FIESTA_ADVISOREntities BD = new FIESTA_ADVISOREntities())
{
Tbl_User Obj_User = BD.Tbl_User.Where(o => o.UserID == UserID).FirstOrDefault();
if (Obj_User.ProfileImage != null)
{
string ext = BD.Assets.Where(o => o.url == Obj_User.ProfileImage).Select(o => o.MimeType).FirstOrDefault();
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = Obj_User.ProfileImage.ToString(), Ext = ext };
OutPut = JsonConvert.SerializeObject(res);
}
else {
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = "111", Ext = "png" };
OutPut = JsonConvert.SerializeObject(res); }
Clients.Client(onlineFriend.ConnetionID.ToString()).OnNewUserConnect(OutPut);
}
}
}
}
Clients.Caller.ShowFriends(ListFriends);
}
Try session variable instead of application variable. Application variable shared through out application working. So Whenever new user this is override. But if you use session variable that will never override by any other user
Also you can use query string in signalr in which you can pass userid as query string so in each request userid will be in query string
$.connection.hub.qs = 'userid=' + "UserId";

Resources