parameterless constructor issue with entity framework - entity-framework-5

I have the following code that is causing the parameterless constructor error with entity framework. I've figured out that it's being caused by the if (search.Active) block and the dates inside there... but I'm not sure how to get around it. How can I construct my dates so that EF will work with them? Thanks.
var members = from m in Members select m;
if (!string.IsNullOrEmpty(search.Letter))
members = members.Where(x => x.LastName.Substring(0, 1) == search.Letter.Substring(0, 1));
if (search.Active)
{
if (DateTime.Now < new DateTime(DateTime.Now.Year, 10, 15))
{
members = members.Where(x => x.ExpireDate >= new DateTime(DateTime.Now.Year, 5, 31));
}
else
{
members = members.Where(x => x.ExpireDate >= new DateTime(DateTime.Now.Year + 1, 5, 31));
}
}
return members.Select(x => new MemberListItem
{
FirstName = x.FirstName,
LastName = x.LastName,
MemberId = x.MemberId,
ExpirationDate = x.ExpireDate
}).ToList();

It's possible that this will solve the problem because EF might have problems to construct the DateTime inside of a LINQ-to-Entities query:
if (search.Active)
{
if (DateTime.Now < new DateTime(DateTime.Now.Year, 10, 15))
{
DateTime date = new DateTime(DateTime.Now.Year, 5, 31);
members = members.Where(x => x.ExpireDate >= date);
}
else
{
DateTime date = new DateTime(DateTime.Now.Year + 1, 5, 31);
members = members.Where(x => x.ExpireDate >= date);
}
}

Related

Repeating {} in node

