I must build a Application that will use Webclient multiple times to retrieve every "t" seconds information from a server.
Here is a small plan to show you what I'm doing in my application:
Connect to the Web Client "USER_LOGIN" that returns me a GUID(user unique ID). I save it and keep it to use it in future Web Client calls.
Connect to the Web Client "USER_GETINFO" using the GUID I saved before as parameter. This Web Service returns an array of strings holding all my personal user information( my Name, Age, Email, etc...). => I save the array information this way: Textblock.Text = e.Result[2].
Starting a Dispatcher.Timer with a 2 seconds Tick to start my Loop. (Purpose of this is to retrieve information and update it every 2 seconds)
Connect to the Web Client "USER GETFRIEND", wich is in my Timer, giving him the GUID as parameter. It returns me an array filled with my friends informations(Name, email, message, etc...). I inserted this WebClient in the timer so my friend list refreshes every 2 seconds.
I am able to create all the steps without any error until step 3. When I call the "USER_GETFRIEND" Web Client I am facing two major problems:
On one side I noticed that my number of Thread increased dramatically. => I always thought that when a WebClient had finished its instructions it would shut down by itself, but apparently that does not happen in Asyncronous calls.
And on the other side I was surprised to see that using the same proxy for two Webclient calls(ie: if i declare test.MainSoapClient proxy = new test.MainSoapClient()), the data i would retrieve from "USER_GETFRIEND" e.Result, was sent directly to my "USER_GETINFO" array. And so my Name and Email adresses on the UI were replaced by the same value in the USER_GETFRIEND array. So my Name is changed to my friends email and so on...
I would like to know if it's possible to close a WebClient call(or Thread) that I am not using anymore to prevent any conflicts? Or if someone has any suggestion concerning my code and the way i should develop my application please feel free to propose.
I got the answer a few weeks ago and figured out it was important to answer my own question.
My whole problem was that I wasn't unsubscribing from my asynchronous calls and that I was using the same proxy class from "Add Service reference":
So when I was using:
proxy.webservice += new Eventhandler<whateverinhere>(my_method);
I never did:
proxy.webservice -= new Eventhandler<whateverinhere>(my_method);
Hope it will help someone.
Related
So I'm making a small chat application like ricochet, but then in C# and I succesfully connect to the tor controlport and create a hidden service id and private key, however after that point i got stuck, I send ADD_ONION NEW:BEST Port=8946,127.0.0.1:8946\r\n to the tor control port and it answers with hidden service id and private key and code 250. But what should I do to make it automatically run the service? I tried googling it but couldnt find anything and all examples are python or c++ if someone could point me in the right direction that would be great. Also, im using Knapcode.TorSharp, so the tor installation is NOT persistent, the user has a profile file where the key etc are saved and it should start from there.
Thanks in advance
When you call ADD_ONION, the hidden service starts running immediately (accessible once it can publish the Hidden Service descriptors and establish circuits [usually within a minute or two]).
If you want those services to start again automatically on subsequent runs (for a non-persisting Tor installation), then you'll need to programatically make similar calls to ADD_ONION when your application restarts and detects that private keys are saved to the profile.
You can re-create hidden services using existing keys with syntax like:
ADD_ONION RSA1024:*PKEY_GOES_HERE* Flags=DiscardPK Port=8946,8946
When you call ADD_ONION the first time, the response should look something like:
250-ServiceID=abcdefg123456
250-PrivateKey=RSA1024:MIICXAIBAAKBgQC91z4mjpNF5ddRL6jm7rnmgwSiQ6dNXF1Fo8sz1wOsGqWKgE4C6Bd3KT+zgQgXJlioIJOCEP9D0b/qlPCvEiGG3/fPEn1+Zpf5N4oNRI+in7J2m3xihhgAinbscJ0vM+1vfnRLlMrtYdE9J5aKle+t+OC6ZoXTxzPZRZkmXtqVpp8QIDAQPXAoGBAK7oh8zChBJch5u3i6jpvsIRaM2QA68VMKKfHPOwYSPKkUcgm7+10xjpGlXqxmd93yVYjk/CFU6JDIe3nmHPFK82BtPgyEMRtmVmcunS262Ead/ffpzAErBSdihOF7zO/wGjGgIaMW9Bhy69aK5LcNUB30Iu9+MWG62xz8tTgcEhAkEA8QNKMyKdRUbgGc9Gv1n8JtMs0Af/a/OHozdn1ywvHxw7mzahF936gqHIdg67XLtIj5TaUSM/44OoEvvURnG7QJBAMmlVttRd8y+/FnA6dPkesQMpPw+ipHLNUrf7qPrX3py670vLbprWDNYCOn6oaxoRtl/iRXPI5CgjMXmnu356pUCQDnWD0VMJi+MvZSUACbZXwP2ApP1bHfla3I7Xaezh5oDxtoAd0PS4STh1+HQUPvQW4WfLUcSsz9UaMAg2NI+fFUCQc7D1PVW7sqSGBth3jXE+3+H6WY2iy8Z1Ji+l2KRdJ8IiIOWdfcgUpMNzZV8jc7Y9Cm5p5l2wy7kjfGADyYBCXkCQD9fnmVMlUO1xITfW8K+pAf6FPcvfo8J0rpWHEhG4CxjFw4s4s9Mzjme1e17YnfK21CNIOxd2bkqVI4j4o=
250 OK
You'll want to save what it gave back in PrivateKey, and use this value to restart the hidden services the next time you run your application.
I need to push notifications to tens of thousands of iOS devices that my app installed. I'm trying to do it with PushSharp, but I'm missing some fundamental concepts here. At first I tried to actually run this in a Windows service, but couldn't get it work - getting null reference errors coming from _push.QueueNotification() call. Then I did exactly what the documented sample code did and it worked:
PushService _push = new PushService();
_push.Events.OnNotificationSendFailure += new ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
_push.Events.OnNotificationSent += new ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
var cert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("..pathtokeyfile.p12"));
_push.StartApplePushService(new ApplePushChannelSettings(false, cert, "certpwd"));
AppleNotification notification = NotificationFactory.Apple()
.ForDeviceToken(deviceToken)
.WithAlert(message)
.WithSound("default")
.WithBadge(badge);
_push.QueueNotification(notification);
_push.StopAllServices(true);
Issue #1:
This works perfectly and I see the notification pop up on the iPhone. However, since it's called a Push Service, I assumed it would behave like a service - meaning, I instantiate it and call _push.StartApplePushService() within a Windows service perhaps. And I thought to actually queue up my notifications, I could do this on the front-end (admin app, let's say):
PushService push = new PushService();
AppleNotification notification = NotificationFactory.Apple()
.ForDeviceToken(deviceToken)
.WithAlert(message)
.WithSound("default")
.WithBadge(badge);
push.QueueNotification(notification);
Obviously (and like I already said), it didn't work - the last line kept throwing a null reference exception.
I'm having trouble finding any other kind of documentation that would show how to set this up in a service/client manner (and not just call everything at once). Is it possible or am I missing the point of how PushSharp should be utilized?
Issue #2:
Also, I can't seem to find a way to target many device tokens at once, without looping through them and queuing up notifications one at a time. Is that the only way or am I missing something here as well?
Thanks in advance.
#baramuse explained it all, if you wish to see a service "processor" you can browse through my solution on https://github.com/vmandic/DevUG-PushSharp where I've implemented the workflow you seek for, i.e. a win service, win processor or even a web api ad hoc processor using the same core processor.
From what I've read and how I'm using it, the 'Service' keyword may have mislead you...
It is a service in a way that you configure it once and start it.
From this point, it will wait for you to push new notifications inside its queue system and it will raise events as soon as something happens (delivery report, delivery error...). It is asynchronous and you can push (=queue) 10000 notifications and wait for the results to come back later using the event handlers.
But still it's a regular object instance you will have to create and access as a regular one. It doesn't expose any "outside listener" (http/tcp/ipc connection for example), you will have to build that.
In my project I created a small selfhosted webservice (relying on ServiceStack) that takes care about the configuration and instance lifetime while only exposing the SendNotification function.
And about the Issue #2, there indeed isn't any "batch queue" but as the queue function returns straight away (enqueue and push later) it's just a matter of a looping into your device tokens list...
public void QueueNotification(Notification notification)
{
if (this.cancelTokenSource.IsCancellationRequested)
{
Events.RaiseChannelException(new ObjectDisposedException("Service", "Service has already been signaled to stop"), this.Platform, notification);
return;
}
notification.EnqueuedTimestamp = DateTime.UtcNow;
queuedNotifications.Enqueue(notification);
}
I work on a multi-tier application and I need to optimize a long-running process in three ways :
Avoiding EF update concurrency problems.
Improving speed.
Informing the user of the progress.
Actually, the client code calls a WCF service using a method that does all the work (evaluating the number of entities to update, querying the entities to update, updating them and finally, saving them back to the database).
The process is very long and nothing is sent back to the user except the final result once the process is done. The user can stay in front of the wait form for up to 10 minutes, not knowing what is happening.
The number, and depth of the queried entities can become really big and I sometimes hit OutOfMemoryExceptions. I had to change the service method to process entity updates 100 entities at a time, so my DbContext will be refreshed often and won't become too big.
My actual problem is that I cannot inform the user each time an entity is updated because my service method does the whole process before returning it's result to the user.
I read about implementing a duplex service but since I have to return two different callbacks to the user (one callback to return the number of entities to update and another callback for the result of each entity update) I have to use multiple interface inheritance on a generic callback interface and it's becoming a little messy (well, to my taste).
Wouldn't it be better to have one WCF service method to return the number of entities to evaluate, and another WCF method that will return a simple entity update result, which will be hit for every entity to update ? My DBContext will be living only for the time of a single entity update, so it would not grow very much, which I think is good. However, I am concerned about hitting the WCF service really often during that process.
What are you thoughts ? What can you suggest ?
Have you thought about adding a WCF host to your client? That way you get full two way comms.
Client connects to server and gives server connection details back to client
Client request long running operation to begin
Server sends multiple updates to the clients WCF host as work progresses.
Server sends work complete to client.
This leaves your client free to do other things, consuming the messages from the server as you see fit. Maybe updating a status area as messages come in.
You could even get the server to maintain a list of clients and send updates to them all.
--------EDIT---------
When I say WCF host I mean a ServiceHost
It can be created automatically from your XML in App.config or though code directly.
var myUri = new Uri[0];
myUri[0] = new Uri("net.tcp://localhost:4000");
var someService = new SomeService(); //implements ISomeService interface
var host = new ServiceHost(someService, myUri);
var binding = new NetTcpBinding(); // need to configure this
host.AddServiceEndpoint(typeof(ISomeService), binding, "");
host.Open();
Proxy is a term I use for what a client uses to connect to the server, it was in an early example I came across and its stuck with me since. Again can be created both ways.
var binding = new NetTcpBinding(); // need to configure this
var endpointAddress = new EndpointAddress("net.tcp://localhost:4000");
var factory = new ChannelFactory<ISomeService>(binding, endpointAddress);
var proxy = factory.CreateChannel();
proxy.DoSomeWork();
So in a typical client/server app you have
CLIENT APP 1 SERVER APP CLIENT APP 2
proxy------------->ServiceHost<-------proxy
What I am suggesting is that you can make the client be a "server" too
CLIENT APP 1 SERVER APP CLIENT APP 2
proxy------------->ServiceHostA<------proxy
ServiceHostB<------proxy1
proxy2------------>ServiceHostB
If you do that, you can still split your large task into smaller ones if needed (you mentioned memory issues), but from the sounds of things they still might take some time and this way progress updates can still be sent back to the client or even all clients if you want everyone to be aware of whats happening. No callbacks needed, though you can still use them if you want.
Avoiding EF update concurrency problems.
See this question/answer Long running Entity Framework transaction
Improving speed.
Some suggestions:
Try using SQL Profiler to see what SQL query is being executed, and optimize the linq query
Or try improving the query itself or calling a stored procedure.
Can the updates be done in parallel? different threads? different processors?
Informing the user of the progress.
I would suggest changing the client to call an async method, or a method which then starts the long running operation asynchronously. This would return control back to the client immediately. Then it would be up to the long running operation to provide feed back as to its progress.
See this article for updating progress from a background thread
Update
the "architecture" I would suggest would be as follows:
. Service . . .
________ . _________ _______ ____
| | . | WCF | | EF | | |
| Client |---->| Service |->| Class |->| DB |
|________| . |_________| |_______| |____|
.
. .
The WCF service is only responsible for accepting client requests, and starting off the long running operation in the EF Class. The client should send an async request to the WCF service so it retains control and responsiveness. The EF class is responsible for updating the database, and you may choose to update all or a subset or records at a time. The EF class can then notify the client via the WCF service of any progress it has made - as required.
This is about my solution to that question
It is been a long time since my last c# coding, and it is my first time to write a Web Service...
Previous Question:
I need to use a DLL on an Ubuntu with Python. Final solution is using a web service for that propose...
My problem is, the API is used for a kind of payment. There are three basic function of the DLL to be used in the webservice... First one is used for connection to the server, second one is asking available payments, third one is selecting one and making the payment...
Since my system is using Python, I wish to keep the logic that selects the payment method on python, not on the web service.
And my problem is, when I make a connection, webservice must create a connection object, and do the following two steps using that connection. That it may dispose that connection object and create a new one for the next connection and payment.
So, my Python code will do something like that...
Use web service and create a connection
Get a list of available payments from web service (these two functions can be used as a single function in the web service)
Do some calculation and select the proper payment in python...
Send payment method info to web service...
All these steps must be done with the connection object from the first step.
As I said before, I do not have much knowledge about web services and using them on python... So I'm confused whether I may use the same connection object for steps 2 and 4. If I create the connection object as a global in my web service on the connection step, then my following function calls use that object? In OOP that's the way it must be, but I can not be sure if it will be same in web services?
Some code snippet :
namespace paymentType{
public class x : System.Web.Services.WebService{
ConnectionObj conn;
ConnResult result;
[WebMethod]
public void ConnectToServer(String deviceId){
conn = new ConnectionObj();
result = baglanti.Connect(deviceId);
}
[WebMethod]
public List<int> GetCompanyList(){
List<int> kurumlar = new List<int>();
if (sonuc.CRCStatus){
if (baglanti.CompanyList != null) { blah blah blah...}
Since conn is a global, can i set it in the function call ConnectToServer and use the baglanti object for the other functions...
UPDATE: Let me try to get it more clear...
When I connect to remote server (via function in the DLL), remote server accepts my connection and give me a somewhat unique id for that connection. Then I ask for available payments for a customer. Server sends all available ones with a transaction id belong to that transaction. And in the final step, I use the transaction id that I want for doing the payment. Problem is, each transaction id is usable within the connection that it was created. So, I must request for transaction id and confirm the one I want in the same connection...
But as far as I see, best solution is using a single function call and do all the job on the web service since API provider considers removing the connection-transactionId lock might cause some security vulnerabilities...
But on the other hand, I do not want to handle it on the web service...
One more question... On the connection step, creating the connection and using set/get functions or returning the connection object and pass it back to the web service for each following step might work?
If you're communicating using a web service, it should preferrably be stateless – that is, you should always send any context information the service implementation needs in the request. While technologies that let you implement stateful web services exist, they'd likely make things more complicated, not less.
I'm not clear from your description on why you need the connection object to be created in Step 1, or why you can't just create a different connection object for steps 2 and 4 – which is how I'd implement this.
in my web-application I want to send mail for users according to pre selected periods by themselves. for example: 1 HTML Mail Per 3days to user 01 and 1 HTML Mail Per 20days to user 02
how can I perform that? any resources? I can send mail by my app from My Gmail Account to any mail addresses in my tables but i dont know how to send it automatically in a period of time.(i use C# and SQL Express)
Help me out!
I found the Solution. according to my search we have 3 ways to handle that:
working with SQL Server to send mail notification in periods of time.(or this)
using Windows service and Creating Timer object and checking the time with it.
but in ways 1 and 2 we should access to server and we need dedicated hosting server to for example installing WinService on it. so it does not work in a sharing Host space we usually use. So I Found the best way as you see:
3. Simulating Windows Services Using ASP.NET Caching For Scheduled Jobs.
the link above is a terrific solution. So there is no need to work out-side of our web application.
You will need something which can periodically run jobs for you, like a cron daemon or windows task scheduler.
Essentially you have the periodic job kick off and do whatever mail handling you need.
You can also do this from code if you can create a windows service to basically sleep until the next batch of mails needs to be sent.
The easiest is to write the task scheduler or cron job to run periodically. In that way you just need a small piece of code to handle the mail sending portion and then you just schedule it to run once an hour or day or whatever needed.
Hai,
Have a look at quartz.net
Quartz.NET is a full-featured, open source job scheduling system that can be used from smallest apps to large scale enterprise systems.
Quartz.NET is a port of very propular open source Java job scheduling framework, Quartz. Quartz.NET supports clustering and database persistence out-of-the-box and has powerful means to schedule jobs using cron like expressions, interval triggers and exclusion advices.
The great thing about IIS hosted ASP.NET is that IIS will (by default) periodically recycle your application pool according to the settings on the app pool itself.
When your application pool is starting (which could be at least once a day especially if it's allowed to idle i.e. a business app where most activity is 9-5) the Application_Start event-handler in Global.asax is fired. This could be used for your recurring task.
Now you don't necessarily want to run this email send synchronously within that Application_Start handler because to me it seems this messaging functionality is not core to the startup but by all means use this event-handler as an easy way to periodically do your housekeeping.
To send async you should use async delegates for example.
i think there a solution:
1- you have to add 2 column in the user table in your sql db if you have a user table and in the first column add the date of the last email sent to the user and the second column has the period for sending the email for that user for ex:
LastEmailSentDate datetime
SendEmailPeriod int
2- in your application code write a function that compare the last date of the last sent email with the period of the sending the email.
// here the funciton code
public void CompareLastSentDate()
{
// lets assume that you bring the data for the db using Sqdatareader reader
//get the field from the LastEmailSentDate field in the database as i mention before
DateTime LastEmailSentDate = Convert.ToDate(reader["DatePeriod"])
// get the field from the SendEmailPeriod of the user field from database
int sendEmailPeriod = Convert.Toint32(reader["SendEmailPeriod"])
// now you have the date before the period of day ex: before 3 days depend on user
DateTime DatePeriod = new DateTime(DateTime.Now.Year, DateTime.Now.Month, (DateTime.Now.Day - sendEmailPeriod ));
// if the last email send is before period of day that mean u have to send an email again
if(LastEmailSentDate.Day <= DatePeriod.Day)
{
// sent the email to the user
}
}
note: now u can loop among the users and sent the email
you can call this function once in a day by calling it from ur app home page Page_Load event and after the first call of the day add an application["LastFunctionCallDate"] = DateTime.Now flag so in the next you can check this flag if its == today and if not call it again