I have a list of the List of Request Types. With the For cycle, I have data from the vertaban. I want to add the dates into detail.
There is an error in the code I wrote. All data are listed as the same.
public IHttpActionResult TalepListele(TalepList model)
{
List<TalepList> detay = new List<TalepList>();
using (var ctx = new ktdbEntities())
{
var query = ctx.talepListele(model.KullaniciId, 0, 10).ToList();
var adet = query.Count;
if (query.Count != 0)
{
for (var i = 0; i < adet; i++)
{
model.OlusturmaTarihi = query[i].olusturulmaTarihi;
model.TalepDurumAdi = query[i].talepDurumuAdi;
model.TalepDurumId = query[i].talepTuruID;
model.TalepTuruAdi = query[i].talepTuruAdi;
model.TalepTuruId = query[i].talepTuruID;
model.talepID = query[i].talepID;
detay.Add(model);
}
return Ok(detay);
}
}
return Ok();
}
You are adding the same instance of TalepList to detay multiple times.
for (var i = 0; i < adet; i++)
{
TalepList mdl = new TalepList();
mdl.OlusturmaTarihi = query[i].olusturulmaTarihi;
...
detay.Add(mdl);
}
You can try this code and you should learn beetween reference type and value type differents.
public IHttpActionResult TalepListele(TalepList model)
{
List<TalepList> detay = new List<TalepList>();
using (var ctx = new ktdbEntities())
{
var query = ctx.talepListele(model.KullaniciId, 0, 10).ToList();
var adet = query.Count;
for (var i = 0; i < adet; i++)
{
TalepList talep = new TalepList();
talep.OlusturmaTarihi = query[i].olusturulmaTarihi;
talep.TalepDurumAdi = query[i].talepDurumuAdi;
talep.TalepDurumId = query[i].talepTuruID;
talep.TalepTuruAdi = query[i].talepTuruAdi;
talep.TalepTuruId = query[i].talepTuruID;
talep.talepID = query[i].talepID;
detay.Add(talep);
}
return Ok(detay);
}
return Ok();
}
Related
I'm trying to use CsvHelper to parse a CSV file and stream it to SQL Database. CsvDataReader class seems perfect for that, however it doesn't implement any async methods, which is weird to me, considering that underlying CsvReader has async versions of all of its reading methods. Is there a way to use CsvDataReader in an asynchronous way?
I've used this before to bulk import CSV files using Entity Framework. This is using LINQPad so you might need to make a couple of changes.
async Task Main()
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
MemberTypes = CsvHelper.Configuration.MemberTypes.Fields
};
using(var reader = new StreamReader(#"C:\MyBulkFile.csv"))
using(var csv = new CsvReader(reader, config))
{
var records = csv.GetRecords<Foo>();
await BulkInsertChunks(records);
}
}
async Task<int> BulkInsertChunks<T>(IEnumerable<T> entites, int chunkAmount = 10000)
{
var i = 0;
var j = 0;
var uploadRecords = new List<T>();
foreach (var record in entites)
{
if (i < chunkAmount - 1)
{
i++;
j++;
uploadRecords.Add(record);
}
else
{
i = 0;
j++;
uploadRecords.Add(record);
Console.WriteLine($"Uploading {j}");
await BulkInsertAll<T>(uploadRecords);
uploadRecords.Clear();
}
}
$"Uploading {j}".Dump();
await BulkInsertAll<T>(uploadRecords);
return j;
}
async Task BulkInsertAll<T>(List<T> entities)
{
var connstr = Connection.ConnectionString;
var conn = new SqlConnection(Connection.ConnectionString);
conn.Open();
Type t = typeof(T);
var tableAttribute = (TableAttribute)t.GetCustomAttributes(typeof(TableAttribute), false).Single();
var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = tableAttribute.Name };
var properties = t.GetMembers().Where(p =>
{
var columnAttribute = Attribute.GetCustomAttribute(p, typeof(ColumnAttribute)) as ColumnAttribute;
if (columnAttribute != null) return true;
return false;
}).ToArray();
var table = new DataTable();
foreach (var property in properties)
{
Type propertyType = ((FieldInfo)property).FieldType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
table.Columns.Add(new DataColumn(property.Name, propertyType));
}
foreach (var entity in entities)
{
var cols = properties.Select(property =>
{
var field = (FieldInfo)property;
var o = field.GetValue(entity);
if (o == null)
return DBNull.Value;
else
return o;
}).ToArray();
table.Rows.Add(cols);
}
await bulkCopy.WriteToServerAsync(table);
conn.Close();
}
I am reading a data from CSV file and trying to add to object. but when i add new record by looping through records the data in object is getting overridden.
public static void Process()
{
var path= #"ABC.csv";
var header = false;
var lines = System.IO.File.ReadAllLines(filePath);
var element = new List<Content>();
var mapTo = new Content();
for (var i = 0; i < lines.Length; i++)
{
var t = lines[i];
if (!header)
{
header = true;
}
else
{
var data = t.Split(',');
mapTo.Key= data[0];
mapTo.Name= data[1];
mapTo.Number= data[2];
mapTo.Date= data[3];
element.Add(mapTo);
}
}
var result = element;
}
so here when i try to add mapTo to element all the content in element variable is getting overridden.Can anybody suggest what's wrong i am doing here.
Move var mapTo = new Content(); into the for loop. Otherwise you have the same instance of Content for each loop iteration which gets overriden by the assigenments in the for loop.
public static void Process()
{
var path= #"ABC.csv";
var header = false;
var lines = System.IO.File.ReadAllLines(filePath);
var element = new List<Content>();
for (var i = 0; i < lines.Length; i++)
{
var mapTo = new Content(); //here
var t = lines[i];
if (!header)
{
header = true;
}
else
{
var data = t.Split(',');
mapTo.Key= data[0];
mapTo.Name= data[1];
mapTo.Number= data[2];
mapTo.Date= data[3];
element.Add(mapTo);
}
}
var result = element;
}
I'm trying to build realtime chat through Realtime Database Firebase and Xamarin. However there is a problem like this, hope someone can help:
protected async void LoadChat()
{
string userid = "123456789";
var getroom = (await fc.Child("RecordsChat").OnceAsync<GetRoomChats>()).Select(x =>
new GetRoomChats
{
RoomID = x.Key
}).ToList();
List<GetRoomChats> listroomuser = new List<GetRoomChats>();
foreach (var room in getroom)
{
string str = null;
string[] strArr = null;
string roomget = room.RoomID;
str = roomget + "_";
char[] splitchar = { '_' };
strArr = str.Split(splitchar);
var getroomuser = strArr.Distinct().ToList();
foreach (var item in getroomuser)
{
if (item == userid)
{
var roomgetuser = new GetRoomChats()
{
RoomID = roomget
};
listroomuser.Add(roomgetuser);
}
}
}
if (listroomuser.Count() > 0)
{
var FirebaseClient = fc
.Child("RecordsChat")
.AsObservable<GetRoomChats>()
.Subscribe(async(dbevent) =>
{
//IteamGetRoomChats.Clear();
foreach (var room in listroomuser)
{
if (dbevent.Key == room.RoomID)
{
var lst = (await fc.Child("RecordsChat").Child(dbevent.Key).OrderByKey().LimitToLast(1).OnceAsync<MyDatabaseRecord>()).Select(x =>
new MyDatabaseRecord
{
NameUser = x.Object.NameUser,
Content = x.Object.Content,
RoomID = x.Object.RoomID,
DayCreate = x.Object.DayCreate,
AvatarUser = x.Object.AvatarUser,
sender_uid = x.Object.sender_uid,
receiver_uid = x.Object.receiver_uid,
receiver_read = x.Object.receiver_read
});
bool unread = false;
foreach (var i in lst)
{
if(i.sender_uid == userid)
{
i.Content = "You: " + i.Content;
var customerList = await apiServiceUserinfo.GetCustomersInfo(i.receiver_uid);
string nameget = customerList.NameStore;
string avatarget = customerList.AvatarStore;
i.NameUser = nameget;
i.AvatarUser = avatarget;
if (i.sender_read == true)
{
unread = false;
}
}
else
{
if (i.receiver_read == false)
{
i.BackgroundUser = "#f5f4f4";
unread = true;
}
}
var last = new GetRoomChats()
{
NameLast = i.NameUser,
ContentLast = i.Content,
RoomID = i.RoomID,
DayCreateLast = i.DayCreate,
AvatarLast = i.AvatarUser,
BackgroundUnread = i.BackgroundUser,
DotUnread = unread
};
IteamGetRoomChats.Add(last);
}
}
}
});
}
BindingContext = this;
}
In my example above, it actually gets the data. I try to check in the loop, to get the last content of the message. However, the displayed results are duplicated
Looking forward to everyone's help. Thank you!
I need to compare two lists of same type. Assume I have CurrentSC List(Current modified data by user) and PreviousSC List(Saved data from database) of below class.
public class SoftClose
{
private int AID = -1;
private bool _softCloseInd;
private bool _softCloseEditInd;
private string _softClosedBy;
private DateTime _softClosedDate;
private ReferenceEnums.ActionStatus _status = ReferenceEnums.ActionStatus.NO_CHANGE;
}
public static void TPostProcessAddRemoveSoftCloseStopPaymentPrefixes(IFPMServiceInternal fpmService, AgreementRevision revision)
{
List<SoftClose> psc = null;
List<SoftClose> csc = null;
string fanValue = revision.Agreement.FAN;
psc = fpmService.GetSoftCloseByFAN(fanValue);
if (psc != null)
{
//var currentprefixes = revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct();
//Create current SoftClose object using revision object
foreach (var prefix in revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct())
{
var newSF =
new SoftClose
{
Id = -1,
Status = ReferenceEnums.ActionStatus.NO_CHANGE,
AgreementRevId = revision.Id,
AgreementId = revision.Agreement.Id,
WorkflowStatus = revision.WorkflowStatus,
FAN = revision.Agreement.FAN,
PID = (int)revision.Agreement.PID,
Prefix = prefix
};
csc.Add(newSF);
}
//Now you have previous and current softcloses to compare prefixes...
psc.OrderBy(x => x.Prefix.Id);
csc.OrderBy(x => x.Prefix.Id);
for(int i = 0; i < csc.Count; i++)
{
}
}
}
Lets say I have changed D3 value in PreviousSC to D2 in CurrentSC. Now i need to delete D3 value from database(As D2 value already there in database i don't need to insert) and chnage _status to DELETE and I added D4 value in CurrentSC which is not there is PreviousSC. Now I need to add D4 value in database and assign _softCloseInd and _softCloseEditInd to Y and change _status to ADD.
How to achieve this in best way?
class Program
{
static void Main(string[] args)
{
List<SoftClose> psc = new List<SoftClose>(){
new SoftClose(){ID=1, Status = "NO_CHANGE",AID=19, Prefix = "D1"},
new SoftClose(){ID=2, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=21, Prefix = "D3"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=22, Prefix = "D9"}
};
List<SoftClose> csc = new List<SoftClose>(){
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=19, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=21, Prefix = "D6"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=22, Prefix = "D4"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=23, Prefix = "D5"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=24, Prefix = "D3"}
};
List<SoftClose> esc = new List<SoftClose>();
Console.WriteLine("---------Previous List----------");
foreach (var item in psc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
Console.WriteLine("---------Current List----------");
foreach (var item in csc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
var addlist = csc.Where(c => psc.All(p => !p.Prefix.Equals(c.Prefix)));
foreach (var n in addlist)
{
var index = csc.FindIndex(p => p.Prefix.Equals(n.Prefix));
csc[index].Status = "ADD";
esc.Add(csc[index]);
}
var deletelist = psc.Where(p => p.Status.Equals("NO_CHANGE") && !csc.Exists(c => c.Prefix.Equals(p.Prefix)));
foreach (var n in deletelist)
{
var index = psc.FindIndex(c => c.Prefix.Equals(n.Prefix));
if (psc.FindIndex(c => c.Prefix.Equals(n.Prefix)) >= 0)
{
psc[index].Status = "REMOVE";
esc.Add(psc[index]);
}
}
Console.WriteLine("---------Effective List----------");
foreach (var item in esc)
{
Console.WriteLine($"Id:{item.ID}, Prefix:{item.Prefix}, Status:{item.Status}");
}
Console.ReadLine();
}
}
public class SoftClose
{
public int ID = -1;
public int AID = -1;
public int WFID = -1;
public string Prefix;
public DateTime SCDATE;
public string Status;
}
I've a requirement in which I've to display the saved users to the SharePoint people editor control. For this, I am saving the user names to People/Group column. And I am using the following code for taking these users to people editor control:
SetPeopleEditor(item, Constants.FieldNames.IT_DIRECTOR, pe_ITDirector, oWeb);
the definition of the above method is shown below:
private PickerEntity SetPeopleEditor(SPListItem item, string columnName, PeopleEditor peopleEditor, SPWeb web)
{
ArrayList entityArrayList = new ArrayList();
PickerEntity entity = null;
if (item[columnName] != null)
{
char[] to_splitter = { ';' };
string to_list = item[columnName].ToString(); // Reads value stored in SPList. (i.e., "Domain\User1; Domain\User2")
string[] arr = to_list.Split(to_splitter);
string user = string.Empty;
for (int i = 1; i < arr.Length; i++)
{
if ((i % 2) != 0)
{
user = arr[i].Substring(arr[i].IndexOf("#") + 1);
entity = new PickerEntity();
entity.Key = user;
entity.IsResolved = true;
entity = peopleEditor.ValidateEntity(entity);
entityArrayList.Add(entity);
}
}
}
return entity;
}
But unfortunately, the control always showing empty value. How can I achieve this by populating data to the people editor control?
You can do as follows,
SPFieldUserValueCollection userValueCollection =
new SPFieldUserValueCollection(SPContext.Current.Web, SPContext.Current.Item["ColumnName"] as string);
if (userValueCollection .Count > 0)
{
spPeoplePickerContol.CommaSeparatedAccounts = userValueCollection[0].User.LoginName;
}
You have to include peopleEditor.Entities.Add(entity) after validating entity to add the entity to peopleEditor control.
private void SetPeopleEditor(SPListItem item, string columnName, PeopleEditor peopleEditor, SPWeb web)
{
if (item[columnName] != null)
{
char[] to_splitter = { ';' };
string to_list = item[columnName].ToString(); // Reads value stored in SPList. (i.e., "Domain\User1; Domain\User2")
string[] arr = to_list.Split(to_splitter);
string user = string.Empty;
for (int i = 1; i < arr.Length; i++)
{
if ((i % 2) != 0)
{
user = arr[i].Substring(arr[i].IndexOf("#") + 1);
PickerEntity entity = new PickerEntity();
entity.Key = user;
entity.IsResolved = true;
entity = peopleEditor.ValidateEntity(entity);
peopleEditor.Entities.Add(entity);
}
}
}
}
Try this:
string x = item["SP_Group"] == null ? "" : item["SP_Group"].ToString();
if (x != "")
{
SPFieldUserValue uv = new SPFieldUserValue(web, x);
SPGroup group = mySite.Groups.GetByID(uv.LookupId);
if (group.Users.Count > 0)
{
System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (SPUser sUser in group.Users)
{
PickerEntity entity = new PickerEntity();
entity.Key = sUser.LoginName;
entity = peopleEditor.ValidateEntity(entity);
entityArrayList.Add(entity);
}
});
peopleEditor.UpdateEntities(entityArrayList);
peopleEditor.Validate();
}
else
{
peopleEditor.Entities.Clear();
}
}
string x = item["SP_Users"] == null ? "" : item["SP_Users"].ToString();
if (x != "")
{
SPFieldUserValueCollection uvcoll = new SPFieldUserValueCollection(mySite, x);
if (uvcoll.Count > 0)
{
System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (SPFieldUserValue uv in uvcoll)
{
SPUser sUser = uv.User;
PickerEntity entity = new PickerEntity();
entity.Key = sUser.LoginName;
entity = peopleEditor.ValidateEntity(entity);
entityArrayList.Add(entity);
}
});
peopleEditor.UpdateEntities(entityArrayList);
peopleEditor.Validate();
}
else
{
peopleEditor.Entities.Clear();
}
}