Silverlight some wcf problems - performance

I have created a WCF Service which is called many times,
An example of a call
This Service will do a call to a Database. Lets say in my Client I do have a List with 200 Values. Every Value will match a Database Entry. Every Database Entry does have 10 Values. Now what I do is the following. I select some of the list entrys and call in a loop the WCF Service.
I have 2 Issues
First: the UI will hang for that time the WCF Calls are made
Second: The data will come back step by step, how can I collect them and send it back when all calls are completed?
Please excuse any typos I made, my english is not the best.
Here is my source code
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[OperationContract]
public List<string> GetData(string sWert1, string sWert2)
{
List<string> realtimanswer = new List<string>();
string applicationPath = HostingEnvironment.MapPath("~/Configuration");
cIniReader _ini = new cIniReader(applicationPath + #"\config.ini");
string connectionString = _ini.ReadString("Database", "ConnectionString", "");
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connectionString;
try
{
connection.Open();
OracleCommand cmd = connection.CreateCommand();
cmd = new OracleCommand("GETDATA", connection);
cmd.Parameters.Clear();
OracleParameter param1 = new OracleParameter("PI_Wert1", OracleDbType.Varchar2);
OracleParameter param2 = new OracleParameter("PI_Wert2", OracleDbType.Varchar2);
OracleParameter param3 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param4 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param5 = new OracleParameter("PO_Wert4", OracleDbType.Int16);
param1.Value = sWert1;
param2.Value = sWert2;
param1.Direction = System.Data.ParameterDirection.Input;
param1.Size = 4096;
param2.Direction = System.Data.ParameterDirection.Input;
param2.Size = 4096;
param3.Direction = System.Data.ParameterDirection.Output;
param3.Size = 4096;
param4.Direction = System.Data.ParameterDirection.Output;
param4.Size = 4096;
param5.Direction = System.Data.ParameterDirection.Output;
param5.Size = 4096;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(param3);
cmd.Parameters.Add(param4);
cmd.Parameters.Add(param5);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//cmd.CommandTimeout = 30;
int test = cmd.ExecuteNonQuery();
string returnCode = cmd.Parameters[17 - 1].Value.ToString();
if (returnCode == "OK")
{
string sErg1 = cmd.Parameters[3 - 1].Value.ToString();
realtimanswer.Add(sErg1);
string sErg2 = cmd.Parameters[4 - 1].Value.ToString();
realtimanswer.Add(sErg2);
string sErg3 = cmd.Parameters[5 - 1].Value.ToString();
realtimanswer.Add(sErg3);
string sErg4 = cmd.Parameters[6 - 1].Value.ToString();
realtimanswer.Add(sErg4);
string sErg5 = cmd.Parameters[7 - 1].Value.ToString();
realtimanswer.Add(sErg5);
}
}
catch (Exception exp)
{
cDebugLog.Log("Error in Function: GetData " + exp.Message + " StackTrace: " + exp.StackTrace);
connection.Close();
}
connection.Close();
return realtimanswer;
}
}
I call this with this Code
void Button1_Click(object sender, EventArgs e)
{
busyRealTimeViewPage.IsBusy = true;
try
{
string url = Application.Current.Host.Source.AbsoluteUri;
url = url.Replace("/ClientBin/ICWeb.xap", "/DBService.svc");
var proxy_GetRealTime_DBService = new DBServiceReference.DBServiceClient();
proxy_GetRealTime_DBService.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
proxy_GetRealTime_DBService.GetDataCompleted += new EventHandler<DBServiceReference.GetDataCompletedEventArgs>(proxy_GetRealTime_DBService_GetDataCompleted);
for (int i = 0; i < lstRealtime.Items.Count; i++)
{
if ((lstRealtim.ItemsSource as ObservableCollection<ListOfData>)[i].IsSelected == true)
{
object[] w_toread = new object[5];
string sWrk = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
w_toread[0] = sDat;
w_toread[1] = sDat + "_DE";
w_toread[2] = sDat + "_FR";
proxy_GetRealTime_DBService.GetDataAsync(w_toread[1].ToString(), "current", w_toread[1]);
proxy_GetRealTime_DBService.GetDataAsync(w_toread[2].ToString(), "current", w_toread[2]);
}
}
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Error in Function: Button1_Click " + exp.Message + " StackTrace: " + exp.StackTrace);
}
and now here is the rest of it
void proxy_GetRealTime_DBService_GetDataCompleted(object sender, DBServiceReference.GetMarqueeDataCompletedEventArgs e)
{
try
{
string help = e.UserState.ToString();
string sWrktoView = cStringFunctions.Left(e.UserState.ToString(), help.Length - 3);
// string sWrktoView = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
string sWrktoViewDE = sWrktoView + "_DE";
string sWrktoViewFR = sWrktoView + "_FR";
if ((sWrktoViewDE == e.UserState.ToString()) || (sWrktoViewFR == e.UserState.ToString()))
{
if (!(toView.Any(wrk => wrk.Workgroup == sWrktoView)))
{
if (sWrktoViewDE == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13], sWrktoViewFR, "", "", "", "", "", "", "", "", "", "", "", "", "", ""));
}
if (sWrktoViewFR == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, "", "", "", "", "", "", "", "", "", "", "", "", "", "", sWrktoViewFR, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13]));
}
}
}
if (sWrktoViewFR == e.UserState.ToString())
{
var wrkFR = toView.FirstOrDefault(x => x.WorkgroupFR == sWrktoViewFR);
if (wrkFR != null)
{
wrkFR.WorkgroupFR = sWrktoViewFR;
wrkFR.erg1FR = e.Result[0];
wrkFR.erg2FR = e.Result[1];
wrkFR.erg3FR = e.Result[2];
wrkFR.erg4FR = e.Result[3];
wrkFR.erg5FR = e.Result[4];
// fill with other data
}
}
if (sWrktoViewDE == e.UserState.ToString())
{
var wrkDE = toView.FirstOrDefault(x => x.WorkgroupDE == sWrktoViewDE);
if (wrkDE != null)
{
wrkDE.WorkgroupDE = sWrktoViewDE;
wrkDE.erg1DE = e.Result[0];
wrkDE.erg2DE = e.Result[1];
wrkDE.erg3DE = e.Result[2];
wrkDE.erg4DE = e.Result[3];
wrkDE.erg5DE = e.Result[4];
// fill with other Data
}
}
dgridRealTimeView.ItemsSource = null;
dgridRealTimeView.ItemsSource = toView;
busyRealTimeViewPage.IsBusy = false;
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Methode: proxy_GetRealTime_DBService_GetDataCompleted: " + exp.Message + " StackTrace: " + exp.StackTrace);
}
}
I hope someone can help me out.
Regards
Martin

