This is my method :-
[Invoke]
public List<FamilyEvent> GetFamilyEvents(int userId)
{
List<FamilyEvent> familyEvents = new List<FamilyEvent>();
int id = -1; //just to fool ria
//this is for birthday reminders.
var qry = ((from member in this.ObjectContext.TreeMembers.Where(m => m.UserId == userId && m.Birthdate == null)
select member.TreeMemberId).Except(from item in this.ObjectContext.FamilyEvents where item.ReminderType ==
FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.BIRTHDAY_REMINDER
select item.TreeMemberId));
var mainQry = from mainMember in this.ObjectContext.TreeMembers
where qry.Contains(mainMember.TreeMemberId)
select mainMember;
foreach (var item in mainQry)
{
FamilyEvent familyEvent = new FamilyEvent
{
FamilyEventId = id--,
TreeMemberId = item.TreeMemberId,
RelatedTreeMemberId = -1,
ReminderType = FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.BIRTHDAY_REMINDER
};
familyEvent.TreeMember = item;
familyEvents.Add(familyEvent);
}
//this is for anniversary events
qry = ((from member in this.ObjectContext.TreeMembers.Where(m => m.UserId == userId && m.RelationId == (short)Relations.Partner)
select member.TreeMemberId).Except(from item in this.ObjectContext.FamilyEvents where item.ReminderType == FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.ANNIVERSARY_REMINDER
select item.TreeMemberId));
mainQry = from mainMember in this.ObjectContext.TreeMembers.Include("RelatedTreeMember")
where qry.Contains(mainMember.TreeMemberId)
select mainMember;
foreach (var item in mainQry)
{
FamilyEvent familyEvent = new FamilyEvent
{
TreeMemberId = item.TreeMemberId,
TreeMember = item,
RelatedTreeMemberId = item.RelatedTreeMemberId,
ReminderType = FMT.Data.Web.Helpers.Global.FAMILY_EVENTS_REMINDERS.ANNIVERSARY_REMINDER
};
familyEvent.RelatedTreeMember = item.RelatedTreeMember;
familyEvents.Add(familyEvent);
}
return familyEvents;
}
As you can see i programmatically populate the entities and populate it. When i put breakpoint on return familyEvents, i can see the correct data. However on client side, the TreeMember and RelatedTreeMember value become null. Why is it so? If i do not use [Invoke] and instead use [Query] it works, but i need Invoke in my case.
Related
enter image description hereThe trigger is working completely fine, but Its not giving 100% code coverage. The main issue with Test class, its not covering the if condition of Role__c.
Trigger:
trigger DrawingSharing on Drawing__c (after insert) {
if(trigger.isInsert){
for (Drawing__c draw : Trigger.new){
System.debug('draw: '+draw);
List<Installation__c> ListInstalltionList = new List <Installation__c>();
for(String installationActivityList :draw.Installation_Activity__c.split(';')){
Installation__c inst = new Installation__c();
inst.Drawing_ID__c = draw.Id;
inst.Installation_Activity__c=installationActivityList;
inst.Execution__c=draw.Execution_ID__c;
inst.Floor__c=draw.Floors__c;
ListInstalltionList.add(inst);
}
system.debug('ListInstalltionList==>'+ListInstalltionList);
insert ListInstalltionList;
List<Drawing__c> newList = new List<Drawing__c>();
newList.add(draw);
Map <Id,Id> DrawingProjectMap = new Map<Id,Id>();
Map<Id,Drawing__c> drawingIdObjMap = new Map<Id,Drawing__c>([select id, name,Approver__c, Execution_ID__r.Project__c from Drawing__c where id in :newList limit 1]);
for(Drawing__c Drawing : drawingIdObjMap.values())
{
DrawingProjectMap.put(Drawing.Id,Drawing.Execution_ID__r.Project__c);
}
system.debug(DrawingProjectMap);
Map<Id,RoleObjectSharing__mdt> roleobjaccessmap = new Map<Id,RoleObjectSharing__mdt>([select id,Object__c,role__c,Accesslevel__c from RoleObjectSharing__mdt where Object__c='Drawing']);
Map<String,String> RoleAccessmap = new Map<String,String>();
for(RoleObjectSharing__mdt Robj : roleobjaccessmap.values()){
RoleAccessmap.put(Robj.role__c,Robj.Accesslevel__c);
}
system.debug(RoleAccessmap.keySet());
system.debug(DrawingProjectMap.values());
Map<Id,Projects__c> teamrolemap = new Map<Id,Projects__c>([select Id,(select id, User_Lookup__c,Role__c from TeamRoles__r where Role__c in:RoleAccessmap.keySet()) from Projects__c where Id in :DrawingProjectMap.values()]);
system.debug('teamrolemap'+teamrolemap);
List <Drawing__Share> DrawShareList = new List<Drawing__Share>();
List <Drawing__c> DrawList = new List<Drawing__c>();
INTEGER countFound = 0;
for(Drawing__c drawobj : newList){
Projects__c proj = teamrolemap.get(DrawingProjectMap.get(drawobj.id));
system.debug(proj.teamroles__r);
***for(teamroles__c tr : proj.teamroles__r){
system.debug(tr);
if(tr.Role__c == 'PlanningEngineer' || tr.Role__c == 'AssistantPlanningEngineer' || tr.Role__c == 'PlanningManager' || tr.Role__c == 'AssistantPlanningManager' && countFound <=0) {
countFound = countFound + 1;
Drawing__c ddd = drawingIdObjMap.values();
ddd.Approver__c = tr.User_Lookup__c;
DrawList.add(ddd);
}
Drawing__Share recruiterShr = new Drawing__Share();
recruiterShr.ParentId = drawobj.Id;
recruiterShr.UserOrGroupId = tr.User_Lookup__c;
recruiterShr.AccessLevel = RoleAccessmap.get(tr.role__c);
recruiterShr.RowCause = tr.role__c+'__c';
DrawShareList.add(recruiterShr);***
}
system.debug(DrawShareList);
}
upsert DrawList;
Database.SaveResult[] lsr = Database.insert(DrawShareList,false);
Integer i=0;
for(Database.SaveResult sr : lsr){
if(!sr.isSuccess()){
}
i++;
}
}
}
}
Test Class:
static testMethod void Test4(){
System.debug('TestSharing = Test4');
Test.startTest();
Projects__c proj = new Projects__c();
proj.Name = 'Hello';
proj.LL_Location__c='Mumbai';
insert proj;
TeamRoles__c tr1 = new TeamRoles__c();
tr1.User_Lookup__c = UserInfo.getUserId();
tr1.Role__c = 'PlanningEngineer';
tr1.Project_Name__c = proj.Id;
insert tr1;
TeamRoles__c tr2 = new TeamRoles__c();
tr2.User_Lookup__c = UserInfo.getUserId();
tr2.Role__c = 'PlanningManager';
tr2.Project_Name__c = proj.Id;
insert tr2;
Execution__c ex = new Execution__c();
ex.Project__c = proj.Id;
insert ex;
Item_Master__c ItemeMaster = new Item_Master__c();
ItemeMaster.Item_Description__c = 'testing';
ItemeMaster.Item_Code__c = 'testing';
insert ItemeMaster;
Project_Items__c projItems = new Project_Items__c();
projItems.Total_PO_Quantity__c = 0;
projItems.ItemMaster__c = ItemeMaster.Id;
projItems.Execution__c = ex.Id;
insert projItems;
List<TeamRoles__c> lstTR = new List<TeamRoles__c>();
TeamRoles__c tr7 = new TeamRoles__c();
tr7.User_Lookup__c = UserInfo.getUserId();
tr7.Role__c = 'PlanningEngineer';
tr7.Project_Name__c = proj.Id;
lstTR.add(tr7);
List<Drawing__c> d= new List<Drawing__c>();
Drawing__c draw = new Drawing__c();
draw.Execution_Id__c = ex.Id;
draw.Floors__c='5F';
draw.Installation_Activity__c='Cable Tray';
draw.Drawing_Line_Items_Count__c = 0;
d.add(draw);
insert d;
//insert draw;
Installation__c inst = new Installation__c();
inst.Drawing_ID__c=draw.Id;
inst.Floor__c= draw.Floors__c;
inst.Installation_Activity__c='Cable Tray';
inst.As_built_Marked_Drawing_Prepared_by_Site__c =False;
inst.Execution__c = ex.Id;
insert inst;
SharingUtilityClass suc = new SharingUtilityClass();
suc.initObjSharing(lstTR);
Drawing_Line_Items__c dll = new Drawing_Line_Items__c();
dll.Drawing_Number__c = draw.Id;
dll.Project_Items__c = projItems.Id;
dll.Project_Name__c = proj.Id;
dll.Installation_Activity__c='Cable Tray';
dll.GFC_Quantity__c = 15;
dll.Shop_Drawing_Quantity__c = 20;
dll.GFC_Drawing_Line_Item_Done__c = true;
dll.Shop_Drawing_Line_Item_Done__c=true;
insert dll;
Installation_Line_Items__c instline = new Installation_Line_Items__c();
instline.Installation__c = inst.Id;
instline.Project_Items__c = projItems.Id;
instline.Installation_Activity__c='Cable Tray';
instline.Total_installed_quantity_DPR_Quantity__c = 100.00;
insert instline;
List<Drawing_Line_Items__c> listProj2 = CircularProgressController.getDrawingLineItem(dll.Id);
List<Drawing_Line_Items__c> listProj3 = CircularProgressController.getDrawingLineItemShop(dll.Id);
List<Drawing__c> listProj4 = Drawing.getDrawing(draw.Id);
List<Project_Items__c> listProj5 = Drawing.getProjectItems(ex.Id);
Test.stopTest();
}
If there are team roles being debugged from this line
for(teamroles__c tr : proj.teamroles__r){
system.debug(tr);
I would then check to see if this is evaluating to true within the test context:
if(tr.Role__c == 'PlanningEngineer' || tr.Role__c == 'AssistantPlanningEngineer' || tr.Role__c == 'PlanningManager' || tr.Role__c == 'AssistantPlanningManager' && countFound <=0)
Here I am able to add the data in more than one table. Let i have 3 tables User, Franchise and Fee.
I am not able to update the data in more than one table,it throwing the exception:
A referential integrity constraint violation occurred: The property value(s) of 'User.Id' on one end of a relationship do not match the property value(s) of 'Franchise.UserId' on the other end.
Code:
public MessageResult SaveAndUpdateFranchisee(UserViewModel model)
{
var result = new MessageResult();
try
{
User userData = new User();
Franchise franchiseData = new Franchise();
var ExistUser = db.Users.Where(a => a.Id == model.Id).FirstOrDefault();
//Update record
if (model.Id > 0)
{
Fee feeData = new Fee
{
FranchiseeFee = model.FranchiseeFee,
PaymentTermsFranchiseFee = model.PaymentTermsFranchiseFee,
EquipmentCost = model.EquipmentCost,
PaymentTermsEquipmentCost = model.PaymentTermsEquipmentCost,
OtherFee = model.OtherFee,
PaymentTermsOtherFee = model.PaymentTermsOtherFee,
ConsumableStock = model.ConsumableStock,
PaymentTermsConsumableStock = model.PaymentTermsConsumableStock,
FrozenFoodStock = model.FrozenFoodStock,
PaymentTermsFrozenFoodStock = model.PaymentTermsFrozenFoodStock,
TotalAmountDue = model.TotalAmountDue,
TotalAmountPaid = model.TotalAmountPaid,
BalanceAmount = model.BalanceAmount,
LoyaltyFeePercentage = model.LoyaltyFeePercentage,
FixedMonthlyFee = model.FixedMonthlyFee,
Note = model.Note,
UserId = model.CurrentUserId,
LOIDocUrl = model.LOIDocUrl,
ModifiedDate = DateTime.Now
};
ExistUser.Email = model.Email;
//var pwd = SecutiryServices.EncodePasswordToBase64(model.Password);
//userData.Password = pwd;
ExistUser.Password = model.Password;
ExistUser.FirstName = model.FirstName;
ExistUser.MiddleName = model.MiddleName;
ExistUser.LastName = model.LastName;
ExistUser.FullName = model.FullName;
ExistUser.MobileNo = model.MobileNo;
ExistUser.ModifyDate = DateTime.Now;
franchiseData.Name = model.FullName;
franchiseData.MobileNo = model.MobileNo;
franchiseData.AlternateNo = model.AlternetNo;
franchiseData.CompanyPhoneNo = model.PhoneNo;
franchiseData.Address = model.Address;
franchiseData.City = model.City;
franchiseData.State = model.State;
franchiseData.PinCode = model.PinCode;
franchiseData.CompanyName = model.CompanyName;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyCity = model.CompanyCity;
franchiseData.CompanyState = model.CompanyState;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyPinCode = model.CompanyPinCode;
franchiseData.ModifiedDate = DateTime.Now;
userData.Franchises.Add(franchiseData);
foreach (var item in userData.Franchises)
{
item.Fees.Add(feeData);
}
db.Users.Attach(userData);
db.Entry(userData).State = System.Data.Entity.EntityState.Modified;
//db.Users.Add(userData);
db.SaveChanges();
result.Message = "Your franchise has been updated successfully..";
result.Status = true;
}
//For Insert recored..
else
{
Fee feeData = new Fee
{
FranchiseeFee = model.FranchiseeFee,
PaymentTermsFranchiseFee = model.PaymentTermsFranchiseFee,
EquipmentCost = model.EquipmentCost,
PaymentTermsEquipmentCost = model.PaymentTermsEquipmentCost,
OtherFee = model.OtherFee,
PaymentTermsOtherFee = model.PaymentTermsOtherFee,
ConsumableStock = model.ConsumableStock,
PaymentTermsConsumableStock = model.PaymentTermsConsumableStock,
FrozenFoodStock = model.FrozenFoodStock,
PaymentTermsFrozenFoodStock = model.PaymentTermsFrozenFoodStock,
TotalAmountDue = model.TotalAmountDue,
TotalAmountPaid = model.TotalAmountPaid,
BalanceAmount = model.BalanceAmount,
LoyaltyFeePercentage = model.LoyaltyFeePercentage,
FixedMonthlyFee = model.FixedMonthlyFee,
Note = model.Note,
UserId = model.CurrentUserId,
LOIDocUrl = model.LOIDocUrl,
CreatedDate = DateTime.Now
};
userData.Email = model.Email;
//var pwd = SecutiryServices.EncodePasswordToBase64(model.Password);
//userData.Password = pwd;
userData.Password = model.Password;
userData.FirstName = model.FirstName;
userData.FullName = model.FirstName + " " + model.LastName;
userData.LastName = model.LastName;
userData.MobileNo = model.MobileNo;
userData.IsActive = true;
userData.IsDelete = false;
userData.CreatedDate = DateTime.Now;
userData.UserTypeId = 2;
franchiseData.CompanyId = model.CurrentUserId;
franchiseData.Name = userData.FullName;
franchiseData.MobileNo = model.MobileNo;
franchiseData.AlternateNo = model.AlternetNo;
franchiseData.Address = model.Address;
franchiseData.City = model.City;
franchiseData.State = model.State;
franchiseData.PinCode = model.PinCode;
franchiseData.CompanyName = model.CompanyName;
franchiseData.CompanyPhoneNo = model.PhoneNo;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyCity = model.CompanyCity;
franchiseData.CompanyState = model.CompanyState;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyPinCode = model.CompanyPinCode;
franchiseData.CreatedDate = DateTime.Now;
franchiseData.IsActive = true;
userData.Franchises.Add(franchiseData);
foreach (var item in userData.Franchises)
{
item.Fees.Add(feeData);
}
db.Users.Add(userData);
db.SaveChanges();
//db.AddUserRole(userData.Id, 4);
result.Message = "Your franchisee has been created successfully..";
result.Status = true;
}
return result;
}
catch (Exception ex)
{
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
return result;
}
}
The error message is straightforward - your code is creating a new Franchise object but it never sets the franchiseData.UserId property.
Add this to your franchiseData population code before you call db.SaveChanges():
franchiseData.UserId = model.CurrentUserId;
BTW, you should add code verify that the current user has permission to set foreign-key reference properties (like UserId) directly from values read from submitted forms because otherwise any user could enter Id values belonging to other users and gain access to information they shouldn't have access to - or otherwise alter with your database.
This is the case, for example, if a user now creates a page. So the next day I need Azure Logic apps to send an email after 1 day.
The problem is: right now, it is by no means sending any email to me if I sign up yesterday. But it sends me an email that now it has gone through with succe.
I would like to know what goes wrong since it by no means email me as I set up yesterday.
My Logic app (From Azure) - Images
However, be aware that the code can be made short but I just need to find out if Logic apps are making mistakes or if thus my code previously works without problems.
[Route("/api/cronjob")]
[HttpGet]
public async Task<IActionResult> NewSletterUserEmail()
{
await Newsletter();
return Ok("Godkendt!");
}
public async Task<IActionResult> Newsletter()
{
var m = new Settings.ArdklarMail();
var dtt = DateTime.Now;
var days = _dbContext.OfferUser.Max(i => i.Days);
var MaxDays = DateTime.Now.AddDays(-days);
var userlist = _dbContext.Users.Where(i => i.Opretdate >= MaxDays && i.TilmeldtNyhedsbrev == true).ToList();
if (userlist != null)
{
foreach (var item in userlist)
{
string mail = item.Brugernavn;
string fullname = item.Navn;
var memberData = _dbContext.MemberShipValue.FirstOrDefault(r => r.UserId == item.UserId);
if (memberData == null)
{
//alm bruger
var result = _dbContext.OfferUser.Where(x => x.Value == 1).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
else
{
var result = _dbContext.OfferUser.Where(x => x.Value == 2).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
}
}
//Det er til dem fra nyhedsbrevet som få tilsendt nyhedsbrev omkring div ting.
var newsletterlist = _dbContext.NewsletterList.Where(i => i.Tilmeldtdato >= MaxDays).ToList();
if (newsletterlist != null)
{
foreach (var item in newsletterlist)
{
string mail = item.Email;
string fullname = item.Email;
//til de nyhedsbrevet område
var result = _dbContext.OfferUser.Where(x => x.Value == 3).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Tilmeldtdato.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(mail);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(3500);
}
}
}
}
}
return Ok("Godkendt!");
}
No, I don't see mistake in Azure Logic Apps. Since the Logic App uses a recurrence trigger, it triggers the Logic App at the defined interval of time.
As there was send email action both side on the parallel branch, it will somehow send you an email by no means.
I need some performance for doing some of my things. I'm trying to import excel data to my SQL Server database here is my code for doing that work but it really takes too much time for that. Could you give me some advice for that
[WebMethod]
public static string VerileriAktar(string alanlar, string gruplar, string shit)
{
ArtiDBEntities entity = new ArtiDBEntities();
string[] eslesmeler = alanlar.Split(',');
string[] grplar = gruplar.Split(',');
DataSet ds = (DataSet)HttpContext.Current.Session["ExcelVerileri"];
DataTable dt = ds.Tables["" + shit + ""];
MembershipUser gelen = (MembershipUser)HttpContext.Current.Session["kimo"];
Guid aa = (Guid)gelen.ProviderUserKey;
List<tbl_AltMusteriler> bulkliste = new List<tbl_AltMusteriler>();
List<tbl_AltMusteriler> ilkkontrol = entity.tbl_AltMusteriler.Where(o => o.UserId == aa).ToList();
List<tbl_AltMusteriler> grupicin = new List<tbl_AltMusteriler>();
List<tbl_OzelAlanlar> ensonatilacakalan = new List<tbl_OzelAlanlar>();
List<tbl_OzelTarihler> ensonalicaktarih = new List<tbl_OzelTarihler>();
// Datatable mın Kolon isimlerini değiştirdim.
foreach (string item_col_name in eslesmeler)
{
string alan = item_col_name.Split('=')[0].Split('_')[1];
string degisecek = item_col_name.Split('=')[1];
if (degisecek == "")
continue;
dt.Columns[degisecek].ColumnName = alan;
}
#region verilerde
foreach (DataRow dr in dt.Rows)
{
tbl_AltMusteriler yeni = new tbl_AltMusteriler();
foreach (DataColumn dtclm in dt.Columns)
{
string gsm1 = "";
if (dtclm.ColumnName == "gsm1")
gsm1 = dr["gsm1"].ToString();
string gsm2 = "";
if (dtclm.ColumnName == "gsm2")
gsm2 = dr["gsm2"].ToString();
string ad = "";
if (dtclm.ColumnName == "ad")
ad = dr["ad"].ToString();
string soyad = "";
if (dtclm.ColumnName == "soyad")
soyad = dr["soyad"].ToString();
if (gsm1 != "")
{
if (Tools.isNumber(gsm1) == false)
continue;
else
{
if (gsm1.Length > 10)
gsm1 = gsm1.Substring(1, 10);
yeni.Gsm1 = gsm1;
}
}
if (gsm2 != "")
{
if (Tools.isNumber(gsm2) == false)
continue;
else
{
if (gsm2.Length > 10)
gsm2 = gsm2.Substring(1, 10);
yeni.Gsm2 = gsm2;
}
}
if (ad != "")
yeni.Ad = ad;
if (soyad != "")
yeni.Soyad = soyad;
}
yeni.UserId = new Guid(aa.ToString());
if (yeni.Gsm1 != "")
grupicin.Add(yeni);
}
#endregion
bulkliste = grupicin.GroupBy(cust => cust.Gsm1).Select(grp => grp.First()).ToList();
List<tbl_AltMusteriler> yokartikin = bulkliste.Where(o => !ilkkontrol.Any(p => o.Gsm1 == p.Gsm1)).ToList();
int saybakim = yokartikin.Count();
DataTable bulkdt = new DataTable();
if (yokartikin.Count > 0)
{
Type listType = yokartikin.ElementAt(0).GetType();
PropertyInfo[] properties = listType.GetProperties();
foreach (PropertyInfo property in properties)
if (property.Name == "UserId")
bulkdt.Columns.Add(new DataColumn() { ColumnName = property.Name, DataType = typeof(Guid) });
else
bulkdt.Columns.Add(new DataColumn() { ColumnName = property.Name });
foreach (object itembulk in yokartikin)
{
DataRow drbk = bulkdt.NewRow();
foreach (DataColumn col in bulkdt.Columns)
drbk[col] = listType.GetProperty(col.ColumnName).GetValue(itembulk, null);
bulkdt.Rows.Add(drbk);
}
}
//var rowsOnlyInDt1 = bulkdt.AsEnumerable().Where(r => !bulkdt44.AsEnumerable()
// .Any(r2 => r["gsm1"].ToString() == r2["gsm1"].ToString()));
//DataTable result = rowsOnlyInDt1.CopyToDataTable();//The third table
if (bulkdt.Rows.Count > 0)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ArtiDBMemberShip"].ConnectionString))
{
SqlTransaction transaction = null;
connection.Open();
try
{
transaction = connection.BeginTransaction();
using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
{
sqlBulkCopy.BulkCopyTimeout = 240;
sqlBulkCopy.DestinationTableName = "tbl_AltMusteriler";
sqlBulkCopy.ColumnMappings.Add("UserId", "UserId");
sqlBulkCopy.ColumnMappings.Add("Ad", "Ad");
sqlBulkCopy.ColumnMappings.Add("Soyad", "Soyad");
sqlBulkCopy.ColumnMappings.Add("Adres", "Adres");
sqlBulkCopy.ColumnMappings.Add("Gsm1", "Gsm1");
sqlBulkCopy.ColumnMappings.Add("Gsm2", "Gsm2");
sqlBulkCopy.ColumnMappings.Add("Faks", "Faks");
sqlBulkCopy.ColumnMappings.Add("Telefonis", "Telefonis");
sqlBulkCopy.ColumnMappings.Add("Telefonev", "Telefonev");
sqlBulkCopy.ColumnMappings.Add("Eposta", "Eposta");
sqlBulkCopy.ColumnMappings.Add("DogumTarihi", "DogumTarihi");
sqlBulkCopy.ColumnMappings.Add("EvlilikTar", "EvlilikTar");
sqlBulkCopy.ColumnMappings.Add("TcNo", "TcNo");
//sqlBulkCopy.ColumnMappings.Add("Deleted", "Deleted");
sqlBulkCopy.WriteToServer(bulkdt);
}
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
entity.SaveChanges();
}
if (grplar.Length > 0)
{
List<tbl_AltMusteriler> guncelliste = entity.tbl_AltMusteriler.Where(o => o.UserId == aa).ToList();
List<tbl_KisiGrup> kisigruplari = new List<tbl_KisiGrup>();
foreach (tbl_AltMusteriler itemblkliste in bulkliste)
{
long AltMusteriIDsi = guncelliste.Where(o => o.Gsm1 == itemblkliste.Gsm1).FirstOrDefault().AltMusteriID;
// Seçili Gruplara kişileri ekleme
#region Gruplara ekleme
if (grplar.Length > 0)
{
foreach (string item_gruplar in grplar)
{
if (item_gruplar == "chkall")
continue;
if (item_gruplar == "")
continue;
if (item_gruplar == null)
continue;
tbl_KisiGrup yeni_kisi_grup = new tbl_KisiGrup()
{
AltMusteriID = AltMusteriIDsi,
GrupID = int.Parse(item_gruplar)
};
kisigruplari.Add(yeni_kisi_grup);
}
}
#endregion
}
List<tbl_KisiGrup> guncel_grup = entity.tbl_KisiGrup.Where(o => o.tbl_AltMusteriler.UserId == aa).ToList();
List<tbl_KisiGrup> kisi_grup_kaydet = kisigruplari.Where(o => !guncel_grup.Any(p => o.AltMusteriID == p.AltMusteriID && o.GrupID == p.GrupID)).ToList();
// Grupları Datatable çevirme
#region Grupları Datatable le çevirme
DataTable bulkdt2 = new DataTable();
if (kisi_grup_kaydet.Count > 0)
{
Type listType = kisi_grup_kaydet.ElementAt(0).GetType();
//Get element properties and add datatable columns
PropertyInfo[] properties = listType.GetProperties();
foreach (PropertyInfo property in properties)
bulkdt2.Columns.Add(new DataColumn() { ColumnName = property.Name });
foreach (object itembulk in kisi_grup_kaydet)
{
DataRow drbk = bulkdt2.NewRow();
foreach (DataColumn col in bulkdt2.Columns)
drbk[col] = listType.GetProperty(col.ColumnName).GetValue(itembulk, null);
bulkdt2.Rows.Add(drbk);
}
}
#endregion
//Burada bulk insert işlemini gerçekleştiriyoruz...
#region Grup Verileri BulkCopy ile birkerede yazdık
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ArtiDBMemberShip"].ConnectionString))
{
SqlTransaction transaction = null;
connection.Open();
try
{
transaction = connection.BeginTransaction();
using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
{
sqlBulkCopy.BulkCopyTimeout = 240;
sqlBulkCopy.DestinationTableName = "tbl_KisiGrup";
sqlBulkCopy.ColumnMappings.Add("AltMusteriID", "AltMusteriID");
sqlBulkCopy.ColumnMappings.Add("GrupID", "GrupID");
sqlBulkCopy.WriteToServer(bulkdt2);
}
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
entity.SaveChanges();
#endregion
}
return "ok";
}
EDIT
actually that codeblock takes time when if there is 70.000 or more rows data
List<tbl_AltMusteriler> yokartikin = bulkliste.Where(o => !ilkkontrol.Any(p => o.Gsm1 == p.Gsm1)).ToList();
I think the my main problem is while I'm just inserting data with sqlbulkcopy. After that I couldn't get the identity ids, for that reason I get data to a generic list and try to find that new ids and creating a new list of group. and sqlbulkcopy again. these are takes lots of time about 10 minutes to import 65.000 rows is there another way to do those things
Your question is very broad. I would recomment reading performance considerations for EF. Also keep in mind that EF is not really meant for bulk operations since it brings all data from the database to the client. This adds a lot of overhead if you want to do this for a lot of entities if you don't need to/want to process them on the client. (Note I have not really looked into your code - it's too much)
My query returns account.name, account.account and account.parentaccountid.
I'm using Silverlight and CRM2011.
Now I'm having trouble to find out how to extract value from parentaccountid attribute.
I have silverlightextensionmethods.cs file included in my VS project, and I'm using GetAttributeValue<Guid>("parentaccountid") to get the value from parentaccountid.
The value returned is empty.
Has anyone any ideas how to accomplish this?
I can get any other attribute value, but parentaccountid in account and parentcustomerid in contact are making my life very difficult.
Code:
FIRST I CREATE QUERYEXPRESSION:
string temp="name;accountid;parentaccountid";
string[] fields = temp.Split(';');
QueryExpression query = new QueryExpression()
{
EntityName = entity,
ColumnSet = new ColumnSet { Columns = new System.Collections.ObjectModel.ObservableCollection<string>(fields) },
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = parentidfield,
Operator = ConditionOperator.Equal,
Values = { id }
}
}
}
};
OrganizationRequest req = new OrganizationRequest();
req.RequestName = "RetrieveMultiple";
req["Query"] = query;
service.BeginExecute(req, new AsyncCallback(GetChildren_ExecuteCallBack), service);
NEXT I TY TO READ VALUES FORM RESPONSE
void GetChildren_ExecuteCallBack(IAsyncResult childresult)
{
List<TreeRecord> listc = new List<TreeRecord>();
try
{
OrganizationResponse childresponse = ((IOrganizationService)childresult.AsyncState).EndExecute(childresult);
EntityCollection childresults = (EntityCollection)childresponse["EntityCollection"];
if (childresults.Entities.Count > 0)
{
TreeConfig sitm = new TreeConfig();
string sdisplay = "";
string[] fields = "".Split(';');
string sid = "";
string pid = "";
foreach (Entity childentity in childresults.Entities)
{
foreach (TreeConfig sitem in Configs)
{
if (sitem.EntityName == childentity.LogicalName)
{
sitm = sitem;
}
}
TreeRecord childitem = new TreeRecord();
string sValue = "";
sdisplay = "name;accountid;parentaccountid";
fields = sdisplay.Split(';');
sid = "accountid";
pid = "parentaccountid";
int i = sdisplay.Split(';').Length;
for (int j = 0; j < i; j++)
{
try { sValue += childentity.GetAttributeValue<string>(fields[j]) + " "; }
catch (Exception ex)
{
//s = "sValue haku: " + ex.Message.ToString();
//this.ReportMessage(s.ToString());
}
}
childitem.Name = sValue;
childitem.EntityName = childentity.LogicalName;
childitem.Level = sitm.Level;
childitem.ParentEntityName = sitm.EntityName;
childitem.Color = sitm.Color;
childitem.RecordId = childentity.GetEntityId<Guid>(sid);
try { childitem.ParentId = childentity.GetAttributeValue<Guid>(pid); }
catch
{
//sb.AppendLine("guid: parentid tietoa ei löydy");
//this.ReportMessage(sb.ToString());
}
listc.Add(childitem);
}
}
}
Instead of
childentity.GetAttributeValue<Guid>(pid)
use
childentity.GetAttributeValue<EntityReference>(pid)