Error #1069: Property Pertanyaan0 not found on String and there is no default value - flash-cs5

I stuck here please help, i'm new in flash, using adobe flash cs5.5
Here's the code :
import flash.net.URLLoaderDataFormat;
import flash.events.DataEvent;
stop();
alert_mc.visible = false;
alert_mc.ok_btn.visible = false;
var score:Number = 0;
var jawaban;
var nextQst:Number = 0;
var i:Number = 0;
a_btn.addEventListener(MouseEvent.CLICK,btna);
function btna(ev:MouseEvent):void
{
cekJawaban("a");
}
b_btn.addEventListener(MouseEvent.CLICK,btnb);
function btnb(ev:MouseEvent):void
{
cekJawaban("b");
}
c_btn.addEventListener(MouseEvent.CLICK,btnc);
function btnc(ev:MouseEvent):void
{
cekJawaban("c");
}
d_btn.addEventListener(MouseEvent.CLICK,btnd);
function btnd(ev:MouseEvent):void
{
cekJawaban("d");
}
var qvar_lv:URLLoader = new URLLoader();
qvar_lv.dataFormat = URLLoaderDataFormat.TEXT;// Step 1
qvar_lv.load(new URLRequest("DaftarSoal.txt")); // Step 2
qvar_lv.addEventListener(Event.COMPLETE, onComplete); // Step 3
function onComplete (event:Event):void // Step 4
{
var faq:String = event.target.data; // Step 5
trace("Success"+faq);
if (faq["Pertanyaan"+i] != undefined) {
no_txt.text = "PERTANYAAN KE-"+i;
soal_txt.text = faq["Pertanyaan"+i]; ja_txt.text = faq["a"+i];
jb_txt.text = faq["b"+i];
jc_txt.text = faq["c"+i];
jd_txt.text = faq["d"+i];
jawaban =faq["benar"+i];
} else {
gotoAndStop(3);
skor_txt.text = score+"";
teks_txt.text = "Score akhir kamu :";
}
}
function cekJawaban(val) {
alert_mc.visible = true;
if (val != jawaban) {
alert_mc.alert_txt.text = "jawaban kamu salah, score anda berkurang 50 points";
score = score-50;
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok);
function btnok(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
} else {
score = score+100;
alert_mc.alert_txt.text = "jawaban kamu benar, score anda bertambah 100 points";
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok2);
function btnok2(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
trace(score);
}
}
Error #1069:
Property Pertanyaan0 not found on String and there is no default value.
at revisi_fla::Symbol5_68/onComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()

Related

Acumatica - Where is the method that writes to CRRelation?