This call
for (int i = 0; i < lstRealtime.Items.Count; i++)
can take a long time if the there are a lot of items in the list.
You should consider creating a new method on the WCF Service to do all the operations and then returning the result.
public List<string> GetData(string[] sWert1, string[] sWert2)
{
}

Related

TOTP Problem - Microsoft Authenticator is not matching the code generated on server

I am getting a not verified using the TOTP method I have found on the following link.
OTP code generation and validation with otp.net
!My! code is below.
The _2FAValue line at the top is embedded into the QR barcode that Microsoft Authenticator attaches too.
The _Check... Function is the server ajax call to the server which implements OTP.Net library exposing TOTP calculation.
MakeTOTPSecret creates an SHA1 version of a Guid which is applied to the User profile and stored in _gTOTPSecret. NB: This IS populated in the places it is used.
I think I must have missed something obvious to get a result, here.
loSetup2FAData._s2FAValue = $#"otpauth://totp/{loUser.UserName}?secret={loUser.MakeTOTPSecret()}&digits=6&issuer={Booking.Library.Classes.Constants._sCompanyName}&period=60&algorithm=SHA1";
[AllowAnonymous]
public JsonResult _CheckTOTPCodeOnServer([FromBody] Booking.Site.Models.Shared.CheckTotpData loCheckTotpData)
{
string lsMessage = "<ul>";
try
{
string lsEmail = this.Request.HttpContext.Session.GetString("Buku_sEmail");
Booking.Data.DB.Extensions.IdentityExtend.User loUser = this._oDbContext.Users.Where(U => U.UserName.ToLower() == lsEmail.ToLower() || U.Email == lsEmail).FirstOrDefault();
if (loUser != null && loUser.Load(this._oDbContext) && loUser._gTOTPSecret != Guid.Empty)
{
OtpNet.Totp loTotp = new Totp(Booking.Library.Classes.Utility.StringToBytes(loUser.MakeTOTPSecret()), 60, OtpHashMode.Sha1, 6);
loTotp.ComputeTotp(DateTime.Now);
long lnTimeStepMatched = 0;
bool lbVerify = loTotp.VerifyTotp(loCheckTotpData._nTotp.ToString("000000"), out lnTimeStepMatched, new VerificationWindow(2, 2));
if (lbVerify)
{
lsMessage += "<li>Successfully validated Totp code</li>";
lsMessage += "<li>Save is now activated</li>";
return this.Json(new { bResult = true, sMessage = lsMessage + "</ul>" });
}
}
}
catch (Exception loException)
{
lsMessage += "<li>" + Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "_CheckTOTPCodeOnServer") + "</li>";
}
lsMessage += "<li>Unsuccessfully validated Totp code</li>";
return this.Json(new { bResult = false, sMessage = lsMessage + "</ul>" });
}
public string MakeTOTPSecret()
{
string lsReturn = String.Empty;
try
{
using (SHA1Managed loSha1 = new SHA1Managed())
{
var loHash = loSha1.ComputeHash(Encoding.UTF8.GetBytes(this._gTOTPSecret.ToString()));
var loSb = new StringBuilder(loHash.Length * 2);
foreach (byte b in loHash)
{
loSb.Append(b.ToString("X2"));
}
lsReturn = loSb.ToString();
}
}
catch (Exception loException)
{
Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "Identity.MakeSHA1Secret");
}
return lsReturn;
}

