Why are we doing so in nested foreach loop? I can't understand I am lost - c#-4.0

I can't grasp the nested foreach loop. Anyone to simplify this for me? I am learning foreach loops in C# but am stuck. What is the logic behind this?
class SudokuFileReader
{
public int[,] ReadFile(string fileName)
{
int[,] sudokuBoard = new int[9, 9];
try
{
var sudokuBoardLines = File.ReadAllLines(fileName);
int row = 0;
foreach (var sudokuBoardLine in sudokuBoardLines)
{
string[] sudokuBoardLineElements = sudokuBoardLine.Split('|').Skip(1).Take(9).ToArray();
int col = 0;
foreach (var sudokuLineElement in sudokuBoardLineElements)
{
sudokuBoard[row, col] = sudokuLineElement.Equals(" ") ? 0 : Convert.ToInt16(sudokuLineElement);
col++;
}
row++;
}
}
catch (Exception ex)
{
throw new Exception("Something went wrong while reading the file: " + ex.Message);
}
return sudokuBoard;
}
}

Related

Apache POI - remove external Book reference

We receive excel files in our system and upon downloading them, i need to remove any reference to external workbook for security reasons.
i wrote the following function to remove external links as well as removing content from the cell referencing the book.
public static byte[] cleanFile(byte[] excelByteArrayworkbook) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (InputStream targetStream = new ByteArrayInputStream(excelByteArrayworkbook)){
try (XSSFWorkbook workbook = new XSSFWorkbook(targetStream)) {
XSSFEvaluationWorkbook evalWorkbook = XSSFEvaluationWorkbook.create((XSSFWorkbook) workbook);
Iterator<Sheet> sheetIterator = workbook.iterator();
int i = 0;
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
EvaluationSheet evalSheet = evalWorkbook.getSheet(i);
i++;
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
EvaluationCell evaluationCell = evalSheet.getCell(cell.getRowIndex(), cell.getColumnIndex());
try {
Ptg[] formulaTokens = evalWorkbook.getFormulaTokens(evaluationCell);
for (Ptg formulaToken : formulaTokens) {
int externalSheetIndex = -1;
if (formulaToken instanceof Ref3DPtg) {
Ref3DPtg refToken = (Ref3DPtg) formulaToken;
externalSheetIndex = refToken.getExternSheetIndex();
} else if (formulaToken instanceof Area3DPtg) {
Area3DPtg refToken = (Area3DPtg) formulaToken;
externalSheetIndex = refToken.getExternSheetIndex();
} else if (formulaToken instanceof Ref3DPxg) {
Ref3DPxg refToken = (Ref3DPxg) formulaToken;
externalSheetIndex = refToken.getExternalWorkbookNumber();
} else if (formulaToken instanceof Area3DPxg) {
Area3DPxg refToken = (Area3DPxg) formulaToken;
externalSheetIndex = refToken.getExternalWorkbookNumber();
}
if (externalSheetIndex >= 0) {
cell.setCellFormula(null);
}
else if (cell.getCellFormula().contains("[")) {
cell.setCellFormula(null);
}
}
} catch (Exception e) {
cell.setCellFormula(null);
}
}
}
}
}
List<ExternalLinksTable> links = workbook.getExternalLinksTable();
links.forEach(link -> {
if(link.getCTExternalLink().isSetDdeLink())
link.getCTExternalLink().unsetDdeLink();
if(link.getCTExternalLink().isSetExtLst())
link.getCTExternalLink().unsetExtLst();
if(link.getCTExternalLink().isSetOleLink())
link.getCTExternalLink().unsetOleLink();
if(link.getCTExternalLink().isSetExternalBook())
link.getCTExternalLink().unsetExternalBook();
link.getCTExternalLink().setNil();
});
try {
workbook.write(bos);
} finally {
bos.close();
}
}
}
try {
bos.close();
} catch (IOException e) {
}
return bos.toByteArray();
}
However, the file i am getting is not valid. Excel prompt me with an error message saying
Excel error message
The version of Apache POI i am using is 3.13 . I can't find an example where i can remove external links
I found the answer. The code was not removing references in the Name Manager area.
I have added the following in my function
List<XSSFName> nameUsingExternalBook = new ArrayList<XSSFName>();
for (int j = 0; j < workbook.getNumberOfNames(); j++) {
XSSFName name= workbook.getNameAt(j);
if(name.getRefersToFormula() != null && name.getRefersToFormula().contains("[")) {
nameUsingExternalBook.add(name);
}
}
nameUsingExternalBook.forEach(name->{
workbook.removeName(name.getNameName());
});
So the new excel file is wellformed

