Friday, December 19, 2014

Twilio API Integration for sending SMS and List of Sent SMS


Now, you can send SMS using Twilio API easily by just following the few Steps:
Steps:
1.  Login in to the http://www.twilio.com and if you are not user then sign in.
2.  Now Open Visual Studio and start your project and download twilio and twilioML library from NuGet package installer.
3.  After Login in twilio it will gives you a “ACCOUNT SID” and “AUTH TOKEN” and also “TELEPHONE NUMBER”. Save this credentials and apply in our project as..
//you have to add namespace for twilio as like,
using twilio.com;
//and Now apply that Credentials in to our project..
String AccountSid  = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Account ID..
String AuthToken  = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"; // Authentication Tocken.. 
String TelephoneNo  = 'NNNNNNNNNN'; // Telephone No from the message will sent.
Now, Create Instance of Twilio Rest Client..
var client = newTwilioRestClient($AccountSid, $AuthToken);
Now, Call the Method SendSmsMessage(“Sender No with country Code”, “Receiver No with Country Code”, “Message Body…”) for sending SMS. as like,
cvar sendsms = client.sendSmsMessage(from,to,msg);
Done…. Yuppp…
Your Project is Working…..
* Note:
You can also set Validation on that like “Message length should not be greater than 160 Characters.. etc.”

Now, You can easily manage sent message list..
as below,
public SMSMessage getMessageList(String to, String from)
{
String AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Account ID..
String AuthToken = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"; // Authentication Tocken..
var client = new TwilioRestClient(AccountSid,AuthToken);
SmsMessageResult msgs = postMaster.ListSmsMessages();
List msg = msgs.SMSMessages;
foreach (var smsmsg in msgs.SMSMessages)
{
 if (smsmsg.Status == “received” && smsmsg.From == from && smsmsg.To == to)
{
  return smsmsg;
}
}
 return null;
}

Send Data from Java Script to Controller in .NET MVC



Now, When you are working on some Java script APIs or like for some other purpose you have to send java script data to Controller for storing that value in Database.
So, for that you have use the $.Ajax() for pass this java script data to controller.
and at Controller side, you can get that data easily…
As Like,

 
var uname = 'Nikhil Prajapati';
$.ajax({
        url: "/Main/getRequestID",      // This is path of your Controller with Action Result.
        dataType: "json",                // Data Type for sending the data
        data: {                         // Data that will be passed to Controller
                'my_name': uname,     // assign data like key-value pair
                  // 'my_name'  like fields in quote is same with parameter in action Result
        },
        type: "POST",                  // Type of Request
        contentType: "application/json; charset=utf-8", //Optional to specify Content Type.
        success: function (data) { // This function is executed when this request is succeed.
                alert(data);
        },
        error: function (data) {
                alert("Error");   // This function is executed when error occurred.
        }
});

Now, At Controller Side,
in MainController.cs
        public ActionResult getRequestID(String my_name)
        {
                MYDBModel myTable = new                 Models.MYDBModel();
                myTable.FBUserName = my_name;
                db.MYDBModel.Add(myTable);
                                db.SaveChanges();                          // db object of our DbContext.cs.
                //return RedirectToAction(“Index”);      // After that you can redirect to some pages…
                return Json(true, JsonRequestBehavior.AllowGet);    // Or you can get that data back after inserting into database.. This json displays all the details to our view as well.
        }
So, Yupp, you can pass the java script data easily to Controller..

Thursday, December 18, 2014

Password Encryption and Decryption in ASP.NET

secure_passwords 
  1.  This Method illustrates the Password Encryption...
public static string Encrypt(string originalString)
{
      if (originalString == null)
      {
            return originalString = “”;
      }
      if (String.IsNullOrEmpty(originalString))
      {
            throw new ArgumentNullException
            (“The string which needs to be encrypted can not be null.”);
      }
      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream memoryStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
      cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
      StreamWriter writer = new StreamWriter(cryptoStream);
      writer.Write(originalString);
      writer.Flush();
      cryptoStream.FlushFinalBlock();
      writer.Flush();
      return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
} 
Now, You can call this mehod as ClassName.Encrypt("Your Password");

  2. This Method illustrates the Password Decryption...
public static string Decrypt(string cryptedString)
{
      if (String.IsNullOrEmpty(cryptedString))
      {
            throw new ArgumentNullException
            (“The string which needs to be decrypted can not be null.”);
      }
      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream memoryStream = new MemoryStream
      (Convert.FromBase64String(cryptedString));
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
      cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
      StreamReader reader = new StreamReader(cryptoStream);
      return reader.ReadToEnd();
} 

Now, You can call this mehod as ClassName.Decrypt("Your Encrypted Password")

Note :  for that you have to add namespace of System.Security.Cryptography as like, 
 using System.Security.Cryptography;  


Saturday, August 2, 2014

Youtube Search and play Video in Windows Phone

Youtube Image

Now, Its Time for Searching the Videos in Youtube and play that Video in our Application so easily..!

