Specific message makes Push Sharp ApplePushService stop working - c#

I am implementing push notifications using push sharp and I have 2 types of messages I am sending RecomendationLiked and NewFollower, I can send RecomendationLiked messages as much as I want and everything works fine but sending a single NewFollower message simpley causes the service to stop responding with no exception, or any of the events called. This happens both in Production and in Development environment
Here is the service creation logic:
private void InitApplePushService()
{
try
{
string appDataPath = HttpContext.Current.Server.MapPath("~/app_data");
//***** Development Server *****//
string file = Path.Combine(appDataPath, "PushSharp.PushCert.Development.p12");
var appleCert = File.ReadAllBytes(file);
_applePushService = new ApplePushService(new ApplePushChannelSettings(false, appleCert, "XXX"));
_applePushService.OnChannelCreated += OnChannelCreated;
_applePushService.OnChannelDestroyed += OnChannelDestroyed;
_applePushService.OnChannelException += OnChannelException;
_applePushService.OnDeviceSubscriptionChanged += OnDeciveSubscriptionChanged;
_applePushService.OnDeviceSubscriptionExpired += OnDeviceSubscriptionExpired;
_applePushService.OnNotificationFailed += OnNorificationFailed;
_applePushService.OnNotificationRequeue += OnNotificationQueued;
_applePushService.OnNotificationSent += OnNOtificationSend;
_applePushService.OnServiceException += OnServiceException;
Trace.TraceInformation("ApplePushService initialized succesfully");
}
catch (Exception e)
{
Trace.TraceError("Error initializing ApplePushService : " + e);
throw;
}
}
RecomendationLiked message creation:
private void SendRecomendationLikedMessageToAppleDevice(User likingUser, Recomendation recomendation)
{
var notification = new AppleNotification();
notification.DeviceToken = recomendation.User.PushNotificationID;
notification.Payload.Alert.LocalizedKey = "NewLikeNotification";
notification.Payload.Alert.LocalizedArgs = new List<object> { likingUser.NickName };
notification.Payload.Sound = "default";
notification.Payload.AddCustom("LikingUser", likingUser.NickName);
notification.Payload.AddCustom("AlertType", "RecomendationLiked");
notification.Payload.AddCustom("ID", likingUser.ID);
notification.Payload.AddCustom("ImageUrl", likingUser.ImageUrl);
_applePushService.QueueNotification(notification);
}
NewFollower message creation:
private void SendNewFollowingUserMessageToAppleDevice(User followingUser, User followedUser)
{
var notification = new AppleNotification();
notification.DeviceToken = followedUser.PushNotificationID;
notification.Payload.Alert.LocalizedKey = "NewFollowingUserNotification";
notification.Payload.Alert.LocalizedArgs = new List<object> { followingUser.NickName };
notification.Payload.Sound = "default";
notification.Payload.AddCustom("followingUser", followingUser.NickName);
notification.Payload.AddCustom("AlertType", "NewFollowingUser");
notification.Payload.AddCustom("ID", followingUser.ID);
notification.Payload.AddCustom("ImageUrl", followingUser.ImageUrl);
Trace.TraceInformation("Trying to send notifications: "+ notification);
_applePushService.QueueNotification(notification);
//_pushService.QueueNotification(notification);
}
The first one works, the second kills the push service silently...
Any ideas?

Solved it finally...
The issue is with the length of the json string that is generated. it seems that the maximum is 255 chars. anything higher and it fails silently...
beware.
Amit

Related

Consume EventArgs from CouchDB

