segunda-feira, 1 de outubro de 2018

Backup pessoal 2018 para Nuvem (Cloud)


Salvaguardar Fotos e vídeos na Cloud

ou/e armazenamento local

2018





(melhores thumbnails)

 vs 

Microsoft OneDrive
(maior capacidade)

 vs 


(Armazenamento ilimitado, tamanho maximo 16 Mb por foto)

  vs 
(melhor preço qualidade anual, somente para armazenamento)
  
  vs 


  vs / ou / e

Armazenamento doméstico (Nas Pessoal)

Synology NAS
(muito intuitivo)

(parecido com google drive)

(hardware melhor que da Synology)


Uso de Smartphone :

     Cada vez mais, utilizamos o smartphone como único meio para gravar os nossos momentos diários, tirarmos fotos e gravamos vídeos, para mais tarde os recordar, os avanços da tecnologia nos últimos anos, nos permite cada vez mais estarmos dependentes do nosso smartphone pessoal.

Tiramos fotos a tudo e mais alguma coisa, para quem tem família e quer gravar todos os momentos, tanto do crescimento dos filhos, como eventos, jantares, almoços em família, entre amigos, não queremos perder esses momentos, por isso queremos guardar e recordar mais tarde esses momentos, e hoje em dia um smartphone nos permite isso. 

     Porem , chegamos rapidamente ao limite de armazenamento disponível nos nossos dispositivos, ou por pouca capacidade de armazenamento, ou pela melhoria da qualidade das fotos e dos vídeos que os novos equipamentos tem vindo a trazer, o que traduz em usar mais armazenamento no dispositivo.

     32 Gb ou 64 Gb ou ate mesmo 128 GB de Armazenamento interno, em 2018 chega a ser pouco.
     Entre 6 a 12 meses conseguimos preencher praticamente mais de 1/2 (metade) do espaço interno do nosso dispositivo móvel.


  Caso Real : 
  • Ok, as fotos e os vídeos, ocupam muito espaço no telemóvel, ao chegar a casa, caso dispomos de um computador ou portátil, copiamos as fotos e os vídeos do telemóvel para o computador.
  • Sim , quando nos lembramos, quando temos tempo, e quando o computador tem um disco com muita capacidade de armazenamento, posteriormente colocamos num dispositivo externo (algumas pessoas fazem isso).
  • Desde que não apanhamos nenhum vírus (que encripte todos os ficheiros de media), desde que o computador não se estrague, desde que o disco externo esteja sempre em bom estado, e guardado em lugar seguro, que não apanhe humidade ou calor, estamos sempre salvaguardados.
  • Mas na realidade, e praticamente impossível, seguir esses passos e manter sempre backup das nossas fotos e vídeos, ou ficheiros importantes.

   Soluções alternativas e/ou complementares :

  1. Backup para serviços online em Nuvem (Cloud)
  2. Backup para dispositivo de armazenamento local (NAS)
  3. Ultimate Backup, Nuvem (Cloud) e Armazenamento Local + USB











quarta-feira, 5 de junho de 2013

Send sms using NEXMO Api




'Create a new class SmsSender or another name
-----------------------------------------
Imports System.Collections.Generic
Imports  System.Net
Imports System.Web
Imports  System.Web.Script
Imports System.Web.Script.Serialization

Namespace API

    Class SmsSender

        Public Function SendSMS(ByVal _numberPara As String, ByVal _fromLab As String, ByVal _smsText As String, ByVal _apiKey As String, ByVal _apiCode As String) As SmsResponse

            Dim uri As String = String.Format("http://rest.nexmo.com/sms/json?api_key={0}&api_secret={1}&from={2}&to={3}&type=unicode&text={4}", _apiKey, _apiCode, _fromLab, _numberPara, _smsText)

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Dim json = New WebClient().DownloadString(uri)

            Return ParseSmsResponseJson(json)

        End Function

