Display dynamic Navigation menu in asp.net core mvc layout page - asp.net-core

I want to display dynamic menu in asp.net core mvc layout page. in my database table has menuid and parentid from that i want to display nested menus. if anyone have solution please help me and if any other method for this give an example.
Model is given below:
public class Menu
{
public int Id { get; set; }
public string MenuText { get; set; }
public string Url { get; set; }
public int? ParentId { get; set; }
public bool Active { get; set; }
public List<Menu> List { get; set; }
}
I want to use this in my layout class .How can i use this?
db_class Connstring = new db_class();
public void ProcessRequest(HttpContext context)
{
var user_id = Convert.ToString(context.Request["Id"]);
var str_company = Convert.ToString(context.Request["str_company"]);
List<Menu> listMenu = new List<Menu>();
string query = #"SELECT TOP (100) PERCENT dbo.Privilege.Name AS MenuText, dbo.[Right].[Add], dbo.[Right].Edit, dbo.[Right].[Delete], dbo.[Right].[view], dbo.[Right].Status AS Active, dbo.Privilege.URL AS url,
dbo.Privilege.ParentID AS ParentId, dbo.[Right].PrivilegeID AS menu_id, dbo.[Right].UserID, dbo.Company.Code, dbo.Company.Name, dbo.Privilege.ID
FROM dbo.Privilege INNER JOIN
dbo.[Right] ON dbo.Privilege.ID = dbo.[Right].PrivilegeID INNER JOIN
dbo.Module ON dbo.Privilege.ModuleID = dbo.Module.ID INNER JOIN
dbo.Department ON dbo.Module.DepartmentID = dbo.Department.ID INNER JOIN
dbo.Company ON dbo.Department.CompanyID = dbo.Company.ID
WHERE (dbo.[Right].Status = 1) AND (dbo.[Right].UserID = '" + user_id.Trim() + "') AND (dbo.Company.Code = '" + str_company.Trim() + "') AND (dbo.Privilege.Platform = 'Web') AND (dbo.Module.Platform = 'Web') OR (dbo.[Right].Status = 1) AND(dbo.[Right].UserID = '" + user_id.Trim() + "') AND(dbo.Privilege.ParentID IS NULL) ORDER BY dbo.Privilege.Priority, dbo.Privilege.ID";
using (SqlConnection con = Connstring.getcon)
{
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Menu menu = new Menu();
menu.Id = Convert.ToInt32(rdr["menu_id"]);
menu.MenuText = rdr["MenuText"].ToString();
menu.ParentId = rdr["ParentId"] != DBNull.Value
? Convert.ToInt32(rdr["ParentId"]) : (int?)null;
menu.Url = rdr["url"].ToString();
menu.Active = Convert.ToBoolean(rdr["Active"]);
listMenu.Add(menu);
}
}
List<Menu> menuTree = GetMenuTree(listMenu, null);
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(menuTree));
}
public List<Menu> GetMenuTree(List<Menu> list, int? parent)
{
return list.Where(x => x.ParentId == parent).Select(x => new Menu
{
Id = x.Id,
MenuText = x.MenuText,
ParentId = x.ParentId,
Url = x.Url,
Active = x.Active,
List = GetMenuTree(list, x.Id)
}).ToList();
}
public bool IsReusable
{
get
{
return false;
}
}
Here is the javascript code :
var sl = 0;
function buildMenu(parent, items) {
$.each(items, function () {
//alert(this.MenuText);
//var icon = this.icon;
//if (icon == "") {
var icon = 'fa fa-circle-o';
//}
//------------------------------------//
if (this.List && this.List.length > 0) {
var pull_right = '</span><span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span>';
icon = "glyphicon glyphicon-plus-sign";
}
else
pull_right = '';
//------------------------------------//
sl = sl + 1;
span_id = '';
if (this.Url != "") {
span_id = 'id="active_span_m' + sl + '"';
}
else {
span_id = '';
}
//-----------------------------------//
var li = $('<li id="m' + sl + '" onclick="set_menu_active(\'m' + sl + '\')" alt="' + this.Id + '" class="treeview"><i class="' + icon + '"></i><span ' + span_id + '>' + this.MenuText + pull_right + '</li>');
li.appendTo(parent);
if (this.List && this.List.length > 0) {
var ul = $('<ul class="treeview-menu menu-open"></ul>');
ul.appendTo(li);
buildMenu(ul, this.List);
}
});
//---------------Set Session---------------//
var str = $("<div />").append($("#menu").clone()).html();
sessionStorage.setItem("str_menu", str);
}
And Ajax:
$.ajax({
url: '../../../../../CDB/System/Common/Layout/Master/Permission.ashx',
method: 'get',
dataType: 'json',
data: { 'Id': u_s_id, 'str_company': str_company },
success: function (data) {
//alert(data);
buildMenu($('#menu'), data);
$('#menu').menu();
},
error: function (err) {
}
});
Output Image like as
Output image
Now i want to know process of use of this code in asp.net core mvc layout to get dynamic navigation menu

