working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,196 snippets matching: communication

    public by cghersi @ MailUp API DEV  206844  8  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by cghersi @ MailUp API DEV  84180  21  6  0

    Base class to setup the secure communication towards MailUp REST API

    This is how to setup a secure connection towards MailUP RESTful API. This base class can be extended with methods that directly call those web methods
    public class BaseAPIInvoker
    { 
        #region App Credentials
    
        protected static String ClientId = "take from your console";
        protected static String ClientSecret = "take from your console"; 
        protected static String UserName = "mxxx@number"; 
    	protected static String Password = "pswsupersecret"; 
        protected static String bypassToken = String.Empty;
    
        #endregion
    
        #region Endpoints
    
        protected static String OAuthAuthorization = "https://services.mailup.com/Authorization/OAuth/Authorization";
        protected static String OAuthToken = "https://services.mailup.com/Authorization/OAuth/Token";
        protected static String BaseEndpoint = "https://services.mailup.com/API/v1/Rest/ConsoleService.svc";
    
        #endregion
    
        public OAuth2Client client;
    
        public BaseAPIInvoker()
        {
            client = new OAuth2Client(OAuthToken, OAuthAuthorization);
            
            client.ClientId = ClientId;
            client.ClientSecret = ClientSecret;
            client.Username = UserName;
            client.Password = Password;
    
            client.ForceToken = bypassToken;
            
            client.GetToken();
        }
    }

    public by cghersi @ MailUp API DEV  113003  11  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by cghersi  3030  0  6  0

    How to create a DefaultHttpClient with proxy settings

    This is how to create a DefaultHttpClient adding information regarding the proxy the client is using
    private static DefaultHttpClient createHttpClient() {
    	DefaultHttpClient httpClient = new DefaultHttpClient();
    	if (!Utils.isNullOrEmpty(proxyAddress) && (proxyPort > 0)) {
    		HttpHost httpproxy = new HttpHost(proxyAddress, proxyPort);
    		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy);
    	}
    	return httpClient;
    }

    public by cghersi  2487  2  6  1

    Communication with UTF-8 for MySQL use in Java

    This is the way to use UTF-8 for the communiocation of a Java application towards a MySQL database
    Class.forName("com.mysql.jdbc.Driver").newInstance();//call jdbc driver
    
    String url = "jdbc:mysql://localhost/unicode?useUnicode=true&characterEncoding=UTF-8";//getting url
                
    conn = DriverManager.getConnection(url,"root","");//create connection
    

    public by cghersi @ MailUp API DEV  69240  7  5  0

    How to Add a recipient to a group of recipients with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void AddRecipientToGroup(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        int idGroup = 1;
        ConsoleRecipientItem recipient = new ConsoleRecipientItem()
        {
            Email = "testGroup@mailup.com",
            Name = "Group - New Recipient" + DateTime.Now.ToFileTimeUtc(),
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "NameGroup" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastNameGroup" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
    
        // 3) Invoke the web method:
        int result = 0;
        try
        {
            result = client.AddRecipientToGroup(idGroup, recipient);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result > 0)
            Console.WriteLine("Recipient Added!");
        else
            Console.WriteLine("An error occurred while adding the recipient.");
    }
    

    public by cghersi @ MailUp API DEV  60009  8  5  0

    How to Retrieve a group of recipients given its ID with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetGroupByID(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        int idList = 1;
        int idGroup = 1;
    
        // 3) Invoke the web method:
        ConsoleGroupItem result = null;
        try
        {
            result = client.GetGroup(idList, idGroup);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result != null)
            Console.WriteLine("Group retrieved with name:" + result.Name);
        else
            Console.WriteLine("An error occurred while retrieving the group.");
    }
    

    public by cghersi @ MailUp API DEV  1829  48  5  0

    MailUp REST API - How to send a transactional email message

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. Explore the MessageDTO object in order to understand how you can customize the message you want to send.
    public static void SendMessage()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) prepare the input:
      MessageDTO msg = new MessageDTO()
      {
        Html = new HtmlDTO()
        {
          Body = "<div>Hello Mr. [firstname][lastname] !!!</div><br><img width='600' height='397' src='cid:img001'>",
          BodyTag = "<body>"
        },
        Text = "Hello world!!!",
        Subject = "Hello friend!",
        From = new EmailAddressDTO() { Name = "Test User", Email = "test@mailup.it" },
        To = new List<EmailAddressDTO>() { new EmailAddressDTO() { Name = "Massimo", Email = "info@mailup.it" } },
        Cc = new List<EmailAddressDTO>(),
        Bcc = new List<EmailAddressDTO>(),
        ReplyTo = null,
        CharSet = "utf-8",
        ExtendedHeaders = null,
        Attachments = null,
        EmbeddedImages = new List<MessagePartDTO>() {
          new MessagePartDTO() {
            Filename = "Image.jpg",
            ContentId = "img001",
            Body = new byte[] { 0x01, 0x02, 0x03, 0x04 }
          }
        },
        XSmtpAPI = new XSmtpAPIDTO()
        {
          CampaignName = "Test Campaign",
          CampaignCode = "1001",
          Header = null,
          Footer = null,
          ClickTracking = null,
          ViewTracking = null,
          Priority = null,
          Schedule = null,
          DynamicFields = new List<NameValueDTO>() {
            new NameValueDTO() { N = "firstname", V = "Mario"},
            new NameValueDTO() { N = "lastname", V = "Rossi"}
          },
          CampaignReport = null,
          SkipDynamicFields = null
        },
        User = new SmtpUserDTO() { Username = smtpplus_username, Secret = smtpplus_password }
      };
    
      // 4) Invoke the web method:
      SendResponseDTO result = null;
      try
      {
        result = client.SendMessage(msg);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 5) Print results:
      if (result != null)
        Console.WriteLine("Result of sending task:" + result.Message);
      else
        Console.WriteLine("An error occurred while sending message.");
    }
    						

    public by cghersi @ MailUp API DEV  1974  30  6  1

    MailUp REST API - How to create and send an email to a specific recipient.

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void CreateAndSendEmail(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Create the message:
        int idList = 1;
        string subject = "Test Creation Email";
        ConsoleMessageDetailItem message = new ConsoleMessageDetailItem()
        {
            Content = "Test Content",
            Embed = false,
            idList = idList,
            IsConfirmation = false,
            Notes = "Bunch of test notes",
            Subject = subject,
            TrackingInfo = new ConsoleEmailTrackingInfo() { Enabled = true, Protocols = new List<string>() { "http" } }
        };
        ConsoleMessageItem createMsgResult = null;
        try
        {
            createMsgResult = client.CreateMessage(idList, message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unable to create the message due to " + ex.Message);
            return;
        }
        if (createMsgResult == null)
        {
            Console.WriteLine("Unable to create the message");
            return;
        }
    
        // 3) Send the just created message:
        EmailSendToRecipientRequest request = new EmailSendToRecipientRequest()
        {
            Email = "recipient@mailup.com",
            idMessage = createMsgResult.idMessage.Value
        };
        MailMessageSendResponse result = null;
        try
        {
            result = client.SendEmailMessage(request);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result != null)
            Console.WriteLine("Message sent to " + result.Sent + " recipient(s).");
        else
            Console.WriteLine("An error occurred while sending the message.");
    }
    

    public by cghersi  4371  4  5  1

    How to run a Socket Server and Client in Java

    This class may act both a server and client of a socket communication, whether the useAsServer variable is set respectively to true or false
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.nio.ByteBuffer;
    import java.nio.channels.ClosedByInterruptException;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.List;
    import java.util.concurrent.ArrayBlockingQueue;
    
    
    /**
     * This class provides the utilities to read the data exchanged  via socket.
     */
    public class SocketComm {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Socket for the communication towards the destination
    	 */
    	private Socket connection;
    	/**
    	 * Singleton instance of the class
    	 */
    	private static SocketComm socketComm;
    	private ListenerThread listener;
    	private Thread listenerThread;
    	/**
    	 * Synchronization variable for the safe instantiation of the singleton
    	 */
    	private static Object synchSingleton = new Object();
    	/**
    	 * IP Address of:
    	 * - the other peer (for client mode)
    	 * - this instance (for server mode)
    	 */
    	private String host = "192.168.1.1";
    	/**
    	 * TCP port of:
    	 * - the other peer (for client mode)
    	 * - this instance (for server mode)
    	 */
    	private int port = 1515;
    	
    	private boolean useAsServer = true; //change accordingly to the way of use
    
    	/**
    	 * Retrieves the singleton instance of the class; if
    	 * the singleton has not yet been instantiated, it builds 
    	 * a new instance using the protected constructor.
    	 * @return The singleton instance of the class
    	 */
    	public static SocketComm get() {
    		if (socketComm == null) {
    			String error = "";
    			synchronized (synchSingleton) {
    				if (socketComm == null) {
    					try {
    						socketComm = new SocketComm();
    					} catch (IOException ex) {
    						error = ex.getMessage();
    					}
    				}
    			}
    		
    			if (error.length() > 0) {
    				socketComm = null;
    				return null;
    			}
    		}
    	
    		return socketComm;
    	}
    
    
    	/**
    	 * Builds a new manager for the communication via socket.
    	 * The port is taken from XML configuration file.
    	 * @exception IOException if an error occurred during the opening of the socket
    	 */
    	protected GatewaySocketComm() throws IOException {
    		super();
    	
    		try {
    			//Create a socket to connect to the gateway:
    			if (useAsServer) {				
    				listener = new ListenerThread();
    				listenerThread = new Thread(listener, "SocketListenerThread");
    				listenerThread.start();
    			}
    		} catch (Exception e) {
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeThread(){
    		//close the streams for socket:
    		try {
    			closeStreams();		
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
    		//stop the threads to send and receive data:
    		if (useAsServer) {			
    			listener.stopThread();
    			Thread moribond2 = this.listenerThread;
    			this.listenerThread = null;
    			moribond2.interrupt();
    		}
    	}
    	
    	
    	/**
    	 * Closes the streams related to the socket and the socket itself
    	 * @throws IOException
    	 */
    	protected void closeStreams() throws IOException {
    		if (inputStream != null)
    			inputStream.close();
    		
    		if (outputStream != null)
    			outputStream.close();
    		
    		if (connection != null)
    			connection.close();
    	}
    
    	public void initializeListeningThread() {
    		if (!useAsServer) {
    			try {
    				//create e new Socket:
    				connection = new Socket(host, port);
    	
    				//Get Input & Output streams:
    				outputStream = connection.getOutputStream();
    				outputStream.flush();
    				inputStream = connection.getInputStream();
    			} catch (UnknownHostException e) {
    				log.error("Cannot connect to host, due to:" + e.getMessage());
    			} catch (IOException e) {
    				log.error("Cannot connect to host, due to:" + e.getMessage());
    			}
    		}
    	}
    
    
    	public void write(byte[] buffer){
    		boolean bufferSent = false;
    		
    		if (!useAsServer) {
    		    try {
    		    	outputStream = connection.getOutputStream();
    		    	outputStream.write(buffer);
    		    	outputStream.flush();
    		    	bufferSent = true;
    		    } catch (IOException e) {
    		    	log.error("Cannot write:" + e);
    		    }
    		}
    	}
    	
    	
    	/**
    	 * This thread is used to listen to the data incoming from the other peer.
    	 * It should be used only when the instance is running as server.
    	 * It tries to listen to the established socket until the flag socketBrokenPipe
    	 * is set to true (from the SenderThread).
    	 * In this case the thread waits until a new connection is accepted. 
    	 */
    	protected class ListenerThread implements Runnable {
    		
    		private boolean stopThread = true;
    
    		private ServerSocketChannel srvr;
    		private SocketChannel sc;
    		private Integer connTimeout;
    		
    		public void run() {
    			
    			this.connTimeout = 30000;
    			try {
    				srvr = ServerSocketChannel.open();
    				srvr.socket().bind (new InetSocketAddress(host, port));
    				srvr.configureBlocking(true);
    			} catch (IOException e) {
    				log.error("Exception opening the socket:" + e);
    			}
    			
    			log.info("ListenerThread has started");
    			stopThread = false;
    			
    	        boolean done = false;
    	        boolean isClosing = false;
    
    			while(!stopThread) {
    				try {
    					log.info("Waiting for connection acceptance...");
    					sc = srvr.accept();
    					log.info("Connection accepted!");
    					connection = sc.socket();
    					connection.setSoTimeout(this.connTimeout);
    					connection.setTcpNoDelay(true);
    					done = false;
    				} catch (ClosedByInterruptException e1) {
    					done = true;
    					isClosing = true;
    				} catch (IOException e1) {
    					log.error("Exception:" + e1.getMessage());
    					done = true;
    				}
    					
    				if (stopThread)
    					break;
    				
    				log.info("Start reading a frame from socket...");
    				ByteBuffer bhBuf = ByteBuffer.allocateDirect(1024);
    
    				if (bhBuf == null) {
    					log.error("Cannot create ByteBuffer to read socket");
    					done = true;
    				}
    				
    				while (!done) {
    					int valueRead = -1;
    					try {
    						bhBuf.clear();					
    						valueRead = sc.read(bhBuf);
    						bhBuf.flip();
    					} catch (SocketException e) {
    						//Connection closed by the client. The server waits for a new connection.
    						log.warn("Socket closed:" + e.getMessage());
    						break;
    					} catch (IllegalArgumentException e) {
    						log.error("Bad Argument:" + e.getMessage());
    						break;
    					} catch (IOException e) {
    						log.error("IO Error:" + e.getMessage());
    						break;
    					}
    	
    					//decode byte stream into a string:
    					if(valueRead <= 0){
    						log.warn("received negative size for buffer, dropping it");
    						continue;
    					}
    					byte[] result = new byte[valueRead];
    					bhBuf.get(result);
    					//do something with result...
    
    					//send a keep alive message:
    					try {
    						outputStream = connection.getOutputStream();
    						outputStream.write(new byte[] { (byte)0x01 });
    						outputStream.flush();
    					} catch (IOException e) {
    						log.error("IO Error:" + e.getMessage());
    						done = true;
    					}
    				}
    				
    				//check if the thread is stopping...
    				//If the thread is stopping, the channel is not open and thus it should not be closed:
    				if (!isClosing){
    					try {
    						closeStreams();
    						
    						sc.close();
    					} catch (IOException e) {
    						log.error("IO Error:" + e.getMessage());
    					}
    				}
    			}
    		}
    		
    		/**
    		 * Stops the thread 
    		 */
    		public void stopThread() {
    			stopThread = true;
    		}
    	}
    }
    • Public Snippets
    • Channels Snippets