'Function to format the Json Response 

        Private Function ParseSmsResponseJson(ByVal json As String) As SmsResponse
            ' hyphens are not allowed in in .NET var names
            json = json.Replace("message-count", "MessageCount")
            json = json.Replace("message-price", "MessagePrice")
            json = json.Replace("message-id", "MessageId")
            json = json.Replace("remaining-balance", "RemainingBalance")
            json = json.Replace("error-text", "ErrorText") 'Adicionei
            Return New JavaScriptSerializer().Deserialize(Of SmsResponse)(json)

        End Function

    End Class

'-------------------------------------------
'Create a new class Message
'Property for each message
'-------------------------------------------

    Public Class Message

        Private m_To As String
        Public Property [To]() As String
            Get
                Return m_To
            End Get
            Set(ByVal value As String)
                m_To = value
            End Set
        End Property

        Private m_Messageprice As String
        Public Property Messageprice() As String
            Get
                Return m_Messageprice
            End Get
            Set(ByVal value As String)
                m_Messageprice = value
            End Set
        End Property

        Private m_Status As String
        Public Property Status() As String
            Get
                Return m_Status
            End Get
            Set(ByVal value As String)
                m_Status = value
            End Set
        End Property

        'Adicionei esta variavel + Propriedade
        Private m_StatusError As String
        Public Property StatusError() As String
            Get
                Return m_StatusError
            End Get
            Set(ByVal value As String)
                m_StatusError = value
            End Set
        End Property

        Private m_MessageId As String
        Public Property MessageId() As String
            Get
                Return m_MessageId
            End Get
            Set(ByVal value As String)
                m_MessageId = value
            End Set
        End Property

        Private m_RemainingBalance As String
        Public Property RemainingBalance() As String
            Get
                Return m_RemainingBalance
            End Get
            Set(ByVal value As String)
                m_RemainingBalance = value
            End Set
        End Property

    End Class

'-------------------------------------------
'Create a new class SmsResponse
'Here we get the response from Nexmo
'with number of message sent and 
'a list for each message with Status
'-------------------------------------------

    Public Class SmsResponse

        Private m_Messagecount As String
        Public Property Messagecount() As String
            Get
                Return m_Messagecount
            End Get
            Set(ByVal value As String)
                m_Messagecount = value
            End Set
        End Property

        Private m_Messages As List(Of Message)
        Public Property Messages() As List(Of Message)
            Get
                Return m_Messages
            End Get
            Set(ByVal value As List(Of Message))
                m_Messages = value
            End Set
        End Property


    End Class

End Namespace

'-----------------------------
'How to use:
'Create a Windows Form 
'Or a WebPage in Asp.Net
'-----------------------------

Imports System.Net
Imports System.IO
Imports SMS.API

 Dim _api As New _cClass_LSettings

    Dim _apiKey, _apiCode, _apiRemetente, _apiDestinatario, _apiSMStext As String

    Dim _smsNexmo As New SmsSender

    Dim _resposta As New SmsResponse

Private Sub _smsAPI()


        _resposta = _smsNexmo.SendSMS("Country Code" & txt_destinatario.Text, _api.remetente,                     txt_msg.Text, _api.apiKey, _api.apiCode)

