send email from asp.net via gmail smtp - asp.net

I have dedicated server. my IP was blocked with only yahoo, since first day. currently i nead 40000 email per day. i decided to create 400 Gmail account and send email from server via gmail smtp server (every gmail account limited to send email to 100 recipients).
the benefit of this solution is all email send to Inbox no SPAM!
what about u?
do you have any better solution?
do you know any better free email provider with lower limitation?
SmtpClient client = new SmtpClient();

This sounds exactly like a spam setup.
I suspect that's why you're blocked from yahoo.
I'm sure you are in violation of the Gmail terms of service. I'm sure they'll take less time to ban you than yahoo.
You're also missing the point of the 100 recipient limit entirely.
What would I do? Get out of the spam business.

You should register for a professional SMTP service, where they will batch-send your emails. Creating 400 emails account on gmail and access them with code? That sounds VERY un-manageable.
There are commersial websites that work with sending emails that you can integrate with, 40 000 emails per month is a lot of emails, I even think you violate some of googles terms of usage when you adapt this solution.
A normal SMTP service that you can purchase works like this:
You purchase an email-limit per day/year/month. 40 000 emails will probably be quite costly.
You integrate with the service with either a Web Service or other API's you DO NOT use SmtpClient ( in some cases you do, but normaly when you send 40 000 emails, that's a NO NO! ).
You use a template that you've set up in their system, hence, you do not send you own "html" from your code, you use a confirmed / verified template.
Another option is to create a SMTP sender yourself, that batches 40 000 emails during a long time period, but this might get you blacklisted as well.

I'm sure that setting up 400 GMail accounts to send, what sounds a lot like SPAM, is against their T&Cs and it's only a matter of time before they close you down as well.
I would suggest that if you have a legitimate need for sending 40000 emails per day that you sign up with a mail provider who specialises in bulk mailing.
See this for more info: Bulk Mail Sending On The Cheap

MailMessage EmailMsg = new MailMessage();
// EmailMsg.From = new MailAddress("yourmail", "dsd");
// EmailMsg.To.Add(new MailAddress(txtEmail.Text, "from plain text name"));
// EmailMsg.Body = txtMsg.Text;
// EmailMsg.IsBodyHtml = true;
// EmailMsg.Priority = MailPriority.Normal;
// SmtpClient mailClient = new SmtpClient();
// mailClient.Host = ("10.10.11.112");
// //mailClient.Credentials = new System.Net.NetworkCredential("yourmail", "pass");
// mailClient.EnableSsl = false;
// mailClient.Port = 25;
// mailClient.Send(EmailMsg);
i did it this way.Hope it will help you.

public class MailMgmt
{
private string _From = "asd#gmail.com";
private string _SMTPServer = "smtp.gmail.com";
private int _SMTPPort = "587";
private string _Password = "password";
private bool _EnableSSL = true;
private string _To = string.Empty;
private string _CC = string.Empty;
private string _BCC = string.Empty;
private string _Subject = string.Empty;
private string _Body = string.Empty;
private string _AttachmentFile = string.Empty;
public string From
{
get { return _From; }
set { _From = value; }
}
public string SMTPServer
{
get { return _SMTPServer; }
set { _SMTPServer = value; }
}
public int SMTPPort
{
get { return _SMTPPort; }
set { _SMTPPort = value; }
}
public string Password
{
get { return _Password; }
set { _Password = value; }
}
public bool EnableSSL
{
get { return _EnableSSL; }
set { _EnableSSL = value; }
}
public string To
{
get { return _To; }
set { _To = value.Trim(); }
}
public string CC
{
get { return _CC; }
set { _CC = value.Trim(); }
}
public string BCC
{
get { return _BCC; }
set { _BCC = value.Trim(); }
}
public string Subject
{
get { return _Subject; }
set { _Subject = value.Trim(); }
}
public string Body
{
get { return _Body; }
set { _Body = value.Trim(); }
}
public string AttachmentFile
{
get { return _AttachmentFile; }
set { _AttachmentFile = value.Trim(); }
}
public MailMgmt()
{
}
public void SendMail()
{
bool result = false;
MailMessage obj = new MailMessage();
try
{
string Expression = #"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*";
string[] StrSpl;
string[] StrSpl1;
obj.From = new MailAddress(_From);
if (_To != "")
{
StrSpl = _To.Split(',');
foreach (string Str in StrSpl)
{
if (Regex.IsMatch(Str, Expression))
{
obj.To.Add(Str);
}
}
}
if (_CC != "")
{
StrSpl = _CC.Split(',');
foreach (string Str in StrSpl)
{
if (Regex.IsMatch(Str, Expression))
{
obj.CC.Add(Str);
}
}
}
if (_BCC != "")
{
StrSpl = _BCC.Split(',');
foreach (string Str in StrSpl)
{
if (Regex.IsMatch(Str, Expression))
{
obj.Bcc.Add(Str);
}
}
}
if (_Subject != "")
{
obj.Subject = _Subject;
}
if (_Body != "")
{
obj.Body = _Body;
}
if (_AttachmentFile != string.Empty)
{
StrSpl1 = _AttachmentFile.Split(',');
foreach (string Str in StrSpl1)
{
Attachment at = new Attachment(Str);
obj.Attachments.Add(at);
}
}
obj.IsBodyHtml = true;
obj.Priority = MailPriority.High;
SmtpClient client = new SmtpClient(_SMTPServer, _SMTPPort);
client.EnableSsl = _EnableSSL;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_From, _Password);
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = SMTPUserInfo;
client.Send(obj);
// return result = true;
}
catch (Exception ex)
{
//return result = false;
}
}
}
Use this class and send mail easily

