Updating data on an existing ParseObject in C# (Unity) - c#

I have now solved this issue. I have left the original question / code in place for comparison.
* SOLUTION *
public static void saveUserData(string emailAddress) {
ParseObject userData = new ParseObject("userData");
ParseObject userLevelData = new ParseObject("levelData");
userData["playerName"] = emailAddress;
try {
ParseQuery<ParseObject> parseData = ParseObject.GetQuery("userData").WhereEqualTo("playerName", userData["playerName"]);
parseData.FirstAsync().ContinueWith(t => {
if(t.IsFaulted) {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
userLevelData["level"] = GameStatus.currentUser.level;
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = -1;
userData.SaveAsync();
userLevelData.SaveAsync();
} else if(!t.IsCanceled) {
userData = t.Result;
try {
userData.SaveAsync().ContinueWith(t2 => {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
ParseQuery<ParseObject> levelData = ParseObject.GetQuery("levelData").WhereEqualTo("playerName", userData["playerName"]).WhereEqualTo("level", GameStatus.currentUser.level);
levelData.FirstAsync().ContinueWith(t3 => {
if(t3.IsFaulted) {
userLevelData["level"] = userData["level"];
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = GameStatus.currentUser.currentLevelData.time;
userLevelData.SaveAsync();
} else if(!t3.IsCanceled) {
userLevelData = t3.Result;
int timeVal = Convert.ToInt32(userLevelData["time"]);
if(timeVal == -1 || GameStatus.currentUser.currentLevelData.time < timeVal) {
try {
userLevelData.SaveAsync().ContinueWith(t4 => {
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = DateTime.Now.Ticks;
userLevelData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
}
});
userData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
});
} catch(Exception e) {
Debug.LogException(e);
}
}
I am trying to update data on an existing ParseObject using C# in Unity3D. My code is as follows:
Original code:
public static void saveUserData(string emailAddress) {
ParseObject userData = new ParseObject("userData");
ParseObject userLevelData = new ParseObject("levelData");
userData["playerName"] = emailAddress;
try {
ParseQuery<ParseObject> parseData = ParseObject.GetQuery("userData").WhereEqualTo("playerName", userData["playerName"]);
parseData.FirstAsync().ContinueWith(t => {
if(t.IsFaulted) {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
userLevelData["level"] = GameStatus.currentUser.level;
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = -1;
userData.SaveAsync();
userLevelData.SaveAsync();
} else if(!t.IsCanceled) {
userData = t.Result;
try {
userData.SaveAsync().ContinueWith(t2 => {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
ParseQuery<ParseObject> levelData = ParseObject.GetQuery("levelData").WhereEqualTo("playerName", userData["playerName"]).WhereEqualTo("level", GameStatus.currentUser.level);
levelData.FirstAsync().ContinueWith(t3 => {
if(t3.IsFaulted) {
userLevelData["level"] = userData["level"];
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = GameStatus.currentUser.currentLevelData.time;
userLevelData.SaveAsync();
} else if(!t3.IsCanceled) {
userLevelData = t3.Result;
int timeVal = Convert.ToInt32(userLevelData["time"]);
if(timeVal == -1 || GameStatus.currentUser.currentLevelData.time < timeVal) {
try {
userLevelData.SaveAsync().ContinueWith(t4 => {
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = DateTime.Now.Ticks;
userLevelData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
}
});
userData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
});
} catch(Exception e) {
Debug.LogException(e);
}
}
Now, I get an output stating the user is found, and creating a user if it's not found works OK. The issue I have is that, although I've specified a userFound bool, the if(userFound) nest is never called.
Can anyone see what I've done (or haven;t done) or am I totally going about this the wrong way?
Any help appreciated.

Related

Windows Service State Running but not working

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());
}
}
}

System.OutOfMemoryExeption C#

When I'm running my application and load a file(25MB) through it, everything runs just fine.
But when I try loading a file(160MB) I get a System.OutOfMemoryExeption.
Although I have been able to load the larger file at some point in time.
Is there anyway to fix this? If so, any help would be much appreciated!
My Code that loads the files:
private void openFile (string fileName)
{
List<Structs.strValidData> _header1 = new List<Structs.strValidData>();
List<Structs.strValidData> _header2 = new List<Structs.strValidData>();
List<Structs.strValidData> _header3 = new List<Structs.strValidData>();
List<Structs.strValidData> _header4 = new List<Structs.strValidData>();
var textBoxArray = new[]
{
textBoxResStart_Status1,
textBoxResStart_Status2,
textBoxResStart_Status3,
textBoxResStart_Status4,
textBoxResStart_Status5,
textBoxResStart_Status6,
textBoxResStart_Status7,
textBoxResStart_Status8,
};
var radioButtonArray = new[]
{
radioButtonResStart_SelectStr1,
radioButtonResStart_SelectStr2,
radioButtonResStart_SelectStr3,
radioButtonResStart_SelectStr4,
radioButtonResStart_SelectStr5,
radioButtonResStart_SelectStr6,
radioButtonResStart_SelectStr7,
radioButtonResStart_SelectStr8,
};
readCSV read;
read = new readCSV();
strInfo = default(Structs.strInfo);
strData = default(Structs.strData);
strSetup = default(Structs.strSetup);
strValidData = new List<Structs.strValidData>();
readID = default(Structs.ReadID);
try
{
strInfo = read.loadInfo(fileName);
strData = read.loadData(fileName);
strSetup = read.loadSetup(fileName);
readID = read.loadID(fileName);
strValidData = read.loadValidData(fileName);
var Str1 = read.loadStr1(fileName);
var Str235678 = read.loadStr235678(fileName);
var Str4 = read.loadStr4(fileName);
foreach (Structs.strValidData items in strValidData)
{
if (items.Str1_ValidData == true)
{
Str1_headers.Add(items);
}
if (items.Str2_ValidData == true ||
items.Str3_ValidData == true ||
items.Str5_ValidData == true ||
items.Str6_ValidData == true ||
items.Str7_ValidData == true ||
items.Str8_ValidData == true)
{
Str235678_headers.Add(items);
}
if (items.Str4_ValidData == true)
{
Str4_headers.Add(items);
}
}
Str1_data = combineData(Str1, Str1_headers);
Str4_data = combineData(Str4, Str4_headers);
var Str235678_CombinedData = combineData(Str235678, Str235678_headers);
foreach (Structs.strValidData items in Str235678_CombinedData)
{
if (items.Str2_ValidData == true)
{
Str2_data.Add(items);
}
if (items.Str3_ValidData == true)
{
Str3_data.Add(items);
}
if (items.Str5_ValidData == true)
{
Str5_data.Add(items);
}
if (items.Str6_ValidData == true)
{
Str6_data.Add(items);
}
if (items.Str7_ValidData == true)
{
Str7_data.Add(items);
}
if (items.Str8_ValidData == true)
{
Str8_data.Add(items);
}
}
strInfo = read.loadInfo(openDialog.FileName);
strData = read.loadData(openDialog.FileName);
strSetup = read.loadSetup(openDialog.FileName);
readID = read.loadID(openDialog.FileName);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
error.logSystemError(err);
}
}
Here are the ReadCSV() code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FileHelpers;
using FileHelpers.Events;
namespace Reading_Files
{
public class readCSV
{
public int strCnt = 0;
private readCSVprogressForm _waitForm;
public List<Structs.strDataImport> copyList(List<strData> copyFrom)
{
List<Structs.strDataImport> list = new List<Structs.strDataImport>();
list.AddRange(copyFrom.Select(s => copyListContents(s)));
return list;
}
public Structs.strDataImport copyListContents(strData copyFrom)
{
Structs.strDataImport data = new Structs.strDataImport();
data.sCD_TimeCP2711 = copyFrom.sCD_TimeCP2711;
data.sCD_TimeCX9020_1 = copyFrom.sCD_TimeCX9020_1;
data.sCD_TimeCX9020_2 = copyFrom.sCD_TimeCX9020_2;
data.rCD_CX9020_1_TimeDiff_DataLow = (Int32)(copyFrom.rCD_CX9020_1_TimeDiff_DataLow);
data.rCD_CX9020_2_TimeDiff_DataLow = (Int32)(copyFrom.rCD_CX9020_2_TimeDiff_DataLow);
data.iCD_NumUpper = copyFrom.iCD_NumUpper;
data.iCD_NumUpper = copyFrom.iCD_NumUpper;
data.iCD_NumLower = copyFrom.iCD_NumLower;
data.iCD_NumLower = copyFrom.iCD_NumLower;
data.bCD_1_Status = copyFrom.bCD_1_Status;
data.bCD_1_Overrange = copyFrom.bCD_1_Overrange;
data.iCD_1_Str_ID = copyFrom.iCD_1_Str_ID;
data.rCD_1_Value = copyFrom.rCD_1_Value;
data.bCD_2_Status = copyFrom.bCD_2_Status;
data.bCD_2_Overrange = copyFrom.bCD_2_Overrange;
data.iCD_2_Str_ID = copyFrom.iCD_2_Str_ID;
data.rCD_2_Value = copyFrom.rCD_2_Value;
data.bCD_3_Status = copyFrom.bCD_3_Status;
data.bCD_3_Overrange = copyFrom.bCD_3_Overrange;
data.iCD_3_Str_ID = copyFrom.iCD_3_Str_ID;
data.iCD_3_RawData = copyFrom.iCD_3_RawData;
data.rCD_3_Value = copyFrom.rCD_3_Value;
data.bCD_4_Status = copyFrom.bCD_4_Status;
data.bCD_4_Overrange = copyFrom.bCD_4_Overrange;
data.iCD_4_Str_ID = copyFrom.iCD_4_Str_ID;
data.iCD_4_RawData = copyFrom.iCD_4_RawData;
data.rCD_4_Value = copyFrom.rCD_4_Value;
data.bCD_5_Status = copyFrom.bCD_5_Status;
data.bCD_5_Overrange = copyFrom.bCD_5_Overrange;
data.iCD_5_Str_ID = copyFrom.iCD_5_Str_ID;
data.iCD_5_RawData = copyFrom.iCD_5_RawData;
data.rCD_5_Value = copyFrom.rCD_5_Value;
data.bCD_6_Status = copyFrom.bCD_6_Status;
data.bCD_6_Overrange = copyFrom.bCD_6_Overrange;
data.iCD_6_Str_ID = copyFrom.iCD_6_Str_ID;
data.iCD_6_RawData = copyFrom.iCD_6_RawData;
data.rCD_6_Value = copyFrom.rCD_6_Value;
data.bCD_7_Status = copyFrom.bCD_7_Status;
data.bCD_7_Overrange = copyFrom.bCD_7_Overrange;
data.iCD_7_Str_ID = copyFrom.iCD_7_Str_ID;
data.iCD_7_RawData = copyFrom.iCD_7_RawData;
data.rCD_7_Value = copyFrom.rCD_7_Value;
data.bCD_8_Status = copyFrom.bCD_8_Status;
data.bCD_8_Overrange = copyFrom.bCD_8_Overrange;
data.iCD_8_Str_ID = copyFrom.iCD_8_Str_ID;
data.iCD_8_RawData = copyFrom.iCD_8_RawData;
data.rCD_8_Value = copyFrom.rCD_8_Value;
data.bCD_9_Status = copyFrom.bCD_9_Status;
data.bCD_9_Overrange = copyFrom.bCD_9_Overrange;
data.iCD_9_Str_ID = copyFrom.iCD_9_Str_ID;
data.iCD_9_RawData = copyFrom.iCD_9_RawData;
data.rCD_9_Value = copyFrom.rCD_9_Value;
data.bCD_10_Status = copyFrom.bCD_10_Status;
data.bCD_10_Overrange = copyFrom.bCD_10_Overrange;
data.iCD_10_Str_ID = copyFrom.iCD_10_Str_ID;
data.iCD_10_RawData = copyFrom.iCD_10_RawData;
data.rCD_10_Value = copyFrom.rCD_10_Value;
data.bCD_11_Status = copyFrom.bCD_11_Status;
data.bCD_11_Overrange = copyFrom.bCD_11_Overrange;
data.iCD_11_Str_ID = copyFrom.iCD_11_Str_ID;
data.iCD_11_RawData = copyFrom.iCD_11_RawData;
data.rCD_11_Value = copyFrom.rCD_11_Value;
data.bCD_12_Status = copyFrom.bCD_12_Status;
data.bCD_12_Overrange = copyFrom.bCD_12_Overrange;
data.iCD_12_Str_ID = copyFrom.iCD_12_Str_ID;
data.iCD_12_RawData = copyFrom.iCD_12_RawData;
data.rCD_12_Value = copyFrom.rCD_12_Value;
data.bCD_13_Status = copyFrom.bCD_13_Status;
data.bCD_13_Overrange = copyFrom.bCD_13_Overrange;
data.iCD_13_Str_ID = copyFrom.iCD_13_Str_ID;
data.iCD_13_RawData = copyFrom.iCD_13_RawData;
data.rCD_13_Value = copyFrom.rCD_13_Value;
data.bCD_14_Status = copyFrom.bCD_14_Status;
data.bCD_14_Overrange = copyFrom.bCD_14_Overrange;
data.iCD_14_Str_ID = copyFrom.iCD_14_Str_ID;
data.iCD_14_RawData = copyFrom.iCD_14_RawData;
data.rCD_14_Value = copyFrom.rCD_14_Value;
data.bCD_15_Status = copyFrom.bCD_15_Status;
data.bCD_15_Overrange = copyFrom.bCD_15_Overrange;
data.iCD_15_Str_ID = copyFrom.iCD_15_Str_ID;
data.iCD_15_RawData = copyFrom.iCD_15_RawData;
data.rCD_15_Value = copyFrom.rCD_15_Value;
data.bCD_16_Status = copyFrom.bCD_16_Status;
data.bCD_16_Overrange = copyFrom.bCD_16_Overrange;
data.iCD_16_Str_ID = copyFrom.iCD_16_Str_ID;
data.iCD_16_RawData = copyFrom.iCD_16_RawData;
data.rCD_16_Value = copyFrom.rCD_16_Value;
data.bCD_17_Status = copyFrom.bCD_17_Status;
data.bCD_17_Overrange = copyFrom.bCD_17_Overrange;
data.iCD_17_Str_ID = copyFrom.iCD_17_Str_ID;
data.iCD_17_RawData = copyFrom.iCD_17_RawData;
data.rCD_17_Value = copyFrom.rCD_17_Value;
data.bCD_18_Status = copyFrom.bCD_18_Status;
data.bCD_18_Overrange = copyFrom.bCD_18_Overrange;
data.iCD_18_Str_ID = copyFrom.iCD_18_Str_ID;
data.iCD_18_RawData = copyFrom.iCD_18_RawData;
data.rCD_18_Value = copyFrom.rCD_18_Value;
data.bCD_19_Status = copyFrom.bCD_19_Status;
data.bCD_19_Overrange = copyFrom.bCD_19_Overrange;
data.iCD_19_Str_ID = copyFrom.iCD_19_Str_ID;
data.rCD_19_Value = copyFrom.rCD_19_Value;
data.bCD_20_Status = copyFrom.bCD_20_Status;
data.bCD_20_Overrange = copyFrom.bCD_20_Overrange;
data.iCD_20_Str_ID = copyFrom.iCD_20_Str_ID;
data.rCD_20_Value = copyFrom.rCD_20_Value;
return data;
}
public Structs.ReaStrID load_ID(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strIDSelector);
var data = engine.ReadFile(FileName);
Structs.ReaStrID structure = new Structs.ReaStrID();
foreach (strID filteredData in data)
{
structure.steID[0] = filteredData._1_Ste_ID;
structure.Status[0] = filteredData._1_Status;
structure.steID[1] = filteredData._2_Ste_ID;
structure.Status[1] = filteredData._2_Status;
structure.steID[2] = filteredData._3_Ste_ID;
structure.Status[2] = filteredData._3_Status;
structure.steID[3] = filteredData._4_Ste_ID;
structure.Status[3] = filteredData._4_Status;
structure.steID[4] = filteredData._5_Ste_ID;
structure.Status[4] = filteredData._5_Status;
}
return structure;
}
public Structs.strInfo loadInfo(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strInfoSelector);
var data = engine.ReadFile(FileName);
Structs.strInfo structure = new Structs.strInfo();
foreach (strInfo filteredData in data)
{
structure.Date = filteredData.Date;
structure.Description1 = filteredData.Description1;
structure.Description2 = filteredData.Description2;
structure.Description3 = filteredData.Description3;
}
return structure;
}
public Structs.strData loadData(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strDataSelector);
var data = engine.ReadFile(FileName);
Structs.strData structure = new Structs.strData();
foreach (strData filteredData in data)
{
structure.iMDstr_var1_TypeID = filteredData.iMDstr_var1_TypeID;
structure.rMDstr_var1_Lenght = filteredData.rMDstr_var1_Lenght;
structure.iMDstr_var2_TypeID = filteredData.iMDstr_var2_TypeID;
structure.rMDstr_var2_Lenght = filteredData.rMDstr_var2_Lenght;
structure.iMDstr_var3_TypeID = filteredData.iMDstr_var3_TypeID;
structure.rMDstr_var3_Lenght = filteredData.rMDstr_var3_Lenght;
structure.iMDstr_var4_TypeID = filteredData.iMDstr_var4_TypeID;
structure.rMDstr_var4_Lenght = filteredData.rMDstr_var4_Lenght;
}
return structure;
}
public Structs.strSetup loadSetup(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strID),
typeof(strData),
typeof(strSetup),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strSetupSelector);
var data = engine.ReadFile(FileName);
Structs.strSetup structure = new Structs.strSetup();
foreach (strSetup filteredData in data)
{
structure.sSSstr_Sens = filteredData.sSSstr_Sens;
structure.bSSstr_S1_A = filteredData.bSSstr_S1_A;
structure.iSSstr_S1_B = filteredData.iSSstr_S1_B;
structure.sSSstr_S1_C = filteredData.sSSstr_S1_C;
structure.rSSstr_S1_D = filteredData.rSSstr_S1_D;
structure.bSSstr_S2_A = filteredData.bSSstr_S2_A;
structure.iSSstr_S2_B = filteredData.iSSstr_S2_B;
structure.sSSstr_S2_C = filteredData.sSSstr_S2_C;
structure.rSSstr_S2_D = filteredData.rSSstr_S2_D;
structure.bSSstr_S3_A = filteredData.bSSstr_S3_A;
structure.iSSstr_S3_B = filteredData.iSSstr_S3_B;
structure.sSSstr_S3_C = filteredData.sSSstr_S3_C;
structure.iSSstr_S3_D = filteredData.iSSstr_S3_D;
}
return structure;
}
public List<Structs.str1> load1(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strData),
typeof(strID),
typeof(strValidData),
typeof(strStartNum),
typeof(str1),
typeof(str4));
engine.RecordSelector = new RecordTypeSelector(str1Selector);
var data = engine.ReadFile(FileName);
List<Structs.str1> list = new List<Structs.str1>();
int i = 0;
foreach (str1 data1 in data)
{
Structs.str1 structure = new Structs.str1();
structure.rGL_1_L_Positive = data1.rGL_1_L_Positive;
structure.rGL_1_L_Negative = data1.rGL_1_L_Negative;
structure.rGL_1_R_Positive = data1.rGL_1_R_Positive;
structure.rGL_1_R_Negative = data1.rGL_1_R_Negative;
list.Add(structure);
i++;
}
return list;
}
public List<Structs.str4> load4(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strData),
typeof(strValidData),
typeof(strStartNum),
typeof(str1),
typeof(str4));
engine.RecordSelector = new RecordTypeSelector(str4Selector);
var data = engine.ReadFile(FileName);
List<Structs.str4> list = new List<Structs.str4>();
int i = 0;
foreach (str4 data4 in data)
{
Structs.str4 structure = new Structs.str4();
structure.rGL_4_1 = data4.rGL_4_1;
structure.rGL_4_2 = data4.rGL_4_2;
structure.rGL_4_3 = data4.rGL_4_3;
structure.rGL_4_4 = data4.rGL_4_4;
structure.rGL_4_5 = data4.rGL_4_5;
structure.rGL_4_6 = data4.rGL_4_6;
structure.rGL_4_7 = data4.rGL_4_7;
structure.rGL_4_8 = data4.rGL_4_8;
list.Add(structure);
i++;
}
return list;
}
public List<Structs.strValidData> loadValidData(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData),
typeof(strValidData));
engine.RecordSelector = new RecordTypeSelector(strValidDataSelector);
var data = engine.ReadFile(FileName);
List<Structs.strValidData> list = new List<Structs.strValidData>();
int i = 0;
foreach (strValidData strValidData in data)
{
Structs.strValidData structure = new Structs.strValidData();
structure._name = String.Format("strItem {0}", i + 1);
structure._index = i;
structure.str1_ValidData = strValidData.str1_ValidData;
structure.str2_ValidData = strValidData.str2_ValidData;
structure.str3_ValidData = strValidData.str3_ValidData;
structure.str4_ValidData = strValidData.str4_ValidData;
structure.str5_ValidData = strValidData.str5_ValidData;
structure.str6_ValidData = strValidData.str6_ValidData;
structure.str7_ValidData = strValidData.str7_ValidData;
structure.str8_ValidData = strValidData.str8_ValidData;
structure.str9_ValidData = strValidData.str9_ValidData;
list.Add(structure);
i++;
}
return list;
}
public List<List<Structs.strDataImport>> loadstrDataAsync(string FileName)
{
var engine_Data = new FileHelperAsyncEngine<strData>();
engine_Data.BeforeReadRecord += BeforeEventAsync;
engine_Data.AfterReadRecord += AfterEventAsync;
engine_Data.Progress += ReadProgress;
List<strData> list = new List<strData>();
List<List<Structs.strDataImport>> list2D = new List<List<Structs.strDataImport>>();
using (engine_Data.BeginReadFile(FileName))
{
var prevRowNo = 0;
var j = 0;
strCnt = 0;
foreach (strData filteredData in engine_Data)
{
if (prevRowNo > filteredData.RowNo)
{
list2D.Add(copyList(list));
list.Clear();
}
prevRowNo = filteredData.RowNo;
list.Add(filteredData);
}
list2D.Add(copyList(list));
}
return list2D;
}
private Type strIDSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_DATA .STATUS .STRID **"))
return typeof(strID);
else
{
return null;
}
}
private Type InfoSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_FILE **"))
return typeof(strInfo);
else
{
return null;
}
}
private Type strDataSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_DATA **"))
return typeof(strData);
else
{
return null;
}
}
private Type strSetupSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_SETUP **"))
return typeof(strSetup);
else
{
return null;
}
}
private Type strValidDataSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_VALID_DATA **"))
return typeof(strValidData);
else
{
return null;
}
}
private Type StartNumSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_START_NUMBER **"))
return typeof(strStartNum);
else
{
return null;
}
}
private Type str1Selector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_1 **"))
return typeof(str1);
else
{
return null;
}
}
private Type str4Selector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_4 **"))
return typeof(str4);
else
{
return null;
}
}
private void BeforeEventAsync(EngineBase engine, BeforeReadEventArgs<strData> e)
{
if (e.RecordLine != "")
{
if (Char.IsDigit(e.RecordLine, 0))
{
}
else
{
e.SkipThisRecord = true;
}
}
if (e.RecordLine.Contains("** #_VALID_DATA **;"))
{
e.SkipThisRecord = true;
}
}
private void AfterEventAsync(EngineBase engine, AfterReadEventArgs<strData> e)
{
if (e.RecordLine.Contains("** #_VALID_DATA **;"))
{
e.SkipThisRecord = true;
}
}
private void ReadProgress(object sender, ProgressEventArgs e)
{
ShowWaitForm("Opening file." + "\n" + "\n" + "Please wait...", "Open File");
_waitForm.progressBar1.Value = Convert.ToInt16(e.Percent);
}
public void ShowWaitForm(string message, string caption)
{
if (_waitForm != null && !_waitForm.IsDisposed)
{
return;
}
_waitForm = new readCSVprogressForm();
_waitForm.ShowMessage(message);
_waitForm.Text = caption;
_waitForm.TopMost = true;
_waitForm.Show();
_waitForm.Refresh();
System.Threading.Thread.Sleep(700);
Application.Idle += OnLoaded;
}
private void OnLoaded(object sender, EventArgs e)
{
Application.Idle -= OnLoaded;
_waitForm.Close();
}
}
}
Given the comments, it sounds like the problem is really that you're using structs extensively. These should almost certainly be classes for idiomatic C#. See the design guidelines for more details of how to pick between these.
At the moment, you're loading all the values in a big List<T>. Internally, that has an array - so it's going to be an array of your struct type. That means all the values are required to be in a single contiguous chunk of memory - and it sounds like that chunk can't be allocated.
If you change your data types to classes, then a contiguous chunk of memory will still be required - but only enough to store references to the objects you create. You'll end up using slightly more data overall (due to per-object overhead and the references to those objects) but you won't have nearly as strict a requirement on allocating a single big chunk of memory.
That's only one reason to use classes here - the reason of "this just isn't a normal use of structs" is a far bigger one, IMO.
As an aside, I'd also very strongly recommend that you start following .NET naming conventions, particularly around the use of capitalization and avoiding underscores to separate words in names. (There are other suggestions for improving the code in the question too, and I'd advise reading them all carefully.)

