I try to add a Link between my Task and my UserStory.
The Program works on my LocalPC, but on the Server the execution fails,
because the workItemStore.WorkItemLinkTypes.LinkTypeEnds are empty.
Whats the problem on the server ?
private static void CreateNewWorkitem(...)
{
using (var tpc = new TfsTeamProjectCollection(new Uri("http://SERVER URI")))
{
var workItemStore = new WorkItemStore(tpc);
var teamProject = workItemStore.Projects["PROJECT"];
var workItemType = teamProject.WorkItemTypes["Fehler"];
WorkItem userStory = new WorkItem(workItemType)
{ Title = Titel, IterationPath = Path };
...
try
{
workItemStore.RefreshCache(true);
WorkItem Task = userStory.Copy(teamProject.WorkItemTypes["Aufgabe"]);
Task.Save();
userStory.Links.Add(new RelatedLink
(workItemStore.WorkItemLinkTypes.LinkTypeEnds
.First(k => k.Name == "Untergeordnet"),Task.Id));
userStory.Save();
}
catch (Exception e)
{
Console.WriteLine("Fehler! " + e.ToString());
}
}
}
Related
We have a web API application which runs on .net4.6.1. We have tried several times to figure out the root cause where it is getting deadlock, but failed. Below is the code snippet. We are hitting this API endpoint every 1 minute. It will pick 300 transaction at a time for processing from the DB. We have observed that it get stuck when there are no files to process from the DB. Not sure though. It would be helpful if someone can help us.TIA
public class TaxEngineIntegratorController : ApiController
{
public async Task Get(int id)
{
try
{
await MainFileMethod();
}
catch (Exception Ex)
{
SerilogMethods.LogError(log, Ex, "Get");
}
}
public async Task MainFileMethod()
{
List<FileTransaction> lstFTtoLock = new List<FileTransaction>();
try
{
List<int> lstStatusIds = new List<int>();
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.ConversionToXmlSucceded));
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.Reprocess));
//Getting the serviceURL of TRTaxEngine
string seriviceURL = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxEngineURL);
//Getting the output path for the file to be placed after processing
string outputfilePath = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxOutputXMLFolder);
FileMasterManager objFileMasterManager = new FileMasterManager();
TRTaxXMLOperations objxmlresp = new TRTaxXMLOperations();
//Getting all the files list for proccessing from the DB
List<FileTransaction> lstFiletoProcess = await objTransManager.GetFileListforProcessingAsync(lstStatusIds, true);
lstFTtoLock = lstFiletoProcess;
if (lstFiletoProcess.Count == 0)
return;
if (lstFiletoProcess.Count > 0)
{
var tasks = new List<Task<string>>();
using (HttpClient httpClnt = new HttpClient())
{
httpClnt.Timeout = TimeSpan.FromMilliseconds(-1);
foreach (FileTransaction item in lstFiletoProcess)
{
TRXMLResponseModel objRespModel = new TRXMLResponseModel();
objRespModel.strxmlResponse = string.Empty;
string fullFileName = item.FilePath + item.ConvertedName;
objRespModel.outputFilename = outputfilePath + item.ConvertedName;
FileMaster fileMaster = objFileMasterManager.GetById(item.FileId);
//Proccessing the file and getting the output filedata
Task<string> t = objxmlresp.GetXMLResponse(seriviceURL, fullFileName, fileMaster.CountryId.GetValueOrDefault(), httpClnt, objFileOperation, objRespModel.outputFilename, item);
tasks.Add(t);
objRespModel.strxmlResponse = await t;
}
var result = await Task.WhenAll(tasks);
}
SerilogMethods.LogCustomException(log, "Http Client Destroyed in Tax Engine", "GetXMLResponse");
}
}
catch (Exception Ex)
{
if (lstFTtoLock != null && lstFTtoLock.Count > 0)
{
objTransManager.UpdateFileTransactionIsPickedtoFalse(lstFTtoLock);
}
throw Ex;
}
}
}
//Getting all the files list for proccessing from the DB
public async Task<List<FileTransaction>> GetFileListforProcessingAsync(List<int> lstStatusList, bool IsActive)
{
try
{
List<FileTransaction> lstFTList = new List<FileTransaction>();
using (SUTBACDEVContext db = new SUTBACDEVContext())
{
//DataTable dtFileTransactions = GetFileTransactionListAsync(lstStatusList, IsActive);
string connectionString = db.Database.GetDbConnection().ConnectionString;
var conn = new SqlConnection(connectionString);
string query = #"[SUTGITA].[GetFileListforProcessing]";
using (var sqlAdpt = new SqlDataAdapter(query, conn))
{
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlAdpt.SelectCommand.Parameters.AddWithValue("#StatusId", string.Join(",", lstStatusList.Select(n => n.ToString()).ToArray()));
sqlAdpt.SelectCommand.Parameters.AddWithValue("#IsActive", IsActive);
sqlAdpt.SelectCommand.CommandTimeout = 60000;
DataTable dtFileTransactions = new DataTable();
sqlAdpt.Fill(dtFileTransactions);
if (dtFileTransactions != null && dtFileTransactions.Rows.Count > 0)
{
IEnumerable<long> ids = dtFileTransactions.AsEnumerable().ToList().Select(p => p["id"]).ToList().OfType<long>();
lstFTList = await db.FileTransaction.Include(x => x.File.Country).Where(x => ids.Contains(x.Id)).OrderBy(x => x.Id).ToListAsync();
}
}
}
return lstFTList;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> GetXMLResponse(string baseUrl, string fullFileName, int countryId, HttpClient client, FileOperations objFileOperation, string outputfilePath, FileTransaction item)
{
try
{
var fileData = new StringBuilder(objFileOperation.ReadFile(fullFileName));
using (HttpContent content = new StringContent(TransformToSOAPXml(fileData, countryId), Encoding.UTF8, "text/xml"))
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, baseUrl))
{
request.Headers.Add("SOAPAction", "");
request.Content = content;
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
using (Stream streamToWriteTo = File.Open(outputfilePath, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
}
var transactionEntry = new FileTransaction
{
FileId = item.FileId,
FilePath = outputfilePath,
ConvertedName = item.ConvertedName,
ActionedBy = Process.Process3,
TimeStamp = DateTime.UtcNow,
StatusId = objStatusManager.GetStatusIdbyName(Status.OutputXmlReceived),
IsActive = true,
CreatedBy = Others.Scheduler,
CreatedOn = DateTime.UtcNow,
ModifiedBy = Others.Scheduler,
ModifiedOn = DateTime.UtcNow
};
//Inserting the new record and Updating isActive filed of previous record in Tranasaction table(Calling updateDataonTRSuccess method of TRTaxXMLOperations class)
await updateDataonTRSuccessAsync(item, transactionEntry);
return "Success";
}
else
{
SerilogMethods.LogCustomException(log, "Error occured in Tax Engine", "GetXMLResponse");
//Log the SOAP response when the SOAP fails with an error message
if (response.Content != null)
{
throw new Exception(await response.Content.ReadAsStringAsync());
}
return null;
}
}
}
}
}
catch (Exception ex)
{
SerilogMethods.LogError(log, ex, "GetXMLResponse");
return null;
}
}
The following changes I have done to make it work to this specific method.
Removal of this line : objRespModel.strxmlResponse = await t;
and added configureawait(false) to this line :List lstFiletoProcess = await objTransManager.GetFileListforProcessingAsync(lstStatusIds, true).ConfigureAwait(false); Below is the working code
public async Task MainFileMethod()
{
List<FileTransaction> lstFTtoLock = new List<FileTransaction>();
try
{
List<int> lstStatusIds = new List<int>();
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.ConversionToXmlSucceded));
lstStatusIds.Add(objStatusManager.GetStatusIdbyName(Status.Reprocess));
//Getting the serviceURL of TRTaxEngine
string seriviceURL = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxEngineURL);
//Getting the output path for the file to be placed after processing
string outputfilePath = objConfigManager.GetConfigurationdbyKey(ConfigurationList.TRTaxOutputXMLFolder);
FileMasterManager objFileMasterManager = new FileMasterManager();
TRTaxXMLOperations objxmlresp = new TRTaxXMLOperations();
//Getting all the files list for proccessing from the DB
List<FileTransaction> lstFiletoProcess = await objTransManager.GetFileListforProcessingAsync(lstStatusIds, true).ConfigureAwait(false);
lstFTtoLock = lstFiletoProcess;
if (lstFiletoProcess.Count == 0)
return;
if (lstFiletoProcess.Count > 0)
{
var tasks = new List<Task<string>>();
using (HttpClient httpClnt = new HttpClient())
{
httpClnt.Timeout = TimeSpan.FromMilliseconds(-1);
//Getting the files for processing
foreach (FileTransaction item in lstFiletoProcess)
{
TRXMLResponseModel objRespModel = new TRXMLResponseModel();
objRespModel.strxmlResponse = string.Empty;
string fullFileName = item.FilePath + item.ConvertedName;
objRespModel.outputFilename = outputfilePath + item.ConvertedName;
FileMaster fileMaster = objFileMasterManager.GetById(item.FileId);
//Proccessing the file and getting the output filedata
Task<string> t = objxmlresp.GetXMLResponse(seriviceURL, fullFileName, fileMaster.CountryId.GetValueOrDefault(), httpClnt, objFileOperation, objRespModel.outputFilename, item, objTransManager);
tasks.Add(t);
//objRespModel.strxmlResponse = await t;
}
var result = await Task.WhenAll(tasks);
}
}
}
catch (Exception Ex)
{
if (lstFTtoLock != null && lstFTtoLock.Count > 0)
{
objTransManager.UpdateFileTransactionIsPickedtoFalse(lstFTtoLock);
}
throw Ex;
}
}
My Recommendation:
The method "Get(int id)" is somewhat confusing. first, it takes "id" and does nothing with it. Also it return nothing so it is not a "Get" method. It is basically asking for all transactions with status "Status.ConversionToXmlSucceded" & "Status.Reprocess" and are active to be gotten and processed via the "objxmlresp.GetXMLResponse" method... You Dont Have To Await the "MainFileMethod();" in "Get(int id)" just return the task or return Ok(); and allow all the process to go on in the background. You can experiment with reducing the "sqlAdpt.SelectCommand.CommandTimeout = 60000;".
i need to use this on premises working code into online
need to make some changes to work on online.the main thing is its showing the same error for all the exceptins.
public static void writeLogsintoList(string Category_Name, string Method_Name, string Error_Message)
{
try
{
//UserCollection ouser = new UserCollection("Suyog.m#totalebizsolutions.com", "Wlcm$$2003");
//Microsoft.SharePoint.Client.ClientResult<PrincipalInfo>
//request.UseDefaultCredentials = true;
//request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
ClientContext context = new ClientContext(ApplicationSiteUrl);
List announcementsList = context.Web.Lists.GetByTitle("Logs");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = announcementsList.AddItem(itemCreateInfo);
newItem["Timestamp"] = DateTime.Now;
newItem["Category_Name"] = Category_Name;
newItem["Method_Name"] = Method_Name;
newItem["Error_Message"] = Error_Message;
newItem.Update();
context.ExecuteQuery();
Console.WriteLine("added");
Console.ReadLine();
}
catch (Exception ex)
{
throw ex;
}
```[enter image description here][1]
[1]: https://i.stack.imgur.com/HX2Pg.png
actually its happening for all exceptions
Try to download SharePointOnline.CSOM from Nuget firstly:
Then use SharePointOnlineCredentials class to pass credential, here is the code snippet for your reference:
static void Main(string[] args)
{
string password = "*******";
string account = "user#Tenant.onmicrosoft.com";
var secret = new System.Security.SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
var credentials = new SharePointOnlineCredentials(account, secret);
using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename/"))
{
ctx.Credentials = new SharePointOnlineCredentials(account, secret);
ctx.Load(ctx.Web);
ctx.ExecuteQuery();
writeLogsintoList(ctx, "TestCategory", "TestMethod", "TestErrorMessage");
}
}
public static void writeLogsintoList(ClientContext context, string Category_Name, string Method_Name, string Error_Message)
{
try
{
List announcementsList = context.Web.Lists.GetByTitle("Logs");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = announcementsList.AddItem(itemCreateInfo);
newItem["Timestamp"] = DateTime.Now;
newItem["Category_Name"] = Category_Name;
newItem["Method_Name"] = Method_Name;
newItem["Error_Message"] = Error_Message;
newItem.Update();
context.ExecuteQuery();
Console.WriteLine("added");
Console.ReadLine();
}
catch (Exception ex)
{
throw ex;
}
}
After couple days (like 3 days or so) my windows service just stops executing the system.timer events don't fire anymore but the service shows as running. Also my log files don't even get created so no errors are thrown and logged. I have try catches on the highest level as well as on the second highest level and also in the constructor, OnStart and OnStop. Please see my code below.
Any idea what could be causing this?
public partial class BetGamesFeedService : ServiceBase
{
private Timer _gamesTimer;
private Timer _nextDrawTimer;
private Timer _drawResultsTimer;
private Timer _plannedScheduleTimer;
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public BetGamesFeedService()
{
try
{
log4net.Config.XmlConfigurator.Configure();
//Games Timer
_gamesTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["GamesInterval"]));
_gamesTimer.Elapsed += GamesTimerOnElapsed;
_gamesTimer.Enabled = true;
//Next Draw Timer
_nextDrawTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["NextDrawInterval"]));
_nextDrawTimer.Elapsed += NextDrawTimerOnElapsed;
_nextDrawTimer.Enabled = true;
//Draw Results Timer
_drawResultsTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["DrawResultsInterval"]));
_drawResultsTimer.Elapsed += DrawResultsTimerOnElapsed;
_drawResultsTimer.Enabled = true;
//Planned Schedule Timer
_plannedScheduleTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["PlannedScheduleInterval"]));
_plannedScheduleTimer.Elapsed += PlannedScheduleTimerOnElapsed;
_plannedScheduleTimer.Enabled = true;
InitializeComponent();
#if DEBUG
OnStart(null);
#endif
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
protected override void OnStart(string[] args)
{
try
{
_gamesTimer.Start();
_nextDrawTimer.Start();
_drawResultsTimer.Start();
_plannedScheduleTimer.Start();
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
protected override void OnStop()
{
try
{
_gamesTimer.Stop();
_nextDrawTimer.Stop();
_drawResultsTimer.Stop();
_plannedScheduleTimer.Stop();
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
private async void GamesTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var GamesOn = Convert.ToBoolean(ConfigurationManager.AppSettings["GamesIntervalOn"]);
if (!GamesOn) return;
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetGamesAndAddToDatabase();
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void NextDrawTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky5);
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky7);
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky6);
await betGames.GetNextDrawAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void DrawResultsTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky5);
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky7);
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky6);
await betGames.GetDrawResultsAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void PlannedScheduleTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky5);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky7);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky6);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
}
public class BetGames
{
private readonly int _partnerId =
Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PartnerId"]);
private readonly string _secretKey = System.Configuration.ConfigurationManager.AppSettings["SecretKey"];
private readonly int _shopId = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ShopId"]);
private readonly string[] _method =
{
"get_screen_urls", "get_games", "ticket_buy", "ticket_check",
"ticket_payout", "ticket_return"
};
private const string Language = "en";
private const string Currency = "eur";
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public async Task GetGamesAndAddToDatabase()
{
try
{
const int methodIndex = 1;
var request = new GetGamesRequest
{
partner_id = _partnerId,
method = _method[methodIndex],
language = Language,
timestamp = GetTimestamp(),
#params = new BaseParams
{
currency = Currency,
shop_id = _shopId
}
};
request.signature = GetSignature(methodIndex, request.timestamp, request.#params);
var api = new BetGamesAPI();
var response = await api.GetGames(request);
if (response == null)
{
log.Info("GetGamesAndAddToDatabase(): No Data Returned.");
return;
}
if (response.response_code != 200)
{
throw new Exception("response.response_code does not indicate success." + Environment.NewLine +
"Response Code: " + response.response_code + Environment.NewLine +
"Response Error: " + response.error_message);
}
var games =
new JavaScriptSerializer().Deserialize(response.response.ToString(), typeof(List<Bo.Models.Game>))
as List<Bo.Models.Game>;
//Add data to database
foreach (var game in games)
{
//#Id
var pId = new SqlParameter("#Id", SqlDbType.Int);
pId.Value = game.id;
//#Name
var pName = new SqlParameter("#Name", SqlDbType.VarChar);
pName.Value = game.name;
//#Type
var pType = new SqlParameter("#Type", SqlDbType.VarChar);
pType.Value = game.type;
//#Items
var dtItems = new DataTable();
dtItems.Columns.Add("Id", typeof(int));
dtItems.Columns.Add("Number", typeof(int));
dtItems.Columns.Add("Color", typeof(string));
foreach (var item in game.items)
{
dtItems.Rows.Add(item.id, item.number, item.color);
}
var pItems = new SqlParameter("#Items", SqlDbType.Structured);
pItems.Value = dtItems;
pItems.TypeName = "bg.ttItem";
//#Odds
var dtOdds = new DataTable();
dtOdds.Columns.Add("Code", typeof(int));
dtOdds.Columns.Add("ItemsCount", typeof(int));
dtOdds.Columns.Add("Name", typeof(string));
dtOdds.Columns.Add("Value", typeof(decimal));
foreach (var odd in game.odds)
{
dtOdds.Rows.Add(odd.code, odd.items_count, odd.name, odd.value);
}
var pOdds = new SqlParameter("#Odds", SqlDbType.Structured);
pOdds.Value = dtOdds;
pOdds.TypeName = "bg.ttOdd";
using (var db = new BetGamesEntities())
{
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertGameOddsAndItems";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pId);
cmd.Parameters.Add(pName);
cmd.Parameters.Add(pType);
cmd.Parameters.Add(pItems);
cmd.Parameters.Add(pOdds);
db.Database.Connection.Open();
await cmd.ExecuteScalarAsync();
db.Database.Connection.Close();
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
private string GetSignature(int methodIndex, int timestamp, object _params)
{
var jsonEncodedObject = new JavaScriptSerializer().Serialize(_params);
var signatureBase = _partnerId + _method[methodIndex] + Language + timestamp + jsonEncodedObject;
//Perform hashing
using (var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(_secretKey)))
{
var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
return string.Concat(hash.Select(x => x.ToString("x2")));
}
}
private static int GetTimestamp()
{
return (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
public async Task GetNextDrawAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
var response = await api.GetNextDraw(game);
if (response == null)
{
log.Info("GetNextDrawAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
return;
}
var data =
new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as List<Bo.Models.Draw>;
using (var db = new BetGamesEntities())
{
db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
data[0].video_url);
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
public async Task GetDrawResultsAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
using (var db = new BetGamesEntities())
{
var drawCode = db.GetDrawCode((int)game).FirstOrDefault();
if (drawCode == null) return;
var response = await api.GetDraws(game, drawCode.Value);
if (response == null)
{
log.Info("GetDrawResultsAndAddToDatabase(" + game + "): No Data Returned");
return;
}
//Insert Data
var data =
new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as
List<Bo.Models.Draw>;
foreach (var draw in data)
{
//If this draw is Cancelled update the draw status to cancelled
if (draw.is_returned == 1)
{
db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
data[0].video_url);
}
//if we have results for this draw
if (draw.results_entered == 1)
{
//#DrawCode
var pDrawCode = new SqlParameter("#DrawCode", SqlDbType.BigInt) { Value = draw.code };
//#Results
var dtResults = new DataTable();
dtResults.Columns.Add("BallNumber");
dtResults.Columns.Add("BallColor");
foreach (var result in draw.results)
{
dtResults.Rows.Add(result.Number, result.Color);
}
var pResults = new SqlParameter("#Results", SqlDbType.Structured)
{
Value = dtResults,
TypeName = "bg.ttDrawResult"
};
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertDrawResults";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pDrawCode);
cmd.Parameters.Add(pResults);
db.Database.Connection.Open();
cmd.ExecuteScalar();
db.Database.Connection.Close();
}
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
public async Task GetScheduledDrawsAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
var response = await api.GetScheduledDraws(game);
if (response == null)
{
log.Info("GetScheduledDrawsAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
return;
}
var data =
new JavaScriptSerializer().Deserialize(response, typeof(List<Bo.Models.ScheduledDraw>)) as List<Bo.Models.ScheduledDraw>;
using (var db = new BetGamesEntities())
{
var scheduledDrawTable = new DataTable();
scheduledDrawTable.Columns.Add("Code", typeof(long));
scheduledDrawTable.Columns.Add("Time", typeof(DateTime));
foreach (var draw in data)
{
scheduledDrawTable.Rows.Add(draw.number, draw.time.AddHours(2));
}
var Draws = new SqlParameter("#Draws", SqlDbType.Structured);
Draws.Value = scheduledDrawTable;
Draws.TypeName = "bg.ttDraw";
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertOrUpdateScheduledDraws";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(Draws);
db.Database.Connection.Open();
cmd.ExecuteScalar();
db.Database.Connection.Close();
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
}
Trying to add new customer to NetSuite like it described in sample in manual.
private static void Main(string[] args)
{
ApplicationInfo _appInfo;
var service = new NetSuiteService();
service.CookieContainer = new CookieContainer();
_appInfo = new ApplicationInfo();
_appInfo.applicationId = "FB31C4F2-CA6C-4E5F-6B43-57632594F96";
service.applicationInfo = _appInfo;
var passport = new Passport();
passport.account = "5920356_SB9";
passport.email = "a#a.com";
var role = new RecordRef();
role.internalId = "3";
passport.role = role;
passport.password = "#sdkkr_5543";
try
{
var status = service.login(passport).status;
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
throw;
}
var cust = new Customer();
cust.entityId = "XYZ Inc";
cust.altEmail = "aaa#aaa.aaa";
var response = service.add(cust);
Console.Out.WriteLine("response.status.isSuccess " + response.status.isSuccess) ;
Console.Out.WriteLine("response.status.isSuccessSpecified " + response.status.isSuccessSpecified);
service.logout();
}
As result I got:
response.status.isSuccess False
response.status.isSuccessSpecified True
I suppose customer was not inserted. What is wrong and how to know that?
When you call add() on the service, the response contains a status property which contains a statusDetail property. statusDetail is an array of the messages (warnings and errors) that resulted from your add(). You can loop through these to find out why saving your customer record was unsuccessful:
var response = service.add(cust);
if (!response.status.isSuccess)
{
foreach (var error in response.status.statusDetail)
{
Console.WriteLine($"Error creating customer: {error.type} {error.message}");
}
}
For Update campaign I am using this Code
public async Task<List<long?>> updateCampaign(Campaign campaign,string status)
{
try
{
campaign.Status = (CampaignStatus)(int)Enum.Parse(typeof(CampaignStatus), status);
var request = new UpdateCampaignsRequest
{
Campaigns = new Campaign[] { campaign },
CustomerId = "xxxxxx",
UserName = "something#outlook.com",
Password = "something#123",
ApplicationToken = "myApplicationToken",
CustomerAccountId = "123456",
DeveloperToken = "1234567890"
};
CampaignService = new ServiceClient<ICampaignManagementService>(_authorizationData);
CampaignService.RefreshOAuthTokensAutomatically = false;
var result = (await CampaignService.CallAsync((s, r) => s.UpdateCampaignsAsync(r), request));
if (result.TrackingId != null)
{
return result.CampaignIds.ToList();
}
else
{
return new List<long?>();
}
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
When I run this code, I got this error "Invalid client data. Check the SOAP fault details for more information"
thanks.
For updating the Campaign we can use "BulkServiceManager" for bulk updating of the campaign,you can use this service single campaign update also.
public async Task<List<long?>> updateCampaign(List<Campaign> campaigns)
{
try
{
var listBulkCampaign = new List<BulkCampaign>();
foreach (var campaign in campaigns)
{
var _bulkCampaign = new BulkCampaign()
{
Campaign = campaign
};
listBulkCampaign.Add(_bulkCampaign);
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(_authorizationData);
string fileName = bingCampaignUpdate.csv;
var campaigns = (await bulkServiceManager.UploadEntitiesAsync(new EntityUploadParameters
{
Entities = listBulkCampaign,
OverwriteResultFile = true,
ResultFileDirectory = FileDirectory,
ResultFileName = fileName,
ResponseMode = ResponseMode.ErrorsAndResults
})).OfType<BulkCampaign>().ToList();
return new List<long?>();
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
You have to download .csv report and update the Campaigns.
I hope it helps you