ASP.net Retrieving data from database always failing with ajax - ado.net

Got this jquery code am using to retrieve data from database through ADO.net:
$(document).ready(getBooks);
function getBooks() {
$.ajax({
type: "POST",
url: "main.aspx/getBooks",
data: "{}",
datatype: "json",
contenttype: "application/json; charset=utf-8",
success: function (data) {
var TableContent = "<table>" +
"<tr>" +
"<td>ISBN</td>" +
"<td>Book Title</td>" +
"<td>Public Year</td>" +
"<td>Category</td>" +
"</tr>";
for (var i = 0; i < data.d.length; i++) {
TableContent += "<tr>" +
"<td>" + data.d[i].ISBN + "</td>" +
"<td>" + data.d[i].BOOK_TITLE + "</td>" +
"<td>" + data.d[i].PUBLICATION_YEAR + "</td>" +
"<td>" + data.d[i].CATEGORY_TYPE + "</td>" +
"</tr>";
}
TableContent += "</table>";
$("#UpdatePanel").html(TableContent);
},
error: $("#UpdatePanel").html("Error")
});
}
C# code looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> getBooks()
{
List<Book> allBooks = new List<Book>();
using (LibraryEntities le = new LibraryEntities())
{
allBooks = le.Books.ToList();
}
return allBooks;
}
My issue is that am always getting nothing and after i added:
error: $("#UpdatePanel").html("Error")
Am only getting "Error" in UpdatePanel element, i am an AJAX Newbie, need your help guys.

Related

Splitting a string Value into chunks of a certain size

public static void SplittingStringIntoChunksCounts(string InputValue)
{
int ChunkSize = 5;
InputValue = "TestingManualTestingAutomTesting";
Dictionary<string, int> dictValue = new Dictionary<string, int>();
for (int i = 0; i < InputValue.Length; i += chunkSize)
{
if (i + chunkSize <= InputValue.Length)
{
Console.WriteLine(InputValue.Substring(i, chunkSize));
string tempValue = InputValue.Substring(i, chunkSize);
if (dictValue.ContainsKey(tempValue))
//if (!dictValue.ContainsKey(tempValue))
{
dictValue[tempValue]++;
//dictValue[tempValue] = 0;
}
else { dictValue[tempValue] = 1; }
// dictValue[tempValue]++;
}
}
foreach (var item in dictValue)
{
Console.WriteLine("Input User== " + " " + item.Key + " " + "Number of Time" + " " + item.Value);
}
}
foreach (var item in dictValue)
{
Console.WriteLine("Input User== " + " " + item.Key + " " + "Number of Time" + " " + item.Value);
}

Windows Service not receiving API response when request takes more than 5 mins to process

We have implented a queuing mechanism with windows service which sends API requests in sequential manner. When the API request take more than 5 mins to process, windonws service not taking the subsequent items.
With the log we observed that, windows service not receiving response from API. But when we debug the same things are working fine.
Do we know whether API not giving response back to windows service or something is going on?
Below is the code piece for this issue:
private void ProcessQueueRequestsByEnvironment(EnvironmentTypes environmentType)
{
try
{
var queueRequests = new DbHelper().GetQueueRequestsByEnvironment(environmentType);
if (queueRequests != null && queueRequests.Count > 0)
{
foreach (var queueRequest in queueRequests)
{
LoggingHelper.WriteToFile("======Request Starting - " + environmentType.ToString() + "====== QueueId: " + queueRequest.QueueId + " AnalysisId: " + queueRequest.AnalysisId + " at " + DateTime.Now);
ApiServiceHelper.SendAnalysisRequestToProcess(queueRequest, environmentType);
LoggingHelper.WriteToFile("======Request Completed - " + environmentType.ToString() + "====== QueueId: " + queueRequest.QueueId + " AnalysisId: " + queueRequest.AnalysisId + " at " + DateTime.Now);
}
}
}
catch (Exception ex)
{
if (!ex.Message.Contains("Could not find stored procedure 'SP_GetQueueRequestsToProcess'"))
{
EmailHelper.SendErrorEmailNotification(ex, "QueueProcessingService::ProcessQueueRequestsByEnvironment");
}
LoggingHelper.WriteToFile("======Error occurred while processing " + environmentType.ToString() + " requests at ======" + DateTime.Now + Environment.NewLine + ex.Message + ex.StackTrace);
}
}
....................
public class ApiServiceHelper
{
public static bool SendAnalysisRequestToProcess(QueueItemModel queueItem, EnvironmentTypes environmentType)
{
try
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan; // Infinite request timeout
string apiUrl = ConfigurationManager.AppSettings["ProductionApiUrl"];
if (environmentType == EnvironmentTypes.STAGING)
{
apiUrl = ConfigurationManager.AppSettings["StagingApiUrl"];
}
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Add("ServiceRequestKey", ConfigurationManager.AppSettings["ServiceRequestKey"]);
using (StringContent content = new StringContent(JsonConvert.SerializeObject(queueItem), Encoding.UTF8, "application/json"))
{
//HTTP POST
var result = client.PostAsync(apiUrl, content).Result;
bool objResult = JsonConvert.DeserializeObject<bool>(result.Content.ReadAsStringAsync().Result);
return objResult;
}
}
}
catch (Exception ex)
{
LoggingHelper.WriteToFile("======Error occurred while processing the request====== QueueId: " + queueItem.QueueId + " AnalysisId: " + queueItem.AnalysisId + " at " + DateTime.Now + Environment.NewLine + ex.Message + ex.StackTrace);
EmailHelper.SendErrorEmailNotification(ex, "ApiServiceHelper::SendAnalysisRequestToProcess");
return false;
}
}