The remote server returned an error: (401) Unauthorized - CSOM - OAuth - after specific time

I am trying to get permissions assigned to each document from the document library using csom in console application. Console app is running fine for almost one hour and post that I get error : "The remote server returned an error: (401) Unauthorized."
I registered an app in SharePoint and I'm using Client ID & Client Secret Key to generate Client Context. Here is the code to get the client context
public static ClientContext getClientContext()
{
ClientContext ctx = null;
try
{
ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(SiteUrl, ClientId, ClientSecret);
ctx.RequestTimeout = 6000000;
ctx.ExecutingWebRequest += delegate (object sender, WebRequestEventArgs e)
{
e.WebRequestExecutor.WebRequest.UserAgent = "NONISV|Contoso|GovernanceCheck/1.0";
};
}
catch (Exception ex)
{
WriteLog("Method-getClientContext, Error - " + ex.Message);
}
return ctx;
}
Here is the code which is getting all the assignments assigned to document in document library.
static StringBuilder excelData = new StringBuilder();
static void ProcessWebnLists()
{
try
{
string[] lists = { "ABC", "XYZ", "DEF", "GHI"};
foreach (string strList in lists)
{
using (var ctx = getClientContext())
{
if (ctx != null)
{
Web web = ctx.Site.RootWeb;
ListCollection listCollection = web.Lists;
ctx.Load(web);
ctx.Load(listCollection);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle(strList);
ctx.Load(list);
ctx.ExecuteQuery();
Console.WriteLine("List Name:{0}", list.Title);
var query = new CamlQuery { ViewXml = "<View/>" };
var items = list.GetItems(query);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (var item in items)
{
var itemAssignments = item.RoleAssignments;
ctx.Load(item, i => i.DisplayName);
ctx.Load(itemAssignments);
ctx.ExecuteQuery();
Console.WriteLine(item.DisplayName);
string groupNames = "";
foreach (var assignment in itemAssignments)
{
try
{
ctx.Load(assignment.Member);
ctx.ExecuteQuery();
groupNames += "[" + assignment.Member.Title.Replace(",", " ") + "] ";
Console.WriteLine($"--> {assignment.Member.Title}");
}
catch (Exception e)
{
WriteLog("Method-ProcessWebnLists, List-" + list.Title + ", Document Title - " + item.DisplayName + ", Error : " + e.Message);
WriteLog("Method-ProcessWebnLists, StackTrace : " + e.StackTrace);
}
}
excelData.AppendFormat("{0},{1},ITEM,{2}", list.Title, (item.DisplayName).Replace(",", " "), groupNames);
excelData.AppendLine();
}
}
excelData.AppendLine();
}
}
}
catch (Exception ex)
{
WriteLog("Method-ProcessWebnLists, Error : " + ex.Message);
WriteLog("Method-ProcessWebnLists, StackTrace : " + ex.StackTrace.ToString());
}
}
Can anyone suggest what else I am missing in this or what kind of changes do I need to make to avoid this error?
The process is taking too much time so I want my application to keep running for couple of hours.
Thanks in advance!
Is there a reason why getClientContext() is inside the foreach loop?
I encountered this error before.
I added this to solve mine.
public static void ExecuteQueryWithIncrementalRetry(this ClientContext context, int retryCount, int delay)
{
int retryAttempts = 0;
int backoffInterval = delay;
if (retryCount <= 0)
throw new ArgumentException("Provide a retry count greater than zero.");
if (delay <= 0)
throw new ArgumentException("Provide a delay greater than zero.");
while (retryAttempts < retryCount)
{
try
{
context.ExecuteQuery();
return;
}
catch (WebException wex)
{
var response = wex.Response as HttpWebResponse;
if (response != null && response.StatusCode == (HttpStatusCode)429)
{
Console.WriteLine(string.Format("CSOM request exceeded usage limits. Sleeping for {0} seconds before retrying.", backoffInterval));
//Add delay.
System.Threading.Thread.Sleep(backoffInterval);
//Add to retry count and increase delay.
retryAttempts++;
backoffInterval = backoffInterval * 2;
}
else
{
throw;
}
}
}
throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, have been attempted.", retryCount));
}
Basically, this code backs off for a certain time/interval before executing another query, to prevent throttling.
So instead of using ctx.ExecuteQuery(), use ctx.ExecuteQueryWithIncrementalRetry(5, 1000);
Further explanation here
https://learn.microsoft.com/en-us/sharepoint/dev/general-development/how-to-avoid-getting-throttled-or-blocked-in-sharepoint-online