Can anyone help me find where in the code Acumatica writes to the CRRelation table when createing a Sales Order from an Opportunity? I've done a search for all instances of "CRRelation" but none of them seem to be doing the actual writing to the table.
It is done in the DoCreateSalesOrder(CreateSalesOrderFilter param) method which is called in the CreateSalesOrder action:
public PXAction<CROpportunity> createSalesOrder;
[PXUIField(DisplayName = Messages.CreateSalesOrder, MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Select)]
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
public virtual IEnumerable CreateSalesOrder(PXAdapter adapter)
{
foreach (CROpportunity opportunity in adapter.Get())
{
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>
.SelectSingleBound(this, new object[] { opportunity });
if (customer == null)
{
throw new PXException(Messages.ProspectNotCustomer);
}
var products = Products.View.SelectMultiBound(new object[] { opportunity }).RowCast<CROpportunityProducts>();
if (products.Any(_ => _.InventoryID == null) && !products.Any(_ => _.InventoryID != null))
{
throw new PXException(Messages.SalesOrderHasOnlyNonInventoryLines);
}
if (CreateOrderParams.AskExtFullyValid((graph, viewName) => { }, DialogAnswerType.Positive))
{
Save.Press();
PXLongOperation.StartOperation(this, delegate()
{
var grapph = PXGraph.CreateInstance<OpportunityMaint>();
grapph.Opportunity.Current = opportunity;
grapph.CreateOrderParams.Current = CreateOrderParams.Current;
grapph.DoCreateSalesOrder(CreateOrderParams.Current);
});
}
yield return opportunity;
}
}
if we look in that method we can find the following lines which are creating the relation:
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
You can find the full code of that method below:
protected virtual void DoCreateSalesOrder(CreateSalesOrderFilter param)
{
bool recalcAny = param.RecalculatePrices == true ||
param.RecalculateDiscounts == true ||
param.OverrideManualDiscounts == true ||
param.OverrideManualDocGroupDiscounts == true ||
param.OverrideManualPrices == true;
var opportunity = this.Opportunity.Current;
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>.Select(this);
SOOrderEntry docgraph = PXGraph.CreateInstance<SOOrderEntry>();
CurrencyInfo info = PXSelect<CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<CROpportunity.curyInfoID>>>>.Select(this);
info.CuryInfoID = null;
info = CurrencyInfo.GetEX(docgraph.currencyinfo.Insert(info.GetCM()));
SOOrder doc = new SOOrder();
doc.OrderType = CreateOrderParams.Current.OrderType ?? SOOrderTypeConstants.SalesOrder;
doc = docgraph.Document.Insert(doc);
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Search<SOOrder.orderNbr>(doc.OrderNbr));
doc.CuryInfoID = info.CuryInfoID;
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Update(doc));
doc.CuryID = info.CuryID;
doc.OrderDate = Accessinfo.BusinessDate;
doc.OrderDesc = opportunity.Subject;
doc.TermsID = customer.TermsID;
doc.CustomerID = opportunity.BAccountID;
doc.CustomerLocationID = opportunity.LocationID ?? customer.DefLocationID;
if (opportunity.TaxZoneID != null)
{
doc.TaxZoneID = opportunity.TaxZoneID;
if (!recalcAny)
{
SOTaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
SOTaxAttribute.SetTaxCalc<SOOrder.freightTaxCategoryID>(docgraph.Document.Cache, null,
TaxCalc.ManualCalc);
}
}
doc.ProjectID = opportunity.ProjectID;
doc.BranchID = opportunity.BranchID;
doc = docgraph.Document.Update(doc);
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
bool failed = false;
foreach (CROpportunityProducts product in SelectProducts(opportunity.QuoteNoteID))
{
if (product.SiteID == null)
{
InventoryItem item = (InventoryItem)PXSelectorAttribute.Select<CROpportunityProducts.inventoryID>(Products.Cache, product);
if (item != null && item.NonStockShip == true)
{
Products.Cache.RaiseExceptionHandling<CROpportunityProducts.siteID>(product, null,
new PXSetPropertyException(ErrorMessages.FieldIsEmpty, typeof(CROpportunityProducts.siteID).Name));
failed = true;
}
}
SOLine tran = new SOLine();
tran = docgraph.Transactions.Insert(tran);
if (tran != null)
{
tran.InventoryID = product.InventoryID;
tran.SubItemID = product.SubItemID;
tran.TranDesc = product.Descr;
tran.OrderQty = product.Quantity;
tran.UOM = product.UOM;
tran.CuryUnitPrice = product.CuryUnitPrice;
tran.TaxCategoryID = product.TaxCategoryID;
tran.SiteID = product.SiteID;
tran.IsFree = product.IsFree;
tran.ProjectID = product.ProjectID;
tran.TaskID = product.TaskID;
tran.CostCodeID = product.CostCodeID;
tran.ManualPrice = true;
tran.ManualDisc = true;
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
tran.POCreate = product.POCreate;
tran.VendorID = product.VendorID;
if (param.RecalculatePrices != true)
{
tran.ManualPrice = true;
}
else
{
if (param.OverrideManualPrices != true)
tran.ManualPrice = product.ManualPrice;
else
tran.ManualPrice = false;
}
if (param.RecalculateDiscounts != true)
{
tran.ManualDisc = true;
}
else
{
if (param.OverrideManualDiscounts != true)
tran.ManualDisc = product.ManualDisc;
else
tran.ManualDisc = false;
}
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
}
tran = docgraph.Transactions.Update(tran);
PXNoteAttribute.CopyNoteAndFiles(Products.Cache, product, docgraph.Transactions.Cache, tran,
Setup.Current);
}
PXNoteAttribute.CopyNoteAndFiles(Opportunity.Cache, opportunity, docgraph.Document.Cache, doc, Setup.Current);
if (failed)
throw new PXException(Messages.SiteNotDefined);
//Skip all customer dicounts
if (param.RecalculateDiscounts != true && param.OverrideManualDiscounts != true)
{
var discounts = new Dictionary<string, SOOrderDiscountDetail>();
foreach (SOOrderDiscountDetail discountDetail in docgraph.DiscountDetails.Select())
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(discountDetail, true);
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
discounts.Add(key, discountDetail);
}
Discount ext = this.GetExtension<Discount>();
foreach (CROpportunityDiscountDetail discountDetail in ext.DiscountDetails.Select())
{
SOOrderDiscountDetail detail;
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
if (discounts.TryGetValue(key, out detail))
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(detail, false);
if (discountDetail.IsManual == true && discountDetail.Type == DiscountType.Document)
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.extDiscCode>(detail, discountDetail.ExtDiscCode);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.description>(detail, discountDetail.Description);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.isManual>(detail, discountDetail.IsManual);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.curyDiscountAmt>(detail, discountDetail.CuryDiscountAmt);
}
}
else
{
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.CreateInstance();
detail.Type = discountDetail.Type;
detail.DiscountID = discountDetail.DiscountID;
detail.DiscountSequenceID = discountDetail.DiscountSequenceID;
detail.ExtDiscCode = discountDetail.ExtDiscCode;
detail.Description = discountDetail.Description;
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.Insert(detail);
if (discountDetail.IsManual == true && (discountDetail.Type == DiscountType.Document || discountDetail.Type == DiscountType.ExternalDocument))
{
detail.CuryDiscountAmt = discountDetail.CuryDiscountAmt;
detail.IsManual = discountDetail.IsManual;
docgraph.DiscountDetails.Cache.Update(detail);
}
}
}
SOOrder old_row = PXCache<SOOrder>.CreateCopy(docgraph.Document.Current);
docgraph.Document.Cache.SetValueExt<SOOrder.curyDiscTot>(docgraph.Document.Current, DiscountEngineProvider.GetEngineFor<SOLine, SOOrderDiscountDetail>().GetTotalGroupAndDocumentDiscount(docgraph.DiscountDetails));
docgraph.Document.Cache.RaiseRowUpdated(docgraph.Document.Current, old_row);
}
doc = docgraph.Document.Update(doc);
if (opportunity.TaxZoneID != null && !recalcAny)
{
foreach (CRTaxTran tax in PXSelect<CRTaxTran, Where<CRTaxTran.quoteID, Equal<Current<CROpportunity.quoteNoteID>>>>.Select(this))
{
SOTaxTran newtax = new SOTaxTran();
newtax.LineNbr = int.MaxValue;
newtax.TaxID = tax.TaxID;
newtax = docgraph.Taxes.Insert(newtax);
if (newtax != null)
{
newtax = PXCache<SOTaxTran>.CreateCopy(newtax);
newtax.TaxRate = tax.TaxRate;
newtax.CuryTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnshippedTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnshippedTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnbilledTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnbilledTaxAmt = tax.CuryTaxAmt;
newtax = docgraph.Taxes.Update(newtax);
}
}
}
if (opportunity.AllowOverrideContactAddress == true)
{
CRContact _CRContact = Opportunity_Contact.SelectSingle();
CRAddress _CRAddress = Opportunity_Address.SelectSingle();
// Insert
if (_CRContact != null)
{
SOBillingContact _billingContact = docgraph.Billing_Contact.Select();
if (_billingContact != null)
{
_billingContact.FullName = _CRContact.FullName;
_billingContact.Salutation = _CRContact.Salutation;
_billingContact.Phone1 = _CRContact.Phone1;
_billingContact.Email = _CRContact.Email;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
_billingContact.IsDefaultContact = false;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
}
}
if (_CRAddress != null)
{
SOBillingAddress _billingAddress = docgraph.Billing_Address.Select();
if (_billingAddress != null)
{
_billingAddress.AddressLine1 = _CRAddress.AddressLine1;
_billingAddress.AddressLine2 = _CRAddress.AddressLine2;
_billingAddress.City = _CRAddress.City;
_billingAddress.CountryID = _CRAddress.CountryID;
_billingAddress.State = _CRAddress.State;
_billingAddress.PostalCode = _CRAddress.PostalCode;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
_billingAddress.IsDefaultAddress = false;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
}
}
}
if (recalcAny)
{
docgraph.recalcdiscountsfilter.Current.OverrideManualPrices = param.OverrideManualPrices == true;
docgraph.recalcdiscountsfilter.Current.RecalcDiscounts = param.RecalculateDiscounts == true;
docgraph.recalcdiscountsfilter.Current.RecalcUnitPrices = param.RecalculatePrices == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDiscounts = param.OverrideManualDiscounts == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDocGroupDiscounts = param.OverrideManualDocGroupDiscounts == true;
docgraph.Actions[nameof(Discount.RecalculateDiscountsAction)].Press();
}
if (!this.IsContractBasedAPI)
throw new PXRedirectRequiredException(docgraph, "");
docgraph.Save.Press();
}
NOTE: you can find most part of the sources by the following path in the Acumatica's server folder App_Data\CodeRepository\PX.Objects,App_Data\CodeRepository\PX.Data,App_Data\CodeRepository\PX.Objects.FS