i am struggling with consuming the data i get from my CouchDB database.
I am trying to consume new data that comes to the specific view.
CouchDB offers an option for feed=continous, but i tested it and dont get any data, same in postman.
But if i change it to feed=eventsource i can see the changes in the console. But i dont know how to handle the events.
I opened a method with the right connection, but im stuck now, any help would be great.
public async Task ObserveDbAndTrigger()
{
var url = "http://localhost:5984/MyDB/_changes?feed=eventsource&filter=_view&view=MyView&include_docs=true&attachments=true&heartbeat=1000&since=0";
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"user:password" + $"")));
var request = new HttpRequestMessage(HttpMethod.Get, url);
// handle the incoming events and work with the incoming data
}
}
Any suggestions ?
Clearly there's work to be done. Normally I shy away from answering such questions as posed because it seems like a code service request, but I believe this answer may benefit others beyond the OP.
Here is an extremely naïve bit of code meant to illustrate event delegation and the simplicity of communicating with CouchDB over TCP.
Ultimately this demonstrates the publish/subscribe pattern, which is a reasonable fit. I tested this against CouchDB 2.3 on Windows. The code is hardwired to localhost:5984 because whatever.
class NaiveChangeWatcher
{
static void Main(string[] args)
{
if (args.Length >= 4)
{
// set up server info.
string db = args[0];
string auth = "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(String.Join(":", args[1], args[2])));
string query = db + "/_changes?feed=continuous&since=0&heartbeat=" + args[3];
// init the publisher
ChangesPublisher pub = new ChangesPublisher();
// let's subscribe to the OnChange event which writes event data to the console.
pub.OnChange += (sender, e) => Console.WriteLine(e.Value);
pub.OnException += (sender, e) => Console.WriteLine(e.Value.ToString() + "\r\n\r\nPress a key to exit.");
//// start publishing.
Task.Run(async () =>
{
await pub.Begin("localhost", 5984, query, auth, int.Parse(args[3]));
});
// Press a key when bored of it all
Console.ReadKey();
// stop the publisher gracefully
pub.Stop = true;
}
else
{
Console.WriteLine("usage: NaiveChangeWatcher db_name username password timeout_millis");
}
}
//
// The ChangesPublisher notifies subscribers of new data from the changes feed
// via the ChangeEvent. The publisher will trigger an OnException event in the
// event of an exception prior to ending its task.
//
public class ChangesPublisher
{
// Set to true to stop publishing. This causes the Begin method to complete.
public bool Stop { get; set; }
// The event posted when data from the server arrived
public class ChangeEvent : EventArgs
{
public string Value { get; set; }
public ChangeEvent(string value)
{
Value = value;
}
}
// Event triggered when the subscriber croaks by exception
public class ExceptionEvent : EventArgs
{
public Exception Value { get; set; }
public ExceptionEvent(Exception value)
{
Value = value;
}
}
// Subscription to changes from the _changes endpoint
public event EventHandler<ChangeEvent> OnChange = delegate { };
// Subscription to publisher exit on error
public event EventHandler<ExceptionEvent> OnException = delegate { };
public async Task Begin(string serverAddr, int port, string query, string auth, int timeout)
{
using (var client = new TcpClient())
{
string request = String.Join("\r\n", new List<string> {
String.Format("GET /{0} HTTP/1.1",query),
"Authorization: " + auth,
"Accept: application/json",
"Host: " + serverAddr,
"Connection: keep-alive",
"\r\n"
});
try
{
await client.ConnectAsync(serverAddr, port);
using (NetworkStream stream = client.GetStream())
{
StreamWriter writer = new StreamWriter(stream);
await writer.WriteAsync(request);
await writer.FlushAsync();
// read lines from the server, ad nauseum.
StreamReader reader = new StreamReader(stream);
while (!Stop)
{
string data = await reader.ReadLineAsync();
// emit a change event
OnChange(this, new ChangeEvent(data));
}
}
}
catch (Exception e)
{
OnException(this, new ExceptionEvent(e));
}
}
}
}
}

Send Voip Push On development but not on production