How to link a module in asp.net, C# web application in all forms

Is there a way for me to link my module in all of my form i'm using c# app and this is my code. This is actually a notification bell that will notify users if he/she has/have notifications. I already linked it on homepage how am i able to do that in all other pages
private void systemNotificationREXS(HomePage module)
{
TextBox Username = (TextBox)module.FindControl("Hide_user");
Label Fullname = (Label)module.FindControl("userfullname");
Label notifLabel = (Label)module.FindControl("notifLabel");
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++ )
{
int notifcount = int.Parse(dt.Rows[i]["notifcount"].ToString());
string modulename = dt.Rows[i]["modulename"].ToString();
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)module.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
module.FindControl(modulebody).Visible = true;
try
{
module.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
module.FindControl(modulebody).Visible = false;
try
{
module.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
}
}
con.Close();
}
}
}
internal void notificationSystemREXS(string fullname, string hide_user, HomePage modulename)
{
systemNotificationREXS(modulename);
}
Code to linked on homepage:
private void systemNotificationREXS()
{
Notification moduleacc = new Notification();
moduleacc.notificationSystemREXS(userfullname.Text, Hide_user.Text, this);
}
Your method does very simple job, but you have made it complicated and over dependent on the module and other stuff.
The method should return only the notification data for the user and let the caller of the method to decide what to do with the data.
Consider doing following.
public class NotificationData
{
public int NotificationCount {get;set;}
public int ModuleName {get;set;}
}
public class NotificationService
{
public static List<NotificationData> GetNotificationData(string username)
{
var notificationList = new List<NotificationData>();
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
for (int i = 0; i < dt.Rows.Count; i++ )
{
var notification = new NotificationData();
notification.NotificationCount = int.Parse(dt.Rows[i]["notifcount"].ToString());
notification.ModuleName = dt.Rows[i]["modulename"].ToString();
}
}
}
}
}
return notificationList
}
}
Now you should use this method from whichever page you want as following.
Let say you want to use it from HomePage. So you may write following code in Page_Load event of HomePage. (I am assuming here that HomePage is a web page and it has all the controls loaded before this code gets executed).
Label userNameLabel = (Label)this.FindControl("userfullname");
var userName = userNameLabelText;
var notificationList = NotificationService.GetNotificationData(userName);
foreach(var notification in notificationList)
{
var modulename = notification.ModuleName;
var notifcount = notification.Count;
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)this.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
this.FindControl(modulebody).Visible = true;
try
{
this.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
this.FindControl(modulebody).Visible = false;
try
{
this.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
I hope this should help you resolve your issue.

data getting moved instead of added

I am trying to create functionality to copy data from one order to another. Here is the code that copies the data:
protected void copySeminarIDButton_Click(object sender, EventArgs e)
{
try
{
//show some message incase validation failed and return
String seminarID = this.copySeminarIDText.Text;
Int32 id;
try
{
id = Convert.ToInt32(seminarID);
} catch (Exception e2)
{
return;
}
//copy over all the registration types now for the entered id
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
var seminars = db.seminars.Where(x => x.id == id);
if (seminars.Any())
{
var s = seminars.First();
//Load RegTypes
try
{
var regList = s.seminar_registration_type
.OrderBy(x => x.sort)
.ToList()
.Select(x => new seminarRegistrationTypeListing
{
id = x.id,
amount = x.amount,
description = x.description,
feeTypeId = x.feeTypeId,
method = x.method,
promoCodes = PromoCodesToString(x.xref_reg_type_promo.Select(z => z.promoId).ToList()),
title = x.title,
isPreorder = x.isPreorder,
sort = x.sort
});
this.dlTypes.DataSource = regList;
this.dlTypes.DataBind();
}
catch (Exception ex)
{
Response.Write("RegTypes: " + ex.Message);
}
} else
{
return;
}
}
}
catch (Exception m)
{
}
}
The user will enter a ID of the invoice they want to copy from. The above code copies pull the right data from the invoice and loads it on the page. When i click save the data is being saved.
The problem that is occurring is that the invoice that i copy data from will no longer have the data any more. So basically instead of copying the data its actually moving the data to the new invoice. I want to copy.
Here is my Save code.
private void SaveRegTypes(int seminarId)
{
//Reg Types
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
try
{
var s = db.seminars.Where(x => x.id == seminarId).First();
var msg = "alert('Saving:" + seminarId + "');";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", msg, true);
this.copySeminarIDText.Text = msg;
//s.seminar_registration_type.Clear();
foreach (DataListItem dli in this.dlTypes.Items)
{
String sId = ((HiddenField)dli.FindControl("hdnId")).Value;
var reg = new seminar_registration_type();
if ((sId != "") && (sId != "0"))
{
Int32 id = Convert.ToInt32(sId);
reg = db.seminar_registration_type.Where(x => x.id == id).Single();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", "alert('hidded field id is empty.');", true);
}
else
{
db.seminar_registration_type.Add(reg);
}
reg.feeTypeId = Convert.ToInt32(((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Value);
reg.amount = Convert.ToDecimal(((TextBox)dli.FindControl("txtPrice")).Text);
reg.title = ((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Text;
reg.description = ((TextBox)dli.FindControl("txtRegDesc")).Text;
reg.method = Convert.ToInt32(((DropDownList)dli.FindControl("ddlDeliveryMethod")).Text);
reg.promocode = null;
reg.isPreorder = Convert.ToBoolean(((CheckBox)dli.FindControl("chkPreorder")).Checked);
reg.sort = 1;
reg.seminarId = seminarId;
string sort = ((TextBox)dli.FindControl("txtRTSort")).Text;
try
{
reg.sort = Convert.ToInt32(sort);
}
catch (Exception ex) { }
//Do Promo Codes
Repeater rptPromocodes = (Repeater)dli.FindControl("rptPromoCodesList");
reg.xref_reg_type_promo.Clear();
foreach (RepeaterItem ri in rptPromocodes.Items)
{
try
{
Int32 id = Convert.ToInt32(((HiddenField)ri.FindControl("hdnCodeId")).Value);
DateTime? expires = null;
try
{
HiddenField exp = (HiddenField)ri.FindControl("hdnExpirationDate");
if (!String.IsNullOrWhiteSpace(exp.Value))
expires = Convert.ToDateTime(((HiddenField)ri.FindControl("hdnExpirationDate")).Value);
}
catch (Exception ex) { }
var code = db.promo_code.Where(x => x.id == id).First();
reg.xref_reg_type_promo.Add(new xref_reg_type_promo
{
expiration = expires,
promoId = code.id
});
}
catch (Exception ex) { }
}
db.SaveChanges();
((HiddenField)dli.FindControl("hdnId")).Value = reg.id.ToString();
}
}
catch (Exception ex)
{
String err = ex.Message;
}
}
}

The code is giving error at MultiSheetsPdf

This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...

Categories

Resources