node.js setInterval does not trigger a this. object

When the page loads the console log part of the function works showing me the current seconds + 3, but it does not repeat and the (innerText =....) does not work at all. I only added the console log part to the code to try to troubleshoot, the inner text change is the important part.
class Main {
constructor() {
// Initiate variables
this.TimerTexts = [];
this.infoTexts = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.currentTime2 = new Date(Date.now());
this.currentTime = new Date(Date.now());
this.remTime = this.currentTime.getSeconds() + 3;
this.looper = window.setInterval(this.intervalfunc(), 1000);
}
// ...
intervalfunc() {
this.TimerTexts.innerText = `Time: ${this.remTime} `;
console.log(this.remTime);
}
// ...
}
The problem is you're calling intervalfunc, not passing in as the function for setInterval.
In addition, you'll need to bind the function to your instance.
this.looper = window.setInterval(this.intervalfunc.bind(this), 1000);
You can use arrow function, inside arrow function you can call intervalfunc.
class Main {
constructor() {
// Initiate variables
this.TimerTexts = [];
this.infoTexts = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.currentTime2 = new Date(Date.now());
this.currentTime = new Date(Date.now());
this.remTime = this.currentTime.getSeconds() + 3;
this.looper = window.setInterval(()=>this.intervalfunc(), 1000);
}
intervalfunc() {
this.TimerTexts.innerText = `Time: ${this.remTime} `;
console.log(this.remTime);
this.remTime += 3;
}
}
new Main()
OR you can do
class Main {
constructor() {
// Initiate variables
this.TimerTexts = [];
this.infoTexts = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.currentTime2 = new Date(Date.now());
this.currentTime = new Date(Date.now());
this.remTime = this.currentTime.getSeconds() + 3;
var self = this;
this.looper = window.setInterval(this.intervalfunc.bind(self), 1000);
}
intervalfunc() {
this.TimerTexts.innerText = `Time: ${this.remTime} `;
console.log(this.remTime);
this.remTime += 3;
}
}
new Main()

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

