I am creating pushnotification in windows phone 8.1.But whenever i am run my code I am not getting any notification to my device.Code is working perfectly without any error. below is my code
string subscriptionUri = "https://hk2.notify.windows.com/?token=AwYAAABR4r1HR4ncUnppJKR5oQ2%2bU1IwNe0dQfXgEltoIoIqBz3sSKHSt8Rge5GtbH2yDvSg2Syd0wd0%2bWhz9cSFMm40QxkEMOafHTXzgKmoKrzuSvDg0xO5etxpJRkqRbl3RWA%3d";
string PushNotificationXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + "sdfsafdsafsdf" + "</wp:BackgroundImage>" + "<wp:Count>" + "0" + "</wp:Count>" + "<wp:Title>" +
"Hi This is Sudheer" + "</wp:Title>" + "</wp:Tile> " + "</wp:Notification>";
string strChannelURI = subscriptionUri;
string secret = "aHsb3Hhhhhnvfuyknk";
string sid = "ms-app://s-1-15-2-435756784356-ffdsfdffd-sfsfsf-1465244715-23315sfdsfdsf61566-4957dsfdsf35136-dsfdsf";
var accessToken = GetAccessToken(secret, sid);
byte[] contentInBytes = Encoding.UTF8.GetBytes(PushNotificationXML);
HttpWebRequest request = HttpWebRequest.Create(subscriptionUri) as HttpWebRequest;
request.Method = "POST";
request.Headers.Add("X-WNS-Type", "wns/badge");
request.ContentType = "text/xml";
request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken.AccessToken));
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(contentInBytes, 0, contentInBytes.Length);
using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
webResponse.StatusCode.ToString();
response "OK";
but not getting any notification to my device.
Related
I am accessing API using Google Apps Script. I am looking for a https://developer.xero.com/documentation/api/reports#TrialBalance
I have tried with the API code as but I get signature invaid as reposnse result [19-09-03 19:45:46:402 IST] oauth_problem=signature_invalid&oauth_problem_advice=Failed%20to%20validate%20signature
function doGet(e) {
getTrialBalances();
}
function getTrialBalances() {
var oauth_nonce = createGuid();
var oauth_timestamp = (new Date().valueOf() / 1000).toFixed(0);
var CONSUMER_KEY = 'B7D5YA8D1HWHUZIGXL1AZS44N'
var PEM_KEY = '-----BEGIN RSA PRIVATE KEY-----' +
'ANIICXAIBAAKBgQC2WiSrkljVAZIgNUe/nBZ+PGJzauBJ6szlzPow1XoySkVikswui1IX4wUzgLmvnCmnQkRPgA43oiZqmK1H68MvirYzQkMa3sETViQAOiRPOrDEUTkemKiDXpaIKedD8T6/P9qzgtgU5hlP/R45POanIuNFvYPdpkm2yybOmI+1TwIjAQABAoGADt/3kc9UU7vXEa2G9shixVVjqoqTVTREFpLL7ePcHfIVCt9yrHFM9wnbyMG9uRZRIyDmbpumClROJImuADxc6reamXdTMX0OwEPogAREnY2diadjVjicoMYYEcdbb6pgDSOWcYtamNmzD5tkPI0bPFU+fTdpzGCOCECQQDvZTha0SRcCZPZipCs7PtAOWtMP1FBe140+cvsWiq2eHMmYDtIi7Mx210i3wzz4+Izl4jXeICKprppaBlJxSFZAkEAwwALfSnpqWeop86nnUICOPmksbK2rTtNVd+WGiAK4reUDJArOOXdDm7fYqppQNA35hxcRmvxeKK7jSYLQYHO5wJAeLFubRL+IszNVqLud9Buh52rQ+C0RbA9+bVqozl+SUqGu3VOzi9oY5114kvUCu38MAiY/BELtVuDpfrOrQuO2QJAHrZZGOOLC8VpyNRBjgEhfHvFNr+hCfO3IHlQmNjHHiIvzTK/u/xoLqfDwzR30194DmQVHHpP0+I9i+OcDjs1rQJBAJMY6h4QdYSFpTPxUOPA/s1lKVvJUIzgzX6oMfvc4TDb0RCz4nCvjJ1NEqPjveB6ze5TzC8BzfRW/aUh49vmgRA=' +
'-----END RSA PRIVATE KEY-----';
var payload = '';
var URL = 'https://api.xero.com/api.xro/2.0/Reports/TrialBalance';
var signatureBase = "GET" + "&" +
encodeURIComponent(URL) + "&" +
encodeURIComponent('date=2019-02-01') + "&" +
encodeURIComponent("oauth_consumer_key=" + CONSUMER_KEY +
"&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=RSA-SHA1&oauth_timestamp=" +
oauth_timestamp + "&oauth_token=" + CONSUMER_KEY + "&oauth_version=1.0");
var rsa = new RSAKey();
rsa.readPrivateKeyFromPEMString(PEM_KEY);
var hashAlg = "sha1";
var hSig = rsa.signString(signatureBase, hashAlg);
var oauth_signature = encodeURIComponent(hextob64(hSig));
var authHeader = "OAuth oauth_token=\"" + CONSUMER_KEY + "\",oauth_nonce=\"" + oauth_nonce +
"\",oauth_consumer_key=\"" + CONSUMER_KEY + "\",oauth_signature_method=\"RSA-SHA1\",oauth_timestamp=\"" +
oauth_timestamp + "\",oauth_version=\"1.0\",oauth_signature=\"" + oauth_signature + "\"";
var headers = {
"Authorization": authHeader,
"Accept": "application/json"
};
var options = {
"headers": headers,
'method': 'GET',
'payload': payload,
'muteHttpExceptions': true,
};
var requestURL = URL + '?date=2019-02-01';
var response = UrlFetchApp.fetch(requestURL, options);
var responseXml = response.getContentText();
Logger.log(responseXml);
}
function createGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16)
});
}
For RSA signing I have used https://github.com/csi-lk/google-app-script-xero-api/blob/master/jsrsasign.gs
UPDATE 2:
I code this, but still not able to get the result
var signatureBase = encodeURIComponent("GET" + "&" + URL + "&" + 'date=2019-02-01' + "&" + "oauth_consumer_key=" + CONSUMER_KEY +
"&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=RSA-SHA1&oauth_timestamp=" +
oauth_timestamp + "&oauth_token=" + CONSUMER_KEY + "&oauth_version=1.0");
Before reading the rest of my answer can you please urgently reset your applications Consumer Key/Secret, as well as create and upload a new public certificate to the developer portal as you've provided both in your question.
At least one issue you're running into that I can spot is how you're building up the signature base string.
Only the initial & should be left unencoded, however the rest of them in the signature base string should be encoded. It looks like the & after the encoded URL and encoded date query param are being left unencoded.
Edit:
The following two lines are leaving the &s out ouf encoding, but they need to be included in the uri encoding
encodeURIComponent(URL) + "&" +
encodeURIComponent('date=2019-02-01') + "&" +
good work
v.b.net I will start a new project on my project and my purpose in this project from the database to extract data from certain tables and I want to save as csv
"##FILE VERSION##","251" "##TABLEDEF START##"
"MESAJ=String,50,""MESAJ"","""",50,Data,"""""
"ID=Integer,0,""ID"","""",10,Data,"""""
"SUBEIND=Integer,0,""SUBEIND"","""",10,Data,"""""
"KASAIND=Integer,0,""KASAIND"","""",10,Data,""""" "##INDEXDEF START##"
"##INDEXDEF END##" "##TABLEDEF END##"
"MESAJ","ID","SUBEIND","KASAIND", "YeniFirma","112","100","101",
"YeniCari","100","100","101", "YeniStok","101","100","101", –
Send your sql dataset result as a parameter to this function. It create csv format for you.
public string ConvertToCSV(DataSet objDataSet)
{
StringBuilder content = new StringBuilder();
if (objDataSet.Tables.Count >= 1)
{
System.Data.DataTable table = objDataSet.Tables[0];
if (table.Rows.Count > 0)
{
DataRow dr1 = (DataRow)table.Rows[0];
int intColumnCount = dr1.Table.Columns.Count;
int index = 1;
foreach (DataColumn item in dr1.Table.Columns)
{
content.Append(String.Format("\"{0}\"", item.ColumnName));
if (index < intColumnCount)
content.Append(",");
else
content.Append("\r\n");
index++;
}
foreach (DataRow currentRow in table.Rows)
{
string strRow = string.Empty;
for (int y = 0; y <= intColumnCount - 1; y++)
{
strRow += "\"" + currentRow[y].ToString() + "\"";
if (y < intColumnCount - 1 && y >= 0)
strRow += ",";
}
content.Append(strRow + "\r\n");
}
}
}
This function send a mail:
public void sendMail(string csv)
{
var sendMailThread = new Thread(() =>
{
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv));
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = DateTime.Now.ToShortDateString() + "Report.csv";
MailMessage ePosta = new MailMessage();
ePosta.From = new MailAddress("xx");
ePosta.To.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.Attachments.Add(attachment);
ePosta.Subject = DateTime.Now + " Subject";
ePosta.Body = DateTime.Now + " body message.";
SmtpClient smtp = new SmtpClient();
smtp.Credentials = new System.Net.NetworkCredential("xxx", "xxx");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
object userState = ePosta;
smtp.SendAsync(ePosta, (object)ePosta);
});
sendMailThread.Start();
}
I have built an SSIS package which reads CSV from certain folder. But now I need to download same csv from exchange server.Also Outlook is not installed on my machine. Will I be able to download CSV from exchange server and how ? Thanks!
I have used some of the code from the link http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html but i have added some new code for removing TCP binding error using ServicePointManager as well as added search filter for retrieving specific emails and this code also takes care of multiple attachment from different emails to be saved on file system.
public void Main()
{
string filePath = "";
string fileName = "";
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
DateTime now = DateTime.Now;
DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
EmailMessage latestEmail = null;
try
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.UseDefaultCredentials = true;
//service.Credentials = new WebCredentials("username", "password");
service.Url = new Uri("");
// 10 mails per page in DESC order
ItemView view = new ItemView(10);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
searchFilterCollection.Add(greaterthanfilter);
SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
searchFilterCollection.Add(lessthanfilter);
SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
//Find mails
FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
foreach (Item item in fir.Items)
{
item.Load(); //Load the entire message with attachment
EmailMessage email = item as EmailMessage;
if (email != null)
{
if (email.HasAttachments == true && email.Attachments.Count == 1)
{
if (email.Subject.StartsWith("Scheduled search") == true)
{
filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
, email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name);
// fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
// email.Attachments[0].Name.ToString();
emailsMap.Add(email, filePath);
}
}
}
}
if (emailsMap.Count > 0) {
foreach (var item in emailsMap) {
//Save attachment
EmailMessage email = item.Key;
filePath = item.Value;
FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
fileAttachment.Load(filePath);
string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name.ToString();
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
}
// Dts.Variables["User::SourceFileName"].Value = fileName;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch(System.Runtime.InteropServices.COMException ex)
{
if (Dts.Variables.Locked == true)
{
Dts.Variables.Unlock();
}
//An error occurred.
Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
Issue: pervasive odbc driver ((called: "Pervasive ODBC engine interface") is visible in ODBC(odbcad32.exe). However, the same odbc driver is not visible in SQL server 2008 import wizard, although I can see the same odbc driver in SQL server 2000 import wizard.
I am using 32-bit win 7 OS with SQL server 2008, SQL server 2000 and pervasive SQL v11. any solution will be very helpful...Many Thanks!
I could never figure out how to do make the 'Import/Export' wizard work in Sql Server Management Studio. I even tried to modify the 'ProviderResources.xml' file as I saw in another response.
I was attempting to migrate Sage Timberline Office data which uses a proprietary 'Timberline Data' ODBC driver. That driver is missing the 'ORDINAL_POSITION' column when you call the 'GetSchema' function in .NET. So 'Import/Export' in Sql Server Management Studio fails.
I ended up having to write my own app to copy the data over to SQL server. The only downside is it doesn't know about primary keys, indexes, or other constraints. Nonetheless, I get the data in MSSQL so I am happy.
I am sure this code will be useful to others, so here you go.
Program.cs
using System;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Diagnostics;
namespace TimberlineOdbcSync
{
class Program
{
static string currentTableName;
const string sourceOdbcDriver = "{Timberline Data}";
const string sourceOdbcDsn = "timberline data source";
const string sourceOdbcUid = "user1";
const string sourceOdbcPwd = "user1a";
const string destSqlServer = "SERVER5";
const string destSqlDatabase = "TSData";
const string destSqlUsername = "";
const string destSqlPassword = "";
const string destSqlOwner = "dbo";
public static void Main(string[] args)
{
DateTime allStartDate = DateTime.Now;
DateTime allEndDate;
DateTime tableStartDate = DateTime.Now;
DateTime tableEndDate;
TimeSpan diff;
string errMsg;
int pCount; //pervasive record count
int sCount; //sql server record count
string sourceOdbcConnString =
"Dsn=" + sourceOdbcDsn + ";" +
"Driver="+ sourceOdbcDriver +";" +
(!string.IsNullOrEmpty(sourceOdbcUid) ? "uid="+ sourceOdbcUid +";" : "") +
(!string.IsNullOrEmpty(sourceOdbcUid) ? "pwd="+ sourceOdbcPwd +";" : "");
string destSqlConnString =
"Server=" + destSqlServer + ";" +
"Database=" + destSqlDatabase+ ";" +
(!string.IsNullOrEmpty(destSqlUsername) && !string.IsNullOrEmpty(destSqlPassword) ?
"User Id=" + destSqlUsername + ";" +
"Password=" + destSqlPassword + ";"
:
"Trusted_Connection=true;");
try{
using(OdbcConnection pConn = new OdbcConnection(sourceOdbcConnString)){
pConn.Open();
List<string> tables = new List<string>();
//get a list of all tables
using(DataTable tableschema = pConn.GetSchema("TABLES"))
foreach(DataRow row in tableschema.Rows)
tables.Add(row["TABLE_NAME"].ToString());
foreach(string tableName in tables){
//set the current table name
currentTableName = tableName;
try{
//get the schema info for the table (from pervasive)
DataTable dtSchema = pConn.GetSchema("Columns", new string[]{null, null, tableName});
//if we could not get the schema
if(dtSchema == null || dtSchema.Rows.Count <= 0){
pConn.Close();
errMsg = "Error: Could not get column information for table " + tableName;
Trace.WriteLine(errMsg);
WriteErrorEvent(errMsg);
return;
}
//emit the table name
Trace.Write("[" + tableName + "]");
//get the number of records in this table
pCount = TableCount(tableName, pConn);
//emit the number of records in this table
Trace.Write(" = P:" + pCount);
//create a data reader to read the pervasive data
string sql = "select * from \""+ tableName + "\"";
OdbcCommand cmd = new OdbcCommand(sql, pConn);
OdbcDataReader dr = cmd.ExecuteReader();
//create a connection to SQL Server
using (SqlConnection sConn = new SqlConnection(destSqlConnString)){
//open the connection
sConn.Open();
//if the table already exists
if(TableExists(tableName, sConn)){
//get the record count for this table
sCount = TableCount(tableName, sConn);
} else {
//set the record count to zero
sCount = 0;
}
//output the record count
Trace.Write(", S: " + sCount);
//if the record counts match
if( pCount == sCount ){
//output an indicator that we are skipping this table
Trace.WriteLine(" -- Skipping");
//skip this table and go to the next
continue;
}
//output a blank line
Trace.WriteLine("");
//create the table in SQL Server using the schema info from Pervasive
CreateTableInDatabase(dtSchema, destSqlOwner, tableName, sConn);
// Copies all rows to the database from the data reader.
using (SqlBulkCopy bc = new SqlBulkCopy(sConn))
{
// Destination table with owner -
// this example does not check the owner names! It uses dbo exclusively.
bc.DestinationTableName = "[" + destSqlOwner + "].[" + tableName + "]";
bc.BulkCopyTimeout = 30;
bc.BatchSize = 3000;
bc.BulkCopyTimeout = 12000;
// User notification with the SqlRowsCopied event
bc.NotifyAfter = 1000;
bc.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
//output the date and time so we know when we started
tableStartDate = DateTime.Now;
Trace.WriteLine("Copying " + pCount + " records to " + destSqlServer + " - " + tableStartDate.ToString("g"));
// Starts the bulk copy.
bc.WriteToServer(dr);
tableEndDate = DateTime.Now;
diff = tableEndDate - tableStartDate;
Trace.WriteLine(String.Format(
"Completed {4} at {0}\r\nDuration: {1}:{2}:{3}",
tableEndDate.ToString("g"),
diff.Hours.ToString(), diff.Minutes.ToString(), diff.Seconds.ToString(),
tableName));
// Closes the SqlBulkCopy instance
bc.Close();
}
dr.Close();
}
}catch(Exception ex){
errMsg = "Error: " + ex.Message + Environment.NewLine +
"Stack: " + ex.StackTrace + Environment.NewLine;
Trace.WriteLine(errMsg);
WriteErrorEvent(errMsg);
if( !ReadBool("Do you want to continue? [y/n]") ){
break;
}
}//end try
}//end for
}//end using
allEndDate = DateTime.Now;
diff = allEndDate - allStartDate;
Trace.WriteLine(
"Bulk copy operation complete" + Environment.NewLine +
"Started: " + allStartDate.ToString("g") + Environment.NewLine +
"Current: " + allEndDate.ToString("g") + Environment.NewLine +
String.Format("Duration: {0}:{1}:{2}",
diff.Hours.ToString(),
diff.Minutes.ToString(),
diff.Seconds.ToString()));
}catch(Exception ex){
errMsg =
"Error: " + ex.Message + Environment.NewLine +
"Stack: " + ex.StackTrace;
Trace.WriteLine(errMsg);
WriteErrorEvent(errMsg);
}//end try
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
static bool TableExists(string tableName, SqlConnection sqlConn){
int retVal = 0;
try{
using(SqlCommand command = sqlConn.CreateCommand()){
command.CommandText = "IF OBJECT_ID('dbo." + tableName + "', 'U') IS NOT NULL SELECT 1 as res ELSE SELECT 0 as res";
retVal = Convert.ToInt32(command.ExecuteScalar());
}
}catch(Exception ex){
string errMsg =
"Error: Could not determine if table " + tableName + " exists."+ Environment.NewLine +
"Reason: " + ex.Message + Environment.NewLine +
"Stack: " + ex.StackTrace;
Trace.WriteLine(errMsg);
WriteErrorEvent(errMsg);
retVal = 0;
}//end try
return (retVal==1);
}
static int TableCount(string tableName, IDbConnection anyConn){
int retVal = 0;
try{
using(IDbCommand command = anyConn.CreateCommand()){
command.CommandText = "SELECT count(*) FROM \"" + tableName + "\"";
retVal = Convert.ToInt32(command.ExecuteScalar());
}
}catch(Exception ex){
string errMsg =
"Error: Could not get table count for " + tableName + "." + Environment.NewLine +
"Reason: " + ex.Message + Environment.NewLine +
"Stack: " + ex.StackTrace;
Trace.WriteLine(errMsg);
WriteErrorEvent(errMsg);
retVal = 0;
}//end try
return (retVal);
}
static bool ReadBool(String question) {
while (true) {
Console.WriteLine(question);
String r = (Console.ReadLine() ?? "").ToLower();
if (r == "y" || r == "yes" || r == "1")
return true;
if (r == "n" || r == "no" || r=="0")
return false;
Console.WriteLine("Please Select a Valid Option!!");
}//end while
}
static void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) {
Trace.WriteLine(String.Format("-- [{1}] Copied {0} rows.", e.RowsCopied, currentTableName));
}
private static string s(object o){
return (Convert.IsDBNull(o) ? "" : Convert.ToString(o));
}
private static string _drToColSql(DataRow dr){
string colName = s(dr["COLUMN_NAME"]);
string ret = "[" + colName + "] ";
string typeName = ((string)s(dr["TYPE_NAME"])).ToLower();
switch(typeName){
case "char":
ret += "CHAR(" + s(dr["LENGTH"]) + ")";
break;
case "byte":
ret += "CHAR(" + s(dr["PRECISION"]) + ")";
break;
case "text":
ret += "VARCHAR(" + s(dr["PRECISION"]) + ")";
break;
case "date":
ret += "DATE";
break;
case "time":
ret += "TIME(7)";
break;
case "double":
ret += "DECIMAL(16,2)"; // + c(dr["PRECISION"]) + "," + c(dr["LENGTH"]) + ")";
break;
case "usmallint":
case "smallint":
ret += "SMALLINT";
break;
case "utinyint":
case "tinyint":
ret += "TINYINT";
break;
case "identity":
case "integer":
ret += "BIGINT";
break;
case "smallidentity":
case "short":
ret += "INT";
break;
case "longvarchar":
case "memo":
ret += "TEXT";
break;
case "checkbox":
ret += "BIT";
break;
case "real":
ret += "REAL";
break;
default:
//this was an unexpected column, figure out what happened
Trace.WriteLine("ERROR - Column '" + colName + "' Details: ");
Trace.WriteLine("\tCOLUMN_NAME: " + s(dr["COLUMN_NAME"]));
Trace.WriteLine("\tTYPE_NAME: " + s(dr["TYPE_NAME"]));
Trace.WriteLine("\tDATA_TYPE: " + s(dr["DATA_TYPE"]));
Trace.WriteLine("\tLENGTH: " + s(dr["LENGTH"]));
Trace.WriteLine("\tPRECISION: " + s(dr["PRECISION"]));
Trace.WriteLine("\tSCALE: " + s(dr["SCALE"]));
Trace.WriteLine("\tNULLABLE: " + s(dr["NULLABLE"]));
throw new Exception("Unexpected data type: " + typeName);
}
if(s(dr["NULLABLE"])=="1"){
ret += " NULL";
}
return ret;
}
private static bool CreateTableInDatabase(DataTable dtSchemaTable, string tableOwner, string tableName, SqlConnection sqlConn) {
// Generates the create table command.
string ctStr = "CREATE TABLE [" + tableOwner + "].[" + tableName + "](\r\n";
for (int i = 0; i < dtSchemaTable.Rows.Count; i++)
{
ctStr += _drToColSql(dtSchemaTable.Rows[i]);
if (i < dtSchemaTable.Rows.Count)
ctStr += ",";
ctStr += "\r\n";
}
ctStr += ")";
// Emit SQL statement
Trace.WriteLine("-".PadLeft(30, '-'));
Trace.WriteLine(ctStr + Environment.NewLine);
// Runs the SQL command to make the destination table.
using(SqlCommand command = sqlConn.CreateCommand()){
command.CommandText = "IF OBJECT_ID('dbo." + tableName + "', 'U') IS NOT NULL DROP TABLE dbo." + tableName;
command.ExecuteNonQuery();
command.CommandText = ctStr;
command.ExecuteNonQuery();
}
return true;
}
private static bool WriteErrorEvent(string errMsg){
const string sSource = "PervasiveOdbcSync";
const string sLog = "Application";
try{
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource,sLog);
EventLog.WriteEntry(sSource, errMsg);
EventLog.WriteEntry(sSource, errMsg, EventLogEntryType.Error, 128);
return true;
}catch(Exception ex){
Trace.WriteLine("Unable to write error to event log. Reason: " + ex.Message);
return false;
}
}
}
}
You'll want to add a System.Diagnostics.ConsoleTraceListener to your app.config file. That way you can see everything that is being outputted. If you also add a System.Diagnostics.TextWriterTraceListener, you can make the app also output everything to a log file.
On my PSQL v11 box which also has SQL Server 2008 R2 installed, I don't see a "Pervasive ODBC Engine Interface" listed in the "Data Source" dialog of the SQL Server Import and Export Wizard. I do see the "Pervasive PSQL OLEDB Provider" and "Pervasive Provider, release v4.0" (and 3.5 and 3.2). THe Pervasive Provider is an ADO.NET provider. I do see a ".Net Framework Data Provider for ODBC" and if I put a DSN name for a Pervasive DSN (like DEMODATA), it works.
i am having one form accepting json post in Asp.net which i need to call from Flash As3...
i am using below code to do that. I have seen some post in which they say its working fine.
But i am encountering below Error
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here is my code.
var messages:Array = new Array ();
messages.push({"From":fromemailTxt.text,"To": ToemailTxt.text,"Body": BodyText.text,"Subject":SubjectText.text});
var JsonObj:String = JSON.encode(messages);
trace(JsonObj);
var variables:URLVariables=new URLVariables(JsonObj);
RequestURL= srvStringURL;
var JSONLoader:URLLoader = new URLLoader();
JSONLoader.dataFormat=URLLoaderDataFormat.TEXT;
JSONLoader.addEventListener(IOErrorEvent.IO_ERROR, GetBookmarkURLError, false, 0, true);
JSONLoader.addEventListener(Event.COMPLETE, parseBookmarkURLResult, false, 0, true);
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var request:URLRequest = new URLRequest(RequestURL);
request.requestHeaders.push(hdr);
request.data=variables;
request.method = URLRequestMethod.POST;
try
{
JSONLoader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred."+error.errorID.toString());
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
Anybody have any idea on this??
Thanks
The error is, because you are passing incorrect string to URLVariables constructor. Do not use URLVariables. Instead pass data as string: request.data=JsonObj;
Below is the code I am using to consume REST Web service and pass json parameter to service it shows. Error #2032: Stream Error.
Andy idea what is going wrong
var ldr:URLLoader = new URLLoader();
ldr.dataFormat = URLLoaderDataFormat.TEXT;
var strData:String = "{\"gparam\": [ {\"productid\": \"" + productId + "\"},{\"message\": \"" + mesage + "\"},{\"googleappid\": \"" + googleappid + "\"},{\"senderid\": \"" + senderid + "\"},{\"appname\": \"" + appName + "\"},{\"userid\": \"" + userId + "\"},{\"receiverid\": \"" + receiverId + "\"} ]}";
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest("http://localhost/AndroidGCM/GCMNotification.svc/SendGCM");
req.requestHeaders.push(hdr);
req.method = URLRequestMethod.POST;
req.data = strData;
trace("data: " + req.data);
ldr.addEventListener(Event.COMPLETE,onComplete);
ldr.addEventListener(IOErrorEvent.IO_ERROR , onError);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR ,onSecurityErr);
ldr.load(req);
function onComplete(e:Event):void
{
trace("LOAD COMPLETE: " + ldr.data);
TextField(parMC.getChildByName("txtCheck")).appendText("\n LOAD COMPLETE: " + ldr.data);
}
function onSecurityErr(e:SecurityErrorEvent):void
{
trace("error: " + e.text );
}
function onError(e:IOErrorEvent):void
{
trace("error: " + e.toString());
}