Related

PATCH in web API for Many to Many relationships using EF

I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.
[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
if (id == 0 || patchNoteDTO == null)
return BadRequest();
var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
if (note == null)
return NotFound();
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
patchNoteDTO.ApplyTo(createNoteDTO, ModelState);
if (!ModelState.IsValid)
return BadRequest(ModelState);
Note updateNote = _mapper.Map<Note>(createNoteDTO);
updateNote.ID = id;
updateNote.ChangedDate = DateTime.Now;
_db.Update(updateNote);
if (!field.ToLower().Equals("category"))
_db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
_db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
_db.SaveChanges();
return NoContent();
}
My ApplicationDBContext looks like this:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Write Fluent API configurations here
modelBuilder.Entity<Note>()
.HasOne(e => e.Category)
.WithMany(e => e.Notes)
.HasForeignKey(e => e.FKCategory)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Note>()
.HasMany(n => n.Tags)
.WithMany(t => t.Notes)
.UsingEntity(j => j
.ToTable("NoteTag")
.HasData
(
new { NotesID = 1, TagsTagID = 1 },
new { NotesID = 2, TagsTagID = 2 }
));
modelBuilder.Entity<Category>().HasData
(
new Category
{
CategoryID = 1,
CategoryName = "testCategory1",
CreatedDate = DateTime.Now
},
new Category
{
CategoryID = 2,
CategoryName = "testCategory2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Tag>().HasData
(
new Tag
{
TagID = 1,
TagName = "testTag1",
CreatedDate = DateTime.Now
},
new Tag
{
TagID = 2,
TagName = "testTag2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Note>().HasData
(
new Note
{
ID = 1,
Title = "testTitle1",
Description = "testDescription1",
FKCategory = 1,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
},
new Note
{
ID = 2,
Title = "testTitle2",
Description = "testDescription2",
FKCategory = 2,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
}
);
}
}
Any suggestions?
Thanks in advance.
Initially I tried without the following if condition:
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
But I got a different error:
I wanted to remove a tag form the following object using a PATCH request:
Note Object

Read Data attributes or Custom Attributes in SQL server from string

I want in SQL prepared dynamic query based on the shortcode.
For Eg.
DECLARE #ShortCode VARCHAR(MAX)
SET #ShortCode = '[User data="Name" data="MobileNumber"]';
User = table name
Name = User table field
MobileNumber = User table field
Query output be like
SELECT [Name],[MobileNumber] FROM [dbo].[User]
SET #ShortCode = '[Country data="Name" ID="1"]';
Country = table name
Name = Country table field
ID = User table field
Query output be like
SELECT [Name] FROM [dbo].[Country] WHERE [ID] = 1
How to extract all data attributes values and how to get User in the []
This functionality is done in C#
Here My c# code
// Model class
public class ShortCodeResult
{
public Guid? ID { get; set; }
public string TableName { get; set; }
public bool IsValidShortCode { get; set; }
public string Message { get; set; }
public Dictionary<string,object> KeyValue { get; set; }
public ShortCodeResult() {
KeyValue = new Dictionary<string, object>();
ID = Guid.NewGuid();
}
}
//Regex Filter
public class RegexFilter
{
private string oPattern = #"(\w+)=[\""]([a-zA-Z0-9_.:\""]+)";
public ShortCodeResult GetShortCodeValues(string Code)
{
var oShortCodeModel = new ShortCodeResult();
var oRegex = new Regex(oPattern, RegexOptions.IgnoreCase);
var oTableNameRegex = Regex.Match(Code, #"\b[A-Za-z]+\b", RegexOptions.Singleline).Value;
var lstMatchCollection = oRegex.Matches(Code).Cast<Match>().Where(x=>x.Value.StartsWith("data")).ToList();
if (lstMatchCollection != null && lstMatchCollection.Count > 0)
{
for (int i = 0; i < lstMatchCollection.Count; i++)
{
var oSelected = new Regex("[^=]+$").Match(Convert.ToString(lstMatchCollection[i]));
if (oSelected != null)
{
oShortCodeModel.KeyValue.Add(i.ToString(), oSelected.Value.Trim('"'));
}
}
}
oShortCodeModel.TableName = oTableNameRegex;
return oShortCodeModel;
}
}
//HtmlHelper Extension
public static MvcHtmlString RenderShortCode(this HtmlHelper htmlHelper, string IdOrExprssion)
{
#region Get short code data
var oShortCode = ShortCodeHelper.GetShortCode(IdOrExprssion);
#endregion
var oMvcHtmlString = new MvcHtmlString(IdOrExprssion);
var oRegexFilter = new RegexFilter();
var shortCodeModel = oRegexFilter.GetShortCodeValues(oShortCode.Expression);
var ostringBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(shortCodeModel.TableName))
{
ostringBuilder.AppendLine("SELECT ");
ostringBuilder.AppendLine((shortCodeModel.KeyValue.Count > 0 ? string.Join(",", shortCodeModel.KeyValue.Select(x => x.Value)) : "*"));
ostringBuilder.AppendLine(" FROM ");
ostringBuilder.AppendLine(oShortCode.TableName);
ostringBuilder.AppendLine(" WITH(NOLOCK) ");
if (oShortCode.FilterCode.Count() > 0)
{
ostringBuilder.AppendLine("WHERE ");
foreach (var filterCode in oShortCode.FilterCode)
{
ostringBuilder.AppendLine(filterCode.FilterColumnName);
ostringBuilder.AppendLine(filterCode.Operator);
ostringBuilder.AppendLine(filterCode.FilterColumnValue);
}
}
}
var oDyanamicData = DBHelper.GetDataTable(ostringBuilder.ToString(), System.Data.CommandType.Text, new List<SqlParameter>());
if (oDyanamicData != null)
{
if (oShortCode.IsHtmlRender)
{
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
string key = Convert.ToString(oDyanamicData.Columns[j]);
string value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
if (oShortCode.DisplayCode.Count > 0)
{
var displayCode = oShortCode.DisplayCode.FirstOrDefault(x => x.DisplayColumnName == key);
if (displayCode != null && !string.IsNullOrEmpty(displayCode?.ReplaceKey))
{
oShortCode.DefinedHtml = oShortCode.DefinedHtml.Replace(displayCode.ReplaceKey, value);
}
}
}
}
return new MvcHtmlString(oShortCode.DefinedHtml);
}
else
{
string key = string.Empty, value = string.Empty;
#region For Json
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
key = Convert.ToString(oDyanamicData.Columns[j]);
value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
return new MvcHtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(dataList));
#endregion
}
}
return oMvcHtmlString;
}
Can anyone help me solved above in SQL server or prepared query in store procedure

