How to make a better coding of this code - exception

I have the following code :
string name1;
string name2;
string name3;
try
{
name1 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name1']").GetAttributeValue("value", "");
name2 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name2']").GetAttributeValue("value", "");
name3 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name3']").GetAttributeValue("value", "");
}
catch(Exception)
{
name1 = "";
name2 = "";
name3 = "";
}
Even thought I couldnt find a case, there is a chance the node is not found and the function SelectSingleNode() returns null.
But if one of them gives an error, all 3 string would be empty.I could solve it like the code below but I dont like calling 3 try/catch in a row like this, is there a better way to do this?
try
{
name1 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name1']").GetAttributeValue("value", "");
} catch (Exception)
{
name1 = "";
}
try
{
name2 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name2']").GetAttributeValue("value", "");
} catch (Exception)
{
name2 = "";
}
try
{
name3 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name3']").GetAttributeValue("value", "");
} catch (Exception)
{
name3 = "";
}

check the following solution may help you.
try {
if (null != htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name1']") && null != htmlDoc.DocumentNode
.SelectSingleNode("//input[#name='name1']").GetAttributeValue("value", "")) {
name1 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name1']").GetAttributeValue("value", "");
} else {
name1 = null;
}
if (htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name2']") && null != htmlDoc.DocumentNode
.SelectSingleNode("//input[#name='name2']").GetAttributeValue("value", "")) {
name2 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name2']").GetAttributeValue("value", "");
} else {
name2 = null;
}
if (htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name3']") && null != htmlDoc.DocumentNode
.SelectSingleNode("//input[#name='name3']").GetAttributeValue("value", "")) {
name3 = htmlDoc.DocumentNode.SelectSingleNode("//input[#name='name3']").GetAttributeValue("value", "");
} else {
name3 = null;
}
} catch (Exception e) {
e.printStackTrace();
}

Related

How set variable with condition with immutable.js

This code in typescript:
const b
if (a == true) {
b = [1]
} else {
b = [2]
}
how to convert above code to immutable.js ?
You have two options:
let b
if (a) {
b = List([1])
} else {
b = List([2])
}
//or
const b = a ? List([1]) : List([2])

Nodes without "root"

I have a question about this code:
#helper BuildTreeView(IEnumerable<dynamic> data, int? parentid = null, int level = 0) {
var nodes = data.Where(n => n.ParentId == parentid).OrderBy(n => n.DisplayOrder);
var aCapo = "";
if (nodes.Any()) {
if(nodes.First().ParentId != null){
level++;
if (level == 1) {aCapo = "<br>";}
else if (level >= 2) {aCapo = ">>";}
}
foreach (var node in nodes) {
#Html.Raw(aCapo) #node.Text
#BuildTreeView(data, node.Id, level);
}
}
}
I would remove "root" so that each category and any subcategories, were not linked to the root.
I would like in practice, this result
cat1 >> subCat1.a
cat2 >> subCat2.a
cat3 subCat3.a subCat3.b
cat4
cat5 >> subCat5.a

Linq + nested GroupBy