Now Here is the Design (.xaml) file of my Youtube Search Application.
<phone:PhoneApplicationPage
x:Class="Nikhil'sYoutubeSearchApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="SearchTemplate">
<Grid Margin="0,0,0,30">
<TextBlock Text="{Binding Title}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="355" Margin="120,0,0,0" TextWrapping="Wrap" />
<Image Source="{Binding VideoImg}" HorizontalAlignment="Left" Width="100" Height="100" Stretch="UniformToFill"/>
</Grid>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBox Height="72" Name="TxtSearch" Text="" Width="460" SelectionBackground="#FF75A9C2" >
<TextBox.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF6E704D" Offset="0.884"/>
<GradientStop Color="#FFB0BA87"/>
</LinearGradientBrush>
</TextBox.Background>
</TextBox>
<Button Content="Button" HorizontalAlignment="Right" Height="72" Name="BtnSearch" Width="160" RenderTransformOrigin="0.5,0.5" Click="BtnSearch_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF113B60" Offset="1"/>
<GradientStop Color="#FF8DBFDA"/>
</LinearGradientBrush>
</Button.Background>
</Button>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox HorizontalAlignment="Left" Margin="0,0,0,0" Height="600" ItemTemplate="{StaticResource SearchTemplate}" ItemsSource="{Binding SearchResults}" x:Name="LstVideobox" VerticalAlignment="Top" Width="460" SelectionChanged="LstVideobox_SelectionChanged">
<ListBox.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF413D31"/>
<GradientStop Color="#FF54564F" Offset="0.457"/>
</LinearGradientBrush>
</ListBox.Background>
</ListBox>
</Grid>
</Grid>

</phone:PhoneApplicationPage>


And Now the Code File for that is.. (xaml.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using Microsoft.Phone.Controls;

namespace Nikhils_YoutubeSearch_App
{
public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    private void BtnSearch_Click(object sender, RoutedEventArgs e)
    {
        var wc = new WebClient();
        wc.DownloadStringCompleted += DownloadStringCompleted;
        var src = string.Format("http://gdata.youtube.com/feeds/api/videos?q={0}&format=6", HttpUtility.UrlEncode(TxtSearch.Text));
        wc.DownloadStringAsync(new Uri(src));
    }

    void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        var atomns = XNamespace.Get("http://www.w3.org/2005/Atom");
        var medians = XNamespace.Get("http://search.yahoo.com/mrss/");
        var xml = XElement.Parse(e.Result);
        var videos = (from entry in xml.Descendants(atomns.GetName("entry"))
        select new VideoClass
            {
              VideoID = entry.Element(atomns.GetName("id")).Value,
              VideoImg = (from thumbnail in entry.Descendants(medians.GetName("thumbnail"))
            where thumbnail.Attribute("height").Value == "360"
            select thumbnail.Attribute("url").Value).FirstOrDefault(),
            Title = entry.Element(atomns.GetName("title")).Value
            }).ToArray();
        LstVideobox.ItemsSource = videos;
    }

    private void LstVideobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var curvid = LstVideobox.SelectedItem as VideoClass;
        if (curvid != null)
        {
            var parsedvid = curvid.VideoID.Split('/');
            var id = parsedvid[parsedvid.Length - 1];
            var url = "vnd.youtube:" + id;

            var myfinalurl = "https://www.youtube.com/embed/" + id;

            var tempurl = "https://www.youtube.com/watch?v=" + id + "?autoplay=1";

            var task = new WebBrowserTask { URL = "https://www.youtube.com/embed/" + id + "?autoplay=1" };
            task.Show();
        }
    }
}
}



Now, Finally you created a Application of Youtube Searching and Playing that video.,,!!
:)

Wednesday, July 23, 2014

Show Pop Up menu in Windows Phone

popup
Now, I show you how to display pop up menu in windows phone 7. and how can we handle it.

      for that you have to create a user control that is your pop up screen. and that is displayed in our home screen in windows phone.


    // Place your Design of your User Control here



And this is the code behind of User Control as MyUserControl.xaml.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Media;

namespace NikhilsProject
{
  public partial class MyPopUpScreen : UserControl
  {
    public MyPopUpScreen(String message)
    {
        InitializeComponent();

        txtMessage.Text = message;
        txtMessageShadow.Text = message;
    }

    public void btnYes_Click(object sender, RoutedEventArgs e)
    {
            // Code that will fire when user clicks Yes button.
    }

    public void btnNotNow_Click(object sender, RoutedEventArgs e)
    {
            // Code that will fire when user clicks Not Now button.
    }

    private void ClosePopup()
    {
        Popup buyPop = this.Parent as Popup;
        buyPop.IsOpen = false;
    }
  }
}

So, Now open HomePage.xaml.cs for display pop up at specific location and you have to handle that pop up. This code helps you.

    Popup MusicPlaying = new Popup();
    MusicPlaying.Child = new MyPopUpScreen("Do you want to Stop Music Player");
    MusicPlaying.IsOpen = true;
    MusicPlaying.VerticalOffset = 100;
    MusicPlaying.HorizontalOffset = 25;
    MusicPlaying.Closed += (s1, e1) =>
    {
            // Add you code here to do something
            // when the Popup is closed
    };


Please see the namespace also that i have used in my project;

And, yup its Done Easily...!!