How to send successfully push notification of APNS in production - iphone

How to send successfully push notification of APNS in production
When I use in development, it's work.
But use in production,it appear error.
My app is in App Store, so p12 file is production.
My server side is asp.net.
asp.net code:
//key
//True if you are using sandbox certificate, or false if using production
bool sandbox = false;
string p12File = "InspirePass.p12";
string p12Filename = System.IO.Path.Combine(MapPath("~"), p12File);
string p12FilePassword = "xxxxxxxx";
NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);
//send
foreach (DataRow eachUserRow in userTable.Rows)
{
//Create a new notification to send
if (eachUserRow["pushStatus"].ToString() == "N")
{ //////no repeat
Notification alertNotification = new Notification(eachUserRow["device_token"].ToString());
alertNotification.Payload.Alert.Body = eachUserRow["menuMessage"].ToString() + "(" + eachUserRow["menuTitle"].ToString() + ")";
alertNotification.Payload.Sound = "default";
alertNotification.Payload.Badge = selectEventPush_IOS.Rows.Count + selectSignPush_IOS.Rows.Count;
// alertNotification.Payload. = 1;
string[] items = new string[1];
string[] items2 = new string[1];
if (userTable.Rows.Count > 0)
{
items[0] = Convert.ToString(selectEventPush_IOS.Rows.Count);
items2[0] = Convert.ToString(selectSignPush_IOS.Rows.Count);
}
alertNotification.Payload.CustomItems.Add("items2", items2);
alertNotification.Payload.CustomItems.Add("items", items);
//Queue the notification to be sent
if (service.QueueNotification(alertNotification))
result = 1;
else
result = -1;
///////change chat_document/pushStatus=Y
string Identifier = "";
Identifier = eachUserRow["Identifier"].ToString();
DataRow yespushuser = DBiphone.UpdatedPushStatus(Identifier);
}
}//end if
service.Close();
service.Dispose();
Response.Write(result.ToString());

Related

CRM 2011, Stopping custom workflow programmatically

i've been trying to stop a workflow programmatically.
I've read both in various posts and in the msdn that this can be done by updating
the Asyncoperation status via update request.
However everytime i update the request. the workflow get stuck on a mid stage such as cancelling or pausing and dosen't reach a final state.
any ideas?
protected void ExecutePostAccountUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
string fetchXML = "<fetch mapping='logical' count='50' version='1.0'>" +
"<entity name='asyncoperation'>" +
"<filter>" +
"<condition attribute='regardingobjectid' operator='eq' value='" +
localContext.PluginExecutionContext.PrimaryEntityId + "' />" +
"</filter>" +
"</entity>" +
"</fetch>";
EntityCollection col = localContext.OrganizationService.RetrieveMultiple(new FetchExpression(fetchXML));
if (col.Entities.Count > 0)
{
AsyncOperation a = (AsyncOperation)col[0];
a.StateCode = AsyncOperationState.Completed;
a.StatusCode = new OptionSetValue(32);
localContext.OrganizationService.Update(a);
}
}
Have a look at my blog: How to Cancel Workflow Programmatically using C#
Make sure the user have permissions to Cancel System Jobs.
QueryExpression queryExpression = new QueryExpression("asyncoperation") { ColumnSet = new ColumnSet("statuscode") };
queryExpression.Criteria.AddCondition("name", ConditionOperator.Equal, Name of Workflow);
queryExpression.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, regardingobjectId);
var asyncOperations = organizationService.RetrieveMultiple(queryExpression);
foreach (var asyncOperation in asyncOperations.Entities)
{
if (((OptionSetValue)asyncOperation["statuscode"]).Value == 10 || // Waiting
((OptionSetValue)asyncOperation["statuscode"]).Value == 20 || // In Process
((OptionSetValue)asyncOperation["statuscode"]).Value == 0)
{
Entity operation = new Entity("asyncoperation")
{
Id = asyncOperation.Id,
["statecode"] = new OptionSetValue(3),
["statuscode"] = new OptionSetValue(32)
};
organizationService.Update(operation);
}
}
Make sure the user have permissions to Cancel System Jobs.
It seems you can un-publish a workflow via code, according to this post.
NOTE: This does not necessarily halt an in-progress workflow, but it will prevent any new workflows of that type from being started.
const int WorkflowStatusDraft = 1;
const int WorkflowStatusPublished = 2;
public void PublishWorkflow(Guid workflowId)
{
SetStateWorkflowRequest publishRequest = new SetStateWorkflowRequest();
publishRequest.EntityId = workflowId;
publishRequest.WorkflowState = WorkflowState.Published;
publishRequest.WorkflowStatus = WorkflowStatusPublished;
this.CrmService.Execute(publishRequest);
}
public void UnpublishWorkflow(Guid workflowId)
{
SetStateWorkflowRequest unpublishRequest = new SetStateWorkflowRequest();
unpublishRequest.EntityId = workflowId;
unpublishRequest.WorkflowState = WorkflowState.Draft;
unpublishRequest.WorkflowStatus = WorkflowStatusDraft;
this.CrmService.Execute(unpublishRequest);
}

