public bool ConnectToAPNS(PushData objPush) { try { string p12Certificate = "WizzDevelopement.p12"; #if DEBUG // p12Certificate = "WizzProductioncert.p12"; #else p12Certificate = "WizzProductioncert.p12"; #endif string p12fileName = p12Certificate; string password = "******"; X509Certificate2Collection certs = new X509Certificate2Collection(); // Add the Apple cert to our collection certs.Add(getServerCert(p12fileName, password)); string apsHost; if (getServerCert(p12fileName, password).ToString().Contains("Production")) apsHost = "gateway.push.apple.com"; // Port= Convert.ToInt32("2195") else apsHost = "gateway.sandbox.push.apple.com"; TcpClient tcpClient = new TcpClient(apsHost, 2195); // Connect(); // Create a TCP socket connection to the Apple server on port 2195 // Create a new SSL stream over the connection sslStream = new SslStream(tcpClient.GetStream()); // Authenticate using the Apple cert sslStream.AuthenticateAsClient(apsHost, certs, SslProtocols.Default, false); //6455903fb51593b5fb930ab8184e39c5ec83b57503e6589596d463ddb4b1d835 Int32 messa = objPush.message.Length; if (messa < 256) { Boolean send = PushMessage(objPush); return send; } else { throw new Exception("Message not exeed 256 character"); } } catch (Exception ex) { return false; // throw new Exception(ex.Message); } }
///this method will called once in a day internal void ChorneJob() { using (var db = new WizzDataContext()) { var tutorList = db.usp_GetPendingRequest().ToList(); if(tutorList!=null&&tutorList.Count>0) { foreach(var item in tutorList ) { if(!string.IsNullOrEmpty(item.devicetoken)) { PushData push = new PushData(); push.registration_ids = item.devicetoken; push.badge = Convert.ToString(item.badge); push.message = PushMessages.cron; if(item.devicetype==Convert.ToInt16(DeviceType.ios)) { SendPush objIOS = new SendPush(); objIOS.ConnectToAPNS(push); } else if (item.devicetype == Convert.ToInt16(DeviceType.android))//android { Android objAndroid = new Android(); objAndroid.send(push); } } } } } }
//internal bool AcceptStudent(StudentTeacherMap objReq) //{ // // var isTutor = Convert.ToBoolean(objReq.userId); // using (var db = new WizzDataContext()) // { // if (objReq.isAccept.ToLower() == "true") // { // tblRequest reqStudent = new tblRequest(); // var studentList = db.tblRequestStudents.Where(x => x.isAccepted != true && x.isDelete == false && x.uniqueRequestId == objReq.uniqueRequestId && x.fkUserId == Convert.ToInt32(objReq.tutorId)).ToList(); // studentList.ForEach(a => { a.isAccepted = true; a.updatedDate = DateTime.UtcNow; }); // db.SubmitChanges();//update student request // var totalList = db.tblRequests.Where(x => x.isAccepted != true && x.uniqueRequestId == objReq.uniqueRequestId && x.fkStudentId==Convert.ToInt32(objReq.studentId)).ToList(); // var deleteList = totalList.Where(x => x.fkTutorId != Convert.ToInt32(objReq.tutorId)).ToList(); // //delete all tutors who recived the notiifcation except the tutor who is accepeting the notification // reqStudent = totalList.Where(x => x.fkTutorId == Convert.ToInt32(objReq.tutorId)).FirstOrDefault(); // db.tblRequests.DeleteAllOnSubmit(deleteList); // db.SubmitChanges(); // //accept the request // if (reqStudent == null)//if request is not exist // return false; // reqStudent.isAccepted = true; // reqStudent.updatedDate = DateTime.UtcNow; // var userData = db.tblUsers.Where(x => x.pkUserId == Convert.ToInt32(objReq.studentId)&& x.isTeacher==false).FirstOrDefault(); // var teacherData = db.tblUsers.Where(x => x.pkUserId == Convert.ToInt32(objReq.tutorId)).FirstOrDefault(); // if (userData!=null &&!string.IsNullOrEmpty(userData.deviceToken)) // { // // objPush.type = Convert.ToInt16(PushType.acceptRequest).ToString(); // PushData push = new PushData() // { // registration_ids = userData.deviceToken, // //push.data = CommonMethod.ObjectToJson(objPush); // message = PushMessages.FormatMessage(PushMessages.acceptRequest, teacherData.userName), // type = Convert.ToInt16(PushType.acceptRequest).ToString(), // badge = Convert.ToString(userData.badge) // }; // if (userData.deviceType == Convert.ToInt16(DeviceType.ios))//ios // { // SendPush objIOS = new SendPush(); // objIOS.ConnectToAPNS(push); // } // else if (userData.deviceType == Convert.ToInt16(DeviceType.android))//android // { // Android objAndroid = new Android(); // objAndroid.send(push); // } // } // // update tblrequest by isAccept=1 and delete rest of request // } // else // { // var objRequestData = db.tblRequests.Where(x => x.isAccepted == false && x.fkTutorId ==Convert.ToInt32(objReq.tutorId) && x.uniqueRequestId==objReq.uniqueRequestId).FirstOrDefault(); // if (objRequestData != null) // { // db.tblRequests.DeleteOnSubmit(objRequestData); // db.SubmitChanges(); // } // else { // return false; // } // } // db.SubmitChanges(); // return true; // } //} #endregion internal bool SendPushForIos(IosPushModel push) { tblUser receiverData = new tblUser(); using (var db = new WizzDataContext()) { receiverData = db.tblUsers.Where(c => c.pkUserId == Convert.ToInt32(push.receiverId)).FirstOrDefault(); var sendor = db.tblUsers.Where(c => c.pkUserId == Convert.ToInt32(push.senderId)).FirstOrDefault(); // objPush.deviceToken = receiverData.deviceToken; PushData objPush = new PushData() { message = sendor.userName + ": " + push.Message, type = Convert.ToInt16(PushType.chatPush).ToString(), messageType=push.Type, userId=push.senderId, subject=push.subjectName, registration_ids = receiverData.deviceToken, badge = Convert.ToString(receiverData.badge), uniqueRequestid=push.requestId }; // push.type = PushType.newRequest.ToString(); // push.data = CommonMethod.ObjectToJson(objPush); // push.Type =push.Type; // push.messageId = push.messageId; // push.Message = push.Message; // push.senderName=push if (receiverData.deviceType == 1)//ios { SendPush objIOS = new SendPush(); objIOS.ConnectToAPNS(objPush); } else if (receiverData.deviceType == 2)//android { PushForIos objAndroid = new PushForIos(); objAndroid.SendPushForIos(push); } } return true; ///throw new NotImplementedException(); }
//internal int SaveTutorSubjects(TutorSubjects objReq) //{ // tblTutorSubject objSubjectData = new tblTutorSubject(); // using (var db = new WizzDataContext()) // { // objSubjectData = db.tblTutorSubjects.Where(x => x.fkTutorId == Convert.ToInt64(objReq.tutorId)).FirstOrDefault(); // if (objSubjectData == null) // { // //objSubjectData = new TutorSubjects(); // //objSubjectData.isApproved = true; // //objSubjectData.isActive = true; // //objSubjectData.fkUserId = Convert.ToInt64(objReq.userId); // //objSubjectData.latitude = Convert.ToDecimal(objReq.latitude); // //objSubjectData.longitude = Convert.ToDecimal(objReq.longitude); // //objSubjectData.subjects = objReq.majors; // //objSubjectData.TimeStamp = Convert.ToDateTime(objReq.timeStamp).Ticks; // //objSubjectData.updatedDate = DateTime.UtcNow; // //objSubjectData.createdDate = DateTime.UtcNow; // //objSubjectData.passingYear = objReq.passingYear; // //objSubjectData.referralcode = objReq.referalCode == null ? "" : objReq.referalCode; // //// profileData.fkClassId = String.Join(",", objReq.classes); // //objSubjectData.fkCollegeId = Convert.ToInt32(objReq.collegeId); // //db.tblTutorProfiles.InsertOnSubmit(objSubjectData); // } // else // { // //objSubjectData.isApproved = true; // //objSubjectData.isActive = true; // //objSubjectData.fkUserId = Convert.ToInt64(objReq.userId); // //objSubjectData.latitude = Convert.ToDecimal(objReq.latitude); // //objSubjectData.longitude = Convert.ToDecimal(objReq.longitude); // //objSubjectData.subjects = objReq.majors; // //objSubjectData.TimeStamp = Convert.ToDateTime(objReq.timeStamp).Ticks; // //objSubjectData.updatedDate = DateTime.UtcNow; // //objSubjectData.createdDate = DateTime.UtcNow; // //// profileData.fkClassId = String.Join(",", objReq.classes); // //objSubjectData.fkCollegeId = Convert.ToInt32(objReq.collegeId); // } // db.SubmitChanges(); // return 1; // } //} //save matched tutos in db and send notifications void SendRequest(StudentRequestModel objReq,List<usp_GetTutorsResult> tutors,string requestId) { var studentId =Convert.ToInt64(objReq.userId); using(var db=new WizzDataContext()) { foreach (var tutor in tutors.ToList()) { var request = new tblRequest(); request.createdDate = DateTime.UtcNow; request.updatedDate = DateTime.UtcNow; request.isAccepted = false; request.isDeleted = false; request.fkStudentId = studentId; request.fkTutorId = tutor.fkUserId; request.uniqueRequestId = requestId; request.timeStamp = DateTime.UtcNow.Ticks; db.tblRequests.InsertOnSubmit(request); db.SubmitChanges(); //sendpush if(!string.IsNullOrEmpty(tutor.deviceToken)) { PushData push=new PushData() { registration_ids = tutor.deviceToken, message = PushMessages.newRequest, type = Convert.ToInt16(PushType.newRequest).ToString(), badge = Convert.ToString(tutor.badge) }; // push.data = CommonMethod.ObjectToJson(objPush); if (tutor.deviceType == Convert.ToInt16(DeviceType.ios))//ios { SendPush objIOS=new SendPush(); objIOS.ConnectToAPNS(push); } else if (tutor.deviceType == Convert.ToInt16(DeviceType.android))//android { Android objAndroid = new Android(); objAndroid.send(push); } } } } }
public string SendMessageDemo(string RegistrationID, PushMessage Message, string AuthString) { //-- Create GCM Web Request Object --// HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send"); Request.Method = "POST"; Request.KeepAlive = false; Request.ContentType = "application/json"; PushData msg = new PushData(); msg.registration_ids = RegistrationID; msg.message = "testing"; //message.data.Add("gcm_message", "12345"); var jsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(msg); byte[] byteArray = Encoding.UTF8.GetBytes(jsonMessage); Request.ContentLength = byteArray.Length; Request.Headers.Add(HttpRequestHeader.Authorization, "AIzaSyChZCTQ0seSaeTmgkC4zltqQDhGWCYyIXQ"); //-- Delegate Modeling to Validate Server Certificate --// ServicePointManager.ServerCertificateValidationCallback += delegate( object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors) { return true; }; //-- Create Stream to Write Byte Array --// Stream dataStream = Request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //-- Post a Message --// WebResponse Response = Request.GetResponse(); HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode; if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden)) { return "Unauthorized - need new token"; } else if (!ResponseCode.Equals(HttpStatusCode.OK)) { return "Response from web service isn't OK"; } StreamReader Reader = new StreamReader(Response.GetResponseStream()); string responseLine = Reader.ReadLine(); Reader.Close(); return responseLine; }
///// <summary> ///// Send Push Message to Device ///// </summary> ///// <param name="RegistrationID">RegistrationID or Token</param> ///// <param name="Message">Message to be sent on device</param> ///// <param name="AuthString">Authentication string</param> ///// //public string send(PushMessage objPush,string type) //{ // // msg = "order confirmed"; // WebRequest tRequest; // tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send"); // tRequest.Method = "post"; // tRequest.ContentType = "application/x-www-form-urlencoded"; // string resistrationId = objPush.registration_ids; // var key=""; // key=ConfigurationManager.AppSettings["androidPushKey"]; // tRequest.Headers.Add(string.Format("Authorization: key={0}", key)); // String collaspeKey = Guid.NewGuid().ToString("n"); // string messagetosend = "{\"aps\":{\"alert\":\"" + objPush.message + "\",\"badge\":\"1\",\"sound\":\"default\",\"Tag\":" + objPush.type + ",\"notificationId\":" + objPush.notificationId + "}}"; // String postData = string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", resistrationId, "" + messagetosend, collaspeKey); // Byte[] byteArray = Encoding.UTF8.GetBytes(postData); // tRequest.ContentLength = byteArray.Length; // Stream dataStream = tRequest.GetRequestStream(); // dataStream.Write(byteArray, 0, byteArray.Length); // dataStream.Close(); // WebResponse tResponse = tRequest.GetResponse(); // dataStream = tResponse.GetResponseStream(); // StreamReader tReader = new StreamReader(dataStream); // String sResponseFromServer = tReader.ReadToEnd(); // tReader.Close(); // dataStream.Close(); // tResponse.Close(); // return sResponseFromServer; //} /// <summary> /// Send Push Message to Device /// </summary> /// <param name="RegistrationID">RegistrationID or Token</param> /// <param name="Message">Message to be sent on device</param> /// <param name="AuthString">Authentication string</param> /// public string send(PushData objPush) { tblUser objuser; try { // msg = "order confirmed"; WebRequest tRequest; tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/x-www-form-urlencoded"; string resistrationId = objPush.registration_ids; string sessionId = objPush.uniqueRequestid; var key = ""; Int16 iBadge = 0; using (var db = new WizzDataContext()) { int bedge = 0; try { bedge = Convert.ToInt32(db.tblUsers.FirstOrDefault(S => S.deviceToken == resistrationId).badge); } catch { bedge = 0; } if (bedge == 0) { iBadge = 1; } else { objuser = db.tblUsers.First(S => S.deviceToken == resistrationId); if (objuser != null) { Int16 addbedge = Convert.ToInt16(objuser.badge + 1); iBadge = addbedge; } } } key = ConfigurationManager.AppSettings["androidPushKey"]; tRequest.Headers.Add(string.Format("Authorization: key={0}", key)); String collaspeKey = Guid.NewGuid().ToString("n"); string messagetosend = "{\"aps\":{\"alert\":\"" + objPush.message + "\",\"badge\":\"" + iBadge.ToString() + "\",\"sound\":\"default\",\"type\":\"" + objPush.type + "\",\"sessionId\":\"" + objPush.sessionId + "\",\"tutorId\":\"" + objPush.tutorId + "\",\"uniqueRequestid\":\"" + objPush.uniqueRequestid + "\",\"userId\":\"" + objPush.userId + "\",\"amount\":\"" + objPush.amount + "\"}}"; String postData = string.Format("registration_id={0}&data.payload={1}&collapse_key={2}&sessionId={3}&amount={3}", resistrationId, "" + messagetosend, collaspeKey, objPush.uniqueRequestid,objPush.amount); Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); String sResponseFromServer = tReader.ReadToEnd(); tReader.Close(); dataStream.Close(); tResponse.Close(); using (var db = new WizzDataContext()) { objuser = db.tblUsers.FirstOrDefault(S => S.deviceToken == objPush.registration_ids); if (objuser != null) { objuser.badge = iBadge; db.SubmitChanges(); } } return sResponseFromServer; } catch (Exception ex) { return null; } }
private void SendSessionEndPushes(string sessionAmt, string uniqueRequestid, WizzDataContext db, long studentId, long sessionId, long tutorId) { var sessionStudents = db.tblInviteFriends.Where(x => x.uniqueRequestId == uniqueRequestid).ToList(); if (sessionStudents != null) { if (sessionStudents.Count == 0) { var studentData = db.tblUsers.Where(x => x.pkUserId == studentId).FirstOrDefault();//missed is tutor intentionally if (!string.IsNullOrEmpty(studentData.deviceToken)) { PushData push = new PushData() { registration_ids = studentData.deviceToken, uniqueRequestid = uniqueRequestid.ToString(), sessionId = sessionId.ToString(), tutorId = tutorId.ToString(), amount = Convert.ToString(sessionAmt), // userId = Convert.ToString(sessionData.fkTutorId), message = PushMessages.sessionEnd, type = Convert.ToInt16(PushType.sessionEnd).ToString(), badge = Convert.ToString(studentData.badge) }; // push.data = CommonMethod.ObjectToJson(objPush); if (studentData.deviceType == Convert.ToInt16(DeviceType.ios))//ios { SendPush objIOS = new SendPush(); objIOS.ConnectToAPNS(push); } else if (studentData.deviceType == Convert.ToInt16(DeviceType.android))//android { Android objAndroid = new Android(); objAndroid.send(push); } } } else { #region multiple pushes foreach (var n in sessionStudents) { if (n.fkFriendId == 0) continue; var studentData = db.tblUsers.Where(x => x.pkUserId == n.fkFriendId).FirstOrDefault();//missed is tutor intentionally if (!string.IsNullOrEmpty(studentData.deviceToken)) { PushData push = new PushData() { registration_ids = studentData.deviceToken, uniqueRequestid = uniqueRequestid.ToString(), amount = Convert.ToString(sessionAmt), // userId = Convert.ToString(sessionData.fkTutorId), message = PushMessages.sessionEnd, type = Convert.ToInt16(PushType.sessionEnd).ToString(), badge = Convert.ToString(studentData.badge), sessionId = sessionId.ToString() }; // push.data = CommonMethod.ObjectToJson(objPush); if (studentData.deviceType == Convert.ToInt16(DeviceType.ios))//ios { SendPush objIOS = new SendPush(); objIOS.ConnectToAPNS(push); } else if (studentData.deviceType == Convert.ToInt16(DeviceType.android))//android { Android objAndroid = new Android(); objAndroid.send(push); } } } #endregion } } }
public Response<string> SendPush(push objReq) { Response<string> response = new Response<string>(); List<string> objResp = new List<string>(); try { if (CheckRequestIsvalidornot(this.Request)) { if (!string.IsNullOrEmpty(objReq.deviceToken)) { PushMessage objPush = new PushMessage(); objPush.message = PushMessages.newRequest; // objPush.type = PushType.newRequest.ToString(); PushData push = new PushData(); push.message = "Testing"; push.registration_ids = objReq.deviceToken; // push.data = CommonMethod.ObjectToJson(objPush); push.type = Convert.ToInt16(PushType.acceptRequest).ToString(); if (objReq.deviceType == "1")//ios { SendPush objIOS = new SendPush(); objIOS.ConnectToAPNS(push); } else if (objReq.deviceType == "2")//android { Android objAndroid = new Android(); objAndroid.send(push); } } else response.Create(false, ModelState.Values.FirstOrDefault().Errors.FirstOrDefault().ErrorMessage, Messages.AppVersion, objResp); } else response.Create(false, Messages.FormatMessage(Messages.InvalidReq), Messages.AppVersion, objResp); } catch (Exception ex) { object session = new JavaScriptSerializer().Serialize(objReq); LogManager.Error("Error occured while Processing Webservice request :{0}", ex, session, ex.Message); response.Create(false, Messages.FormatMessage(Messages.ErrorOccure), Messages.AppVersion, objResp); } finally { } return response; }
public bool PushMessage(PushData objPush) { try { String cToken = objPush.registration_ids; // String cAlert = objPush.data; Int16 iBadge = 0; using(var db=new WizzDataContext()) { Int16 bedge = 0; try { bedge = Convert.ToInt16(db.tblUsers.FirstOrDefault(S => S.deviceToken == cToken).badge); } catch { bedge = 0; } if (bedge == 0) { iBadge = 1; } else { tblUser objuser = new tblUser(); objuser = db.tblUsers.First(S => S.deviceToken == cToken); if (objuser != null) { Int16 addbedge = Convert.ToInt16(objuser.badge + 1); iBadge = addbedge; } } } // Ready to create the push notification byte[] buf = new byte[256]; MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(new byte[] { 0, 0, 32 }); byte[] deviceToken = HexToData(cToken); bw.Write(deviceToken); bw.Write((byte)0); // Create the APNS payload - new.caf is an audio file saved in the application bundle on the device //string msg = "{\"aps\":{\"alert\":\"" + cAlert + "\",\"badge\":" + iBadge.ToString() + ",\"sound\":\"default\",\"Tag\":\"" + tag + "\"}}"; // string msg = "{\"aps\":{\"alert\":\"" + objPush.message + "\",\"badge\":\"1\",\"sound\":\"default\",\"type\":" + objPush.type + ",\"sessionId\":" + objPush.sessionId + ",\"userId\":" + objPush.userId + ",\"amount\":" + objPush.amount + "}}"; string msg = "{\"aps\":{\"alert\":\"" + objPush.message + "\",\"badge\":" + iBadge + ",\"sound\":\"default\",\"type\":\"" + objPush.type + "\",\"sessionId\":\"" + objPush.sessionId + "\",\"uniqueRequestId\":\"" + objPush.uniqueRequestid + "\",\"userId\":\"" + objPush.userId + "\",\"tutorId\":\"" + objPush.tutorId + "\",\"amount\":\"" + objPush.amount + "\",\"subject\":\"" + objPush.subject + "\",\"messageType\":\"" + objPush.messageType + "\"}}"; // Write the data out to the stream bw.Write((byte)msg.Length); bw.Write(msg.ToCharArray()); bw.Flush(); if (sslStream != null) { sslStream.Write(ms.ToArray()); tblUser objuser = new tblUser(); using (var db = new WizzDataContext()) { objuser = db.tblUsers.FirstOrDefault(S => S.deviceToken == cToken); if (objuser != null) { objuser.badge = iBadge; db.SubmitChanges(); } } return true; } return false; } catch (Exception ex) { throw new Exception(ex.Message); } }