I searched on the Internet, but I didn’t find much, I need to read a Google sheet and get a datatable at the output. Please tell me how can I do this (I'm just learning)
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Dynamic;
namespace GoogleSheetsHelper
{
public class GoogleSheetsHelper
{
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
static string ApplicationName = "GoogleSheetsHelper";
private readonly SheetsService _sheetsService;
private readonly string _spreadsheetId;
public GoogleSheetsHelper(string credentialFileName, string spreadsheetId)
{
var credential = GoogleCredential.FromStream(new FileStream(credentialFileName, FileMode.Open)).CreateScoped(Scopes);
_sheetsService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
_spreadsheetId = spreadsheetId;
}
public List<ExpandoObject> GetDataFromSheet(GoogleSheetParameters googleSheetParameters)
{
googleSheetParameters = MakeGoogleSheetDataRangeColumnsZeroBased(googleSheetParameters);
var range = $"{googleSheetParameters.SheetName}!{GetColumnName(googleSheetParameters.RangeColumnStart)}{googleSheetParameters.RangeRowStart}:{GetColumnName(googleSheetParameters.RangeColumnEnd)}{googleSheetParameters.RangeRowEnd}";
SpreadsheetsResource.ValuesResource.GetRequest request =
_sheetsService.Spreadsheets.Values.Get(_spreadsheetId, range);
var numberOfColumns = googleSheetParameters.RangeColumnEnd - googleSheetParameters.RangeColumnStart;
var columnNames = new List<string>();
var returnValues = new List<ExpandoObject>();
if (!googleSheetParameters.FirstRowIsHeaders)
{
for (var i = 0;i<=numberOfColumns;i++)
{
columnNames.Add($"Column{i}");
}
}
var response = request.Execute();
int rowCounter = 0;
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
if (googleSheetParameters.FirstRowIsHeaders && rowCounter == 0)
{
for (var i = 0; i <= numberOfColumns; i++)
{
columnNames.Add(row[i].ToString());
}
rowCounter++;
continue;
}
var expando = new ExpandoObject();
var expandoDict = expando as IDictionary<String, object>;
var columnCounter = 0;
foreach (var columnName in columnNames)
{
expandoDict.Add(columnName, row[columnCounter].ToString());
columnCounter++;
}
returnValues.Add(expando);
rowCounter++;
}
}
return returnValues;
}
public void AddCells(GoogleSheetParameters googleSheetParameters, List<GoogleSheetRow> rows)
{
var requests = new BatchUpdateSpreadsheetRequest {Requests = new List<Request>()};
var sheetId = GetSheetId(_sheetsService, _spreadsheetId, googleSheetParameters.SheetName);
GridCoordinate gc = new GridCoordinate
{
ColumnIndex = googleSheetParameters.RangeColumnStart - 1,
RowIndex = googleSheetParameters.RangeRowStart - 1,
SheetId = sheetId
};
var request = new Request {UpdateCells = new UpdateCellsRequest {Start = gc, Fields = "*"}};
var listRowData = new List<RowData>();
foreach (var row in rows)
{
var rowData = new RowData();
var listCellData = new List<CellData>();
foreach (var cell in row.Cells)
{
var cellData = new CellData();
var extendedValue = new ExtendedValue {StringValue = cell.CellValue};
cellData.UserEnteredValue = extendedValue;
var cellFormat = new CellFormat {TextFormat = new TextFormat()};
if (cell.IsBold)
{
cellFormat.TextFormat.Bold = true;
}
cellFormat.BackgroundColor = new Color { Blue = (float)cell.BackgroundColor.B/255, Red = (float)cell.BackgroundColor.R/255, Green = (float)cell.BackgroundColor.G/255 };
cellData.UserEnteredFormat = cellFormat;
listCellData.Add(cellData);
}
rowData.Values = listCellData;
listRowData.Add(rowData);
}
request.UpdateCells.Rows = listRowData;
// It's a batch request so you can create more than one request and send them all in one batch. Just use reqs.Requests.Add() to add additional requests for the same spreadsheet
requests.Requests.Add(request);
_sheetsService.Spreadsheets.BatchUpdate(requests, _spreadsheetId).Execute();
}
private string GetColumnName(int index)
{
const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var value = "";
if (index >= letters.Length)
value += letters[index / letters.Length - 1];
value += letters[index % letters.Length];
return value;
}
private GoogleSheetParameters MakeGoogleSheetDataRangeColumnsZeroBased(GoogleSheetParameters googleSheetParameters)
{
googleSheetParameters.RangeColumnStart = googleSheetParameters.RangeColumnStart - 1;
googleSheetParameters.RangeColumnEnd = googleSheetParameters.RangeColumnEnd - 1;
return googleSheetParameters;
}
private int GetSheetId(SheetsService service, string spreadSheetId, string spreadSheetName)
{
var spreadsheet = service.Spreadsheets.Get(spreadSheetId).Execute();
var sheet = spreadsheet.Sheets.FirstOrDefault(s => s.Properties.Title == spreadSheetName);
int sheetId = (int)sheet.Properties.SheetId;
return sheetId;
}
}
public class GoogleSheetCell
{
public string CellValue { get; set; }
public bool IsBold { get; set; }
public System.Drawing.Color BackgroundColor { get; set; } = System.Drawing.Color.White;
}
public class GoogleSheetParameters
{
public int RangeColumnStart { get; set; }
public int RangeRowStart { get; set; }
public int RangeColumnEnd { get; set; }
public int RangeRowEnd { get; set; }
public string SheetName { get; set; }
public bool FirstRowIsHeaders { get; set; } }
public class GoogleSheetRow
{
public GoogleSheetRow() => Cells = new List<GoogleSheetCell>();
public List<GoogleSheetCell> Cells { get; set; }
}
}
Related
I have to parse a TSV file which has the following structure:
[Secti
"1 2"
"2 3"his?
I'm not sure if this is what you were trying to do or not. I also noticed that it appeared to be 4 spaces between records. If it is actually a tab, you can change the delimiter to a tab Delimiter = "\t",
void Main()
{
var data = #"[Section one of info]
""Atr1 1""
""Atr2 2""
[Section two of info]
""Atr3 Atr4""
""1 2""
""2 3""
""4 5""";
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = " ",
Mode = CsvMode.Escape
};
using (var reader = new StringReader(data))
using (var csv = new CsvReader(reader, config))
{
var isSectionOne = true;
var record = new Foo() { Atr3 = new List<int>(), Atr4 = new List<int>() };
while(csv.Read())
{
if (csv.GetField(0).StartsWith("["))
continue;
if (isSectionOne)
{
if (csv.GetField(0) == "Atr1")
{
record.Atr1 = csv.GetField<int>(1);
}
if (csv.GetField(0) == "Atr2")
{
record.Atr2 = csv.GetField<int>(1);
}
if (csv.GetField(0) == "Atr3")
{
isSectionOne = false;
}
}
else
{
record.Atr3.Add(csv.GetField<int>(0));
record.Atr4.Add(csv.GetField<int>(1));
}
}
record.Dump();
}
}
public class Foo
{
public int Atr1 { get; set; }
public int Atr2 { get; set; }
public List<int> Atr3 { get; set; }
public List<int> Atr4 { get; set; }
}
I have an MVC that takes values from a form, sends them to a dll, to have logic performed on them & assigned to a model. The model is then returned to the view. In localhost it is successful and I get the following result:
However when I publish the webapp to an azure instance, it doesn't return any of the values. You can see it here: http://levelupsite.azurewebsites.net/ or see the image here
Does anyone know what could cause this? I will attach the code below:
Controller:
[HttpPost]
public ActionResult CBC(System.Web.Mvc.FormCollection form, FFAC model)
{
//recieve values from form
var email = escapeCharactersspace((form["email"].ToString()));
var Gender = Convert.ToString(model.UserGender);
var UserID = escapeCharactersspace((form["username"].ToString()));
var Neutrophils = escapeCharactersspace(form["Neutrophils"]);
var Lymphocytes = escapeCharactersspace(form["Lympthocytes"]);
var Monocytes = escapeCharactersspace(form["Monocytes"]);
var Eosinophils = escapeCharactersspace(form["Eosinophils"]);
var Basophils = escapeCharactersspace(form["Basophils"]);
var Platelets = (escapeCharactersspace(form["Platelets"]));
var Haematocrit = escapeCharactersspace(form["Haematocrit"]);
var Haemoglobin = escapeCharactersspace(form["Haemoglobin"]);
var MCV = escapeCharactersspace(form["MCV"]);
var MCH = (escapeCharactersspace(form["MCH"]));
var MCHC = escapeCharactersspace(form["MCHC"]);
//turn form to array
decimal[] cbcInputs = { Convert.ToDecimal(Neutrophils), Convert.ToDecimal(Lymphocytes), Convert.ToDecimal(Monocytes), Convert.ToDecimal(Eosinophils), Convert.ToDecimal(Basophils), Convert.ToDecimal(Platelets), Convert.ToDecimal(Haematocrit), Convert.ToDecimal(Haemoglobin), Convert.ToDecimal(MCV), Convert.ToDecimal(MCH), Convert.ToDecimal(MCHC) };
//create instance of model
var scfiae = new FIAECBC();
//create instance of external class library
var fiae = new FIAEngine();
//send inputs & model instance to external class library to perform logic
fiae.setcbcvals(cbcInputs, UserID, Gender, scfiae);
//return the get results page
return View("GetResults", scfiae);
}
FIAEngine - dll that performs the logic
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharedComponents;
using static SharedComponents.FIAECBC;
namespace FIAE
{
public class FIAEngine
{
decimal d_Neutrophils;
decimal d_Lymphocytes;
decimal d_Monocytes;
decimal d_Eosinophils;
decimal d_Basophils;
decimal d_Platelets;
decimal d_Haematocrit;
decimal d_Haemoglobin;
decimal d_MCV;
decimal d_MCH;
decimal d_MCHC;
string UserID;
string Gender;
string Neutrophils;
string Lymphocytes;
string Monocytes;
string Eosinophils;
string Basophils;
string Platelets;
string Haematocrit;
string Haemoglobin;
string MCV;
string MCH;
string MCHC;
string rag_Neutrophils;
string rag_Lymphocytes;
string rag_Monocytes;
string rag_Eosinophils;
string rag_Basophils;
string rag_Platelets;
string rag_Haematocrit;
string rag_Haemoglobin;
string rag_MCV;
string rag_MCH;
string rag_MCHC;
public void Setcbcfilevals(FIAECBC cbcmodel)
{
}
public void setcbcvals(decimal[] inputs, string _UserID, string _Gender, FIAECBC cbcmodel)
{
d_Neutrophils = inputs[0];
d_Lymphocytes = inputs[1];
d_Monocytes = inputs[2];
d_Eosinophils = inputs[3];
d_Basophils = inputs[4];
d_Platelets = inputs[5];
d_Haematocrit = inputs[6];
d_Haemoglobin = inputs[7];
d_MCV = inputs[8];
d_MCH = inputs[9];
d_MCHC = inputs[10];
UserID = _UserID;
Gender = _Gender;
Neutrophils = "Neutrophils";
Lymphocytes = "Lymphocytes";
Monocytes = "Monocytes";
Eosinophils = "Eosinophils";
Basophils = "Basophils";
Platelets = "Platelets";
Haematocrit = "Haematocrit";
Haemoglobin = "Haemoglobin";
MCV = "MCV";
MCH = "MCH";
MCHC = "MCHC";
rag_Neutrophils = "i";
rag_Lymphocytes = "i";
rag_Monocytes = "i";
rag_Eosinophils = "i";
rag_Basophils = "i";
rag_Platelets = "i";
rag_Haematocrit = "i";
rag_Haemoglobin = "i";
rag_MCV = "i";
rag_MCH = "i";
rag_MCHC = "i";
try
{
//male calculations
if (Gender == "Male")
{
rag_Neutrophils = FindMaleRAG(d_Neutrophils, 1);
rag_Lymphocytes = FindMaleRAG(d_Lymphocytes, 2);
rag_Monocytes = FindMaleRAG(d_Monocytes, 3);
rag_Eosinophils = FindMaleRAG(d_Eosinophils, 4);
rag_Basophils = FindfeMaleRAG(d_Basophils, 5);
rag_Platelets = FindMaleRAG(d_Platelets, 6);
rag_Haematocrit = FindMaleRAG(d_Haematocrit, 7);
rag_Haemoglobin = FindMaleRAG(d_Haemoglobin, 8);
rag_MCV = FindMaleRAG(d_MCV, 9);
rag_MCH = FindMaleRAG(d_MCH, 10);
rag_MCHC = FindMaleRAG(d_MCHC, 11);
//set view model values to the form values
cbcmodel.d_Neutrophils = d_Neutrophils;
cbcmodel.d_Lymphocytes = d_Lymphocytes;
cbcmodel.d_Monocytes = d_Monocytes;
cbcmodel.d_Eosinophils = d_Eosinophils;
cbcmodel.d_Basophils = d_Basophils;
cbcmodel.d_Platelets = d_Platelets;
cbcmodel.d_Haematocrit = d_Haematocrit;
cbcmodel.d_Haemoglobin = d_Haemoglobin;
cbcmodel.d_MCV = d_MCV;
cbcmodel.d_MCH = d_MCH;
cbcmodel.d_MCHC = d_MCHC;
cbcmodel.Neutrophils = Neutrophils;
cbcmodel.Lymphocytes = Lymphocytes;
cbcmodel.Monocytes = Monocytes;
cbcmodel.Eosinophils = Eosinophils;
cbcmodel.Basophils = Basophils;
cbcmodel.Platelets = Platelets;
cbcmodel.Haematocrit = Haematocrit;
cbcmodel.Haemoglobin = Haemoglobin;
cbcmodel.MCV = MCV;
cbcmodel.MCH = MCH;
cbcmodel.MCHC = MCHC;
cbcmodel.rag_Neutrophils = rag_Neutrophils;
cbcmodel.rag_Lymphocytes = rag_Lymphocytes;
cbcmodel.rag_Monocytes = rag_Monocytes;
cbcmodel.rag_Eosinophils = rag_Eosinophils;
cbcmodel.rag_Basophils = rag_Basophils;
cbcmodel.rag_Platelets = rag_Platelets;
cbcmodel.rag_Haematocrit = rag_Haematocrit;
cbcmodel.rag_Haemoglobin = rag_Haematocrit;
cbcmodel.rag_MCV = rag_MCV;
cbcmodel.rag_MCH = rag_MCH;
cbcmodel.rag_MCHC = rag_MCHC;
}
else if (Gender == "Female")
{
rag_Neutrophils = FindfeMaleRAG(d_Neutrophils, 1);
rag_Lymphocytes = FindfeMaleRAG(d_Lymphocytes, 2);
rag_Monocytes = FindfeMaleRAG(d_Monocytes, 3);
rag_Eosinophils = FindfeMaleRAG(d_Eosinophils, 4);
rag_Basophils = FindfeMaleRAG(d_Basophils, 5);
rag_Platelets = FindfeMaleRAG(d_Platelets, 6);
rag_Haematocrit = FindfeMaleRAG(d_Haematocrit, 7);
rag_Haemoglobin = FindfeMaleRAG(d_Haemoglobin, 8);
rag_MCV = FindfeMaleRAG(d_MCV, 9);
rag_MCH = FindfeMaleRAG(d_MCH, 10);
rag_MCHC = FindfeMaleRAG(d_MCHC, 11);
//set view model values to the form values
cbcmodel.d_Neutrophils = d_Neutrophils;
cbcmodel.d_Lymphocytes = d_Lymphocytes;
cbcmodel.d_Monocytes = d_Monocytes;
cbcmodel.d_Eosinophils = d_Eosinophils;
cbcmodel.d_Basophils = d_Basophils;
cbcmodel.d_Platelets = d_Platelets;
cbcmodel.d_Haematocrit = d_Haematocrit;
cbcmodel.d_Haemoglobin = d_Haemoglobin;
cbcmodel.d_MCV = d_MCV;
cbcmodel.d_MCH = d_MCH;
cbcmodel.d_MCHC = d_MCHC;
cbcmodel.Neutrophils = Neutrophils;
cbcmodel.Lymphocytes = Lymphocytes;
cbcmodel.Monocytes = Monocytes;
cbcmodel.Eosinophils = Eosinophils;
cbcmodel.Basophils = Basophils;
cbcmodel.Platelets = Platelets;
cbcmodel.Haematocrit = Haematocrit;
cbcmodel.Haemoglobin = Haemoglobin;
cbcmodel.MCV = MCV;
cbcmodel.MCH = MCH;
cbcmodel.MCHC = MCHC;
cbcmodel.rag_Neutrophils = rag_Neutrophils;
cbcmodel.rag_Lymphocytes = rag_Lymphocytes;
cbcmodel.rag_Monocytes = rag_Monocytes;
cbcmodel.rag_Eosinophils = rag_Eosinophils;
cbcmodel.rag_Basophils = rag_Basophils;
cbcmodel.rag_Platelets = rag_Platelets;
cbcmodel.rag_Haematocrit = rag_Haematocrit;
cbcmodel.rag_Haemoglobin = rag_Haematocrit;
cbcmodel.rag_MCV = rag_MCV;
cbcmodel.rag_MCH = rag_MCH;
cbcmodel.rag_MCHC = rag_MCHC;
}
}
catch (Exception ex)
{
}
//return inputs;
}
public string FindMaleRAG(decimal i, int x)
{
String connString = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLServerCon"]);
//for each row, do this
//find the threshld values
String thresholdquery = #"select * from dbo.malethreshold where ID = " + x;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(thresholdquery, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//compare threshold values t posted values from form
string composite = Convert.ToString(reader[1]);
decimal redlow = Convert.ToDecimal(reader[2]);
decimal greenlow = Convert.ToDecimal(reader[3]);
decimal greenhigh = Convert.ToDecimal(reader[4]);
decimal redhigh = Convert.ToDecimal(reader[5]);
if (i < redlow)
{
// Red low
return ("red");
}
else if (i > redlow && i < greenlow)
{
// Amber Low
return ("orange");
}
else if (i >= greenlow && i <= greenhigh)
{
//green
return ("green");
}
else if (i > greenhigh && i < redhigh)
{
//amber high
return ("orange");
}
else if (i > redhigh)
{
// Redhigh
return ("red");
}
else
{
//sorting error
return ("error in sorting");
}
}
}
}
}
return ("sorting error");
}
public string FindfeMaleRAG(decimal i, int x)
{
String connString = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLServerCon"]);
//for each row, do this
//find the threshld values
String thresholdquery = #"select * from dbo.malethreshold where ID = " + x;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(thresholdquery, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//compare threshold values t posted values from form
string composite = Convert.ToString(reader[1]);
decimal redlow = Convert.ToDecimal(reader[2]);
decimal greenlow = Convert.ToDecimal(reader[3]);
decimal greenhigh = Convert.ToDecimal(reader[4]);
decimal redhigh = Convert.ToDecimal(reader[5]);
if (i < redlow)
{
// Red low
return ("red");
}
else if (i > redlow && i < greenlow)
{
// Amber Low
return ("orange");
}
else if (i >= greenlow && i <= greenhigh)
{
//green
return ("green");
}
else if (i > greenhigh && i < redhigh)
{
//amber high
return ("orange");
}
else if (i > redhigh)
{
// Redhigh
return ("red");
}
else
{
//sorting error
return ("error in sorting");
}
}
}
}
}
return ("sorting error");
}
}
}
FIAECBC model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace SharedComponents
{
public class FIAECBC
{
public string Neutrophils { get; set; }
public string Lymphocytes { get; set; }
public string Monocytes { get; set; }
public string Eosinophils { get; set; }
public string Basophils { get; set; }
public string Platelets { get; set; }
public string Haematocrit { get; set; }
public string Haemoglobin { get; set; }
public string MCV { get; set; }
public string MCH { get; set; }
public string MCHC { get; set; }
public decimal d_Neutrophils { get; set; }
public decimal d_Lymphocytes { get; set; }
public decimal d_Monocytes { get; set; }
public decimal d_Eosinophils { get; set; }
public decimal d_Basophils { get; set; }
public decimal d_Platelets { get; set; }
public decimal d_Haematocrit { get; set; }
public decimal d_Haemoglobin { get; set; }
public decimal d_MCV { get; set; }
public decimal d_MCH { get; set; }
public decimal d_MCHC { get; set; }
public string rag_Neutrophils { get; set; }
public string rag_Lymphocytes { get; set; }
public string rag_Monocytes { get; set; }
public string rag_Eosinophils { get; set; }
public string rag_Basophils { get; set; }
public string rag_Platelets { get; set; }
public string rag_Haematocrit { get; set; }
public string rag_Haemoglobin { get; set; }
public string rag_MCV { get; set; }
public string rag_MCH { get; set; }
public string rag_MCHC { get; set; }
public Gender UserGender { get; set; }
public static IEnumerable<SelectListItem> GetSelectItems()
{
yield return new SelectListItem { Text = "Male", Value = "Male" };
yield return new SelectListItem { Text = "Female", Value = "Female" };
}
public bool Bookkeeping { get; set; }
}
public enum Gender
{
Male,
Female
}
}
I can't connect my XML file and my C# in microsoft visual studio. How do I solve this?
Here you find what need to be in your DA
public class LeegstaandXML
{
public string Index { get; set; }
public string Aard { get; set; }
public string Adres { get; set; }
public static int intElementsCount;
private List<LeegstaandXML> _leegstaand;
public List<LeegstaandXML> Lleegstaand
{
get
{
XmlDocument doc = new XmlDocument();
doc.Load("Lijst_leegstaande_bedrijfspanden.xml");
XmlNodeList elementlist = doc.GetElementsByTagName("fme:Lijst_leegstaande_bedrijfspanden");
intElementsCount = elementlist.Count;
_leegstaand = new List<LeegstaandXML>();
_leegstaand.Add(new LeegstaandXML()
{
Index = elementlist[Form1.counter]["fme:Dossier_ID"].InnerXml,
Adres = elementlist[Form1.counter]["fme:Adres"].InnerXml,
Aard = elementlist[Form1.counter]["fme:Aard_van_het_gebouw"].InnerXml,
});
return _leegstaand;
}
set
{
_leegstaand = value;
}
}
}
This is your connection in your form
private void btnVullen_Click(object sender, EventArgs e)
{
Leegstaand p = new Leegstaand();
do
{
counter++;
LeegstaandXML leegstaand2 = new LeegstaandXML();
foreach(LeegstaandXML lp in leegstaand2.Lleegstaand)
{
leegstaandDA NewItem = new leegstaandDA(lp.Index, lp.Adres, lp.Aard);
NewItem.AddItem();
//ListViewItem item = new ListViewItem(new string[] { lp.id.ToString(), lp.aard, lp.adres, lp.index.ToString() });
// item.Tag = lp;
//lsvLeegstaand.Items.Add(item);
}
} while (counter < LeegstaandXML.intElementsCount -1);
MessageBox.Show("implementatie is geslaagd");
counter = 0;
leegstaandDA.Getleegstaand();
foreach (Leegstaand l in leegstaandDA.Getleegstaand())
{
ListViewItem item = new ListViewItem(new string[] { l.index.ToString(), l.adres, l.aard});
item.Tag = l;
lsvLeegstaand.Items.Add(item);
}
}
Currently I create that ActiveDirectory user is store to file and it's working perfect. What I want for now is that I need to comapre data from ActiveDirectory and data from database and if status is 0 change it and store to database result. It means if account is active = 1 is not active = 0.
So far I create this
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.IO;
namespace ActiverDirectory
{
public class Korisnik
{
public int Id { get; set; }
public string Username { get; set; } //samaccountname
public string DisplayName { get; set; } //displayname
public bool isEnabled { get; set; } //AccountExpires
public bool PassNevExp { get; set; } //PassExpires
}
class Program
{
static void Main(string[] args)
{
foreach (Korisnik korisnik in VratiKorisnike())
{
Console.WriteLine(korisnik);
}
}
public static List<Korisnik> VratiKorisnike()
{
List<Korisnik> lstADUsers = new List<Korisnik>();
string sDomainName = "saoos";
string DomainPath = "LDAP://" + sDomainName;
string constring = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
string Query = "SELECT * FROM tblZaposleni_AD";
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(Query, constring);
adapter.Fill(table);
string txt = "";
string fileLoc = #"C:\output.txt";
foreach (DataRow row in table.Rows)
{
string line = "";
foreach (DataColumn column in table.Columns)
{
line += "," + row[column.ColumnName].ToString();
}
txt += line.Substring(1);
}
using (var sw = new StreamWriter(fileLoc))
{
sw.WriteLine(txt);
}
Console.WriteLine("Ok");
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname"); // Username
search.PropertiesToLoad.Add("displayname"); // display name
search.PropertiesToLoad.Add("userAccountControl"); // isEnabled
search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("samaccountname");
resultsTable.Columns.Add("displayname");
resultsTable.Columns.Add("Neaktivan");
resultsTable.Columns.Add("dontexpirepassword");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString = string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname")
&& result.Properties.Contains("displayname"))
{
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
int isEnable;
int Dont_Expire_Password;
if (userAccountControl > 0)
{
isEnable = 0;
}
else
{
isEnable = 1;
}
if ((userAccountControl & 65536) != 0)
{
Dont_Expire_Password = 1;
}
else
{
Dont_Expire_Password = 0;
}
Korisnik korisnik = new Korisnik();
korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
korisnik.DisplayName = result.Properties["displayname"][0].ToString();
korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);
//long value = (long)result.Properties["pwdLastSet"][0];
//DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);
DataRow dr = resultsTable.NewRow();
dr["samaccountname"] = korisnik.Username.ToString();
dr["displayname"] = korisnik.DisplayName.ToString();
dr["neaktivan"] = Math.Abs(isEnable);
dr["dontexpirepassword"] = Dont_Expire_Password;
resultsTable.Rows.Add(dr);
lstADUsers.Add(korisnik);
}
}
var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
var res = json;
Console.WriteLine("Ispis uspjesno obavljen");
Console.ReadLine();
File.WriteAllText(fileLoc, json);
}
return lstADUsers;
}
}
}
So far everything is here, I just need to store this to [db].[table]
This is some peace of code which check from ActiveDirectory if UserAccount is active or disable
If account is active in ActiveDirectory and in [db].[table] is inactive change status to 1 and store data. When I run this I get properly output, but status is not changed.
Any ideas
Try something like this :
public class Korisnik
{
public int Id { get; set; }
public string Username { get; set; } //samaccountname
public string DisplayName { get; set; } //displayname
private bool _isEnabled { get; set; } //AccountExpires
public int isEnabled {
get { return (_isEnabled == true)? 1 : 0;}
set { _isEnabled = (value == 0) ? false : true; }
} //AccountExpires
public bool PassNevExp { get; set; } //PassExpires
}
I have DataGrid which must have childGrid in RowDetails but i dont know how to create columns for child grid.
At the moment i have child grid with Autogenerated columns that i dont need:
private static bool CopyWork(TextBox textBox)
{
try
{
var match = Regex.Match(textBox.Text, #"^коп раб");
if (match.Success)
{
var copyWorkWindow = new Window()
{
Topmost = true,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
Title = "Копирование документов",
SizeToContent = SizeToContent.WidthAndHeight
};
var documents = new ObservableCollection<CopyWorkDocument>();
var dataGrid = new DataGrid()
{
ItemsSource = documents,
AutoGenerateColumns = false
};
var generateColumn = new Func<string, string, object[], FrameworkElementFactory>((header, bindingItem, items) =>
{
var column = new FrameworkElementFactory(typeof(DataGridTemplateColumn));
column.SetValue(DataGridTemplateColumn.HeaderProperty, header);
var binding1 = new Binding(bindingItem)
{
Mode = BindingMode.TwoWay
};
var elementTextBlock = new FrameworkElementFactory(typeof(TextBlock));
elementTextBlock.SetValue(TextBlock.TextProperty, binding1);
var cellTemplate = new DataTemplate
{
VisualTree = elementTextBlock
};
column.SetValue(DataGridTemplateColumn.CellTemplateProperty, cellTemplate);
if (items != null)
{
var elementComboBox = new FrameworkElementFactory(typeof(ComboBox));
elementComboBox.SetValue(ComboBox.BackgroundProperty, Brushes.White);
elementComboBox.SetValue(ComboBox.ItemsSourceProperty, items);
elementComboBox.SetValue(ComboBox.SelectedItemProperty, binding1);
var cellEditingTemplate = new DataTemplate
{
VisualTree = elementComboBox
};
column.SetValue(DataGridTemplateColumn.CellEditingTemplateProperty, cellEditingTemplate);
}
return column;
});
dataGrid.Columns.Add(new DataGridTextColumn() { Header = "Название документа", Binding = new Binding("Name") });
dataGrid.Columns.Add(new DataGridTextColumn() { Header = "Количество копий", Binding = new Binding("Documentcount") });
var rowDetailsTemplate = new DataTemplate();
var pagesGrid = new FrameworkElementFactory(typeof(DataGrid));
//pagesGrid.SetValue(DataGrid.AutoGenerateColumnsProperty, false);
pagesGrid.SetValue(DataGrid.ItemsSourceProperty, new Binding("Pages"));
rowDetailsTemplate.VisualTree = pagesGrid;
dataGrid.RowDetailsTemplate = rowDetailsTemplate;
copyWorkWindow.Content = dataGrid;
copyWorkWindow.ShowDialog();
var sB = new StringBuilder();
foreach (var document in documents)
{
sB.Append(document).Append(Environment.NewLine);
}
if (sB.Length > 0)
{
textBox.Text = sB.ToString();
}
}
return match.Success;
}
catch (Exception ex)
{
ex.LogAndShow();
return false;
}
}
There is columnGenerator below.
Object class:
private class CopyWorkDocument
{
public string Name { get; set; }
public int Documentcount { get; set; } = 1;
public List<CopyPage> Pages { get; set; } = new List<CopyPage> { new CopyPage() };
public override string ToString()
{
var sB = new StringBuilder().Append(Name);
foreach (var page in Pages)
{
sB.Append(Environment.NewLine).Append(Documentcount).Append("шт (").Append(page).Append(")");
}
return sB.ToString();
}
public class CopyPage
{
public int Pagecount { get; set; } = 1;
public string Pageformat { get; set; } = "A4";
public string Worktype { get; set; } = "печать";
public string Printtype { get; set; } = "односторонняя";
public bool IsColored { get; set; } = false;
public static string[] Worktypes { get => new string[] { "печать", "копирование", "сканирование", "брошюровка", "твердый переплет" }; }
public static string[] Printtypes { get => new string[] { "односторонняя", "двусторонняя" }; }
public static string[] Formats { get => new string[] { "A4", "A3", "A2", "A1" }; }
public override string ToString()
{
var sB = new StringBuilder().Append(Pagecount).Append(" ").Append(Pageformat);
if (IsColored)
{
sB.Append(" цвет");
}
return sB.ToString();
}
}
}
Example for colum generator:
DataGrid.Columns.Add(generateColumn("ColumnName", "ColumnBinding", "ColumnItemsHelper"[]));
First i did this generator for DataGrid (Conrol), but then i rework it for FrameworkElementFactory (This useless details added because of StackOverflow codelimitation post)
As stated on MSDN, using the FrameworkElementFactory class is a deprecated way to programmatically create templates: https://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory(v=vs.110).aspx.
You could use the System.Windows.Markup.XamlReader.Parse method instead:
StringBuilder sb = new StringBuilder();
sb.Append("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x =\"http://schemas.microsoft.com/winfx/2006/xaml\">");
sb.Append("<DataGrid ItemsSource=\"{Binding Pages}\" AutoGenerateColumns=\"False\">");
sb.Append("<DataGrid.Columns>");
//append for each column:
sb.Append("<DataGridTextColumn Binding=\"{Binding Name}\" Header=\"Name\" />");
sb.Append("</DataGrid.Columns>");
sb.Append("</DataGrid>");
sb.Append("</DataTemplate>");
dataGrid.RowDetailsTemplate = XamlReader.Parse(sb.ToString()) as DataTemplate;