Problem two query db2 sqlserver is not print output

This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}

Can't find way to debug Internal Server Error (500) caused by new class

I've read a lot of the postings about 500 errors because of the channel emulator, but this is not the case here. I took the standard bot template, which works just fine with the emulator, and replaced it with
ConnectorClient connector = new ConnectorClient(new
Uri(activity.ServiceUrl));
// calculate something for us to return
// int length = (activity.Text ?? string.Empty).Length;
string responseText=
***Bot_Application2.SilviaRestClass.GetRestResult(activity.Text);***
So the issue is in executing the GetRestResult method in the SilivaRestClass.
The code itself works, I'm using it in lots of other places, as it basically sets up a simple 1)get an input utterance in text, 2)send to my SILVIA AI server, and 3)get an utterance back routine. I have a feeling it has something to do with either private vs public methods, and/or [Serializable], based on what I have read so far. The code (minus the credentials) is below. Many thanks, in advance, for any suggestions to try.
`
bool exit = false;
restResponse = "Hello";
bool sessionNew = true;
string viewMessage = null;
string SILVIAUri = "";
string SILVIACore = "/Core/Create/unique/silName";
string SILVIASubmit = "/IO/SetInputManaged/unique/hello";
string SILVIARead = "/IO/GetAll/unique";
string SILVIARelease = "/Core/Release/{unique}";
string SILVIASubKey = "";
string silName = "";
string returnMessage = null;
string holdit = null;
string holdit2 = null;
int forHold = 0;
string responseFromServer = null;
string isfalse = "false";
string myURI = null;
string unique = null;
//CREATE CORE from SILVIA SERVER
myURI = SILVIAUri + SILVIACore;
myURI = myURI.Replace("silName", silName);
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest request = WebRequest.Create(myURI);
request.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
if (sessionNew)
{
Random rnd1 = new Random();
unique = rnd1.Next().ToString() + "askgracie";
sessionNew = false;
WebResponse wResponse = request.GetResponse();
Stream dataStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
wResponse.Close();
}
//SEND UTTERANCE to SILVIA
holdit = null;
myURI = null;
myURI = SILVIAUri + SILVIASubmit;
holdit = restResponse;
// holdit = HttpUtility.UrlEncode(holdit);
myURI = myURI.Replace("hello", holdit);
myURI = myURI.Replace("unique", unique);
if (holdit == "exit")
{
exit = true;
myURI = SILVIAUri + SILVIARelease;
}
System.Net.WebRequest sendRequest = WebRequest.Create(myURI);
sendRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse sendResponse = sendRequest.GetResponse();
Stream sendStream = sendResponse.GetResponseStream();
StreamReader sendReader = new StreamReader(sendStream);
string send_ResponseFromServer = sendReader.ReadToEnd();
// Clean up the streams and the response.
sendReader.Close();
sendResponse.Close();
holdit = send_ResponseFromServer;
forHold = holdit.IndexOf("success");
holdit2 = holdit.Substring(forHold + 9, 5);
if (holdit2 == isfalse)
{
var simpleUtterResponse = "The bot failed to send the
utterance to SILVIA";
}
//GETRESPONSES FROM SILVIA
returnMessage = null;
holdit = null;
responseFromServer = null;
myURI = SILVIAUri + SILVIARead;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest readRequest = WebRequest.Create(myURI);
readRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse readResponse = readRequest.GetResponse();
Stream readStream = readResponse.GetResponseStream();
StreamReader readReader = new StreamReader(readStream);
string read_ResponseFromServer = readReader.ReadToEnd();
viewMessage = read_ResponseFromServer;
string lastRead = "ID ";
List<string> myArray = new List<string>(viewMessage.Split(new
string[] { "\r\n" }, StringSplitOptions.None));
foreach (string s in myArray)
{
if (lastRead == "type: voice")
{
returnMessage = returnMessage + " " + s.Substring(8);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
}
// Clean up the streams and the response.
//readReader.Close();
//readResponse.Close();
if (exit)
{
myURI = SILVIAUri + SILVIARelease;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest closeRequest =
WebRequest.Create(myURI);
closeRequest.Headers["Ocp-Apim-Subscription-Key"] =
SILVIASubKey;
WebResponse closeResponse = closeRequest.GetResponse();
}
return returnMessage;
}
}
}`
I ended up resolving this by cut/paste the class inside the same namespace and physical .cs file. – Brian Garr just now edit

format export to excel using closedxml with Title

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

Issue in reading google text document

I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}

Resources