We are using mySQL with WCF Restful service, we want to fetch our database content PACKAGEID wise...as mentioned below:
PackageId=2
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;![enter image description here][1]
},
{
StartRange =101;
EndRange = 500;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
PackageId=3
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
We have created a Result class to return result from out wcf service...for above service we have result class defined as below
[DataContract]
public class PackagePointRangeConfigurationResult : ResultBase
{
[DataMember]
public List<PackagePointRangeResult> Result;
}
public class PackagePointRangeResult
{
public int PackageId { get; set; }
public List<PointPlanInfo> Result { get; set; }
}
For fetching record we use following linq query:
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare =planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
But it gives me below error:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[PointPlanInfo] ToList[PointPlanInfo](System.Collections.Generic.IEnumerable1[PointPlanInfo])' method, and this method cannot be translated into a store expression.

LINQ2SQL A problem with return items based on a parameter

I occured a strange problem. I have that method
public static void ProcessCategories(int? myID)
{
var tmpList = Adapter.Category.Where(x => x.IdParentCategory == myID).ToList();
}
when myID == null (the parameter), the tmpList doesn't contain any elements, but if I type
x.IdParentCategory == null then some items are returned. Why ?
Try this:
public static void ProcessCategories(int? myID)
{
var tmpList = Adapter.Category.Where(x => x.IdParentCategory == myID || (myID == null && x.IdParentCategory == null)).ToList();
}

Unsupported overload used for query operator 'Intersect'

I am able to do this query just fine with the test repository which is In Memory
when I move to the sqlRepository I get this error
Unsupported overload used for query operator 'Intersect'.
I assume it is because sending the query to sql is too complicated for Linq to Sql to do when it is not dealing with the Model.Model.Talent Type. Is there some way around doing a search like this with Intersect?
thanks
public class TalentService : ITalentService
{
ITalentRepository _repository = null;
private IQueryable<Talent> BasicSearch(string searchExpression)
{
IQueryable<Talent> t;
string[] sa = searchExpression.Trim().ToLower().Replace(" ", " ").Split(' ');
t = _repository.GetTalents();
foreach (string s in sa)
{
t = t.Intersect(AddBasicSearch(s), new TalentComparer());
}
return t;
}
private IQueryable<Talent> AddBasicSearch(string s)
{
IQueryable<Talent> t2 = _repository.GetTalents()
.Where(tal => tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
return t2;
}
}
public class SqlTalentRepository:ITalentRepository
{
public IQueryable<Model.Model.Talent> GetTalents()
{
var tal = from t in _db.Talents
let tLanguage = GetTalentLanguages(t.TalentID)
where t.Active == true
select new Model.Model.Talent
{
Id = t.TalentID,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages())
};
return tal ;
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
public static class TalentExtensions
{
public static string ToLanguageNameString(this IEnumerable<TalentLanguage> source
, IEnumerable<Model.Model.Language> allLanguages)
{
StringBuilder sb = new StringBuilder();
const string del = ", ";
foreach (TalentLanguage te in source)
{
sb.AppendFormat("{0}{1}", allLanguages
.Where(x => x.LanguageId == te.LanguageID).SingleOrDefault().LanguageName, del);
}
string sReturn = sb.ToString();
if (sReturn.EndsWith(del))
sReturn = sReturn.Substring(0, sReturn.Length - del.Length);
return sReturn;
}
}
public class TestTalentRepository : ITalentRepository
{
IList<Talent> talentList;
public TestTalentRepository(ILanguageRepository _LanguageRepo )
{
this._LanguageRepository = _LanguageRepo;
talentList = new List<Talent>();
talentLanguageList = new List<TalentLanguage>();
for (int i = 0; i < 55; i++)
{
var t = new Talent();
t.Id = i;
t.FirstName = (i % 3 == 0) ? "Ryan" : "Joe";
t.LastName = (i % 2 == 0) ? "Simpson" : "Zimmerman";
AddLanguagesToTestTalent(i, t);
talentList.Add(t);
}
}
private void AddLanguagesToTestTalent(int i, Talent t)
{
IList<Language> Languages = _LanguageRepository.GetLanguages().ToList<Language>();
Random rLanguages = new Random();
int numLanguages = rLanguages.Next(Languages.Count - 1) + 1;
t.TalentLanguages = new LazyList<TalentLanguage>();
for (int j = 0; j < numLanguages; j++)
{
var x = new TalentLanguage();
x.TalentLanguageId = j;
x.TalentId = i;
Random random2 = new Random();
int rand = random2.Next(Languages.Count);
var y = Languages.ElementAtOrDefault(rand);
Languages.RemoveAt(rand);
x.Language = y;
x.LanguageId = y.LanguageId;
t.TalentLanguages.Add(x);
}
}
public IQueryable<Talent> GetTalents()
{
var ts = from t in this.talentList
let tLanguage = GetTalentLanguages(t.Id)
where t.Active == true
select new Model.Model.Talent
{
Id = t.Id,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages()),
City = t.City,
};
return ts.AsQueryable<Model.Model.Talent>();
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
If you're trying to find entries which match all of those criteria, you just need multiple where clauses:
private static readonly char[] SplitDelimiters = " ".ToCharArray();
private IQueryable<Talent> BasicSearch(string search)
{
// Just replacing " " with " " wouldn't help with "a b"
string[] terms = search.Trim()
.ToLower()
.Split(SplitDelimiters,
StringSplitOptions.RemoveEmptyEntries);
IQueryable<Talent> query = _repository.GetTalents();
foreach (string searchTerm in terms)
{
query = AddBasicSearch(query, searchTerm);
}
return query;
}
private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> query, string s)
{
return query.Where(tal =>
tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
}