I have a "main" function that reads data from input data and generates an output dtoOut of a kind of Employee ID with a random name, surname, etc.
Example of input data
const dtoIn = {
count: 50,
age: {
min: 19,
max: 35
}
}
Example of output data
const dtoOut = [
{
gender: "male",
birthdate: "1993-08-07T00:00:00.000Z",
name: "Vratislav",
surname: "Sýkora",
workload: 40
}
with this code:
// main function
function main(input_data) {
// how many employees work at the firm
let dtoIn_counter = input_data.count
// minimal age of employees
let dtoIn_min = input_data.age.min
// maximal age of employees
let dtoIn_max = input_data.age.max
//output data
const dtoOut = {}
// for loop that counts the number of employees and repeats the process for each one
for (let i = 0; i < dtoIn_counter; i++) {
// randomly decides if the employee will be male or female and assigns first and last name
const male_female = getRandomArbitrary(1, 3)
if (male_female === 1){
dtoOut.name += male_name1[getRandomArbitrary(0, male_name1.length)]
dtoOut.surname += male_name2[getRandomArbitrary(0, male_name2.length)]
dtoOut.gender += "male"
dtoOut.workload += workload[getRandomArbitrary(0, workload.length)]
}
else {
dtoOut.name += female_name1[getRandomArbitrary(0, female_name1.length)]
dtoOut.surname += female_name2[getRandomArbitrary(0, female_name2.length)]
dtoOut.gender += "female"
dtoOut.workload += workload[getRandomArbitrary(0, workload.length)]
}
}
return dtoOut
}
I am struggling with how to put more of these "dictionaries" in the const without overwriting the already-made dictionary. So from my understanding is that what this code does so far is overwrite the output code 50 times and I would like to fix it but not really sure how.
Also if anybody knew how to randomly assign a birthrate from min, max age object and put it into the ISO Date-Time format - YYYY-MM-DDTHH:MM:SSZ that would be awesome.
Hopefully this question wont be too broad and I was clear in what I need help with. Thanks!
Are you looking to get back something like:
const result = main(input_data)
// Where result is:
[
{
gender: "male",
birthdate: "1993-08-07T00:00:00.000Z",
name: "Vratislav",
surname: "Sýkora",
workload: 40
},
... // <-- a bunch more objects
]
Maybe something like this?
const inputData = {
count: 50,
age: {
min: 18,
max: 50
}
}
function main(input_data) {
let dtoIn_counter = input_data.count
let dtoIn_min = input_data.age.min
let dtoIn_max = input_data.age.max
//output data
// turn this into an array to collect the entries in your for loop
const dtoOut = [] // <-- change to array
for (let i = 0; i < dtoIn_counter; i++) {
// we'll create a new object each time to get the employee data
let employee = {} // <-- use to track employee
// you'll have to reuse your existing logic but the idea is here
employee.name = `some name - ${i}`
employee.surname = `some surname - ${i}`
employee.gender = "male"
employee.workload = `a workload - ${i}`
// add this employee to the dtoOut array
dtoOut.push(employee) // <-- add employee to array
}
return dtoOut // finally, return the entire collection
}
const result = main(inputData)
console.log(result)
If you wanna set random names with no repeat and without changing the original random data arrays, you can store their indexes in arrays and remove the index of the random item that has been selected from that array each time.
const dtoOut = [{
gender: "male",
birthdate: "1993-08-07T00:00:00.000Z",
name: "Vratislav",
surname: "Sýkora",
workload: 40
}]
const input_data = {
count: 4,
age: {
min: 19,
max: 35
}
}
const randWorkloads = [40, 56, 12, 14]
const male_name1 = ["David", "Json", "Coby", "Tyler"]
const male_name2 = ["Davidson", "johnson", "Briant", "Smith"]
const female_name1 = ["Mary", "Rose", "Lilly", "Monica"]
const female_name2 = ["Williams", "Doe", "Joseph", "Hart"]
let workloadIndexes = [...Array(male_name1.length).keys()]
let maleNameIndexes = [...Array(male_name1.length).keys()];
let maleSurNameIndexes = [...Array(male_name2.length).keys()];
let femaleNameIndexes = [...Array(female_name1.length).keys()];
let femaleSurNameIndexes = [...Array(female_name2.length).keys()];
function getRandomArbitrary(min, max) {
return parseInt(Math.floor(Math.random() * (max - min) + min));
}
function main(input_data) {
// how many employees work at the firm
let dtoIn_counter = input_data.count
// minimal age of employees
let dtoIn_min = input_data.age.min
// maximal age of employees
let dtoIn_max = input_data.age.max
//output data
const arr = [...Array(dtoIn_counter).keys()]
const result = arr.reduce((acc, item) => {
const gender = getRandomArbitrary(1, 3) === 1 ? "male" : "female";
let name;
let surname;
let workloadIndex = Math.floor(Math.random() * (workloadIndexes.length - 1));
let index = workloadIndexes[workloadIndex];
const workload = randWorkloads[index];
workloadIndexes.splice(workloadIndex, 1);
const age = parseInt(getRandomArbitrary(dtoIn_min, dtoIn_max + 1))
if (gender === "female") {
let nameIndex = Math.floor(Math.random() * (femaleNameIndexes.length - 1));
let index1 = femaleNameIndexes[nameIndex];
name = female_name1[index1];
femaleNameIndexes.splice(nameIndex, 1);
let surnameIndex = Math.floor(Math.random() * (femaleSurNameIndexes.length - 1));
let index2 = femaleSurNameIndexes[surnameIndex];
surname = female_name2[index2];
femaleSurNameIndexes.splice(surnameIndex, 1);
} else {
let nameIndex = Math.floor(Math.random() * (maleNameIndexes.length - 1));
let index1 = maleNameIndexes[nameIndex];
name = male_name1[index1];
maleNameIndexes.splice(nameIndex, 1);
let surnameIndex = Math.floor(Math.random() * (maleSurNameIndexes.length - 1));
let index2 = maleSurNameIndexes[surnameIndex];
surname = male_name2[index2];
maleSurNameIndexes.splice(surnameIndex, 1);
}
const newEmployee = {
name,
surname,
gender,
workload,
age
}
return [...acc, newEmployee]
}, [])
return result
}
console.log(main(input_data))

REVIT Transfer floor sketch to Void Extrusion in Family

Struggling with some Revit code to copy the profile of a floor and use it as the sketch profile for a void extrusion in a family.
Here is the Full Sharp Development Code. It half works in my custom project template, when I try to use it in an out of the box project generated from revit default template it gives the error "a managed exception was thrown by revit or by one of its external applications"
In my template it cannot properly split the curves into a secondary array. It says the array elements are being changed but when the loop runs again the element i is back to it's original content??? The TaskDialog clearly says the elements have changed, until the loop iterates again.
Full code: To work it requires a generic family with the name "Void - Custom" to be in the project. The "If found" near the bottom last page and a half of code, is where the for loop is not behaving as expected.
/*
* Created by SharpDevelop.
* User: arautio
* Date: 4/30/2019
* Time: 11:10 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace ARC
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("3411F411-6FC1-4A4D-9CFD-37ABB2028A15")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{
}
private void Module_Shutdown(object sender, EventArgs e)
{
}
#region Revit Macros generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}
#endregion
public void FloorGrating()
{
StringBuilder sb = new StringBuilder();
Dictionary<Floor, List<ModelCurve>> dict_SketchLines = new Dictionary<Floor, List<ModelCurve>>();
UIDocument uidoc = this.ActiveUIDocument;
Document document = uidoc.Document;
View activev = document.ActiveView;
ElementId levelId = null;
levelId = activev.LevelId;
Element levelem = document.GetElement( levelId );
Level lev = document.ActiveView.GenLevel;
Reference refsel = uidoc.Selection.PickObject(ObjectType.Element, "Select Floor to Add Grating To");
Element elem = document.GetElement(refsel.ElementId);
Floor f = elem as Floor;
List<ElementId> _deleted = null;
using (Transaction t = new Transaction(document, "temp"))
{
t.Start();
document.Regenerate();
_deleted = document.Delete(elem.Id).ToList();
t.RollBack();
}
bool SketchLinesFound = false;
List<ModelCurve> _sketchCurves = new List<ModelCurve>();
foreach (var id in _deleted)
{
ModelCurve mc = document.GetElement(id) as ModelCurve;
if (mc != null)
{
_sketchCurves.Add(mc);
SketchLinesFound = true;
}
else
{
if (SketchLinesFound) break;
}
}
dict_SketchLines.Add(f, _sketchCurves);
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
sb.AppendLine(string.Format("floor {0} has sketchlines:", key.Id));
foreach (ModelCurve mc in _curves)
{
sb.AppendLine(string.Format("{0} <{1}>", mc.GetType(), mc.Id));
sb.AppendLine(string.Format("<{0}>", mc.GeometryCurve.IsBound.ToString()));
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
TaskDialog.Show("Revit", "Circle Found");
}
try
{
sb.AppendLine(string.Format("<{0} -- {1}>", mc.GeometryCurve.GetEndPoint(0), mc.GeometryCurve.GetEndPoint(1)));
}
catch
{
}
}
sb.AppendLine();
}
//TaskDialog.Show("debug", sb.ToString());
Document docfamily;
Family fam;
string ftitle = document.Title;
string fpath = document.PathName;
int ftitlelen = ftitle.Length + 4;
int fpathlen = fpath.Length;
int finpathlen = fpathlen - ftitlelen;
string sfinpath = fpath.Substring(0,finpathlen);
string famname = "GratingVoid";
string fext = ".rfa";
int counter = 1;
while (counter < 100)
{
famname = ("GratingVoid" + counter as String);
Family family = FindElementByName(document,typeof(Family),famname)as Family;
if( null == family )
{
sfinpath = (sfinpath + famname + fext);
counter = 1000;
}
counter += 1;
}
FilteredElementCollector collector0 = new FilteredElementCollector(document);
ICollection<Element> collection0 = collector0.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym0 = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb0 = null;
foreach (FamilySymbol symb in fsym0)
{
if (symb.Name == "Void - Custom")
{
famsymb0 = symb as FamilySymbol;
}
}
fam = famsymb0.Family;
docfamily = document.EditFamily(fam);
try
{
docfamily.SaveAs(#sfinpath);
}
catch
{
TaskDialog.Show("Revit", "Could Not Save Void Family");
}
using (Transaction trans = new Transaction(docfamily))
{
trans.Start("family");
bool circleflag = false;
ElementId delid = null;
FilteredElementCollector collector = new FilteredElementCollector( docfamily );
foreach(Element element in collector.OfClass(typeof(GenericForm)))
{
delid = element.Id;
}
docfamily.Delete(delid);
CurveArray loccurva = new CurveArray();
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
foreach (ModelCurve mc in _curves)
{
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
circleflag = true;
}
LocationCurve lcurve = mc.Location as LocationCurve;
Curve c = lcurve.Curve as Curve;
loccurva.Append(c);
}
}
try
{
if (circleflag == true && loccurva.Size == 2)
{
Curve tempc;
if (loccurva.get_Item(0).GetType().ToString() == "Autodesk.Revit.DB.Arc")
{
tempc = loccurva.get_Item(0);
}
else
{
tempc = loccurva.get_Item(1);
}
loccurva.Clear();
loccurva.Append(tempc);
}
CurveArrArray newcurarr = new CurveArrArray();
newcurarr.Append(loccurva);
SortCurvesContiguousArray(newcurarr);
TaskDialog.Show("Revit CurveArray Array Size" , newcurarr.Size.ToString());
foreach (CurveArray ca in newcurarr)
{
TaskDialog.Show("Revit CurveArray within Array Size" , ca.Size.ToString());
}
// Below is edited for error control - leaving out the secondary loops for now
CurveArrArray switcharr = new CurveArrArray();
//switcharr.Append(newcurarr.get_Item(1));
switcharr.Append(newcurarr.get_Item(0));
//SortCurvesContiguousArray(loccurva);
//CurveArrArray newcurarr = new CurveArrArray();
//newcurarr.Append(loccurva);
double end = 1;
SketchPlane sketch = FindElementByName( docfamily,typeof( SketchPlane ), "Ref. Level" ) as SketchPlane;
docfamily.FamilyCreate.NewExtrusion(false, switcharr, sketch, end);
}
catch
{
TaskDialog.Show("Revit", "Could Not Write to Curve Array or Create Extrusion");
}
trans.Commit();
}
docfamily.Save();
docfamily.LoadFamily(document, new CustomFamilyLoadOption());
docfamily.Close();
File.Delete(sfinpath);
Family familynew = FindElementByName(document,typeof(Family),famname)as Family;
if( null == familynew )
{
TaskDialog.Show("Revit", "Family Does Not Exist");
}
FilteredElementCollector collector1 = new FilteredElementCollector(document);
ICollection<Element> collection = collector1.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb = null;
foreach (FamilySymbol symb in fsym)
{
if (symb.Name == famname)
{
famsymb = symb as FamilySymbol;
}
}
using (Transaction trans = new Transaction(document))
{
trans.Start("PlaceVoid");
if( ! famsymb.IsActive )
{
famsymb.Activate();
}
XYZ p = new XYZ(0,0,0);
FamilyInstance gratingvoid = document.Create.NewFamilyInstance( p, famsymb, lev, lev, StructuralType.NonStructural );
document.Regenerate();
trans.Commit();
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
static public Element FindElementByName(Document doc,Type targetType,string targetName)
{
return new FilteredElementCollector( doc ).OfClass( targetType ).FirstOrDefault<Element>(e => e.Name.Equals( targetName ) );
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public class CustomFamilyLoadOption : IFamilyLoadOptions
{
public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
{
overwriteParameterValues = true;
return true;
}
public bool OnSharedFamilyFound(Family sharedFamily,bool familyInUse,out FamilySource source, out bool overwriteParameterValues)
{
source = FamilySource.Family;
overwriteParameterValues = true;
return true;
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
const double _inch = 1.0 / 12.0;
const double _sixteenth = _inch / 16.0;
static Curve CreateReversedCurve(Curve orig )
{
//if( !IsSupported( orig ) )
//{
// throw new NotImplementedException("CreateReversedCurve for type " + orig.GetType().Name );
//}
if( orig is Line )
{
//return creapp.NewLineBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
return Line.CreateBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
}
else if( orig is Arc )
{
// return creapp.NewArc( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
return Arc.Create( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
}
else
{
throw new Exception(
"CreateReversedCurve - Unreachable" );
}
}
public static void SortCurvesContiguousArray(CurveArrArray curvesarr)
{
double _precision1 = 1.0 / 12.0 / 16.0; // around 0.00520833
double _precision2 = 0.001; // limit for CurveLoop.Create(...)
int cn = curvesarr.Size;
int ci = 0;
while (ci < cn)
{
CurveArray curves = curvesarr.get_Item(ci);
ci +=1;
// account for multiple curve loops with secondary array
CurveArray loop1 = new CurveArray();
CurveArray loop2 = new CurveArray();
int n = curves.Size;
int split = 1;
// Walk through each curve (after the first)
// to match up the curves in order
for (int i = 0; i < n; ++i)
{
TaskDialog.Show("Revit I Loop Run", i.ToString());
Curve curve = curves.get_Item(i);
if (curve.GetType().ToString() == "Autodesk.Revit.DB.Arc" && curve.IsBound == false)
{
break;
}
XYZ beginPoint = curve.GetEndPoint(0);
XYZ endPoint = curve.GetEndPoint(1);
XYZ p,q;
// Find curve with start point = end point
bool found = (i + 1 >= n);
for (int j = i + 1; j < n; ++j)
{
p = curves.get_Item(j).GetEndPoint(0);
q = curves.get_Item(j).GetEndPoint(1);
// If there is a match end->start,
// this is the next curve
if (p.DistanceTo(endPoint) < _precision1)
{
if (p.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + p.X) / 2.0, (endPoint.Y + p.Y) / 2.0, (endPoint.Z + p.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(intermediate, q));
}
if (i + 1 != j)
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, curves.get_Item(j));
curves.set_Item(j, tmp);
}
found = true;
break;
}
// If there is a match end->end,
// reverse the next curve
if (q.DistanceTo(endPoint) < _precision1)
{
if (q.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + q.X) / 2.0, (endPoint.Y + q.Y) / 2.0, (endPoint.Z + q.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(p, intermediate));
}
if (i + 1 == j)
{
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
}
else
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
curves.set_Item(j, tmp);
}
found = true;
break;
}
}
if (!found)
{
// if not found, must be part of a new loop - move it to the back and keep going and add to second array
TaskDialog.Show("Revit No Match Found for item", i.ToString());
TaskDialog.Show("Revit", "Moveing it to back of list");
Curve tmp1 = curves.get_Item(i);
TaskDialog.Show("Revit tmp1 Current i item endpt", tmp1.GetEndPoint(0).ToString());
loop2.Append(tmp1);
Curve tmp2 = curves.get_Item(n - split);
TaskDialog.Show("Revit tmp2 Back of list item endpt", tmp2.GetEndPoint(0).ToString());
// set current item to rear
curves.set_Item(i, tmp2);
// set rear item to current
curves.set_Item(n - split, tmp1);
TaskDialog.Show("Revit new item i endpt", curves.get_Item(i).GetEndPoint(0).ToString());
TaskDialog.Show("Revit moved item endpt", curves.get_Item(n - split).GetEndPoint(0).ToString());
// error testing - try to append in a different manner and check values
//curves.set_Item(i, Line.CreateBound(curves.get_Item(i).GetEndPoint(0), curves.get_Item(i).GetEndPoint(1)));
//curves.set_Item(n - split, Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1)));
//Curve ncurve = Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1));
//TaskDialog.Show("Revit Appended to Loop2 Endpoint", ncurve.GetEndPoint(0).ToString());
//loop2.Append(ncurve);
//set the split off counter so items not fitting in first loop can be split to new array.
split += 1;
//reset the counter back so item moved from rear can be checked in next run of for loop
i -= 2;
}
//set counter to end for loop when all items that do not fit in first loop are processed
if (i >= n - (split + 1))
{
TaskDialog.Show("Revit", "End Of Looping");
TaskDialog.Show("Revit - The Split Number", split.ToString());
i = n;
}
}
int counter = 0;
// recreate array with only items from first loop found
while (counter <= (n - split))
{
loop1.Append(curves.get_Item(counter));
counter += 1;
}
TaskDialog.Show("Revit loop1 Size", loop1.Size.ToString());
curvesarr.Clear();
curvesarr.Append(loop1);
if (loop2.Size > 0)
{
string stringinfo = "";
// run the loop detection on a second array that was split from the first
TaskDialog.Show("Revit loop2 Size", loop2.Size.ToString());
CurveArrArray tmpcurvesarr = new CurveArrArray();
tmpcurvesarr.Append(loop2);
SortCurvesContiguousArray(tmpcurvesarr);
loop2.Clear();
loop2 = tmpcurvesarr.get_Item(0);
curvesarr.Append(loop2);
foreach (Curve ccc in loop2)
{
stringinfo = (stringinfo + " " + ccc.GetEndPoint(0).ToString() + " - " + ccc.GetEndPoint(1).ToString());
}
TaskDialog.Show("Revit", stringinfo);
}
}
}
}
}
Thanks for any and all help.
Shane

How to read values from dictionary value collection and make it comma seperated string?

I have a dictionary object as under
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>();
dictStr.Add("Culture", new List<string>() { "en-US", "fr-FR" });
dictStr.Add("Affiliate", new List<string>() { "0", "1" });
dictStr.Add("EmailAddress", new List<string>() { "sreetest#test.com", "somemail#test.com" });
And I have an entity as under
public class NewContextElements
{
public string Value { get; set; }
}
What I need to do is that for every value in a particular index of the dictionary value collection, I have to make a comma separated string and place it into List collection.
e.g. the NewContextElements collection will have (obviously at run time)
var res = new List<NewContextElements>();
res.Add(new NewContextElements { Value = "en-US" + "," + "0" + "," + "sreetest#test.com" });
res.Add(new NewContextElements { Value = "fr-FR" + "," + "1" + "," + "somemail#test.com" });
I was trying as
var len = dictStr.Values.Count;
for (int i = 0; i < len; i++)
{
var x =dictStr.Values[i];
}
no it is of-course not correct.
Help needed
Try this:
Enumerable.Range(0, len).Select( i =>
new NewContextElements {
Value = string.Join(",", dictStr.Values.Select(list => list[i]))
}
);
len is the number of items inside the individual lists (in your example, it's two).
This isn't a slick as #dasblinkenlight's solution, but it should work:
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>( );
dictStr.Add( "Culture", new List<string>( ) {"en-US", "fr-FR"} );
dictStr.Add( "Affiliate", new List<string>( ) {"0", "1"} );
dictStr.Add( "EmailAddress", new List<string>( ) {"sreetest#test.com", "somemail#test.com"} );
int maxValues = dictStr.Values.Select(l => l.Count).Max();
List<NewContextElements> resultValues = new List<NewContextElements>(dictStr.Keys.Count);
for (int i = 0; i < maxValues; i++) {
StringBuilder sb = new StringBuilder();
string spacer = string.Empty;
dictStr.Keys.ForEach( k => {
sb.AppendFormat( "{0}{1}", spacer, dictStr[k][i] );
spacer = ", ";
} );
resultValues.Add( new NewContextElements( ){ Value = sb.ToString() });
}
do you mean transform your data like
1 2
3 4
5 6
to
1 3 5
2 4 6
try this block of code? it can be optimized in a few ways.
var res = new List<NewContextElements>();
int i = dictStr.values.count()
for (int i=0; i < len; i++) {
NewContextElements newContextElements = new NewContextElements();
foreach (List<string> list in dictStr) {
if (newContextElements.value() == null ) {
newContextElements.value = list[i];
} else {
newContextElements.value += ", " + list[i] );
}
}
res.add(newContextElements);
}
let me know if there are problems in the code, most like there is when you write it without a real ide.

Share point 2010 ItemAdding insert Recurrence data on calendar

i am trying to add some Recurrence data on a calendar by using ItemAdding events. My code is as follows :
public override void ItemAdding(SPItemEventProperties properties)
{
string evtTitle = Console.ReadLine();
SPListCollection listCollectioon = properties.List.ParentWeb.Lists;
SPList list = listCollectioon.TryGetList("Calendar");
SPListItemCollection listItems = list.Items;
SPListItem recEvent = listItems.Add();
string recData = "<recurrence><rule>" +
"<firstDayOfWeek>su</firstDayOfWeek>" +
"<repeat><daily dayFrequency='1' /></repeat>" +
"<repeatInstances>1</repeatInstances></rule></recurrence>";
recEvent["Title"] = evtTitle;
recEvent["RecurrenceData"] = recData;
recEvent["EventType"] = 1;
recEvent["EventDate"] = new DateTime(2012, 3, 1, 8, 0, 0);
recEvent["EndDate"] = new DateTime(2012, 3, 12, 9, 0, 0);
recEvent["UID"] = System.Guid.NewGuid();
recEvent["TimeZone"] = 13;
recEvent["Recurrence"] = -1;
recEvent["XMLTZone"] = "<timeZoneRule>" +
"<standardBias>480</standardBias>" +
"<additionalDaylightBias>-60</additionalDaylightBias>" +
"<standardDate><transitionRule month='10' day='su' weekdayOfMonth='last' />" +
"<transitionTime>2:0:0</transitionTime></standardDate>" +
"<daylightDate><transitionRule month='4' day='su' weekdayOfMonth='first' />" +
"<transitionTime>2:0:0</transitionTime>" +
"</daylightDate></timeZoneRule>";
recEvent.Update();
listItems.Add();
base.ItemAdding(properties);
}
But problem is that it is creating 10 separate events on a same date. I am unable to get the reason of this and how i resolve this issue?
This works for me.
SPList calendar = web.Lists["Calendar"];
SPListItem recEvent = calendar.Items.Add();
//string recData = "<recurrence><rule>" +
// "<firstDayOfWeek>su</firstDayOfWeek>" +
// "<repeat><daily dayFrequency=\"1\" /></repeat>" +
// "<repeatInstances>1</repeatInstances></rule></recurrence>";
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><windowEnd>2012-02-26T01:00:00Z</windowEnd></rule></recurrence>";
recEvent["Title"] = "Test 1";
recEvent["RecurrenceData"] = recData;
recEvent["EventType"] = 1;
recEvent["Start Time"] = new DateTime(2012, 2, 21, 10, 0, 0);
recEvent["End Time"] = new DateTime(2012, 2, 25, 11, 0, 0);
recEvent["TimeZone"] = 10;
recEvent["Recurrence"] = true;
recEvent["XMLTZone"] = "<timeZoneRule><standardBias>300</standardBias><additionalDaylightBias>-60</additionalDaylightBias><standardDate><transitionRule month='11' day='su' weekdayOfMonth='first' /><transitionTime>2:0:0</transitionTime></standardDate><daylightDate><transitionRule month='3' day='su' weekdayOfMonth='second' /><transitionTime>2:0:0</transitionTime></daylightDate></timeZoneRule>";
recEvent.Update();
calendar.Update();
"repeatInstance" if you want to limit the recurrence events to certain number or use "windowEnd"

C# - Trying to create a threaded process using a function that has as Action as a parameter

This is a project I'm doing for my own amusement.
I started out wanting to experiment with combination and permutations. In a console application I have the following code
public static void Save(string newWord)
{
using (var db = new MyDataContext())
{
var w = new Word {word = newWord};
db.Words.InsertOnSubmit(w);
db.SubmitChanges();
}
}
static void Main(string[] args)
{
var letters = new[] { 'A', 'B', 'C', '1', '2', '3'};
for (var i = 2; i < 10; i++)
{
letters.GetPermutations(a => Save(string.Join(string.Empty, a.ToArray())), i, true);
}
}
In an extension class, I have the code to generate the combinations. I found the code for the combinations here (http://blog.noldorin.com/2010/05/combinatorics-in-csharp/) for those wanting to review that.
public static void GetCombinations<T>(this IList<T> list, Action<IList<T>> action, int? resultSize = null, bool withRepetition = false)
{
if (list == null)
throw new ArgumentNullException("list");
if (action == null)
throw new ArgumentNullException("action");
if (resultSize.HasValue && resultSize.Value <= 0)
throw new ArgumentException(errorMessageValueLessThanZero, "resultSize");
var result = new T[resultSize.HasValue ? resultSize.Value : list.Count];
var indices = new int[result.Length];
for (int i = 0; i < indices.Length; i++)
indices[i] = withRepetition ? -1 : indices.Length - i - 2;
int curIndex = 0;
while (curIndex != -1)
{
indices[curIndex]++;
if (indices[curIndex] == (curIndex == 0 ? list.Count : indices[curIndex - 1] + (withRepetition ? 1 : 0)))
{
indices[curIndex] = withRepetition ? -1 : indices.Length - curIndex - 2;
curIndex--;
}
else
{
result[curIndex] = list[indices[curIndex]];
if (curIndex < indices.Length - 1)
curIndex++;
else
action(result);
}
}
}
Then I thought it would be cool to calculate the combinations for all charaters in a list, each in its own thread. So in my for/next loop, I tried
Thread t = new Thread(letters.GetPermutations(a => Save(string.Join(string.Empty, a.ToArray())), i, true));
But apparently, the Action that is being passed in, the call to the 'Save' function, is not liked in the Thread. If someone could give me a nudge in the right direction, I'd appreciate it.
Thanks,
Andy
The Thread constructor is looking for a delegate but you're appearing to pass a value instead. Try wrapping it in an ThreadStart delegate.
ThreadStart del = () => letters.GetPermutations(a => Save(string.Join(string.Empty, a.ToArray())), i, true);
Thread t = new Thread(del);
t.Start();

Resources