'Get sms status If was or Not Send 
        If _resposta.Messagecount > 1 Then ' if more then 1 message

            For Each item In _resposta.Messages
               
                    'Save the response
                _lblStatus.Visible = True

                'Save a big message(2 or more parts) in the same row in database
                _messagem = _messagem + txt_msg.Text '''''

                _mostrarStatusSMS(item.Status.ToString)

                Exit For

            Next

        Else 'if only 1 messagem

            For Each item In _resposta.Messages

                _lblStatus.Visible = True

                _mostrarStatusSMS(item.Status.ToString)

         Next

   End If

End Sub

--------------------------

A DEMO Project - NexmoSMS_SourceCode





segunda-feira, 26 de novembro de 2012

PHP Connect to MySql


<?PHP

define ("DEBUG", true); //to authorize debugging

  function connectSRVBD(){
   
        $host="localhost"; // or IP // Server where database is located
       
        $user="DB_UserName"; //user with rights to connect to database
       
        $pass="DB_Password"; // user password
       
        $schema="DataBase"; // the database name
       
        $port=3306;  //Port by Default ;
       
        $db=mysqli_connect($host, $user, $pass, $schema, $port);
       
        $errorCode=mysqli_connect_errno(); // Mysql - Error Code
        $errorMessage=mysqli_connect_error(); // Mysql - Error Message

        if (DEBUG && $errorCode>0)
            echo "ERROR connectSRVBD : $errorCode : $errorMessage<br>";
                                     
        return $errorCode===0?$db:false;
    }
   
?>

 

quarta-feira, 17 de outubro de 2012

Add columns to DataTable



static void Main(string[] args)
{

DataTable dt = new DataTable();

// Add the column to the DataTable to create
DataColumn col1 = dt.Columns.Add();

// Configure the column
//-- integer with a default = 0
// that  does not allow nulls
col1.ColumnName = "1Column";
col1.DataType = typeof(int);
col1.DefaultValue = 0;
col1.Unique = true;
col1.AllowDBNull = false;

// Create  the column
DataColumn col2 = new DataColumn();

// Configure the column
//string with max length = 50
col2.ColumnName = "2Column";
col2.DataType = typeof(string);
col2.MaxLength = 50;


// Add column to the DataTable
dt.Columns.Add(col2);

// Add a column directly using an overload of the Add()
 // method of the DataTable.Columns collection -- the column
 // is a string with max length = 50
dt.Columns.Add("3Column", typeof(string)).MaxLength = 50;

// Add multiple existing columns to the DataTable
DataColumn col4 = new DataColumn("4Column");

// ... configure column 5
DataColumn col5 = new DataColumn("5Column", typeof(int));

// Add columns 4 and 5 to the DataTable
dt.Columns.AddRange(new DataColumn[] { col4, col5 });

// Show the columns in the DataTable to the console
Console.WriteLine("DataTable has {0} DataColumns named:",dt.Columns.Count);

foreach (DataColumn col in dt.Columns)

Console.WriteLine("\t{0}", col.ColumnName);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}










Table Mapping in DOT.NET



static void Main(string[] args)
{

// Configure Sql Provider - to connect to server or database
  string sqlConnectString = @"Data Source=(local)\sqlexpress;" +
  "Integrated security=SSPI; Initial Catalog=DataBase;";

// Creating a table Cliente in a DataBase (Sql, Access...)

 // Query to get desired data
  String sqlSelect = "SELECT TOP 5 IDCliente,Apelido,PrimNome " +
  "From Cliente";

 //Get data from sql to adapter
  SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);

//Mappeding the table
  DataTableMapping dtm =da.TableMappings.Add("Table", "mappedCliente");

// Mapping the column
  dtm.ColumnMappings.Add("IDCliente", "mappedIDCliente");
  dtm.ColumnMappings.Add("Apelido", "mappedApelido"); //...

   dtm.ColumnMappings.Add("PrimNome", "mappedPrimNome"); //...

 // (DataSet = DataBase Virtual)
  DataSet ds = new DataSet();

 // dataset get data from adapter 
   da.Fill(ds);
  Console.WriteLine("DataTable name = {0}",ds.Tables[0].TableName);

// show the mapped columns
 foreach (DataColumn col in ds.Tables["mappedCliente"].Columns)

  {
   Console.WriteLine("\tDataColumn {0} name = {1}",col.Ordinal, col.ColumnName);
  }

 Console.WriteLine();

// A break to view the mapped columns - Enter to continue
 Console.ReadKey(); 

// show data in rows
  foreach (DataRow row in ds.Tables[ "mappedCliente"].Rows)

  {
  Console.WriteLine("IDCliente = {0}, Apelido = {1}, PrimNome = {2}",
      row["mappedIDCliente"], row["mappedApelido"],row["mappedPrimNome"]);

  }

  Console.WriteLine("\nEnd DataTableMapping - Press any Key to           continue");
  Console.ReadKey(); 

}


sexta-feira, 7 de setembro de 2012

Sending SMS using VOIP Web Service


An easy and simple way  to use VOIP services available on the web to send cheap SMS (Messages).

SMS - Sending Page
Source Code:

Imports System.Net
Imports System.IO 

Public Class Form1

Dim LS As New LSettings 'Classe of SMS Server Config

Dim SMSserver, User, Pass, Remetente, Destinatario, SMStext As String

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

If txt_destinatario.Text = String.Empty Or txt_msg.Text = String.Empty Then

MessageBox.Show("Number or Message can not be Empty!")

Else
Cursor = Cursors.WaitCursor
' Create a new web client to send the requestDim client As WebClient = New WebClient()SMSserver = LS.server
User = LS.user
Pass = LS.pass
Remetente = LS.remetente
Destinatario =
"Country Code EX: 00351 " & txt_destinatario.Text & ""SMStext = "" & txt_msg.Text & ""
' Set the URL to send the request to, please note' you can use either HTTP or HTTPS

Dim url As String = _
"https://" _& SMSserver &
"username=" _& User &
"&password=" _& Pass &
"&from=" _& Remetente &
"&to=" _& Destinatario &
"&text=" _& SMStext &
""
Try
' Send the request and read the response
Dim stream As Stream = client.OpenRead(url)
Dim reader As StreamReader = New StreamReader(stream)
Dim response As String = reader.ReadToEnd()

' Close the data stream and HTTP connection
stream.Close()
reader.Close()
Catch ex As ExceptionMsgBox(ex.Message _
& vbNewLine _
&
"The message is in sending state")

End Try
Cursor = Cursors.Default
lblSMSinfo.Visible = True

End If

End Sub

Private Sub txt_destinatario_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles txt_destinatario.MouseClick

lblSMSinfo.Visible = False

End Sub

Private Sub bt_limpar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_limpar.Click

txt_destinatario.Clear()
txt_msg.Clear()
lblSMSinfo.Visible = False

End Sub

Private Sub SettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SettingsToolStripMenuItem.Click

SMSSettings.Show()

End Sub

'Limit insert text only numbers

Private Sub txt_destinatario_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_destinatario.KeyPress

Dim KeyAscii As Short = CShort(Asc(e.KeyChar))
KeyAscii = CShort(LS.ValidarNumero(KeyAscii, "0123456789"))

If KeyAscii = 0 Then
e.Handled = True

End If

End Sub

End Class


SMS - Config. SMS Server Page
Source Code:

Public Class LSettings

Private _server As StringPrivate _user As StringPrivate _pass As StringPrivate _remetente As String 

Public Property server() As String
Get
Return _server
End Get

Set(ByVal value As String)
_server = value

End Set
End Property 

Public Property user() As StringGet
Return _user
End Get

Set(ByVal value As String)
_user = value

End Set
End Property

Public Property pass() As String
Get
Return _pass
End Get

Set(ByVal value As String)
_pass = value

End Set
End Property

Public Property remetente() As String
Get
Return _remetente
End Get

Set(ByVal value As String)
_remetente = value

End Set
End Property

Public Sub Settings(ByVal Dserver As String, ByVal Duser As String, _
                     ByVal Dpass As String, ByVal Dremetente As String)
server = Dserveruser = Duser
pass = Dpass
remetente = Dremetente
End Sub

Public Function ValidarNumero(ByVal Keyascii As Short, ByVal filtroDados As String) As Short'filtroDados = "0123456789,-+" Exemplo

If InStr(filtroDados, Chr(Keyascii)) = 0 Then
ValidarNumero = 0
ElseValidarNumero = Keyascii
End If

Select Case Keyascii
Case 8
ValidarNumero = Keyascii
Case 13
ValidarNumero = Keyascii
Case 32
ValidarNumero = Keyascii
End Select
End Function

End Class