How to execute query on csv file

i have uploaded a csv file and also make a data-table from csv file.now i want to find distinct values from each columns of data-table.what will be the code for this.
i have tried by this code but there is error show that object is not ADODB.what is ADODB and how can i remove this error
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
//read column names
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
foreach (DataColumn col in csvdata.Columns)
{
foreach (DataRow ro in csvdata.Rows)
{
textBox1.Text = "" + ro[col];
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Command Timeout, longer to get response back

I am executing large query,so my app throwing time out error. Some of the thread suggested to added command time out but after adding those lines it take longer to get response back, any idea why or what am i missing in my code?
public int CreateRecord(string theCommand, DataSet theInputData)
{
int functionReturnValue = 0;
int retVal = 0;
SqlParameter objSqlParameter = default(SqlParameter);
DataSet dsParameter = new DataSet();
int i = 0;
try
{
//Set the command text (stored procedure name or SQL statement).
mobj_SqlCommand.CommandTimeout = 120;
mobj_SqlCommand.CommandText = theCommand;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
for (i = 0; i <= (theInputData.Tables.Count - 1); i++)
{
if (theInputData.Tables[i].Rows.Count > 0)
{
dsParameter.Tables.Add(theInputData.Tables[i].Copy());
}
}
objSqlParameter = new SqlParameter("#theXmlData", SqlDbType.Text);
objSqlParameter.Direction = ParameterDirection.Input;
objSqlParameter.Value = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + dsParameter.GetXml();
//Attach to the parameter to mobj_SqlCommand.
mobj_SqlCommand.Parameters.Add(objSqlParameter);
//Finally, execute the command.
retVal = (int)mobj_SqlCommand.ExecuteScalar();
//Detach the parameters from mobj_SqlCommand, so it can be used again.
mobj_SqlCommand.Parameters.Clear();
functionReturnValue = retVal;
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
finally
{
//Clean up the objects created in this object.
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
mobj_SqlConnection.Dispose();
mobj_SqlConnection = null;
}
if ((mobj_SqlCommand != null))
{
mobj_SqlCommand.Dispose();
mobj_SqlCommand = null;
}
if ((mobj_SqlDataAdapter != null))
{
mobj_SqlDataAdapter.Dispose();
mobj_SqlDataAdapter = null;
}
if ((dsParameter != null))
{
dsParameter.Dispose();
dsParameter = null;
}
objSqlParameter = null;
}
return functionReturnValue;
}

Listing all records j2me

I want to list all records in the record store. I've declared a list:
Private List tlist = new List("Select One", List.IMPLICIT);
Also enumerated the records:
Form mainf;
Command exit = new Command("Exit", Command.EXIT, 0);
RecordEnumeration re = null;
int numrecords = 0;
try {
re = contactList.enumerateRecords(null, null, false);
numrecords = re.numRecords();
} catch (RecordStoreException rse ) { numrecords = 0;}
Now I just need to know how to list all the records in a list.
Add the Record into Vector and use the loop for append the Vector values into List. See below sample code,
RecordStore s = RecordStore.openRecordStore(recordStoreName, true);
RecordEnumeration e = s.enumerateRecords(null, null, false);
Vector vector = new Vector();
while(e.hasNextElement()) {
vector.addElement(new String(e.nextRecord()));
}
List l = new List(null, CENTER);
for (int i = 0; i < vector.size(); i++) {
l.append(vector.elementAt(i).toString(), null);
}
you can use following code,
public String [] getRecordData()
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);
str = new String[rs.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}

Resources