Why is parallel.Invoke not working in this case

I have an array of files like this..
string[] unZippedFiles;
the idea is that I want to parse these files in paralle. As they are parsed a record gets placed on a concurrentbag. As record is getting placed I want to kick of the update function.
Here is what I am doing in my Main():
foreach(var file in unZippedFiles)
{ Parallel.Invoke
(
() => ImportFiles(file),
() => UpdateTest()
);
}
this is what the code of Update loooks like.
static void UpdateTest( )
{
Console.WriteLine("Updating/Inserting merchant information.");
while (!merchCollection.IsEmpty || producingRecords )
{
merchant x;
if (merchCollection.TryTake(out x))
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
}
This is what the import code looks like. It's pretty much a giant string parser.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
producingRecords = true;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
catch (Exception ex)
{
producingRecords = false;
}
finally
{
producingRecords = false;
}
}
the problem i am having is that the Update runs once and then the importfile function just takes over and does not yield to the update function. Any ideas on what am I doing wrong would be of great help.
Here's my stab at fixing your thread synchronisation. Note that I haven't changed any of the code from the functional standpoint (with the exception of taking out the catch - it's generally a bad idea; exceptions need to be propagated).
Forgive if something doesn't compile - I'm writing this based on incomplete snippets.
Main
foreach(var file in unZippedFiles)
{
using (var merchCollection = new BlockingCollection<merchant>())
{
Parallel.Invoke
(
() => ImportFiles(file, merchCollection),
() => UpdateTest(merchCollection)
);
}
}
Update
private void UpdateTest(BlockingCollection<merchant> merchCollection)
{
Console.WriteLine("Updating/Inserting merchant information.");
foreach (merchant x in merchCollection.GetConsumingEnumerable())
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
Import
Don't forget to pass in merchCollection as a parameter - it should not be static.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
finally
{
merchCollection.CompleteAdding();
}
}

How do I programmatically create a FTP site in IIS7 on Windows7?

I am looking to do this step: 'Creating a New FTP Site by Editing the IIS 7.0 Configuration Files' with a batch file and was wondering if anybody has done this already?
http://learn.iis.net/page.aspx/301/creating-a-new-ftp-site/
Try this. You need to reference the COM component "AppHostAdminLibrary"
using AppHostAdminLibrary;
...
public void AddFtp7Site(String siteName, String siteId, String siteRoot) {
String configPath;
String configSectionName;
var fNewSite = false;
var fNewApplication = false;
var fNewVDir = false;
//
// First setup the sites section
//
configPath = "MACHINE/WEBROOT/APPHOST";
configSectionName = "system.applicationHost/sites";
var adminManager = new AppHostAdminLibrary.AppHostWritableAdminManager();
adminManager.CommitPath = configPath;
try {
var sitesElement = adminManager.GetAdminSection(configSectionName, configPath);
IAppHostElement newSiteElement = null;
//
// check if site already exists
//
for (var i = 0; i < sitesElement.Collection.Count; i++) {
var siteElement = sitesElement.Collection[i];
if (siteElement.Properties["name"].Value.Equals(siteName) &&
siteElement.Properties["id"].Value.Equals(siteId)) {
newSiteElement = siteElement;
break;
}
}
if (newSiteElement == null) {
//
// Site doesn't exist yet. Add new site node
//
newSiteElement = sitesElement.Collection.CreateNewElement("");
newSiteElement.Properties["id"].Value = siteId;
newSiteElement.Properties["name"].Value = siteName;
fNewSite = true;
}
// setup bindings for the new site
var ftpBindingString = "*:21:";
var Bindings = newSiteElement.GetElementByName("bindings");
var BindingElement = Bindings.Collection.CreateNewElement("");
BindingElement.Properties["protocol"].Value = "ftp";
BindingElement.Properties["bindingInformation"].Value = ftpBindingString;
try {
Bindings.Collection.AddElement(BindingElement, 0);
}
catch (Exception ex) {
if (ex.Message != "") // ERROR_ALREADY_EXISTS ?
{
throw;
}
}
IAppHostElement newApplication = null;
//
// check if root application already exists
//
for (var i = 0; i < newSiteElement.Collection.Count; i++) {
var applicationElement = newSiteElement.Collection[i];
if (applicationElement.Properties["path"].Value.Equals("/")) {
newApplication = applicationElement;
break;
}
}
if (newApplication == null) {
newApplication = newSiteElement.Collection.CreateNewElement("application");
newApplication.Properties["path"].Value = "/";
fNewApplication = true;
}
IAppHostElement newVirtualDirectory = null;
//
// search for the root vdir
//
for (var i = 0; i < newApplication.Collection.Count; i++) {
var vdirElement = newApplication.Collection[i];
if (vdirElement.Properties["path"].Value.Equals("/")) {
newVirtualDirectory = vdirElement;
break;
}
}
if (newVirtualDirectory == null) {
newVirtualDirectory = newApplication.Collection.CreateNewElement("");
newVirtualDirectory.Properties["path"].Value = "/";
fNewVDir = true;
}
newVirtualDirectory.Properties["physicalPath"].Value = siteRoot;
if (fNewVDir) {
newApplication.Collection.AddElement(newVirtualDirectory, 0);
}
if (fNewApplication) {
newSiteElement.Collection.AddElement(newApplication, 0);
}
var ftpSiteSettings = newSiteElement.GetElementByName("ftpServer").GetElementByName("security").GetElementByName("authentication");
Console.WriteLine("Enable anonymous authentication");
var anonAuthSettings = ftpSiteSettings.GetElementByName("anonymousAuthentication");
anonAuthSettings.Properties["enabled"].Value = "true";
Console.WriteLine("Disable basic authentication");
var basicAuthSettings = ftpSiteSettings.GetElementByName("basicAuthentication");
basicAuthSettings.Properties["enabled"].Value = "false";
BindingElement.Properties["bindingInformation"].Value = "*:21:";
//
// Time to add new site element and commit changes
//
if (fNewSite) {
sitesElement.Collection.AddElement(newSiteElement, 0);
}
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured in AddDefaultFtpSite: " + ex.Message);
}
//
// Add <authorization> section to allow everyone Read
//
Console.WriteLine("Enable everyone Read access");
try {
configPath = "MACHINE/WEBROOT/APPHOST/" + siteName;
configSectionName = "system.ftpServer/security/authorization";
var azSection = adminManager.GetAdminSection(configSectionName, configPath);
azSection.Collection.Clear();
var newAzElement = azSection.Collection.CreateNewElement("");
newAzElement.Properties["accessType"].Value = "Allow";
newAzElement.Properties["users"].Value = "*";
newAzElement.Properties["permissions"].Value = "Read";
azSection.Collection.AddElement(newAzElement, 0);
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured while adding authorization section: " + ex.Message);
}
}
Does this help?:
http://blogs.iis.net/jaroslad/archive/2007/06/13/how-to-programatically-create-an-ftp7-site.aspx

Resources