Related

Microsoft.Exchange.WebServices.Data.ServiceResponseException: 'There are no public folder servers available.'

further to this question, i have the same problem. PubFolder on Prem , users in O365
I have fetched and added the routing headers from Glen's post but still get the error
GetToken works...
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
GetX headers works...
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/public-folder-access-with-ews-in-exchange
--->> ewsClient.FindFolders(WellKnownFolderName.PublicFoldersRoot, new FolderView(10))
Microsoft.Exchange.WebServices.Data.ServiceResponseException: 'There are no public folder servers available.'
static async System.Threading.Tasks.Task Test3()
{
string ClientId = ConfigurationManager.AppSettings["appId"];
string TenantId = ConfigurationManager.AppSettings["tenantId"];
string secret = ConfigurationManager.AppSettings["clientSecret"];
string uMbox = ConfigurationManager.AppSettings["userId"];
string uPwd = ConfigurationManager.AppSettings["userPWD"];
// Using Microsoft.Identity.Client 4.22.0
//https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth//
var cca = ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithClientSecret(secret)
.WithTenantId(TenantId)
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
try
{
var authResult = await cca.AcquireTokenForClient(ewsScopes)
.ExecuteAsync();
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
ewsClient.ImpersonatedUserId =
new ImpersonatedUserId(ConnectingIdType.SmtpAddress, uMbox);
AutodiscoverService autodiscoverService = GetAutodiscoverService(uMbox, uPwd);
GetUserSettingsResponse userResponse = GetUserSettings(autodiscoverService, uMbox, 3, UserSettingName.PublicFolderInformation, UserSettingName.InternalRpcClientServer);
string pfAnchorHeader= userResponse.Settings[UserSettingName.PublicFolderInformation].ToString();
string pfMailboxHeader = userResponse.Settings[UserSettingName.InternalRpcClientServer].ToString(); ;
// Make an EWS call
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
foreach (var folder in folders)
{
Console.WriteLine($"Folder: {folder.DisplayName}");
}
//get Public folder root
//Include x-anchormailbox header
Console.WriteLine("X-AnchorMailbox value for public folder hierarchy requests: {0}", pfAnchorHeader);
Console.WriteLine("X-PublicFolderMailbox value for public folder hierarchy requests: {0}", pfMailboxHeader);
//var test3 = GetMailboxGuidAddress(ewsClient, pfAnchorHeader, pfMailboxHeader, uMbox);
///https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-route-public-folder-content-requests <summary>
ewsClient.HttpHeaders.Add("X-AnchorMailbox", userResponse.Settings[UserSettingName.PublicFolderInformation].ToString());
//ewsClient.HttpHeaders.Add("X-AnchorMailbox", "SharedPublicFolder#contoso.com");
ewsClient.HttpHeaders.Add("X-PublicFolderMailbox", userResponse.Settings[UserSettingName.InternalRpcClientServer].ToString());
try
{
var pubfolders = ewsClient.FindFolders(WellKnownFolderName.PublicFoldersRoot, new FolderView(10));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
foreach (var folder in folders)
{
Console.WriteLine($"Folder: {folder.DisplayName}");
}
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring access token: {ex}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Hit any key to exit...");
Console.ReadKey();
}
}
public static AutodiscoverService GetAutodiscoverService(string username, string pwd)
{
AutodiscoverService adAutoDiscoverService = new AutodiscoverService();
adAutoDiscoverService.Credentials = new WebCredentials(username, pwd);
adAutoDiscoverService.EnableScpLookup = true;
adAutoDiscoverService.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
adAutoDiscoverService.PreAuthenticate = true;
adAutoDiscoverService.TraceEnabled = true;
adAutoDiscoverService.KeepAlive = false;
return adAutoDiscoverService;
}
public static GetUserSettingsResponse GetUserSettings(
AutodiscoverService service,
string emailAddress,
int maxHops,
params UserSettingName[] settings)
{
Uri url = null;
GetUserSettingsResponse response = null;
for (int attempt = 0; attempt < maxHops; attempt++)
{
service.Url = url;
service.EnableScpLookup = (attempt < 2);
response = service.GetUserSettings(emailAddress, settings);
if (response.ErrorCode == AutodiscoverErrorCode.RedirectAddress)
{
url = new Uri(response.RedirectTarget);
}
else if (response.ErrorCode == AutodiscoverErrorCode.RedirectUrl)
{
url = new Uri(response.RedirectTarget);
}
else
{
return response;
}
}
throw new Exception("No suitable Autodiscover endpoint was found.");
}
Your code won't work against an OnPrem Public folder tree as EWS in Office365 won't proxy to an OnPrem Exchange Org (even if hybrid is setup). (Outlook MAPI is a little different and allows this via versa setup but in that case it never proxies either it just makes a different connection to that store and its all the Outlook client doing this).
Because your trying to use the client credentials oauth flow for that to work onPrem you must have setup hybrid modern authentication https://learn.microsoft.com/en-us/microsoft-365/enterprise/hybrid-modern-auth-overview?view=o365-worldwide. Then you need to acquire a token with an audience set to the local OnPrem endpoint. (this is usually just your onPrem ews endpoint's host name but it should be one of the service principal names configured in your hybrid auth setup Get-MsolServicePrincipal). So in your code you would change
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
to
var ewsScopes = new string[] { "https://OnPrem.whatever.com/.default" };
which will then give you a token with an audience set for the onprem server then you need to send the EWS request to that endpoint so change that eg
ewsClient.Url = new Uri("https://OnPrem.whatever.com/EWS/Exchange.asmx");
if Hybird Modern Auth is setup then you need to default back to use Integrated or Basic Authenticaiton.

How to send a zipped file to S3 bucket from Apex?

Folks,
I am trying to move data to s3 from Salesforce using apex class. I have been told by the data manager to send the data in zip/gzip format to the S3 bucket for storage cost savings.
I have simply tried to do a request.setCompressed(true); as I've read it compresses the body before sending it to the endpoint. Code below:
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:'+DATA_NAMED_CRED+'/'+URL+'/'+generateUniqueTimeStampforSuffix());
request.setMethod('PUT');
request.setBody(JSON.serialize(data));
request.setCompressed(true);
request.setHeader('Content-Type','application/json');
But no matter what I always receive this:
<Error><Code>XAmzContentSHA256Mismatch</Code><Message>The provided 'x-amz-content-sha256' header does not match what was computed.</Message><ClientComputedContentSHA256>fd31b2b9115ef77e8076b896cb336d21d8f66947210ffcc9c4d1971b2be3bbbc</ClientComputedContentSHA256><S3ComputedContentSHA256>1e7f2115e60132afed9e61132aa41c3224c6e305ad9f820e6893364d7257ab8d</S3ComputedContentSHA256>
I have tried multiple headers too, like setting the content type to gzip/zip, etc.
Any pointers in the right direction would be appreciated.
I had a good amount of headaches attempting to do a similar thing. I feel your pain.
The following code has worked for us using lambda functions; you can try modifying it and see what happens.
public class AwsApiGateway {
// Things we need to know about the service. Set these values in init()
String host, payloadSha256;
String resource;
String service = 'execute-api';
String region;
public Url endpoint;
String accessKey;
String stage;
string secretKey;
HttpMethod method = HttpMethod.XGET;
// Remember to set "payload" here if you need to specify a body
// payload = Blob.valueOf('some-text-i-want-to-send');
// This method helps prevent leaking secret key,
// as it is never serialized
// Url endpoint;
// HttpMethod method;
Blob payload;
// Not used externally, so we hide these values
Blob signingKey;
DateTime requestTime;
Map<String, String> queryParams = new map<string,string>(), headerParams = new map<string,string>();
void init(){
if (payload == null) payload = Blob.valueOf('');
requestTime = DateTime.now();
createSigningKey(secretKey);
}
public AwsApiGateway(String resource){
this.stage = AWS_LAMBDA_STAGE
this.resource = '/' + stage + '/' + resource;
this.region = AWS_REGION;
this.endpoint = new Url(AWS_ENDPOINT);
this.accessKey = AWS_ACCESS_KEY;
this.secretKey = AWS_SECRET_KEY;
}
// Make sure we can't misspell methods
public enum HttpMethod { XGET, XPUT, XHEAD, XOPTIONS, XDELETE, XPOST }
public void setMethod (HttpMethod method){
this.method = method;
}
public void setPayload (string payload){
this.payload = Blob.valueOf(payload);
}
// Add a header
public void setHeader(String key, String value) {
headerParams.put(key.toLowerCase(), value);
}
// Add a query param
public void setQueryParam(String key, String value) {
queryParams.put(key.toLowerCase(), uriEncode(value));
}
// Create a canonical query string (used during signing)
String createCanonicalQueryString() {
String[] results = new String[0], keys = new List<String>(queryParams.keySet());
keys.sort();
for(String key: keys) {
results.add(key+'='+queryParams.get(key));
}
return String.join(results, '&');
}
// Create the canonical headers (used for signing)
String createCanonicalHeaders(String[] keys) {
keys.addAll(headerParams.keySet());
keys.sort();
String[] results = new String[0];
for(String key: keys) {
results.add(key+':'+headerParams.get(key));
}
return String.join(results, '\n')+'\n';
}
// Create the entire canonical request
String createCanonicalRequest(String[] headerKeys) {
return String.join(
new String[] {
method.name().removeStart('X'), // METHOD
new Url(endPoint, resource).getPath(), // RESOURCE
createCanonicalQueryString(), // CANONICAL QUERY STRING
createCanonicalHeaders(headerKeys), // CANONICAL HEADERS
String.join(headerKeys, ';'), // SIGNED HEADERS
payloadSha256 // SHA256 PAYLOAD
},
'\n'
);
}
// We have to replace ~ and " " correctly, or we'll break AWS on those two characters
string uriEncode(String value) {
return value==null? null: EncodingUtil.urlEncode(value, 'utf-8').replaceAll('%7E','~').replaceAll('\\+','%20');
}
// Create the entire string to sign
String createStringToSign(String[] signedHeaders) {
String result = createCanonicalRequest(signedHeaders);
return String.join(
new String[] {
'AWS4-HMAC-SHA256',
headerParams.get('date'),
String.join(new String[] { requestTime.formatGMT('yyyyMMdd'), region, service, 'aws4_request' },'/'),
EncodingUtil.convertToHex(Crypto.generateDigest('sha256', Blob.valueof(result)))
},
'\n'
);
}
// Create our signing key
void createSigningKey(String secretKey) {
signingKey = Crypto.generateMac('hmacSHA256', Blob.valueOf('aws4_request'),
Crypto.generateMac('hmacSHA256', Blob.valueOf(service),
Crypto.generateMac('hmacSHA256', Blob.valueOf(region),
Crypto.generateMac('hmacSHA256', Blob.valueOf(requestTime.formatGMT('yyyyMMdd')), Blob.valueOf('AWS4'+secretKey))
)
)
);
}
// Create all of the bits and pieces using all utility functions above
public HttpRequest createRequest() {
init();
payloadSha256 = EncodingUtil.convertToHex(Crypto.generateDigest('sha-256', payload));
setHeader('date', requestTime.formatGMT('yyyyMMdd\'T\'HHmmss\'Z\''));
if(host == null) {
host = endpoint.getHost();
}
setHeader('host', host);
HttpRequest request = new HttpRequest();
request.setMethod(method.name().removeStart('X'));
if(payload.size() > 0) {
setHeader('Content-Length', String.valueOf(payload.size()));
request.setBodyAsBlob(payload);
}
String finalEndpoint = new Url(endpoint, resource).toExternalForm(),
queryString = createCanonicalQueryString();
if(queryString != '') {
finalEndpoint += '?'+queryString;
}
request.setEndpoint(finalEndpoint);
for(String key: headerParams.keySet()) {
request.setHeader(key, headerParams.get(key));
}
String[] headerKeys = new String[0];
String stringToSign = createStringToSign(headerKeys);
request.setHeader(
'Authorization',
String.format(
'AWS4-HMAC-SHA256 Credential={0}, SignedHeaders={1},Signature={2}',
new String[] {
String.join(new String[] { accessKey, requestTime.formatGMT('yyyyMMdd'), region, service, 'aws4_request' },'/'),
String.join(headerKeys,';'), EncodingUtil.convertToHex(Crypto.generateMac('hmacSHA256', Blob.valueOf(stringToSign), signingKey))}
));
system.debug(json.serializePretty(request.getEndpoint()));
return request;
}
// Actually perform the request, and throw exception if response code is not valid
public HttpResponse sendRequest(Set<Integer> validCodes) {
HttpResponse response = new Http().send(createRequest());
if(!validCodes.contains(response.getStatusCode())) {
system.debug(json.deserializeUntyped(response.getBody()));
}
return response;
}
// Same as above, but assume that only 200 is valid
// This method exists because most of the time, 200 is what we expect
public HttpResponse sendRequest() {
return sendRequest(new Set<Integer> { 200 });
}
// TEST METHODS
public static string getEndpoint(string attribute){
AwsApiGateway api = new AwsApiGateway(attribute);
return api.createRequest().getEndpoint();
}
public static string getEndpoint(string attribute, map<string, string> params){
AwsApiGateway api = new AwsApiGateway(attribute);
for (string key: params.keySet()){
api.setQueryParam(key, params.get(key));
}
return api.createRequest().getEndpoint();
}
public class EndpointConfig {
string resource;
string attribute;
list<object> items;
map<string,string> params;
public EndpointConfig(string resource, string attribute, list<object> items){
this.items = items;
this.resource = resource;
this.attribute = attribute;
}
public EndpointConfig setQueryParams(map<string,string> parameters){
params = parameters;
return this;
}
public string endpoint(){
if (params == null){
return getEndpoint(resource);
} else return getEndpoint(resource + '/' + attribute, params);
}
public SingleRequestMock mockResponse(){
return new SingleRequestMock(200, 'OK', json.serialize(items), null);
}
}
}

WCF Forms Authentication authorization using ASP.NET roles = Access Denied?

I have a basic WPF application where the client writes to a database. I'm using IIS on a server 2012 machine to host the web service. I'm trying to implement Forms authentication, and I have all that working (passing a username and password in the xaml.cs from the client which authenticates my ASP.NET user which works. I then want to implement ASP.NET roles authorization for different commands (Submit Request, Remove Request, etc). The method we're supposed to use is "[PrincipalPermission(SecurityAction.Demand, Role = "Allowed")]"
In theory this should just use the credentials passed in the client (which I've confirmed works) when I try to hit the buttons and it should check if the user I passed is in the role, and if so it allows and if not it denies. However, whether or not the user is in the role it still says "Access is Denied".
Any thoughts?
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Security.Permissions;
using RequestRepository;
using System.Threading;
using System.Web;
namespace RequestServiceLibrary
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class RequestService : IRequestService
{
private List<Request> requests = new List<Request>();
private RequestLibraryEntities context = new RequestLibraryEntities();
[PrincipalPermission(SecurityAction.Demand, Role = "Allowed")]
public string SubmitRequest(Request req)
{
Thread.CurrentPrincipal = HttpContext.Current.User;
if (context.Requests.Count() == 0)
populateRequests();
req.Id = Guid.NewGuid().ToString();
req.TimeSubmitted = DateTime.Now;
requests.Add(req);
addRequest(req);
return req.Id;
}
[PrincipalPermission(SecurityAction.Demand, Role = "Allowed")]
public bool UpdateRequest(Request req)
{
Thread.CurrentPrincipal = HttpContext.Current.User;
bool returnval = false;
try
{
var getobject = requests.Find(x => x.Id.Equals(req.Id));
if (getobject != null) //checks to make sure the object isn't empty
{
getobject.Username = req.Username;
getobject.Password = req.Password;
getobject.RequestedResource = req.RequestedResource;
getobject.TimeSubmitted = req.TimeSubmitted;
}
//Find the request object in the database
var Id = Guid.Parse(req.Id);
var rl = context.Requests.Find(Id);
//Update that object with the values from req
rl.Username = req.Username;
rl.Password = req.Password;
rl.RequestedResource = req.RequestedResource;
rl.TimeTransmitted = req.TimeSubmitted;
context.SaveChanges();
returnval = true;
return returnval;
}
catch (Exception) { return returnval; }
}
public List<Request> GetRequests()
{
populateRequests();
return requests;
}
[PrincipalPermission(SecurityAction.Demand, Role = "Disallowed")]
public bool RemoveRequest(string id)
{
bool rval = false;
try
{
Request req = requests.Find(x => x.Id.Equals(id));
requests.Remove(req);
rval = delRequest(req);
return rval;
}
catch (Exception)
{
return false;
}
}
private void populateRequests()
{
requests = new List<Request>();
var rl = context.Requests.ToList();
foreach (var r in rl)
{
requests.Add(new Request()
{
Id = r.Id.ToString(),
Password = r.Password,
RequestedResource = r.RequestedResource,
TimeSubmitted = r.TimeTransmitted,
Username = r.Username
});
}
}
private void addRequest(Request req)
{
try
{
var r = context.Requests.Create();
r.Id = Guid.Parse(req.Id);
r.Username = req.Username;
r.Password = req.Password;
r.RequestedResource = req.RequestedResource;
r.TimeTransmitted = req.TimeSubmitted;
context.Requests.Add(r);
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
private bool delRequest(Request req)
{
Guid Id = Guid.Parse(req.Id);
var r = context.Requests.Create();
r.Id = Id;
var rl = context.Requests.Find(Id);
try
{
context.Requests.Remove(rl);
context.SaveChanges();
return true;
}
catch (Exception) { return false; }
}
}
}
In order to be able to use PrincipalPermissionAttribute in this way, you need to first set Thread.CurrentPrincipal to a Principal with the appropriate roles ("Allowed" in this case).
For example you could use ClientRoleProvider to do this, or simply create the Principal manually (possibly using roles you retrieve from the web service).

GetMessageCount() returns 0 (zero)

public class _Variable
{
public bool MailStat;
public Pop3Client pop3;
public int lastmailCount;
public int currentmailCount;
public Message msg;
public MessagePart msgPart;
public Timer _timer;
}
public List<int> _MailReader()
{
_Variable _var = new _Variable();
try
{
//HttpContext.Current.Session["Pop3Client"]
if (HttpContext.Current.Session["Pop3Client"] == null)
{
_var.pop3 = new Pop3Client();
_var.pop3.Connect("pop.gmail.com", 995, true);
_var.MailStat = _var.pop3.Connected;
_var.pop3.Authenticate("nithin.testing1#gmail.com", "xxxxxxx");
HttpContext.Current.Session["Pop3Client"] = _var.pop3;
}
else
{
_var.pop3 = (Pop3Client)HttpContext.Current.Session["Pop3Client"];
}
if (_var.MailStat)
{
//HttpContext.Current.Application["lastmailCount"] = _var.pop3.GetMessageCount();
_var.currentmailCount = _var.pop3.GetMessageCount();
_var.lastmailCount = _global.lastmailCount;
if (_var.lastmailCount < _var.currentmailCount)
{
_global.lastmailCount = _var.currentmailCount;
int _diff = _var.currentmailCount - _var.lastmailCount;
for (int _loop = _var.currentmailCount; _diff > 0; _diff--)
{
_var.msg = _var.pop3.GetMessage(_loop-(_diff-1));
_var.msgPart = _var.msg.MessagePart.MessageParts[0];
string bodyPart = _var.msgPart.BodyEncoding.GetString(_var.msgPart.Body).ToString().Trim();
int _result;
if (int.TryParse(bodyPart, out _result))
{
_global._vbill.Add(Int32.Parse(bodyPart));
_global._vDate.Add(_var.msg.Headers.DateSent.ToString());
}
}
}
}
_var.pop3.Dispose();
return _global._vbill;
}
catch (Exception ex)
{
return _global._vbill;
}
}
I am using the OpenPop.dll and In the following code pop.getMessageCount is returning zero even there are mails in my account.
_Variable method contains all the variables I used in the code and in _MailReader. I am just reading all my mails from my application and returning into a list but this is the problem count is zero always.
It's a feature of gmail pop3 server. By default, you can receive only unread messages. That means, if you or somebody else already has downloaded certain message once, it will not be possible to receive it by pop3 protocol anymore.
To avoid it, you have to configure your gmail account. Check "Enable POP for all mail (event mail that's already been downloaded)" in "Forwarding and POP/IMAP" section of gmail settings.
Screenshot: http://i.stack.imgur.com/UE7ip.png

Blackberry HttpConnection failure on device

I'm after some BlackBerry suggestions again. I'm developing a REST based app using the standard BB code that appends to the URI connection string (I'll post if you like but don't want to take up space here as I suspect that those of you that know about this know exactly what I mean).
The code works fine in the emulator in MDS mode and is good on the phone too with straight WiFi.
Now, the problem is when I come to use 3G on an actual phone. At that point it fails. Is this some kind of transcoding problem?
I'm using a raw HttpConnection.
An HTTP POST works (with body info) but the GET (which uses a cookie for auth purposes as a header requestproperty) fails.
The failure is only with header (GET) based info on non WiFi connections on the mobile device.
Any suggestions would be most appreciated.
public static String httpGet(Hashtable params, String uriIn) {
String result = null;
LoginDetails loginDetails = LoginDetails.getInstance();
HttpConnection _connection;
String uri = uriIn + "?api_key=" + loginDetails.getApi_key();
Enumeration e = params.keys();
// iterate through Hashtable keys Enumeration
while (e.hasMoreElements()) {
String key = (String) (e.nextElement());
String value = (String) params.get(key);
uri += "&" + key + "=" + value;
}
uri = uri + HelperMethods.getConnectionString();
try {
_connection = (HttpConnection) Connector.open(uri);
_connection.setRequestMethod(HttpConnection.GET);
_connection.setRequestProperty("Content-Type",
"text/plain; charset=UTF-8");
_connection.setRequestProperty("x-rim-authentication-passthrough",
"true");
_connection.setRequestProperty("Cookie", loginDetails.getCookie());
_connection.setRequestProperty("Content-Type", "application/json");
String charset = "UTF-8";
_connection.setRequestProperty("Accept-Charset", charset);
_connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream _outputStream = _connection.openOutputStream();
int rc = _connection.getResponseCode();
InputStream _inputStream = _connection.openInputStream();
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = _inputStream.read()) != -1) {
bytestream.write(ch);
}
result = new String(bytestream.toByteArray());
bytestream.close();
{
if (_outputStream != null)
try {
_outputStream.close();
} catch (Exception e1) {
}
if (_connection != null)
try {
_connection.close();
} catch (Exception e2) {
}
}
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
return result;
}
And this uses:
public synchronized static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Fixed - see above.
It turns out that there were spaces in the uri's.
Quite why this worked over WiFi & not 3G etc. is still puzzling.

Resources