i Am Using JsSoft.Apple.Apns.Notification . When i do sandbox= true. it works fine but when i change into false Notification is not received. also i No error will be arise. Please Tell Me what i missed or Doing wrong?
Apple .p12 Certificate is Created for Production.
here is the Code. or (https://github.com/Redth/APNS-Sharp).
using System;
using System.Collections.Generic;
using System.Text;
using JdSoft.Apple.Apns.Notifications;
namespace JdSoft.Apple.Apns.Test
{
class Program
{
[STAThread]
static void Main(string[] args)
{
//Variables you may need to edit:
//---------------------------------
//True if you are using sandbox certificate, or false if using production
bool sandbox = false;
//Put your device token in here
string testDeviceToken = "7e6baf66c0a908f65e15b9575dd04c291021b7b77079624223b39cd053d38c26";
//Put your PKCS12 .p12 or .pfx filename here.
// Assumes it is in the same directory as your app
string p12File = #"C:\Users\Nouman\source\repos\AsteriskComunicationApi\AsteriskComunicationApi\p12File\VOIP_iOS_New.p12";
//This is the password that you protected your p12File
// If you did not use a password, set it as null or an empty string
string p12FilePassword = "12345678";
//Number of notifications to send
int count = 3;
//Number of milliseconds to wait in between sending notifications in the loop
// This is just to demonstrate that the APNS connection stays alive between messages
int sleepBetweenNotifications = 3000;
//Actual Code starts below:
//--------------------------------
string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);
NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);
service.SendRetries = 5; //5 retries before generating notificationfailed event
service.ReconnectDelay = 5000; //5 seconds
service.Error += new NotificationService.OnError(service_Error);
service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);
service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);
service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
service.Connecting += new NotificationService.OnConnecting(service_Connecting);
service.Connected += new NotificationService.OnConnected(service_Connected);
service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);
//The notifications will be sent like this:
// Testing: 1...
// Testing: 2...
// Testing: 3...
// etc...
for (int i = 1; i <= count; i++)
{
//Create a new notification to send
Notification alertNotification = new Notification(testDeviceToken);
alertNotification.Payload.Alert.Body = string.Format("Testing {0}...", i);
alertNotification.Payload.Sound = "default";
alertNotification.Payload.Badge = i;
//Queue the notification to be sent
if (service.QueueNotification(alertNotification))
Console.WriteLine("Notification Queued!");
else
Console.WriteLine("Notification Failed to be Queued!");
//Sleep in between each message
if (i < count)
{
Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");
System.Threading.Thread.Sleep(sleepBetweenNotifications);
}
}
Console.WriteLine("Cleaning Up...");
//First, close the service.
//This ensures any queued notifications get sent befor the connections are closed
service.Close();
//Clean up
service.Dispose();
Console.WriteLine("Done!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}

IOS Push notification using Pushsharp in c#

i have developed code for push notification in ios in c# but it is not sending notification in mobile.
I have used pushsharp library.
My code is as followed:
PushNotificationApple pushNotification = new PushNotificationApple();
pushNotification.SendNotification(postData);
My PushNotificationApple constructor code is as below:-
public PushNotificationApple()
{
if (_pushBroker == null)
{
//Create our push services broker
_pushBroker = new PushBroker();
//Wire up the events for all the services that the broker registers
_pushBroker.OnNotificationSent += NotificationSent;
_pushBroker.OnChannelException += ChannelException;
_pushBroker.OnServiceException += ServiceException;
_pushBroker.OnNotificationFailed += NotificationFailed;
_pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
_pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
_pushBroker.OnChannelCreated += ChannelCreated;
_pushBroker.OnChannelDestroyed += ChannelDestroyed;
var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/Certificates" + ConfigSettings.SnaptymAPNSCertificate));
_pushBroker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert,ConfigSettings.SnaptymAPNSPassword)); //Extension method
}
}
My SendNotification function is as below:-
public bool SendNotification(GcmNotificationPostDataModel postData)
{
if (_pushBroker != null)
{
foreach (var registrationId in postData.RegistrationIds)
{
_pushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(registrationId) //the recipient device id
.WithAlert(postData.Data.Message) //the message
.WithBadge(1)
.WithSound("sound.caf"));
}
}
return true;
}
I am making use of PushSharp 4.0.10 and the following code works for me.
private void SendMessage()
{
//IOS
var MainApnsData = new JObject();
var ApnsData = new JObject();
var data = new JObject();
MainApnsData.Add("alert", Message.Text.Trim());
MainApnsData.Add("badge", 1);
MainApnsData.Add("Sound", "default");
data.Add("aps", MainApnsData);
ApnsData.Add("CalledFromNotify", txtboxID.Text.Trim());
data.Add("CustomNotify", ApnsData);
//read the .p12 certificate file
byte[] bdata = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/CertificatesPushNew.p12"));
//create push sharp APNS configuration
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,bdata,"YourPassword");
//create a apnService broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine("Apple Notification Sent!");
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string deviceToken1, DateTime timestamp) =>
{
//Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
Console.WriteLine("Feedback received!");
};
fbs.Check();
// Start the broker
apnsBroker.Start();
var deviceToken = "Your device token";
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload= data
});
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
}

RabbitMQ C# verify message was sent

