I've a requirement where I should display the list of all files from google drive (of course using oAuth for authorization and authentication)... displaying the list of files which has the extension (.mp3) along with the full path where the user can either copy the path of the file and paste it in a seperate url or can click on the file name to download the file. I'm not getting proper inputs of getting the full path of the file from google drive. I'm using asp.net application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Client;
using Google.GData.Documents;
using System.IO;
using Google.Apis.Drive.v2;
using Google.Apis.Drive;
using Google.Apis;
namespace AccessGoogleDriveData
{
public partial class GoogleOAuthCallback : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string state = Request.QueryString["state"];
// creating oauthparameter with client id and secret key
OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = "myclientid.apps.googleusercontent.com",
ClientSecret = "clientsecretid",
RedirectUri = "http://localhost:16615/GoogleOAuthCallback.aspx">,
Scope = "https://docs.google.com/feeds/ ",
State = "documents",
AccessType = "offline"
};
lstDocuments.Visible = false;
if (state != null)
{
parameters.AccessCode = Request.QueryString["code"];
// it gets accesstoken from google
Google.GData.Client.OAuthUtil.GetAccessToken(parameters);
GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MyDocumentsListIntegration-v1", parameters);
DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
service.RequestFactory = requestFactory;
DocumentsListQuery query = new DocumentsListQuery();
// Make a request to the API and get all documents.
DocumentsFeed feed = service.Query(query);
lstDocuments.Visible = true;
if (feed.Entries.Count > 0)
{
// var documentsList = from entry in feed.Entries select entry.Title.Text;
var documentsList = from entry in feed.Entries where GetFileExtension(entry.Title.Text.ToString()) == "mp3" select entry.Title.Text;
lstDocuments.DataSource = documentsList;
lstDocuments.DataBind();
}
}
}
protected void btnGetDocuments_Click(object sender, EventArgs e)
{
OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = "myclientid.apps.googleusercontent.com",
ClientSecret = "clientsecretid",
RedirectUri = "http://localhost:16615/GoogleOAuthCallback.aspx",
Scope = "https://docs.google.com/feeds/ ">,
State = "documents",
AccessType = "offline" // offline means it creats a refreshtoken
};
string url = Google.GData.Client.OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
Session["oauthDocumentsParameters"] = parameters;
// it redirct to google login page
Response.Redirect(url);
}
private string GetFileExtension(string sFileName)
{
sFileName = sFileName.Trim();
if (String.IsNullOrEmpty(sFileName))
{
return String.Empty;
}
string sExtension = String.Empty;
char[] cArr = sFileName.ToCharArray();
int iIndex = 0;
for (int i = cArr.Length - 1; i > -1; i--)
{
if (cArr[i].Equals('.'))
{
iIndex = i;
break;
}
}
if (iIndex > 0)
{
for (int i = iIndex + 1; i < cArr.Length; i++)
{
sExtension += cArr[i];
}
}
return sExtension.ToLower();
}
}
}
Related
I have a fairly simple HTML page rendered via asp.net. It looks beautiful in the PDF after running it through HtmlRenderer.PdfSharp EXCEPT that the images don't appear. Just the red X of a missing image in the PDF even though the web page itself does display the image correctly.
Here is my HtmlRenderer.PdfSharp code:
public void BuildPDF( string url, string pdfPath ) {
string html = GetHTML(url);
Byte[] res = null;
using( MemoryStream ms = new MemoryStream() ) {
using( FileStream file = new FileStream(pdfPath, FileMode.Create, FileAccess.Write) ) {
byte[] bytes = new byte[ms.Length];
var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
pdf.Save(ms);
res = ms.ToArray();
file.Write(res, 0, res.Length);
ms.Close();
}
}
}
private string GetHTML(string url) {
string html = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
using( Stream stream = response.GetResponseStream() )
using( StreamReader reader = new StreamReader(stream) ) {
html = reader.ReadToEnd();
}
return html;
}
And here is the img HTML that doesn't render in the PDF: <img src="images/ChartImg.png" />
How can I solve this?
Use the absolute path to the images.
<img src="http://example.org/images/ChartImg.png" />
You can parse the html and do a string replace first before passing it to the pdf converter.
The Code below:
var pdf = PdfGenerator.GeneratePdf(Html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
... ...
public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
var url = e.Src;
if (!e.Src.StartsWith("http://") && !e.Src.StartsWith("https://"))
{
var ImgFilePath = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath))
e.Callback(XImage.FromFile(ImgFilePath));
var ImgFilePath2 = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath2))
e.Callback(XImage.FromFile(ImgFilePath2));
}
else
{
using (var client = new WebClient())
{
using (var stream = new MemoryStream(client.DownloadData(url)))
{
e.Callback(XImage.FromStream(stream));
}
}
}
}
It's better to use the image resolution callback for this for this:
var pdf = PdfGenerator.GeneratePdf(html, pdfConfig, imageLoad: OnImageLoad);
// snip
private void OnImageLoad(object sender, HtmlImageLoadEventArgs e)
{
using (var client = new WebClient())
{
var url = e.Src;
if (!e.Src.StartsWith("http://") && !e.Src.StartsWith("https://"))
{
url = Properties.Settings.Default.BaseUrl.TrimEnd('/') + e.Src;
}
using (var stream = new MemoryStream(client.DownloadData(url)))
{
e.Callback(XImage.FromStream(stream));
}
}
}
I'm late for your problem but maybe this will help someone else.
I used absolute urls and they were correct. Images were loaded correctly when I opened html file in browser.
However, they were not loaded after I converted this html to pdf. So I tried to use image resolution callback like #ohjo suggested. An exception occured here: An existing connection was forcibly closed by the remote host.
I was able to solve this but adding one more line that sets SecurityProtocol to this solution:
var pdf = PdfGenerator.GeneratePdf(Html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
... ...
public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
var url = e.Src;
if (!e.Src.StartsWith("http://") && !e.Src.StartsWith("https://"))
{
var ImgFilePath = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath))
e.Callback(XImage.FromFile(ImgFilePath));
var ImgFilePath2 = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath2))
e.Callback(XImage.FromFile(ImgFilePath2));
}
else
{
using (var client = new WebClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var stream = new MemoryStream(client.DownloadData(url)))
{
e.Callback(XImage.FromStream(stream));
}
}
}
}
Im developing a small Tcp Client Socket application in windows phone. Actually i have a text box, in that whatever the data received from a TCP server, should update continuously in UI text box control.
while (val)
{
result = Receive();
Dispatcher.BeginInvoke((Action)(() =>
{
txtOutput.Text += result;
}));
}
Here in above code, method receive() will receive string data and should update in textbox control but it is not happening,no data is updating to it.
Can any one suggest, how can i resolve this.
Just telling you what i have been advised, "avoid Dispatcher, CoreDispatcher, etc. There are always better solutions."
Below is the piece of code worked for me for both wp8 and wp8.1 WinRT app,
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
where UpdateTicker() method contains your instructions, in this case...
public void UpdateTicker()
{
result = Receive();
txtOutput.Text += result;
}
Hope this helps...
Thanks for everyone, who given a valuable response for my post.
Hi Nishchith,
I tried your code, but it dint works for me
Here is my logic used to update textbox continuously with data received from TCP server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using Windows.Phone.Networking;
using System.Threading.Tasks;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 1000;
const int MAX_BUFFER_SIZE = 2048;
const int ECHO_PORT = 9055; // The Echo protocol uses port 7 in this sample
const int QOTD_PORT = 49152; // The Quote of the Day (QOTD) protocol uses port 17 in this sample
string result = string.Empty;
public MainPage()
{
InitializeComponent();
}
private void btnEcho_Click(object sender, RoutedEventArgs e)
{
SocketClient client = new SocketClient();
Connect(txtRemoteHost.Text, ECHO_PORT);
//close();
}
public void Connect(string hostName, int portNumber)
{
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(2000);
_socket.ConnectAsync(socketEventArg);
Thread.Sleep(5000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
bool val;
if (result == "Success")
{
val = true;
}
else
{
val = false;
}
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
}
public void UpdateTicker()
{
result = Receive();
string[] strsplit = result.Split(' ');
txtOutput.Text = strsplit[1];
}
public string Receive()
{
string response = "Operation Timeout";
if (_socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(1000);
_socket.ReceiveAsync(socketEventArg);
Thread.Sleep(1000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
}
I have created a Windows phone app based on a quiz game. I want that when the user give the correct answer for some question then a small tick mark will be permanently on in the tab of the question.
I want to store score for every question so that i can display that in a place name as 'your score'. And that score will not be reset even if the app is closed.I have used IsolatedStorageFile to store the data for each page separately. In each page i have provided a back button which will navigate to category page using "NavigationService.GoBack()".
//mainpage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using logic.Resources;
using System.IO;
using System.IO.IsolatedStorage;
namespace logic
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/logo.xaml", UriKind.Relative));
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
int y = 0;
if (!fileStorage.FileExists("amazon.txt"))
{
//Create a new StreamWriter, to write the file to the specified location.
StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("amazon.txt", FileMode.OpenOrCreate, fileStorage));
//Write the contents of our TextBox to the file.
fileWriter.WriteLine(y);
//Close the StreamWriter.
fileWriter.Close();
}
}
}
}
//category page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
namespace logic
{
public partial class logo : PhoneApplicationPage
{
public logo()
{
InitializeComponent();
int x = 0;
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new StreamReader
StreamReader fileReader = null;
if (fileStorage.FileExists("amazon.txt"))
{
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("amazon.txt", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
x = Convert.ToInt32(textFile);
//Write the contents of the file to the TextBlock on the page.
fileReader.Close();
if (x == 1)
{
ama.Visibility = System.Windows.Visibility.Visible;
}
}
}
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.Navigate(new Uri("/amazon.xaml", UriKind.Relative));
}
}}
//question page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
namespace logic
{
public partial class amazon : PhoneApplicationPage
{
public amazon()
{
InitializeComponent();
}
//check the answer is correct or not
int count = 0;
int x;
private void b1_Click(object sender, RoutedEventArgs e)
{
if (tb1.Text.Length == 0 || tb2.Text.Length == 0 || tb3.Text.Length == 0 || tb4.Text.Length == 0 || tb5.Text.Length == 0 || tb6.Text.Length == 0)
{
}
else
{
Char s1, s2, s3, s4, s5, s6;
s1 = Char.ToUpper(tb1.Text[0]);
s2 = Char.ToUpper(tb2.Text[0]);
s3 = Char.ToUpper(tb3.Text[0]);
s4 = Char.ToUpper(tb4.Text[0]);
s5 = Char.ToUpper(tb5.Text[0]);
s6 = Char.ToUpper(tb6.Text[0]);
if (s1 == 'A' && s2 == 'M' && s3 == 'A' && s4 == 'Z' && s5 == 'O' && s6 == 'N')
{
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new StreamReader
StreamReader fileReader = null;
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("amazon.txt", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
x = Convert.ToInt32(textFile);
//Write the contents of the file to the TextBlock on the page.
fileReader.Close();
if (x == 0)
{
fileStorage.DeleteFile("amazon.txt");
//Create a new StreamWriter, to write the file to the specified location.
StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("amazon.txt", FileMode.OpenOrCreate, fileStorage));
fileWriter.WriteLine("1");
//Close the StreamWriter.
fileWriter.Close();
}
ans.Text = "Correct!!!";
}
else
{
ans.Text = "\n\nINCORRECT";
}
}
}
//reset the value
private void reset_Click(object sender, RoutedEventArgs e)
{
tb1.Text = "";
tb2.Text = ""; tb3.Text = ""; tb4.Text = ""; tb5.Text = ""; tb6.Text = "";
}
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.GoBack();
}
}
}
The problem is that when ever i gave the correct answer and press the back button which navigate to logo page the trick(named as "ama" in category code) do not show. But when again i navigate to mainpage then come back to category page the trick is shown. I want that when ever i give the correct answer and navigate back to category page using the back button provided in the app or back button of mobile the trick should be shown at that time only.
According to your code.
Your logic is in constructor of that class. Which is called once you navigate to it from main page and is not called again when you navigate back from question page.
So, you are logically not executing any code when it navigates back, hence displaying the same view as it was.
To make it update, write your logic code in Page_Loaded event.
I'm working on a 2D mobile game for ios and android using Unity3D.
The game requires to save a JSON response to a file.
I use NGUI and MiniJSON for that.
I want to know how to implement that starting from www function to get JSOn response and save it to a file(including path) and load it from other script.
if it is too much, just give me a example for that.
Thank you
I haven't tested the code yet, but it might give you an idea :-)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class WWWJsonTest : MonoBehaviour
{
private const float SECONDS_BEFORE_TIMEOUT = 10;
private const string URL = "INSERT URL HERE";
private const string FILE_PATH = "INSERT FILE PATH";
public void DownloadAndSave()
{
StartCoroutine(DownloadCoroutine());
}
public Dictionary<object, object> GetSavedData()
{
// Use ReadContents() and do your MiniJSON magic here
return null;
}
private IEnumerator DownloadCoroutine()
{
var requestHeaders = new Hashtable()
{
{ "Connection", "close"},
{ "Accept", "application/json"}
};
using(var request = new WWW(URL, null, requestHeaders))
{
float timeStarted = Time.realtimeSinceStartup;
while(!request.isDone)
{
// Check if the download times out
if(Time.realtimeSinceStartup - timeStarted > SECONDS_BEFORE_TIMEOUT)
{
Debug.Log("Download timed out");
yield break;
}
yield return null;
}
// Check for other errors
if(request.error != null)
{
Debug.Log(request.error);
yield break;
}
SaveContents(request.text);
}
}
private string ReadContents()
{
string ret;
using(FileStream fs = new FileStream(FILE_PATH, FileMode.Open))
{
BinaryReader fileReader = new BinaryReader(fs);
ret = fileReader.ReadString();
fs.Close();
}
return ret;
}
private void SaveContents(string text)
{
using(FileStream fs = new FileStream(FILE_PATH, FileMode.Create))
{
BinaryWriter fileWriter = new BinaryWriter(fs);
fileWriter.Write(text);
fs.Close();
}
}
}
I am working on reading email attachment using java mail. This is the code I've used :
public static void main(String args[]) throws Exception {
String host = "172.16.0.186";
String user = "admin";
String password = "1234";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Get a Store object that implements the specified protocol.
Store store = null;
try {
store = session.getStore("pop3");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
} catch (Exception e) {
logger.warn("An exception occured," + e);
}
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("Inbox");
// Open the Folder.
folder.open(Folder.READ_WRITE);
Message[] message = folder.getMessages();
for (int a = 0; a < message.length; a++) {
System.out.println("-------------" + (a + 1) + "-----------");
System.out.println(message[a].getSentDate());
Multipart multipart = (Multipart) message[a].getContent();
for (int i = 0; i < multipart.getCount(); i++) {
//System.out.println(i);
//System.out.println(multipart.getContentType());
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
File file = new File("C:\\Attachments\\" + bodyPart.getFileName());
BufferedReader br = new BufferedReader(
new InputStreamReader(stream));
while (br.ready()) {
System.out.println(br.readLine());
}
saveFile(bodyPart.getFileName(), stream);
attachments.add(file);
System.out.println();
}
System.out.println();
}
folder.close(true);
store.close();
}
/**
* Save file.
*
* #param filename
* the filename
* #param input
* the input
*/
public static void saveFile(String filename, InputStream input) {
System.out.println(filename);
try {
if (filename == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
// Do no overwrite existing file
filename = "C:\\Attachments\\" + filename;
File file = new File(filename);
for (int i = 0; file.exists(); i++) {
file = new File(filename + i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) >= 0) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
} //end of saveFile()
}
The following exception occured : javax.mail.NoSuchProviderException: pop3
the last question : if it is possible to read all file types using java mail API then how can we read an excel file ,HTML file, or a word file.