I am facing the following problem: I want to add dynamically a mobile site for specific templates, I specified the mobile layout in the standard values of the specific item. This all works fine but when I changed a field of the Item the layout and renderings of the default site is gone! Does anyone has a solution/suggestion for this problem?
I am working with Sitecore 6.4.
Thanx in advance!
The code that I am currently using (this is to add hardcoded a layout to an item, the next step is (when I fixed this problem) to get the layout from the standard_values item)
public class CheckMobileLayout
{
public void Process([NotNull] SaveArgs args)
{
try
{
foreach (Sitecore.Pipelines.Save.SaveArgs.SaveItem saveItem in args.Items)
{
Item orgItem = Context.ContentDatabase.Items[saveItem.ID, saveItem.Language, saveItem.Version];
if(orgItem.Name != "Content Editor")
{
TemplateItem testTemplate = orgItem.Template;
foreach (Field orgField in orgItem.Fields)
{
if (orgField != null)
{
if (orgField.GetTemplateField().Type == "Mobile Checkbox")
{
foreach (Sitecore.Pipelines.Save.SaveArgs.SaveField saveField in saveItem.Fields)
{
if (saveField.ID == orgField.ID)
{
if (saveField.Value != orgField.Value)
{
if (saveField.Value == "1") AddMobileLayout(orgItem);
else RemoveMobileLayout(orgItem);
}
}
}
}
}
}
}
}
}
catch (NullReferenceException)
{
}
}
private void RemoveMobileLayout(Item orgItem)
{
using (new SecurityDisabler())
{
Database masterDatabase = Database.GetDatabase("master");
orgItem = masterDatabase.GetItem(orgItem.Paths.Path);
string renderingXml = orgItem[Strings.Renderings];
LayoutDefinition layoutDefinition = new LayoutDefinition();
layoutDefinition.LoadXml(renderingXml);
string mobileDeviceId = Strings.mobileDeviceID;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(mobileDeviceId);
deviceDefinition.Layout = String.Empty;
string outputXml = layoutDefinition.ToXml();
Log.Info(outputXml, this);
orgItem.Editing.BeginEdit();
orgItem[Strings.Renderings] = outputXml;
orgItem.Editing.EndEdit();
}
}
private void AddMobileLayout(Item orgItem)
{
using (new SecurityDisabler())
{
Database masterDatabase = Database.GetDatabase("master");
Item testItem = masterDatabase.GetItem(orgItem.Paths.Path);
string renderingXml = testItem[Strings.Renderings];
LayoutDefinition layoutDefinition = new LayoutDefinition();
layoutDefinition.LoadXml(renderingXml);
string mobileDeviceId = Strings.mobileDeviceID;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(mobileDeviceId);
deviceDefinition.Layout = Strings.mobileLayoutID;
string outputXml = layoutDefinition.ToXml();
testItem.Editing.BeginEdit();
testItem[Strings.Renderings] = layoutDefinition.ToXml();
testItem.Editing.EndEdit();
}
}
}
I've fixed this with the following to methods:
protected void RemoveMobileLayout(Item item)
{
using (new SecurityDisabler())
{
LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(item[Sitecore.FieldIDs.LayoutField]);
DeviceDefinition mobileDevice = layoutDefinition.GetDevice(Resources.mobileDeviceID);
if (mobileDevice.Layout != null) mobileDevice.Layout = null;
if (mobileDevice.Renderings != null) mobileDevice.Renderings = null;
item.Editing.BeginEdit();
item[Sitecore.FieldIDs.LayoutField] = layoutDefinition.ToXml();
item.Editing.EndEdit();
}
}
protected void AddMobileLayout(Item item)
{
using (new SecurityDisabler())
{
LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(item[Sitecore.FieldIDs.LayoutField]);
DeviceDefinition mobileDevice = layoutDefinition.GetDevice(Resources.mobileDeviceID);
TemplateItem itemTemplate = item.Template;
if (itemTemplate != null)
{
if (itemTemplate.StandardValues != null)
{
Item standardValues = itemTemplate.StandardValues;
foreach (DeviceItem deviceItem in Sitecore.Configuration.Factory.GetDatabase("master").Resources.Devices.GetAll())
{
if (deviceItem.ID.ToString() == Resources.mobileDeviceID)
{
mobileDevice.Layout = standardValues.Visualization.GetLayout(deviceItem).ID.ToString();
RenderingReference[] sublayouts = standardValues.Visualization.GetRenderings(deviceItem, true);
foreach (RenderingReference sublayout in sublayouts) mobileDevice.AddRendering(new RenderingDefinition() { ItemID = sublayout.RenderingItem.ID.ToString(), Placeholder = sublayout.RenderingItem.Placeholder });
}
}
}
}
item.Editing.BeginEdit();
item[Sitecore.FieldIDs.LayoutField] = layoutDefinition.ToXml();
item.Editing.EndEdit();
}
}
Related
Hi I am using Entity Framework Code First, I have a collection of Entities that need to be saved, but I have my EF Repository created as below
public T Create(T item)
{
try
{
if (ufb != null && ufb.CurrentUser != null)
{
SetValue("CreatedByUserId", item, ufb.CurrentUser.Id);
SetValue("UpdatedByUserId", item, ufb.CurrentUser.Id);
}
SetValue("DateCreated", item, DateTime.Now);
SetValue("DateUpdated", item, DateTime.Now);
var newEntry = this.DbSet.Add(item);
this.Context.Database.Log = message => LogHandler.LogInfo(1111, message);
try
{
this.Context.SaveChanges();
}
catch (Exception ex)
{
LogHandler.LogInfo(2501, ex.Message);
}
BuildMetaData(item, true, true);
return newEntry;
}
catch (DbEntityValidationException dbEx)
{
// http://forums.asp.net/t/2014382.aspx?Validation+failed+for+one+or+more+entities+See+EntityValidationErrors+property+for+more+details+
string msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
msg += validationError.PropertyName;
msg += "---";
msg += validationError.ErrorMessage;
msg += "||";
}
}
throw new Exception("7777 CREATE EntityValidationErrors: " + msg);
}
}
My calling method is as below:
public List<VehicleInfo> Create(List<VehicleInfo> vehicleInfos, string Entity, int EntityId)
{
bool vehicleExists = false; List<VehicleInfo> newVehicleInfos = null;
if ((vehicleInfos != null) && (vehicleInfos.Count > 0))
{
newVehicleInfos = new List<VehicleInfo>();
foreach (VehicleInfo vehicleInfo in vehicleInfos)
{
vehicleExists = false;
if (vehicleInfo != null)
{
vehicleExists = this.VehicleExists(vehicleInfo.VehicleId, Entity, EntityId);
vehicleInfo.Entity = Entity;
vehicleInfo.EntityId = EntityId;
VehicleInfo v = this.UnitOfWork.VehicleInfoRepository.Create(vehicleInfo);
newVehicleInfos.Add(v);
}
}
}
return newVehicleInfos;
}
Hence when I am calling repositories create method for multiple times, its throwing me the above error, any help or suggestion would be very helpful, please thank you.
void BuildMetaDataNoThread(object item, bool active, bool isNew = false)
{
if (item.GetType() != typeof(JsonObject))
{
var dm = new DataAccessUnitOfWork(Constants.DefaultConnection);
var qtype = item.GetType();
if (qtype.BaseType.BaseType != null)
{
if ((isNew && qtype.BaseType.Name == typeof(ModelBase).Name) | qtype.BaseType.BaseType.Name == typeof(ModelBase).Name)
{
Thread.Sleep(500);
//collect data
var element = (ModelBase)item;
element.BuildMetaData(DataRequestType.CurrentItem);
var records = ModelBase.MetaData;
ModelBase.MetaData = new List<ModelRecord> { };
if (records == null) return;
foreach (ModelRecord r in records)
{
if (r!=null)
{
var jsr = new JavaScriptSerializer();
//object meta = r;
object rdata = r.Data;
var type = rdata.GetType();
var token = type.BaseType.Name;
List<string> include = r.Include;
// Cycle-through clieanup of models to be encoded into Json Data.
// this helper eliminates infinate relations by including records specified
// by a list of strings
if (include.Where(x => x.Contains("CreatedByUser")).Count() == 0)
include.Add("CreatedByUser");
if (include.Where(x => x.Contains("UpdatedByUser")).Count() == 0)
include.Add("UpdatedByUser");
var data = ClassCloner.CollectData(rdata, include);
List<string> tags = ClassCloner.CollectTags(data);
string _tags = "";
tags.ForEach((xtm) =>
{
_tags += xtm + ',';
});
var json = jsr.Serialize(data);
int id = 0;
//get identity
foreach (var prop in type.GetProperties())
{
if (id == 0)
{
foreach (var cp in prop.CustomAttributes)
{
if (cp.AttributeType.Name == "KeyAttribute")
{
var _id = ((Dictionary<string, object>)data)[prop.Name];
id = (int)_id;
break;
}
}
}
else { break; }
}
var query = dm.JsonObjectRepository.GetAll();
var key = "_" + token;
var _data = (Dictionary<string, object>)data;
var ExistingMetaData = (from x in query where x.SourceKey == key && x.SourceId == id select x).FirstOrDefault();
if (ExistingMetaData != null)
{
if (_data.ContainsKey("DateUpdated")) ExistingMetaData.Date = (DateTime)_data["DateUpdated"];
ExistingMetaData.SourceData = data;
ExistingMetaData.Encode();
ExistingMetaData.Active = active;
ExistingMetaData.SearchTags = _tags;
dm.JsonObjectRepository.Update(ExistingMetaData);
}
else
{
var newData = new JsonObject
{
Active = true,
Date = (DateTime)_data["DateUpdated"],
SourceData = data,
SourceId = id,
SourceKey = key,
SearchTags = _tags,
TargetKey = "GlobalSearchMetaData"
};
newData.Encode();
dm.JsonObjectRepository.Create(newData);
}
}
}
}
}
}
}
void BuildMetaData(object dataRecord, bool active, bool isNew)
{
new Thread((item) => { BuildMetaDataNoThread(item, active, isNew); }).Start(dataRecord);
}
I get errors when I decompile my code. It's a syntax I don't understand and I don't know how to fix it, can you help me?
enter image description here
enter image description here
enter image description here
public void performrolemapping(Customer customer, bool newcustomer)
{
if (!newcustomer)
{
IList<CustomerRole> customerRoles = this._customerservice.GetCustomerRoles(customer, false);
Func<CustomerRole, bool> u003cu003e9_170 = ParagonAuthenticationController.<> c.<> 9__17_0;
if (u003cu003e9_170 == null)
{
u003cu003e9_170 = new Func<CustomerRole, bool>(ParagonAuthenticationController.<> c.<> 9, (CustomerRole cr) => cr.get_SystemName() == NopCustomerDefaults.get_RegisteredRoleName());
ParagonAuthenticationController.<> c.<> 9__17_0 = u003cu003e9_170;
}
if ((object)Enumerable.FirstOrDefault<CustomerRole>(customerRoles, u003cu003e9_170) != (object)null)
{
return;
}
}
IList<CustomerRole> allCustomerRoles = this._customerservice.GetAllCustomerRoles(true);
List<CustomerRole> list = new List<CustomerRole>();
foreach (CustomerRole allCustomerRole in allCustomerRoles)
{
list.Add(allCustomerRole);
}
foreach (CustomerRole customerRole in list)
{
if (customerRole.Name != "Registered")
{
continue;
}
ICustomerService customerService = this._customerservice;
CustomerCustomerRoleMapping customerCustomerRoleMapping = new CustomerCustomerRoleMapping();
customerCustomerRoleMapping.CustomerId = customer.Id;
customerCustomerRoleMapping.CustomerRoleId = customerRole.Id;
customerService.AddCustomerRoleMapping(customerCustomerRoleMapping);
return;
}
}
public static string RandomString()
{
ParagonAuthenticationController.<> c__DisplayClass18_0 variable = null;
int num = 40;
Random random = new Random();
return new string(Enumerable.ToArray<char>(Enumerable.Select<string, char>(Enumerable.Repeat<string>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*+", num), new Func<string, char>(variable, (string s) => s[this.random.Next(s.get_Length())]))));
}
This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...
While using Dapper for multiple Query:
var result = sqlConnection.QueryMultiple(query, Parameters, commandType: commandType);
How can i get the table count returned from query? It has two overloaded implementation of .Read() method, which each time called, moves to next available result set (No result.Count() property). Eventually i want to put that number in a loop to iterate as many time as number of tables returned from query.
var reader = this.DbConnection.QueryMultipleAsync(sql, Params, commandType: CommandType.StoredProcedure).Result;
if(reader.IsConsumed == false)
{
DeviceTypeReport = reader?.ReadAsync<dynamic>().Result;
}
This is probably what you are looking for hope it helps.
This is probably what you are looking for hope it helps.
List<dynamic> data = new List<dynamic>();
while (reader.IsConsumed == false)
{
data.Add(await reader?.ReadAsync<dynamic>());
}
int totalRecordSet = data.Count;
public List NotificationExecuteMultiple(OutdoorRequest objreq, IConfiguration configuration)
{
var lst = new List<dynamic>();
using (DbConnection connection = new MySqlConnection(configuration.GetConnectionString("SquareHrConn")))
{
using (var dr = connection.QueryMultiple(ProcedureName, GetParamenter(objreq), commandType: CommandType.StoredProcedure))
{
while (dr.IsConsumed == false)
{
lst.Add(dr.Read());
}
}
}
return lst;
}
Consider the follwoing method to cover all cases
protected List<object> ExecuteMultiQuery<A, B, C, D, E, F, G, H, I, J>(string procedureName, DynamicParameters param = null)
{
List<object> result = new List<object>();
using (var connection = new SqlConnection(ConnectionManager.ConnectionString))
{
try
{
connection.Open();
using (var multi = connection.QueryMultiple(procedureName, param, commandType: CommandType.StoredProcedure, commandTimeout: 120))
{
var varA = multi.Read<A>();
if (varA != null) { result.Add(varA.ToList()); }
var varB = multi.Read<B>();
if (varB != null) { result.Add(varB.ToList()); }
var varC = multi.Read<C>();
if (varC != null) { result.Add(varC.ToList()); }
var varD = multi.Read<D>();
if (varD != null) { result.Add(varD.ToList()); }
var varE = multi.Read<E>();
if (varE != null) { result.Add(varE.ToList()); }
var varF = multi.Read<F>();
if (varF != null) { result.Add(varF.ToList()); }
var varG = multi.Read<G>();
if (varG != null) { result.Add(varG.ToList()); }
var varH = multi.Read<H>();
if (varH != null) { result.Add(varH.ToList()); }
var varI = multi.Read<I>();
if (varI != null) { result.Add(varI.ToList()); }
var varJ = multi.Read<J>();
if (varJ != null) { result.Add(varJ.ToList()); }
//if (varA != null) { result.Add(varA.ToList()); }
//if (resultSets > 1) { result.Add(multi.Read<B>().ToList()); }
//if (resultSets > 2) { result.Add(multi.Read<C>().ToList()); }
//if (resultSets > 3) { result.Add(multi.Read<D>().ToList()); }
//if (resultSets > 4) { result.Add(multi.Read<E>().ToList()); }
//if (resultSets > 5) { result.Add(multi.Read<F>().ToList()); }
//if (resultSets > 6) { result.Add(multi.Read<G>().ToList()); }
//if (resultSets > 7) { result.Add(multi.Read<H>().ToList()); }
//if (resultSets > 8) { result.Add(multi.Read<I>().ToList()); }
//if (resultSets > 9) { result.Add(multi.Read<J>().ToList()); }
return result;
}
}
catch (System.Exception e)
{
string message = e.Message;
}
}
return result;
}
here is my code :
var allEles = webBrowser1.Document.All;
foreach (HtmlElement item in allEles)
{
if (item.TagName.ToLower() == "div")
{
if(//Here i want to check if div has a background-image css property)
{
//do anything
}
}
}
i searched a lot to no avail :(
I wrote my own extension method :
public static class Extensions
{
public static bool hasBackgroundImage(this HtmlElement ele, string cssFolderPath)
{
string styleAttr = ele.Style.ToLower();
if (styleAttr.IndexOf("background-image") != -1 || styleAttr.IndexOf("background") != -1)
{
if (styleAttr.IndexOf("url") != -1)
{
return true;
}
}
string[] classes = ele.GetAttribute("className").Split(' ');
foreach (string className in classes)
{
if (className.Trim() == "")
{
continue;
}
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(cssFolderPath);
foreach (System.IO.FileInfo item in d.GetFiles().Where(p => p.Extension == ".css"))
{
string cssFile = System.IO.File.ReadAllText(item.FullName);
int start = cssFile.IndexOf(className);
if (start != -1)
{
string sub = cssFile.Substring(start + className.Length);
int end = sub.IndexOf('}');
string cssProps = sub.Substring(1, end).Replace("{", "").Replace("}", "").ToLower();
if (cssProps.IndexOf("background-image") != -1 || cssProps.IndexOf("background") != -1)
{
if (cssProps.IndexOf("url") != -1)
{
return true;
}
}
}
}
}
return false;
}
}
and now i can call my method :
var allEles = webBrowser1.Document.All;
foreach (HtmlElement item in allEles)
{
if (item.TagName.ToLower() == "div")
{
if(item.hasBackgroundImage("myCssFolderPathHere"))
{
//do anything
}
}
}
but this working only if am running a local html file .... because you must throw the css folder path as a parameter in my extension method , and thats what i was looking for :)