I'm new to RabbitMQ and trying to write to a Queue and verify the message was sent. If it fails I need to know about it.
I made a fake queue to watch it fail but no matter what I see no execptions and when I am looking for a ack I always get one. I never see the BasicNack.
I'm not even sure i'm the BasicAcks is the way to go.
private void button1_Click(object sender, EventArgs e)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("task_queue", true, false, false, null);
var message = ("Helllo world");
var body = Encoding.UTF8.GetBytes(message);
channel.ConfirmSelect();
var properties = channel.CreateBasicProperties();
properties.SetPersistent(true);
properties.DeliveryMode = 2;
channel.BasicAcks += channel_BasicAcks;
channel.BasicNacks += channel_BasicNacks;
//fake queue should be task_queue
channel.BasicPublish("", "task_2queue", true, properties, body);
channel.WaitForConfirmsOrDie();
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
void channel_BasicNacks(IModel model, BasicNackEventArgs args)
{
}
void channel_BasicAcks(IModel model, BasicAckEventArgs args)
{
}
For those looking for a C# answer - here is what you need.
https://rianjs.net/2013/12/publisher-confirms-with-rabbitmq-and-c-sharp
Something like this: (BasicAcks attaches an event handler - there is also BasicNacks)
using (var connection = FACTORY.CreateConnection())
{
var channel = connection.CreateModel();
channel.ExchangeDeclare(QUEUE_NAME, ExchangeType.Fanout, true);
channel.QueueDeclare(QUEUE_NAME, true, false, false, null);
channel.QueueBind(QUEUE_NAME, QUEUE_NAME, String.Empty, new Dictionary<string, object>());
channel.BasicAcks += (sender, eventArgs) =>
{
//implement ack handle
};
channel.ConfirmSelect();
for (var i = 1; i <= numberOfMessages; i++)
{
var messageProperties = channel.CreateBasicProperties();
messageProperties.SetPersistent(true);
var message = String.Format("{0}\thello world", i);
var payload = Encoding.Unicode.GetBytes(message);
Console.WriteLine("Sending message: " + message);
channel.BasicPublish(QUEUE_NAME, QUEUE_NAME, messageProperties, payload);
channel.WaitForConfirmsOrDie();
}
}
You need a Publisher Confirms
as you can read you can implement:
The transaction:
ch.txSelect(); <-- start transaction
ch.basicPublish("", QUEUE_NAME,
MessageProperties.PERSISTENT_BASIC,
"nop".getBytes());
ch.txCommit();<--commit transaction
The message is stored to the queue and to the disk.
This way can be slow, if you need performance you shouldn't use it.
You can use the Streaming Lightweight Publisher Confirms, using:
ch.setConfirmListener(new ConfirmListener() {
public void handleAck(long seqNo, boolean multiple) {
if (multiple) {
unconfirmedSet.headSet(seqNo+1).clear();
} else {
unconfirmedSet.remove(seqNo);
}
}
public void handleNack(long seqNo, boolean multiple) {
// handle the lost messages somehow
}
I hope it helps
Ok, you always get the ACK for your message sent because "Every time message is delivered to Default Exchange Successfully."
PS: You are not sending message directly to Queue, Once Exchange recevis the message it gives you ACK then it route the message to all bound queue using the routing keys if any.

C# WinForms App Maxing Processor But Doing Nothing Strenuous!

I have a netbook with 1.20Ghz Processor & 1GB Ram.
I'm running a C# WinForms app on it which, at 5 minute intervals, reads every line of a text file and depending on what the content of that line is, either skips it or writes it to an xml file. Sometimes it may be processing about 2000 lines.
When it begins this task, the processor gets maxed out, 100% use. However on my desktop with 2.40Ghz Processor and 3GB Ram it's untouched (for obvious reasons)... is there any way I can actually reduce this processor issue dramatically? The code isn't complex, I'm not bad at coding either and I'm not constantly opening the file, reading and writing... it's all done in one fell swoop.
Any help greatly appreciated!?
Sample Code
***Timer.....
#region Timers Setup
aTimer.Tick += new EventHandler(OnTimedEvent);
aTimer.Interval = 60000;
aTimer.Enabled = true;
aTimer.Start();
radioButton60Mins.Checked = true;
#endregion Timers Setup
private void OnTimedEvent(object source, EventArgs e)
{
string msgLoggerMessage = "Checking For New Messages " + DateTime.Now;
listBoxActivityLog.Items.Add(msgLoggerMessage);
MessageLogger messageLogger = new MessageLogger();
messageLogger.LogMessage(msgLoggerMessage);
if (radioButton1Min.Checked)
{
aTimer.Interval = 60000;
}
if (radioButton60Mins.Checked)
{
aTimer.Interval = 3600000;
}
if (radioButton5Mins.Checked)
{
aTimer.Interval = 300000;
}
// split the file into a list of sms messages
List<SmsMessage> messages = smsPar.ParseFile(smsPar.CopyFile());
// sanitize the list to get rid of stuff we don't want
smsPar.SanitizeSmsMessageList(messages);
ApplyAppropriateColoursToRecSMSListinDGV();
}
public List<SmsMessage> ParseFile(string filePath)
{
List<SmsMessage> list = new List<SmsMessage>();
using (StreamReader file = new StreamReader(filePath))
{
string line;
while ((line = file.ReadLine()) != null)
{
var sms = ParseLine(line);
list.Add(sms);
}
}
return list;
}
public SmsMessage ParseLine(string line)
{
string[] words = line.Split(',');
for (int i = 0; i < words.Length; i++)
{
words[i] = words[i].Trim('"');
}
SmsMessage msg = new SmsMessage();
msg.Number = int.Parse(words[0]);
msg.MobNumber = words[1];
msg.Message = words[4];
msg.FollowedUp = "Unassigned";
msg.Outcome = string.Empty;
try
{
//DateTime Conversion!!!
string[] splitWords = words[2].Split('/');
string year = splitWords[0].Replace("09", "20" + splitWords[0]);
string dateString = splitWords[2] + "/" + splitWords[1] + "/" + year;
string timeString = words[3];
string wholeDT = dateString + " " + timeString;
DateTime dateTime = DateTime.Parse(wholeDT);
msg.Date = dateTime;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
Application.Exit();
}
return msg;
}
public void SanitizeSmsMessageList(List<SmsMessage> list)
{
// strip out unwanted messages
// list.Remove(some_message); etc...
List<SmsMessage> remove = new List<SmsMessage>();
foreach (SmsMessage message in list)
{
if (message.Number > 1)
{
remove.Add(message);
}
}
foreach (SmsMessage msg in remove)
{
list.Remove(msg);
}
//Fire Received messages to xml doc
ParseSmsToXMLDB(list);
}
public void ParseSmsToXMLDB(List<SmsMessage> list)
{
try
{
if (File.Exists(WriteDirectory + SaveName))
{
xmlE.AddXMLElement(list, WriteDirectory + SaveName);
}
else
{
xmlE.CreateNewXML(WriteDirectory + SaveName);
xmlE.AddXMLElement(list, WriteDirectory + SaveName);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
Application.Exit();
}
}
public void CreateNewXML(string writeDir)
{
try
{
XElement Database = new XElement("Database");
Database.Save(writeDir);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void AddXMLElement(List<SmsMessage> messages, string writeDir)
{
try
{
XElement Database = XElement.Load(writeDir);
foreach (SmsMessage msg in messages)
{
if (!DoesExist(msg.MobNumber, writeDir))
{
Database.Add(new XElement("SMS",
new XElement("Number", msg.MobNumber),
new XElement("DateTime", msg.Date),
new XElement("Message", msg.Message),
new XElement("FollowedUpBy", msg.FollowedUp),
new XElement("Outcome", msg.Outcome),
new XElement("Quantity", msg.Quantity),
new XElement("Points", msg.Points)));
EventNotify.SendNotification("A New Message Has Arrived!", msg.MobNumber);
}
}
Database.Save(writeDir);
EventNotify.UpdateDataGridView();
EventNotify.UpdateStatisticsDB();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public bool DoesExist(string number, string writeDir)
{
XElement main = XElement.Load(writeDir);
return main.Descendants("Number")
.Any(element => element.Value == number);
}
Use a profiler and/or Performance Monitor and/or \\live.sysinternals.com\tools\procmon.exe and/or ResourceMonitor to determine what's going on
If the 5 minute process is a background task, you can make use of Thread Priority.
MSDN here.
If you do the processing on a separate thread, change your timer to be a System.Threading.Timer and use callback events, you should be able to set a lower priority on that thread than the rest of your application.
Inside your ParseFile loop, you could try adding a Thread.Sleep and/or an Application.DoEvents() call to see if that helps. Its better to do this in the parsing is on a seperate thread, but at least you can try this simple test to see if it helps.
Might be that the MessageBoxes in your catches are running into cross-thread problems. Try swapping them out for writing to the trace output.
In any case, you've posted an entire (little) program, which will not help you get specific advice. Try deleting method bodies -- one at a time, scientifically -- and try to get the problem to occur/stop occurring. This will help you to locate the problem and eliminate the irrelevant parts of your question (both for yourself and for SO).
Your current processing model is batch based - do the parsing, then process the messages, and so on.
You'll likely reduce the memory overhead if you switched to a Linq style "pull" approach.
For example, you could convert your ParseFile() method in this way:
public IEnmerable<SmsMessage> ParseFile(string filePath)
{
using (StreamReader file = new StreamReader(filePath))
{
string line;
while ((line = file.ReadLine()) != null)
{
var sms = ParseLine(line);
yield return sms;
}
}
}
The advantage is that each SmsMessage can be handled as it is generated, instead of parsing all of the messages at once and then handling all of them.
This lowers your memory overhead, which is one of the most likely causes for the performance difference between your netbook and your desktop.

Categories

Resources