Entity framework in order

Sourcefile and file name are the source path . Archive folder and the archive filename is the destination folder . The value of the input file should be moved to the destination file.Getting error while copying file from source to destination. Showing "File has been already created". Please let me know how to find the directory of a source file without hardcode. How can I write the valid details in another file in the XML Format.
using System; using System.Collections.Generic;using System.IO;
using System.Linq;using System.Security; using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using EmployeeValidation;
using static EmployeeValidation.FundsValidatorException;
namespace FundsValidator
{
public class empValidator
{
public bool ProcessData(string sourceFolder, string fileName, string archiveFolder, string archiveFileName, SqlConnection connection)
{
List<Order> Orders = ReadAllDataFromInputFile(sourceFolder,fileName);
//Step 2
//SetValidationFlag
List<Order> ValidOrder = SetValidationFlag(Orders);
//Step 3
//InsertOrderData
bool insertBit = InsertOrderData(ValidOrder, connection);
//Step 4
//GetProductsCommission
DataTable dtprodcomm = GetProductsCommission(connection);
//Step 5
//archive file
bool archive = CopyToArchive( sourceFileName, sourceFilePath, archiveFileName, archiveFilePath)
return true;
}
public List<Order> ReadAllDataFromInputFile(string sourceFolder, string fileName)
{
List<Order> inputlist = null;
{
try
{
inputlist = new List<Order>();
var inputlines = File.ReadAllLines(sourceFolder + fileName);
foreach (var item in inputlines)
{
string[] datas = item.Split(',');
Order orderdetails = new Order()
{
OrderId = datas[0],
SalesPersonId = datas[1],
OrderDate = Convert.ToDateTime(datas[2]).ToShortDateString(),
ModelNbr = datas[3],
Quantity = datas[4],
CustomerId = datas[5],
DeliveryDate = datas[6]
};
inputlist.Add(orderdetails);
}
}
catch(OrderProcessorException)
{
throw new OrderProcessorException();
}
}
return inputlist;
}
public List<Order> SetValidationFlag(List<Order> Orders)
{
List<Order> validList = null;
validList = new List<Order>();
int num = 0;
DateTime dtOrderdate;
DateTime dtdeliverydate;
if (Orders != null && Orders.Count >0)
{
foreach(var item in Orders)
{
if(int.TryParse(item.OrderId, out num) &&
item.SalesPersonId.StartsWith("SP") && item.SalesPersonId.Substring(2).Length == 3 && int.TryParse(item.SalesPersonId.Substring(2), out num) &&
DateTime.TryParse(item.OrderDate, out dtOrderdate) &&
item.ModelNbr.StartsWith("ML") && item.ModelNbr.Substring(2).Length == 3 && int.TryParse(item.ModelNbr.Substring(2), out num) &&
int.TryParse(item.Quantity, out num) && DateTime.TryParse(item.DeliveryDate, out dtdeliverydate) && (Convert.ToDateTime(item.DeliveryDate) - Convert.ToDateTime(item.OrderDate)).TotalDays > 7)
{
item.ValidFlag = "V";
}
else
{
item.ValidFlag = "E";
}
validList.Add(item);
}
}
return validList;
}
public bool InsertOrderData(List<Order> Orders, SqlConnection connectionString)
{
bool bret = true;
{
if(Orders !=null && Orders.Count >0)
{
foreach(var item in Orders)
{
using (SqlCommand command = connectionString.CreateCommand())
{
command.CommandText = "Insert into SBA.Orders(OrderId,SalesPersonId,OrderDate,ModelNbr,Quantity,CustomerId,Deliverydate,ValidFlag) Values('" + item.OrderId + "','" + item.SalesPersonId + "','" + item.OrderDate + "','" + item.ModelNbr + "','" + item.Quantity + "','" + item.CustomerId + "','" + item.DeliveryDate + "','" + item.ValidFlag + "')";
command.Connection = connectionString;
connectionString.Open();
int count = command.ExecuteNonQuery();
connectionString.Close();
if (count > 0)
{
bret = true;
}
else
bret = false;
}
}
}
else
{
bret = false;
}
}
return bret;
}
public DataTable GetProductsCommission(SqlConnection connectionString)
{
DataTable dtProductsCommission = null;
using (SqlCommand command = connectionString.CreateCommand())
{
command.CommandText = "Select ModelNbr,Commission_Percentage,Base_Price from SBA.Product_Commission";
command.Connection = connectionString;
connectionString.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
dtProductsCommission = ds.Tables[0];
}
return dtProductsCommission;
}
public bool InsertCommissionData(List<Order> Orders, DataTable dtProductsCommission, SqlConnection connectionString)
{
bool bret = true;
if (Orders != null && Orders.Count > 0 && dtProductsCommission.Rows.Count > 0)
{
foreach (var item in Orders)
{
if (item.ValidFlag == "V")
{
foreach (DataRow dr in dtProductsCommission.Rows)
{
float commamt = Convert.ToInt32(dr["Commission_Percentage"]) * Convert.ToInt32(dr["Base_Price"]) * Convert.ToInt32(item.Quantity);
using (SqlCommand cmd = connectionString.CreateCommand())
{
cmd.CommandText = "Insert into SBA.Order_Commission(OrderId,CommissionAmt) Values('" + item.OrderId + "','" + commamt + "')";
connectionString.Open();
cmd.ExecuteNonQuery();
connectionString.Close();
bret = true;
}
}
}
}
}
else
{
bret = false;
}
return bret;
}
public bool CopyToArchive(string sourceFileName, string sourceFilePath, string archiveFileName, string archiveFilePath)
{
bool bret = true;
if(!File.Exists(archiveFilePath + archiveFileName))
{
File.Copy(sourceFilePath + sourceFileName, archiveFilePath + archiveFileName);
}
else
{
File.Delete(archiveFilePath + archiveFileName);
File.Copy(sourceFilePath + sourceFileName, archiveFilePath + archiveFileName);
}
return bret;
}
}
}
I have fixed this problem.Please refer this program for more details
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using System.Xml;
namespace EmployeeValidation
{
public class FundsValidator
{
public void ProcessData(string FilePath, string FileName, SqlConnection connection, string errorFilename, string errorFilepath)
{
List<Funds> Alllstfunds = new List<Funds>();
List<Funds> Validlstfunds = new List<Funds>();
Alllstfunds= ReadValuesfromInputfile(FilePath, FileName);
Validlstfunds = GetValidFunds(Alllstfunds, errorFilename, errorFilepath);
SaveValidListToDB(Validlstfunds,connection);
List<Funds> Removeddup= GerPerFundDetails(Validlstfunds);
CalculateNavandSaveToDatabase(Removeddup,connection);
}
public List<Funds> ReadValuesfromInputfile(string FilePath, string FileName)
{
List<Funds> AllListfunds = new List<Funds>();
string s1= null;
StreamReader sw = File.OpenText(FilePath + FileName);
while ((s1 = sw.ReadLine()) != null)
{
Funds fund = new Funds();
string[] s = s1.Split(',');
fund.FundsID = s[0].ToString();
fund.SubfundID = s[1].ToString();
fund.Asset = s[2].ToString();
fund.La = s[3].ToString();
fund.o = s[4].ToString();
AllListfunds.Add(fund);
}
return AllListfunds;
}
public List<Funds> GetValidFunds(List<Funds> Alllstfunds, string errorFilename,string errorFilepath)
{
try
{
List<Funds> validlist = new List<Funds>();
List<Funds> Invalid = new List<Funds>();
foreach (Funds x in Alllstfunds)
{
bool valid = true;
valid = valid && (!string.IsNullOrEmpty(x.FundsID) && x.FundsID.StartsWith("F")) && x.FundsID.Length == 4 && x.FundsID.Substring(1).Length == 3 && x.FundsID.Substring(1).All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.SubfundID)) && x.SubfundID.StartsWith("SF") && x.SubfundID.Length == 5 && x.SubfundID.Substring(2).Length == 3 && x.SubfundID.Substring(2).All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.Asset)) && x.Asset.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.La)) && x.La.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.o)) && x.o.All(char.IsDigit);
if (valid)
{
validlist.Add(x);
}
else
{
Invalid.Add(x);
}
}
SaveInValidinErrorTxt(Invalid, errorFilename, errorFilepath);
return validlist;
}
catch (Exception ex)
{
throw new FundsValidatorException(ex.Message);
}
}
public void SaveInValidinErrorTxt(List<Funds> Invalid,string errorFilename,string errorFilepath)
{
if (Invalid.Count > 0 && Invalid != null)
{
if (!File.Exists(errorFilepath + errorFilename))
{
var i=File.Create(errorFilepath + errorFilename);
i.Close();
}
StreamWriter sw = File.AppendText(errorFilepath+errorFilename);
foreach (Funds f in Invalid)
{
sw.WriteLine(f.FundsID+","+f.SubfundID+","+f.Asset+","+f.La+","+f.o);
}
sw.Flush();
sw.Close();
}
}
public void SaveValidListToDB(List<Funds> Validlstfunds, SqlConnection connection)
{
try
{
foreach (Funds f in Validlstfunds)
{
connection.Open();
SqlCommand cmd = new SqlCommand(("Insert into SBA.Fund_Details (FundId,SubFundId,Assets,Liabilities,OutstandingShares) Values ( '" + f.FundsID + "','" + f.SubfundID + "','" + f.Asset + "','" + f.La + "','" + f.o + "')"), connection);
int i = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
}
}
catch (Exception ex)
{
throw new FundsValidatorException(ex.Message);
}
}
public List<Funds> GerPerFundDetails(List<Funds> Validlists)
{
List<string> s = new List<string>();
List<Funds> RemoveDup = new List<Funds>();
String[] r = (from a in Validlists
select a.FundsID).Distinct().ToArray();
foreach (String x in r)
{
int assetnum = 0;
int lanum = 0;
int onum=0;
foreach (Funds q in Validlists)
{
if (x.ToString() == q.FundsID)
{
assetnum = assetnum + int.Parse(q.Asset);
lanum=lanum+int.Parse(q.La);
onum=onum+int.Parse(q.o);
}
}
Funds f= new Funds();
f.FundsID=x.ToString();
f.Asset=assetnum.ToString();
f.La=lanum.ToString();
f.o= onum.ToString();
RemoveDup.Add(f);
}
return RemoveDup;
}
public void CalculateNavandSaveToDatabase(List<Funds> Removeddup,SqlConnection connection)
{
List<Funds> NAVClaculated = new List<Funds>();
foreach(Funds item in Removeddup)
{
item.NAV= (float)(Math.Round(((float.Parse(item.Asset) - float.Parse(item.La))/(float.Parse(item.o))),2));
NAVClaculated.Add(item);
}
foreach (Funds f in NAVClaculated)
{
connection.Open();
SqlCommand cmd = new SqlCommand(("Insert into SBA.Nav_Report (FundId,Assets,Liabilities,OutstandingShares,Nav) Values ( '" + f.FundsID + "','" + f.Asset + "','" + f.La + "','" + f.o +"','"+f.NAV+ "')"), connection);
int i = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
}
}
}
}
namespace Tarriffs
{
public class Tariff
{
public string UserId { get; set; }
public string UserName { get; set; }
public string Category { get; set; }
public string LastMeterReading { get; set; }
public string CurrentMeterReading { get; set; }
public string ReadingDate { get; set; }
public string NoofUnits { get; set; }
public string CalculatedAmount { get; set; }
}
class Program
{
static void Main(string[] args)
{
string inputfile = #"D:\Tarriffs\Input file\Tarriff_0919.txt";
List<Tariff> read = new List<Tariff>();
StreamReader sr = File.OpenText(inputfile);
string s= null;
while((s= sr.ReadLine())!=null)
{
string[] item = s.Split(',');
Tariff tar = new Tariff();
tar.UserId= item[0];
tar.UserName= item[1];
tar.Category= item[2];
tar.LastMeterReading= item[3];
tar.CurrentMeterReading= item[4];
tar.ReadingDate= item[5];
bool valid = validandlogger(tar.UserId, tar.UserName, tar.Category, tar.LastMeterReading, tar.CurrentMeterReading, tar.ReadingDate);
if (valid)
{
double[] tarriffcalculation = tarriffcalc(tar.LastMeterReading, tar.CurrentMeterReading);
Tariff final = new Tariff();
final.UserId = item[0];
final.UserName = item[1];
final.NoofUnits = tarriffcalculation[0].ToString();
final.CalculatedAmount = tarriffcalculation[1].ToString();
SqlConnection conn= new SqlConnection(#"Data Source=NA03OSDVP00746\SQLEXPRESS;Initial Catalog=DBTarriffValidation;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into dbo.custom values ('" + final.UserId + "','" + final.UserName + "','" + final.NoofUnits + "','" + final.CalculatedAmount + "')", conn);
int i = cmd.ExecuteNonQuery();
conn.Close();
}
}
}
public static bool validandlogger(string UserId, string UserName, string Category, string LastMeterReading, string CurrentMeterReading, string ReadingDate)
{
bool valid = true;
DateTime dt;
Regex name = new Regex("^[a-zA-Z0-9]{6}$");
valid = valid && (!string.IsNullOrEmpty(UserId)) && UserId.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(UserName)) && name.IsMatch(UserName);
string[] vcategory = { "COM", "DOM", "OTD" };
valid = valid && vcategory.Contains(Category);
valid = valid && LastMeterReading.All(char.IsDigit);
valid = valid && CurrentMeterReading.All(char.IsDigit);
valid = valid && DateTime.TryParseExact(ReadingDate, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (!valid)
{
string errortextfile = #"D:\Tarriffs\Error_log\";
string errorfile = "Error_"+DateTime.Now.ToString("MMyyyy")+".txt";
if (!File.Exists(errortextfile + errorfile))
{
var i = File.Create(errortextfile + errorfile);
i.Close();
}
StreamWriter sw = File.AppendText(errortextfile + errorfile);
sw.WriteLine(UserId + "," + UserName + "," + Category + "," + LastMeterReading + "," + CurrentMeterReading + "," + ReadingDate);
sw.Flush();
sw.Close();
}
else
{
return true;
}
return false;
}
public static double[] tarriffcalc(string LastMeterReading, string CurrentMeterReading)
{
int LMeterReading = 0;
int CMeterReading = 0;
LMeterReading = int.Parse(LastMeterReading);
CMeterReading = int.Parse(CurrentMeterReading);
int units = CMeterReading - LMeterReading;
double totalamount = 0;
if (units <= 100)
{
var baserate = 20;
totalamount = (units * 1) + baserate;
}
else if (units <= 200)
{
var baserate = 20;
totalamount = (units * 1.5) + baserate;
}
else if (units <= 500)
{
var baserate = 40;
totalamount = 250 +((units-200)*3)+baserate;
}
else if (units > 500)
{
var baserate = 40;
totalamount = 1700 + ((units - 500) * 5.75) + baserate;
}
return new double[] {units,totalamount};
}
}
}

Getting all the Term Stores in Sharepoint 2010 (web services or client-side object model)?

Is it possible with Sharepoint 2010 (not 2013!) to get a list of all the Term Stores on the site using either the web services or the client-side object model?
I know 2013 has added a library for it, but that will not help me on 2010.
If not the whole list, how do I get the Term Store ID, if I know a Term (that might or might not be in the TaxonomyHiddenList)?
Someone mentioned checking out the TaxonomyFieldType fields, so I hacked together these 2 methods. I do not know if these will work under all circumstances.
First function just returns the Term Store ID which is stored in the info of the first TaxonomyFieldType* we come over.
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
The second function goes through all the fields and gets all the possible Term Store IDs and returns them in a list.
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
Is this a correct answer to my question do anyone have a more sure way to get the IDs?
Does not seem like anyone else has a good answer for this question.
I have added the utility class I made from this below. Big block of uncommented code below for those who might need:
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;
namespace VitaminTilKanbanPusher.Sharepoint {
public class SharepointTaxonomyAgent {
//URLS:
//http://www.novolocus.com/2012/02/06/working-with-the-taxonomyclientservice-part-1-what-fields-are-there/
//
public static void Test() {
var site = ConfigurationManager.AppSettings["VitaminSite"];
//var list = ConfigurationManager.AppSettings["VitaminList"];
//var id = GetDefaultTermStore(site);
//var ids = GetTermStores(site);
var rs = GetAllTermSetNames(site);
var ts = GetTermSetTerms(site, "Some Name");
//var ts = GetTermSetTerms(site, "Some other name");
//var term = GetTermInfo(site, "Priority");
//var term2 = GetTermInfo(site, "My term");
//var termset = GetTermSetInfo(site, "My term");
//var termsets = GetTermSets(site, "My term");
}
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
//field.InternalName== "TaxKeyword" -> possibly default?
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
private static List<TermSet> _termSets;
public static List<TermSet> GetAllTermSetNames(string site, string onlySpecificTermSetName = null) {
if (_termSets != null) {
if (onlySpecificTermSetName == null) return _termSets;
foreach (var ts in _termSets) {
if (ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
return new List<TermSet>() { ts };
}
}
return new List<TermSet>();
}
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
var termSets = new List<TermSet>();
TermSet theChosenTermSet = null;
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var ts = new TermSet();
var doc = XDocument.Parse(field.SchemaXml);
var fn = doc.Element("Field");
if (fn == null) continue;
if (fn.Attribute("DisplayName") == null) continue;
if (fn.Attribute("ID") == null) continue;
ts.Name = fn.Attribute("DisplayName").Value;
//Only 1 set?
if (onlySpecificTermSetName != null) {
if (!ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
theChosenTermSet = ts;
}
}
if (fn.Attribute("Description") != null) {
ts.Description = fn.Attribute("Description").Value;
}
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
ts.TermStoreId = node.Value;
}
var node2 = doc.XPathSelectElement("//Name[text()='TermSetId']/../Value");
if (node2 != null && !string.IsNullOrEmpty(node2.Value)) {
ts.Id = node2.Value;
}
else {
continue; //No ID found
}
//Unique hites
if (!hashlist.Contains(ts.Id)) {
hashlist.Add(ts.Id);
termSets.Add(ts);
}
}
}
_termSets = termSets;
if (onlySpecificTermSetName != null) return (theChosenTermSet == null ? new List<TermSet>() : new List<TermSet>() { theChosenTermSet });
return termSets;
}
public static TermSet GetTermSetTerms(string site, string termName) {
var ts = GetAllTermSetNames(site, termName);
if (ts.Count == 0) throw new Exception("Could not find termset: " + termName);
var theTermSet = ts[0];
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var clientTime = DateTime.Now.AddYears(-2).ToUniversalTime().Ticks.ToString();
var termStoreId = new Guid(theTermSet.TermStoreId);// Guid.Parse(theTermSet.TermStoreId);
var termSetId = new Guid(theTermSet.Id);
string clientTimestamps = string.Format("<timeStamp>{0}</timeStamp>", clientTime);
string clientVersion = "<version>1</version>";
string termStoreIds = string.Format("<termStoreId>{0}</termStoreId>", termStoreId.ToString("D"));
string termSetIds = string.Format("<termSetId>{0}</termSetId>", termSetId.ToString("D"));
string serverTermSetTimestampXml;
string result = proxy.GetTermSets(termStoreIds, termSetIds, 1033, clientTimestamps, clientVersion, out serverTermSetTimestampXml);
var term = ParseTermSetInfo(result);
term.Description = theTermSet.Description;
term.Id = theTermSet.Id;
term.Name = theTermSet.Name;
return term;
}
//public static Term GetTermSetInfo(string site, string termName) {
// var proxy = new SharepointTaxWS.Taxonomywebservice();
// proxy.UseDefaultCredentials = true;
// proxy.PreAuthenticate = true;
// proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
// GetAuthCookie(proxy, site);
// var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
// var sets = proxy.GetChildTermsInTermSet(Guid.Parse(""), lciden, Guid.Parse("termsetguid"));
// var term = ParseTermInfo(sets);
// return term;
//}
public static Term GetTermInfo(string site, string termName) {
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var sets = proxy.GetTermsByLabel(termName, lciden, SharepointTaxWS.StringMatchOption.StartsWith, 100, null, false);
var term = ParseTermInfo(sets);
return term;
}
private static TermSet ParseTermSetInfo(string xml) {
//Not done
var info = XDocument.Parse(xml);
var ts = new TermSet();
ts.Terms = new List<Term>();
var n1 = info.XPathSelectElements("//T");
if (n1 != null) {
foreach (var item in n1) {
var t = new Term();
t.Id = item.Attribute("a9").Value;
t.Name = item.XPathSelectElement("LS/TL").Attribute("a32").Value;
t.TermSet = ts;
ts.Terms.Add(t);
}
}
return ts;
}
private static Term ParseTermInfo(string xml) {
var info = XDocument.Parse(xml);
var t = new Term();
var ts = new TermSet();
var n1 = info.XPathSelectElement("TermStore/T");
var n2 = info.XPathSelectElement("TermStore/T/LS/TL");
var n3 = info.XPathSelectElement("TermStore/T/TMS/TM");
if (n1 != null && n1.Attribute("a9") != null) {
t.Id = n1.Attribute("a9").Value;
}
if (n2 != null && n2.Attribute("a32") != null) {
t.Name = n2.Attribute("a32").Value;
}
if (n3 != null && n3.Attribute("a24") != null) {
ts.Id = n3.Attribute("a24").Value;
}
if (n3 != null && n3.Attribute("a12") != null) {
ts.Name = n3.Attribute("a12").Value;
}
t.TermSet = ts;
return t;
}
private static CookieCollection _theAuth;
private static bool _bNoClaims;
static void GetAuthCookie(SoapHttpClientProtocol proxy, string site) {
return;
//if (_bNoClaims) {
// return; //Ingen claims.
//}
//// get the cookie collection - authentication workaround
//CookieCollection cook = null;
//try {
// if (_theAuth == null) {
// cook = ClaimClientContext.GetAuthenticatedCookies(site, 925, 525);
// }
// else {
// cook = _theAuth;
// }
// _theAuth = cook;
// _bNoClaims = false;
//}
//catch (ApplicationException ex) {
// if (ex.Message.Contains("claim")) _bNoClaims = true;
// Console.Write("Auth feilet: " + ex.Message + " - ");
// //IGNORE
//}
//if (_theAuth != null) {
// proxy.CookieContainer = new CookieContainer();
// proxy.CookieContainer.Add(_theAuth);
//}
}
static void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e) {
//add the header that tells SharePoint to use Windows Auth
e.WebRequestExecutor.RequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
}
public class TermSet {
public string Id { get; set; }
public string Name { get; set; }
public List<Term> Terms { get; set; }
public string TermStoreId { get; set; }
public string Description { get; set; }
public override string ToString() {
int tc = 0;
if (Terms != null) tc = Terms.Count;
return Name + "|" + Id + " (" + tc + "terms)";
}
}
public class Term {
public string Id { get; set; }
public string Name { get; set; }
public TermSet TermSet { get; set; }
public override string ToString() {
return Name + "|" + Id;
}
}
}

Why does this controller double the inserts when I try to archive the results of the Bing Search API?

I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.