I need to make a generic logger to record certain insert/update statements so that my testers can verify the data being inserted is correct.
My first thought was that I would just use a function that accepted DynamicParameters and I would foreach through the DynamicParameters to generate a string to list the parameter's name and value and make them easier to read for the testers.
Unfortunately, Dapper.DynamicParameters does not contain a public definition for "GetEnumerator"
Here is basic example of what I was hoping to do:
string myFormattedListofParameters = "";
foreach (var p in myDynamicParameters)
{
myFormattedListofParameters += p.Name + "=" + p.Value.ToString();
}
Try:
var sb = new StringBuilder();
foreach (var name in p.ParameterNames)
{
var pValue = p.Get<dynamic>(name);
sb.AppendFormat("{0}={1}\n", name, pValue.ToString());
}
string ParametersToString(DynamicParameters parameters)
{
var result = new StringBuilder();
if (parameters != null)
{
var firstParam = true;
var parametersLookup = (SqlMapper.IParameterLookup)parameters;
foreach (var paramName in parameters.ParameterNames)
{
if (!firstParam)
{
result.Append(", ");
}
firstParam = false;
result.Append('#');
result.Append(paramName);
result.Append(" = ");
try
{
var value = parametersLookup[paramName];// parameters.Get<dynamic>(paramName);
result.Append((value != null) ? value.ToString() : "{null}");
}
catch
{
result.Append("unknown");
}
}
}
return result.ToString();
}
One line with Linq:
string.Join(", ", from pn in sprocParams.ParameterNames select string.Format("#{0}={1}", pn, (sprocParams as SqlMapper.IParameterLookup)[pn]))
I'm using that to log with log4net:
Log.InfoFormat("Exec {0} {1}", storedProc, string.Join(", ", from pn in sprocParams.ParameterNames select string.Format("#{0}={1}", pn, (sprocParams as SqlMapper.IParameterLookup)[pn])));
Just in case,
var pmaster = new Dapper.DynamicParameters();
SortedList l = new SortedList();
l.Add("param1", object1);
l.Add("param2", object2);
l.Add("param3", object3);
l.Add("param4", object4);
foreach(var key in l.Keys)
{
var val = l[key];
pmaster.Add(key.ToString(), val);
}
Worked for me.
Related
New to c# here, I have done some research about this problem but couldn't find anything, lack of vocabulary maybe.
My task here is to a read a huge file and to extract only the lines which are following the conditions.
Code I'm using to test some things:
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("R ") | line.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N", "").Replace("+", ",").Replace("·", ",").Replace("?", ",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}
This is a part of the file :
R XRPA168VC
B A
L 手动紧急停堆
E XRPA300KS
A 反应堆停堆 汽轮机停机
R XRPR111VR
B IP
E F2/3(XRPR144KS, XRPR145KS, XRPR146KS)
What I noticed is that the letters aren't even letter if there chinese around it, for example I tried the condition line.Substring(0,1) == "R", it couldn't find those lines.
No matter what I do, my codes would only return this
XPR111VR
F2/3XRPR144KS, XRPR145KS, XRPR146KS
I really need to be able to extract every R and E lines.
I just tried to copy my whole doc into Notepad and put the encoding into UTF8,
seems to work afterward but not sure if it's reliable.
Try this...it works
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
string line;
string data;
List<string> Data = new List<string>();
while ((line = sr.ReadLine()) != null)
{
var utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(line);
string myString = utf8.GetString(utfBytes, 0,
utfBytes.Length);
try
{
if (myString.Contains("R ") || myString.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N",
"").Replace("+", ",").Replace("·", ",").Replace("?",
",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}
How do I get values read values line a DataReader to read values of fields returned by multi in the following code to set the values in the Class
OracleRefCursor m_Cursor=null;
Dapper.SqlMapper.GridReader multi =null;
using (m_Conn = new OracleConnection(m_ConnectionString))
{
try
{
m_Conn.Open();
String m_LastName = "S" + "%";
String m_Id = "";
String m_EmpId = "";
var p = new OracleDynamicParameters();
p.Add(":p_LastName", m_LastName);
p.Add(":p_Id", m_Id);
p.Add(":p_EmpId", m_EmpId);
p.Add( ":p_Cursor1", dbType: OracleDbType.RefCursor, direction: ParameterDirection.Output );
using (multi = m_Conn.QueryMultiple(m_ProcedureName, param: p, commandType: CommandType.StoredProcedure))
{
}
}
catch (Exception ex)
{
String m_Error = ex.ToString();
}
}//end of using statement
From Dapper docs:
var sql =
#"
select * from Customers where CustomerId = #id
select * from Orders where CustomerId = #id
select * from Returns where CustomerId = #id";
using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
var customer = multi.Read<Customer>().Single();
var orders = multi.Read<Order>().ToList();
var returns = multi.Read<Return>().ToList();
...
}
I want to read programatically data using iterator in ADF mobile. My code is :
try {
ValueExpression vex = AdfmfJavaUtilities.getValueExpression("#{bindings.WeatherDescriptionIterator}", Object.class);
AmxIteratorBinding iter = (AmxIteratorBinding)vex.getValue(AdfmfJavaUtilities.getAdfELContext());
GenericType row = null;
BasicIterator bIter = iter.getIterator();
iter.getIterator().first();
ArrayList employees = new ArrayList();
for(int i = 0; i < iter.getIterator().getTotalRowCount(); i++) {
row = (GenericType)iter.getCurrentRow();
String phone = "";
String email = "";
if(row.getAttribute("Description") != null)
phone = row.getAttribute("Description").toString();
if(row.getAttribute("WeatherID") != null)
email = row.getAttribute("WeatherID").toString();
setTempValue(phone + " " + email);
iter.getIterator().next();
}
}
catch(Exception e1) {
AdfException ex = new AdfException(""+e1.getLocalizedMessage(), AdfException.ERROR );
throw ex;
}
I get error :-> cant not find property bindings
the expression should be :
ValueExpression vex = AdfmfJavaUtilities.getValueExpression("#bindings.WeatherDescriptionIterator.iteratorBinding}", Object.class);
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)