Submitting a WebRequest from within a CLR Trigger

I just implemented a prototype solution for updating my caching server in real-time by assigning a CLR Trigger to a table so that whenever a certain column is updated the URL called from the trigger will update the caching server with the correct data.
It's working fine and the code is as follows:
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AdStatusChanged", Target = "Ads", Event = "FOR UPDATE")]
public static void AdStatusChanged()
{
SqlTriggerContext triggContext = SqlContext.TriggerContext;
int adID = 0, adStatusID_Old = 0, adStatusID_New = 0;
if (triggContext.TriggerAction == TriggerAction.Update)
{
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand sqlComm = new SqlCommand();
SqlPipe sqlP = SqlContext.Pipe;
sqlComm.Connection = conn;
sqlComm.CommandText = "SELECT AdID, AdStatusID from INSERTED";
SqlDataReader reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_New = reader.GetInt32(1);
}
reader.Close();
sqlComm.CommandText = "SELECT AdID, AdStatusID from DELETED WHERE AdID = " + adID;
reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_Old = reader.GetInt32(1);
}
}
if (adID == 0 || adStatusID_New == adStatusID_Old)
{
// Check could be more thorough !
return;
}
WebResponse httpResponse = null;
try
{
string apiURL = string.Format("{0}/{1}", "http://localhost:14003/Home", "UpdateAdStatus?adID=" + adID + "&adStatusID=" + adStatusID_New);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
httpWebRequest.Method = "GET";
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// check for successful response
}
catch (Exception ex)
{
Log("WebRequest from within SQL Server failed ! " + ex.Message);
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
I would like to have some expert/experienced views on the "CONS" of this approach regarding performance, deadlocks, sql crashing, or other areas that could be of potential concern.
Has anyone tried this (I'm sure many must have) and what was the result ? a successful implementation or did you revert to some other method or updating the cache real-time?

saving email attachments as binary to the database using c#

I can get email attachments from exchange server 2003 (MAPI.Attachment). How can I save the pdf attachment file as binary into the database?
Here's some code to understand better. For testing purposes I am saving the attachment pdf file into a filesystem. How ca I go about saving that into a database? Or how can I convert that into a byte array? Also, how can I get the size of the file since I need that when I declare the byte array "fileData"...
byte[] fileData = new byte[10000];
string[] fileTokens = new string[2];
string[] result = new string[3];
message.Unread = false;
emailSubject = message.Subject.ToString();
emailBody = message.Text.ToString();
MAPI.Attachments test = null;
test = (MAPI.Attachments)message.Attachments;
int attachmentCount = (int)test.Count;
for (int loopCounter = 1; loopCounter <= attachmentCount; loopCounter++)
{
MAPI.Attachment test2 = (MAPI.Attachment)test.get_Item(loopCounter);
bool temp = (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0);
if (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0)
{
//test2.ReadFromFile(fileData);
test2.WriteToFile("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
}
RequestHistorySet historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);
bool res = historySet.Update();
message.Unread = false;
message.Update();
And here's the Update function from historySet Class
public bool Update()
{
using (SqlConnection mySqlConnection = ...))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("CONNECTION STRING..", mySqlConnection);
// Set up the OriginalName parameter
SqlParameter prmId = new SqlParameter("#id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
SqlParameter prmRequsetDate = new SqlParameter("#requestDate", SqlDbType.DateTime);
prmRequsetDate.Value = requestDate;
myCommand.Parameters.Add(prmRequsetDate);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("#uplodedQuote_File ", SqlDbType.VarBinary);
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
myCommand.Parameters.Add(prmFileData);
SqlParameter prmFileExtension = new SqlParameter("#uplodedQuote_Ext", SqlDbType.NVarChar);
prmFileExtension.Value = fileExtension;
myCommand.Parameters.Add(prmFileExtension);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
return result;
}
}
As of now this is what I have done. I save it to a filesystem and then read from there.
test2.WriteToFile("d:\\data\\" + test2.Name);
fileData = FileToByteArray("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
TryToDelete("d:\\data\\" + test2.Name);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);

Using CRM 4.0 SDK to send emails to multiple contacts at once

Is it possible to send out an email with multiple email addresses specified in the "to" field? I have it working for single recipients, but can't figure out how to send to multiple, here is my current code for emailing a single user:
public static void sendCRMNotification(string userGuid, string emailSubject, string emailBody, string recipientType)
{
//Set up CRM service
crmService crmservice = GetCrmService();
// Create a FROM activity party for the email.
activityparty fromParty = new activityparty();
fromParty.partyid = new Lookup();
fromParty.partyid.type = EntityName.systemuser.ToString();
fromParty.partyid.Value = new Guid(/*guid of sending user*/);
//Create a TO activity party for email
activityparty toParty = new activityparty();
toParty.partyid = new Lookup();
toParty.partyid.type = EntityName.contact.ToString();
toParty.partyid.Value = new Guid(userGuid);
//Create a new email
email emailInstance = new email();
//set email parameters
emailInstance.from = new activityparty[] { fromParty };
emailInstance.to = new activityparty[] { toParty };
emailInstance.subject = emailSubject;
emailInstance.description = emailBody;
//Create a GUId for the email
Guid emailId = crmservice.Create(emailInstance);
//Create a SendEmailRequest
SendEmailRequest request = new SendEmailRequest();
request.EmailId = emailId;
request.IssueSend = true;
request.TrackingToken = "";
//Execute request
crmservice.Execute(request);
}
This is what I have done in the past. Create the array in the beginning before you set it to the email property.
activityparty[] toParty = new activityparty[2];
toParty[0] = new activityparty();
toParty[0].partyid = new Lookup(EntityName.contact.ToString(), userGuid);
toParty[1] = new activityparty();
toParty[1].partyid = new Lookup(EntityName.contact.ToString(), anotherUserGuid);
emailMessage.to = toParty;

Iphone push notification issue

I am working on iphone push notification. I can able to get my device token. I am using .net for pushing json data. But the issue is i cant get the notification. I just want to know whether .net has to push json data over in hosted machine?
Regards,
sathish
I believe that is related to:
Add iPhone push notification using ASP.NET server
Read through the linked project in there. It is pretty comprehensive. You can actually just use that library... it is pretty good.
Unless I misunderstood the question?
Use following snippet to send Push Notification
public void PendingNotification(string DeviceToken,string message)
{
try
{
int port = 2195;
//Developer
String hostname = "gateway.sandbox.push.apple.com";
//Production
//String hostname = "gateway.push.apple.com";
String certificatePassword = "XXXXXXX";
string certificatePath = Server.MapPath("~/cer.p12");
TcpClient client = new TcpClient(hostname, port);
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certificatePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
//String DeviceToken = "XXXXXXXXXXXX";
String LoginName = "Name";
int Counter = 1; //Badge Count;
String Message = message;
String UID = "your choice UID";
string payload = "{\"aps\":{\"alert\":\"" + Message + "\",\"badge\":" + Counter + ",\"sound\":\"default\"},\"UID\":\"" + UID + "\",\"LoginName\":\"" + LoginName + "\"}";
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(DeviceToken.ToUpper()));
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
public static byte[] HexStringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false;
}