facebook photo upload via image data

I'm using graph api v2.1. AS3-code generates data, calls JS-code via ExternalInterface, JS-code calls FB API
I'm able to upload photo via {image-url}, but getting error when trying to upload photo via {image-data}:
{message: "(#324) Requires upload file", type: "OAuthException", code:
324}
I guess, i'm formatting {image-data} wrong. here is my code:
AS3:
var id:int = Math.random()*10000;
var stream:ByteArray = new ByteArray();
var imageName:String = id.toString() + ".png";
var boundary:String = "I" + id.toString();
stream.writeUTFBytes(
'Content-Type: multipart/form-data; boundary=' + boundary +
'\r\n\r\n--' + boundary +
'\r\nContent-Disposition: file; filename="' + imageName + '"' +
'\r\nContent-Type: image/png' +
'\r\nContent-Transfer-Encoding: binary' +
'\r\n\r\n');
stream.writeBytes(picture);
stream.writeUTFBytes("\r\n--" + boundary + '--\r\n');
if (ExternalInterface.available)
{
ExternalInterface.call('savePhoto', stream, null, id);
}
JS:
function savePhoto(bytes, url, requestId)
{
var data;
if (bytes != null)
data = {"source": bytes, "no_story":true}; //getting error
else
data = {"url": url, "no_story":true}; //works fine
FB.api(
"/me/photos",
"POST",
data,
function (response)
{
//handle response
}
);
}
UPD:
Here is how picture initialised:
[Embed(source="../res/logo_2.png", mimeType="image/png")]
private var testImage:Class;
<...>
var data:Bitmap = new testImage() as Bitmap;
var picture:ByteArray = PNGEncoder.encode(data.bitmapData);
Did you try base64?
var params: Object = new Object;
var encoder:JPGEncoder = new JPGEncoder(75);
var bytes:ByteArray = encoder.encode(bmp.bitmapData);
params.message = message;
params.image = bytes;
params.fileName = "image.jpg";
Facebook.api("/me/photos",null,params,"POST");
https://code.google.com/p/as3corelib/
Try this code to prepare data:
var pngData:ByteArray = PNGEncoder.encode(image.bitmapData);
var strForStart:String = "\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"photo\"; filename=\"file1.png\"\r\n" + "Content-Type: image/png\r\n\r\n" + "";
var strForEnd:String = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"Upload\"\r\n\r\n" + "Submit Query\r\n" + "--" + boundary + "--";
var beginBA:ByteArray = new ByteArray();
beginBA.writeMultiByte(strForStart, "ascii");
var endBA:ByteArray = new ByteArray();
endBA.writeMultiByte(strForEnd, "ascii");
var resultBytes:ByteArray = new ByteArray();
resultBytes.writeBytes(beginBA, 0, beginBA.length);
resultBytes.writeBytes(pngData, 0, pngData.length);
resultBytes.writeBytes(endBA, 0, endBA.length);

Add a user to a group programatically

Is it possible to add a user to a group via REST/sdk?
Scenario: We want to add all our users to a mandatory group on a regularly basis.
Thanks!Max
you can get group ids from share point list like this
function GetMandatoryGroups() {
var context;
var factory;
var appContextSite;
var oList;
var collListItem;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
oList = this.web.get_lists().getByTitle('MandatoryGroups');
context.load(oList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Title,Id)');
context.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
function successHandler() {
MandatoryGroups = new Array();
var listItemInfo = '';
var listitemenumerator = collListItem.getEnumerator();
while (listitemenumerator.moveNext()) {
var olistitem = listitemenumerator.get_current();
//listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
MandatoryGroups.push(olistitem.get_item('Title'));
}
AutoJoinGroups();
// document.getElementById("message").innerHTML = 'Lists found' + oList.get_title() + ':<ul>' + listItemInfo + '</ul>';
}
function errorHandler(sender, args) {
document.getElementById("message").innerText =
"Could not complete cross-domain call: " + args.get_message();
}
}
you can join users to the mendatory groups like this (after user logs in )
function AutoJoinGroups() {
yam.platform.request({
// yam.request({
url: "groups.json?mine=1",
method: "GET",
data: {},
success: function (group) {
//for ($i = 0; $i < MandatoryGroups.length; $i++) {
// if (!ArrayContains(MandatoryGroups[$i].toString(), group)) {
// joinGroupAsync(MandatoryGroups[$i].toString());
// setTimeout('', 10000);
// // setTimeout(joinGroupAsync(MandatoryGroups[$i].toString()),5000);
// }
//}
var i = 0;
function AsyncAutoJoinLoop() {
if (i < MandatoryGroups.length) {
if (!ArrayContains(MandatoryGroups[i].toString(), group)) {
setTimeout(function () {
joinGroupAsync(MandatoryGroups[i].toString());
i++;
if (i < MandatoryGroups.length) {
AsyncAutoJoinLoop();
}
}, 3000)
}
}
}
AsyncAutoJoinLoop();
// getMyGroups();
},
error: function (group) {
console.error("There was an error with the request.");
}
});
}
function joinGroupAsync(id) {
yam.platform.request({
// yam.request({
url: "group_memberships.json?group_id=" + id,
method: "POST",
data: {},
success: function (group) {
},
error: function (group) {
console.error("There was an error with the request.");
}
});
}
you can add group to the sharepoint list like this.
function InsertMandatoryItem() {
var context;
var factory;
var appContextSite;
var oListItem;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
var oList = this.web.get_lists().getByTitle('MandatoryGroups');
var itemCreateInfo = new SP.ListItemCreationInformation();
oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', InsertGroupId);
oListItem.update();
context.load(oListItem);
context.executeQueryAsync(
Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);
function onQuerySucceeded() {
//alert('Item created: ' + oListItem.get_id());
// getMyGroups();
// AutoJoinGroups();
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
}
function onQueryFailed(sender, args) {
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
You can remove remove group from sharepoint list like this
function RemoveMandatoryGroup() {
var context;
var factory;
var appContextSite;
var collListItem;
var itemId;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
var oList = this.web.get_lists().getByTitle('MandatoryGroups');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + RemoveGroupId.toString() + "</Value></Eq></Where></Query></View>");
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Title,Id)');
// this.oListItem.deleteObject();
context.executeQueryAsync(
Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);
function onQuerySucceeded() {
var oListItem;
var listitemenumerator = collListItem.getEnumerator();
while (listitemenumerator.moveNext()) {
var itemtoDelete = listitemenumerator.get_current();
////listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
//MandatoryGroups.push(olistitem.get_item('Title'));
itemId = itemtoDelete.get_id();
}
oListItem = oList.getItemById(itemId);
oListItem.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, onQueryDeleteSucceeded), Function.createDelegate(this, onQueryDeleteFailed));
//alert('Item created: ' + oListItem.get_id());
function onQueryDeleteSucceeded() {
//alert('Request failed. ' + args.get_message() +
// '\n' + args.get_stackTrace());
getMyGroups();
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
}
function onQueryDeleteFailed() {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
No, there isn't. This is by design. Yammer likes to entice with the carrot, not by the stick. What we've done is create communications to ask people to join a specific group.
The api does allow the ability for the currently logged to be joined to a specific group. E.g. Put a link on a SharePoint site that says "Join the Yammer group", and have the action join that user to the group. You can see the details for how to do that here:
https://developer.yammer.com/restapi/#rest-groups
ya, in costume app yo can autojoin that user when he logs in..Same thing i ma doing.

I am using iOS InAppPurchaseManager

with phonegap 1.5.0rc1 and XCode 4.3.
I can not upgrade my mac for the moment.
When I use plugins I do not have any answer, no alert and no message.
I try to do this :
function onDeviceReady() {
processdiv = document.getElementById('processdiv');
processdiv.innerHTML = "Loading...";
window.plugins.inAppPurchaseManager.onPurchased = function(transactionIdentifier, productId, transactionReceipt) {
console.log('purchased: ' + productId);
/* Give coins, enable subscriptions etc */
}
processdiv.innerHTML += "<br />onPurchased OK";
window.plugins.inAppPurchaseManager.onRestored = function(transactionIdentifier, productId, transactionReceipt) {
console.log('restored: ' + productId);
/* See the developer guide for details of what to do with this */
}
processdiv.innerHTML += "<br />onRestored OK";
window.plugins.inAppPurchaseManager.onFailed = function(errno, errtext) {
console.log('failed: ' + errtext);
}
processdiv.innerHTML += "<br />onFailed OK";
}
function requestProdData(prodStr) {
window.plugins.inAppPurchaseManager.requestProductData(prodStr, function(productId, title, description, price) {
console.log("productId: " + productId + " title: " + title + " description: " + description + " price: " + price);
showAlert("productId: " + productId + " title: " + title + " description: " + description + " price: " + price);
window.plugins.inAppPurchaseManager.makePurchase(productId, 1);
}, function(id) {
console.log("Invalid product id: " + id);
showAlert("par la ?? " + id);
}
);
processdiv.innerHTML = "ProductID: " + prodStr + "<br />";
}
Help
I try to add alert in different place of code to know what is the problem.
I had many products in a test app.
I search example to use this plugins. Thanks.
Do not foget to add plugins inAppPurchaseManager in you plugins Cordova.plist :(