Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all 1698 articles
Browse latest View live

Linq to Sql Framework 4

$
0
0

Hi,

I'm using Linq-To-Sql.

Given the following code:

casefile.cs

publicpartialclasscasefile
{
     publicstaticint getCaseId(string asCaseNumber)
  
{
           int aiCaseId = -1;

    
using (CMSDataContext dc =new CMSDataContext())
    
{
                 aiCaseId = (from cin dc.casefile
                    
where c.case_nbr == asCaseNumber
                   
select c.case_id).FirstOrDefault();

        if (aiCaseId ==null || aiCaseId < 1)       
                {
                       thrownewException(String.Concat("Case Number ", asCaseNumber, " not found."));
       
}
          }

  return aiCaseId;
}
}

WebFormCMSCopyCommentEvent.aspx.cs

publicpartialclassWebFormCMSCopyCommentEvent : System.Web.UI.Page
{

      protectedvoid ButtonShowRecords_Click(object sender,EventArgs e)         
            {
                    //validate CaseIds
          
int aiCaseId1 =casefile.getCaseId(TextBoxCaseNo1.Text); errors here => CS0117: casefile does not get a definition for 'getCaseId'

      }
}

}

Thanks,

tinac99


Problem with inserting with a large db

$
0
0

Hi,

I have one table with large data around 1mio rows but if i have a large data why taking so long for next inserting data?
Is possible increase for fast?

Regards

Error using Contains

$
0
0

I have two entities in the model, Audit and Audit_Measure. They are in a many to many relationship which is reflected in the model.
i.e. Audit has a virtual ICollection Audit_Measures, and Audit_Measure has a corresponding virtual ICollectionAudits.

I am trying to return a list of Audit_Measures, for a particular Audit.

Assuming the usual try..catch..using etc, the code is:

audit_measures_in_audit = await db.Audit_Measures
                        .Where(am => am.Audits.Contains(audit))
                        .ToListAsync();

It's falling over on the 'Contains' clause with an exception:
"Unable to create a constant value of type 'CACS_GNS_Data.Models.Audit'. Only primitive types or enumeration types are supported in this context.."

I have since managed to get around it, but am not sure why I am getting the error.
Surely this is why the virtual collections exist in the model.

Thanks

How to compare tow list of object ?

$
0
0

Hello all,

imagine this scenario, i have a device when the user connect i call a web service and get some resutl

IEnumerable<someObject>

i insert all content into the database all works fine.

Now, we add in the back end some new object, modify, update, delete and so on ...

user make a log off, when user connect again i call again the web service and get the new IEnumerable<someObject>

I would like to know i can make a find the DIFFERENCE between these two objects ?

because i need to insert some news, and delete some old ...

I've try that, but that's work only if i have some new object IN the wsDatas

//a: get datas from db
                    var dbDatas = from db in xxx.SelectAll<someObject(true)
                                  select new { db.ProfileCode, db.ProductCode, db.CategoryCode, db.OptionCode };

//b: get data from web service
                    var wsDatas = from ws in datas
                                  select new { ws.ProfileCode, ws.ProductCode, ws.CategoryCode, ws.OptionCode };

                    // compare
                    var newDatas = wsDatas.Except(dbDatas);

of course, i can delete all datas and replace all but i would like to know how to find difference between two list of objects

thanks in advance

Sql Script

$
0
0

Hi

  I am executing sql script it is giving me error 'An unhandled exception of type System.Outofmemoryexecption' occurred in mscorlib.dll. File size is more than 10 G.B

Thanks

IIS 6.0 Session Timeout Vs Web.Config Timeout Vs App pool Idle time out

$
0
0

I want to increase the session timing of my ASP.NET web App hosted in IIS 6.0. So, I changed the SessionState timing to 600 mins in web.config of the site. But it didn't work and my session times out like in an hour.(Session["myVariable"] == null)

<system.web><sessionState timeout="600"/></system.web>

Now I tried setting the Timeout value in IIS website where this application is hosted by going to website -> Properties -> Home Directory Tab -> Configuration button -> Options tab and changin it to 600 mins, still no luck. The question here says that this is for classic ASP Pages but not for ASP.NET web sites. which means that I am doing it wrong.

Then I checked the app pool under which this application runs (app Pool->Properties-->Performance tab). This says "Recycle Worker Process(in minutes)" as 10 mins. I read many questions on SO but none of them gives a clear cut answer on how to increase the session timeout on ASP.NET WebApp.

I want to know the difference between these three settings and when to use which and how do we increase the session timeout of my webApp.

I know I can use other session state methods like StateServer and SQL Server but It could be quite laborious for me to change the way each session variable is accessed. More over Session_End method doesn't fire in StateServer mode which Ia m using for some resource cleaning.

So, overall i am looking to extend the session time to 600 mins with INPROC session mode which is not working. Any pointers on that and help me understand the best option possible

ASP.NET with WebForm C# project,Create Entity Framework 6 DbContetxt Generator appear an error

$
0
0

My project is ASP.NET with WebForm C#. I install Oracle Developer Tools for Visual Stduio 2017. I create an Entity Framework 6 DbContext Generator, but Visual Studio Professional disappears an error as below. Does somebody know how to solve this problem?

Error           Transforming in progress: Override the Substitute Substitution Primitives with the actual name from which you generated the .edmx file '$edmxInputFile$'. eBook.csharp D:\MyWeb\eBookHis5\eBook.CSharp\ModelOracle.tt 1 
錯誤  正在執行轉換: 請使用您要從中產生 .edmx 檔的實際名稱,覆寫替代語彙基元 '$edmxInputFile$'。 eBook.csharp D:\MyWeb\eBookHis5\eBook.CSharp\ModelOracle.tt 1 

No column name was specified for column 1 of 'T'.

$
0
0

Hi,

after add SELECT MAX I got: No column name was specified for column 1 of 'T'.

My sql:

			SELECT MatchId,COUNT(OddsType)
		FROM
		(
	SELECT MAX(TS.SuggestionId),TS.MatchId,TS.OddsType
			FROM [dbo].[tbl_Suggestions] TS
			INNER JOIN dbo.tbl_Matches TM ON TS.MatchId=TM.MatchId AND TM.SportId = 1 AND  TM.Isopen=1 AND TS.Isopen=1
			INNER JOIN dbo.tbl_OddsTypes OT ON OT.OddsTypeId=TS.OddsType AND OT.SportID=1
						AND TS.IsLatest=1 AND TM.StatusInfoOff=0
			WHERE TS.OutCome!='-1' AND TM.SportId=1 AND TM.MatchDate >= GETDATE() AND TM.CountSuggestion > 0 --AND DATEDIFF(hh,GETDATE(),TM.MatchDate) <=24
			GROUP BY TS.MatchId,TS.OddsType
		) AS T
		GROUP BY MatchId


SQL last record

$
0
0

Hi,

I have a large database and I want to retrieve last record.

Example:
Id, FirstName, LastName
1, firstname1, lastname1
2, firstname1, lastname1
3, firstname1, lastname1
4, firstname2, lastname2
5, firstname3, lastname3
6, firstname3, lastname3
7, firstname4, lastname4

I need to get:
Id, FirstName, LastName
3, firstname1, lastname1
4, firstname2, lastname2
6, firstname3, lastname3
7, firstname4, lastname4

How can I do with mssql?









Show all the Expences each Department

$
0
0

Good day to all,

Goal: I am sure there is a better way of doing this and would be appreciate this learning opportunity.

I have list of product requested items and i want to compute theirexpense each department based on daterequested for7 days or a week , and I want to create abudgetController to display all theexpences ,budget , balance each departments for7days or a week  , and we can also able to input the budget each department per week and save it,

I have three tables,kindly refer below.

TRANSACTIONISSUEDITEMS - list of product reqquested.TRANSACTIONISSUEDITEMS -TABLESREQUESTNO	ITEM	         QTY	COST	   TOTALCOST	DATEREQUESTED 	DEPARTMENTS
10118193	ZMV49000336010	2500	0.01968	   49.2	           4-Jan-18	 IT_Department
10118193	ZMV49000256010	10000	0.01968	   196.8	   5-Jan-18	 IT_Department
10218194	100-472-0	2	2.51	   5.02	           5-Jan-18	 IT_Department
10218195	ZGA74000312622	20000	0.016483   329.66	   6-Jan-18	 IT_Department
10218195	ZGA74000450160	12000	0.027388   328.656	   6-Jan-18      IT_Department
10218195	ZMV74000301001	12000	0.0775	   930	           6-Jan-18	 IT_Department
10218195	ZMV74000300110	19200	0.04236	   813.312	   7-Jan-18    	 IT_Department
10317002	GRAPHPAPER-002	1	47.33535   47.33535	   8-Jan-18	 Sample_Department
10317003	BONDPAPER-002	2	2.87134	   5.74268	   8-Jan-18	 Sample_Department
10317003	N08177G001	50	0.15056	   7.528	   9-Jan-18	 Sample_Department
10317003	N08179G001      100	0.20889	   20.889	   9-Jan-18	 Sample_Department
10317003	N08179G001	50	0.20809    10.4045  	   10-Jan-18	 Sample_Department
10317003	CARRIERTAPE-019	1	44.04027   44.04027        12-Jan-18	 Sample_Department
10317003	CARRIERTAPE-028	1	23.50145   23.50145        14-Jan-18	 Sample_Department
10317003	CARRIERTAPE-056	3	25.67001   77.01003        14-Jan-18	 Sample_Department
BUDGETDEPARTMENTS - assign each department budgetBUDGETDEPARTMENTS - TABLESMONTH WORKWEEK YEAR DEPARTMENTID DATEINSERTED BUDGET
FISCALYEAR- fiscal we can upload a calendar, we have a separate calendar kindly my screenshot link below . https://imgur.com/a/VbluB - Calendar 1
https://imgur.com/a/ljkCd - Calendar 2 FISCALYEAR - TABLESMONTH YEAR WORKWEEK STARTDATE ENDDATE

Could you please help me to revised my code Adding saving data in Index Controller

Controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using WarehouseRtoRSystem.Models;
using WarehouseRtoRSystem.BusinessLayer.EDMX;
using OfficeOpenXml;
using System.Drawing;
using OfficeOpenXml.Style;
using WarehouseRtoRSystem.Models.Budget;
using System.Globalization;

namespace WarehouseRtoRSystem.Controllers
{
    [Authorize]
    public class BudgetController : Controller
    {
        private readonly RoleDataContext _roleDataContext = new RoleDataContext();
        private readonly RoleAuthentication authenticate = new RoleAuthentication();
        private readonly BudgetContext BudgetDb = new BudgetContext();
        private readonly DepartmentContext DepartmentDB = new DepartmentContext();
        private readonly EmployeeContext _employeeContext = new EmployeeContext();
        private readonly InventoryContext inv = new InventoryContext();



        public ActionResult Index()
        {
            ViewBag.month1 = 1;
            ViewBag.month2 = 12;
            ViewBag.year = 2018;
            ViewBag.DepName = "DepName";
            ViewBag.DepID = "1";

            BudgetContext db = new BudgetContext();
            var listSelectitem = db.List().Select(x => x.DEPARTMENTID).Distinct();
            List<SelectListItem> ddllist = new List<SelectListItem>();
            foreach (string bvm in listSelectitem)
            {
                ddllist.Add(new SelectListItem
                {

                    Text = bvm,
                    Value = bvm
                });
            };

            ViewBag.DeptList = ddllist;
            var list = db.List().Where(b => b.DEPARTMENTID.Contains("DepName") && b.MONTH >= 1 && b.MONTH <= 12 && b.YEAR == 2018).ToList();
            return View(list);
        }



        // POST: /Budget/
        [HttpPost]
        public ActionResult Index(string DepName , int day = 1, int month1 = 1, int month2 = 12, int year = 2018)
        {
            //check if the user has an Account
            if (!RoleAuthentication.HasAccount(User.Identity.GetUserName()))
            {
                return RedirectToAction("Create", "Employee");
            }
            //check if the user is a requestor
           if (!RoleAuthentication.IsAuthenticated(User.Identity.GetUserName(), "6"))
            {
                return RedirectToAction("Index", "Budget");
            }



           var InvContext = new InventoryContext();
           var TRANSACTIONSISSUED = new List<TRANSACTIONISSUEDITEM>();
           var ListTrans = InvContext.Transactions();
           var Employeedb = new EmployeeContext();
           var Employee = Employeedb.Find(User.Identity.GetUserName());
           var budgetDb = new BudgetContext();
           var DeptBudget = budgetDb.List().ToList();

           TRANSACTIONSISSUED = InvContext.IssuedItems();
           ViewBag.Message = "";
           var YearSelected = new List<string>();
           ViewBag.month1 = month1;
           ViewBag.month2 = month2;
           ViewBag.year = year;
           ViewBag.Department = DepName;

           BudgetContext db = new BudgetContext();
           var listSelectitem = db.List().Select(x => x.DEPARTMENTID).Distinct();
           List<SelectListItem> ddllist = new List<SelectListItem>();
           foreach (string bvm in listSelectitem)
           {
               ddllist.Add(new SelectListItem
               {

                   Text = bvm,
                   Value = bvm
               });
           };

           ViewBag.DeptList = ddllist;
           var list = db.List().Where(b => b.DEPARTMENTID.Contains(DepName) && b.MONTH >= month1 && b.MONTH <= month2 && b.YEAR == year  ).ToList();




           var Expences = (from i in TRANSACTIONSISSUED
                           join r in ListTrans
                           on i.REQUESTNO.Trim() equals r.REQUESTNO.Trim()
                           where
                           i.DEPARTMENT.Trim() == DepName.Trim() &&
                           i.DATETIME.Month == Month && i.DATETIME.Year == year
                           select new EXpenseTransactionViewModel
                           {
                               Month = i.DATETIME.Month,
                               Year = i.DATETIME.Year,
                               Department = i.DEPARTMENT,
                               Cost = i.COST,
                               Qty = i.QTY
                           }).ToList();

           foreach (BudgetViewModel item in list)
           {
               double Expense = Expences.Where(e => e.Month == item.MONTH && e.week == item.WORKWEEK  && e.Year == item.YEAR && e.Department.Trim() == item.DEPARTMENTID.Trim()).Sum(e => e.Cost * e.Qty);
               item.EXPENCES = Expense;
               item.BALANCE = item.BUDGET - item.EXPENCES;
           }

           return View(list.ToList());
        }


        //
        // GET: /Budget/Create
        public ActionResult Create()
        {

            var name = User.Identity.GetUserName();
            var userroles = _roleDataContext.USERROLEs.Where(u => u.USERNAME.ToLower().Trim() == name.ToLower().Trim() && u.ROLE.Trim() == "6");


            var rolegroup = from u in userroles.ToList()
                            join rg in _roleDataContext.ROLEGROUPs.ToList()
                                on u.ROLEID equals rg.ROLEID
                            select rg;
            var usergroup = (from rg in rolegroup.ToList()
                             join ug in _roleDataContext.USERGROUPs.ToList()
                             on rg.GROUPID equals ug.GROUPID
                             select ug).OrderBy(i => i.DEPTCODE);

            var listSelectitem = usergroup.Select(@group => new SelectListItem
            {
                Selected = true,
                Text = @group.DEPTCODE.Length > 20 ? @group.DEPTCODE.Substring(0, 20) : @group.DEPTCODE,
                Value = @group.DEPTCODE.Trim()
            }).ToList();


            var firstOrDefault = usergroup.FirstOrDefault();
            if (firstOrDefault != null)
            {
                ViewBag.DeptList = new SelectList(listSelectitem, "Value", "Text", firstOrDefault.DEPTCODE);
            }


            return View();
        }

        //
        // POST: /Budget/Create
        [HttpPost]
        public ActionResult Create(BudgetViewModel model , int month = 1, int year = 2017)
        {
           // try
          //  {
                // TODO: Add insert logic here
                model.DATETIME = DateTime.Now;
                BudgetDb.insert(model);
                return RedirectToAction("Index");
          //  }
           // catch
            //{
              //  return View(model);
           // }
        }

        //
        // GET: /Budget/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Budget/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Budget/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Budget/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Model

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace WarehouseRtoRSystem.Models
{



    public class BudgetModel
    {
        public int MONTH { get; set; }
        public int YEAR { get; set; }
        public int WORKWEEK { get; set; }
        public string DEPARTMENTID { get; set; }
        public DateTime DATEINSERTED { get; set; }
        public double BUDGET { get; set; }

    }

    public class BudgetViewModel : BudgetModel
    {


        public string DEPARTMENTNAME { get; set; }
        public double EXPENCES { get; set; }
        public double BALANCE { get; set; }


    }




    public class BudgetContext
    {
        private readonly OracleCommand cmd = new OracleCommand();
        private OracleConnection Conn = new OracleConnection();
        private readonly OracleConnModel ORCONN = new OracleConnModel();


        public List<BudgetViewModel> List()
        {
            var Departments = new List<BudgetViewModel>();

            ///SQL QUERY
            Conn = ORCONN.con;
            if (Conn.State != ConnectionState.Open)
            {
                Conn.Open();
            }
            try
            {


                cmd.Connection = Conn;
                cmd.CommandText = "SELECT * From SSMP.SYSTEMBUDGET";
                cmd.CommandType = CommandType.Text;

                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var Dept = new BudgetViewModel();
                    Dept.MONTH = dr.GetInt32(0);
                    Dept.YEAR = dr.GetInt32(1);
                    Dept.DEPARTMENTID = dr.IsDBNull(2) ? "" : dr.GetString(2) ;
                    Dept.DATETINSERTED = dr.GetDateTime(3);
                    Dept.BUDGET = dr.IsDBNull(4) ? 0 :  dr.GetDouble(4);
                    Dept.WORKWEEK = dr.GetInt32(8);




                    Departments.Add(Dept);
                }
            }
            finally
            {
                Conn.Close();
            }
            return Departments;
        }


        public string insert(BudgetViewModel model)
        {
            Conn = ORCONN.con;
            if (Conn.State != ConnectionState.Open)
            {
                Conn.Open();
            }

            try
            {


                cmd.Connection = Conn;
                //var date = new DateTime();
               // date = DateTime.Now;


                var query = "INSERT into SSMP.SYSTEMBUDGET(";

                query += "MONTH,";
                query += "YEAR,";
                query += "DEPARTMENTID,";
                query += "DATEINTERTED,";
                query += "BUDGET,";
                query += "WORKWEEK,";



                query += ")";

                query += "VALUES(";

                query += "'" + model.MONTH + "',";
                query += "'" + model.YEAR + "',";
                query += "'" + model.DEPARTMENTID + "',";
                query += "TO_DATE('" + DateTime.Now + "','MM/DD/YYYY HH:MI:SS AM'),";
                query +=  "'"+ model.BUDGET + "'," ;
                query += "'" + model.WORKWEEK + "'";


                query += ")";


                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();


            }
              catch(Exception e)
            {

                Console.WriteLine("{0} Exception caught.", e);

            }
            finally
            {
            Conn.Close();
            }

            return "Seccessfully inserted";
        }
    }
}

View

View

@model IEnumerable<WarehouseRtoRSystem.Models.BudgetViewModel><style>
    td, th, li {
        font-size: 8pt;
    }

    th, .label-heading {
        font-size: 10pt;
        font-weight: bold;
    }

    .body-content {
        margin: 30px;
    }
</style><h2><b>Budget</b></h2>



@{ string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; }<div class="w3-container w3-light-grey" style=""><div class="w3-container"><div class="w3-col m12 "><br /></div><div class="w3-col m12 "><br /></div>
        @using (Html.BeginForm())
        {
            @ViewBag.Message<label>&nbsp; &nbsp;DEPARTMENT</label><span class="">@Html.DropDownList("DepName", (List<SelectListItem>)ViewBag.DeptList, "Please Select",new { @id = "RemarksId", @class = "" })</span><label>From </label><select id="month1" name="month1">
                @for (var i = 0; i < 12; i++)
                {
                    var m = i + 1;
                    if (Convert.ToInt32(ViewBag.month1) == m)
                    {<option value=@m selected>@Months[i]</option>
                    }
                    else
                    {<option value=@m>@Months[i]</option>
                    }
                }</select><label>To </label><select id="month2" name="month2">
                @for (var i = 0; i < 12; i++)
                {
                    var m = i + 1;
                    if (Convert.ToInt32(ViewBag.month2) == m)
                    {<option value=@m selected>@Months[i]</option>
                    }
                    else
                    {<option value=@m>@Months[i]</option>
                    }
                }</select><label>YEAR</label><select id="year" name="year">
                @for (var c = 0; c < 1000; c++)
                {
                    var yr = c + 2017;
                    if (Convert.ToInt32(ViewBag.year) == yr)
                    {<option value=@yr selected>
                            @yr</option>
                    }
                    else
                    {<option value=@yr> @yr</option>
                    }
                }</select><b> <input type="submit" value="Filter" class="btn btn-default" /></b>
        }<br /><a href="#" data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-sm">Update Budget</a><div id="showModal"></div><div class="table-responsive col-lg-12 w3-light-grey w3-border" style=" height:500px;"><table class="table table-striped table-bordered"><tr class="w3-border"><th></th><th></th>
                    @for (int i = Convert.ToInt32(ViewBag.month1); i <= Convert.ToInt32(ViewBag.month2); i++)
                    {
                        var list = Model.Where(m => m.MONTH == i).OrderBy(m => m.WORKWEEK).Count() + 1;<th colspan='@list'><b>@Months[i - 1]</b></th>
                    }</tr><tr class="w3-light-grey"><td></td><td></td>

                   @for (int i = Convert.ToInt32(ViewBag.month1); i <= Convert.ToInt32(ViewBag.month2); i++)
                    {
                    var list = Model.Where(m => m.MONTH == i).OrderBy(m => m.WORKWEEK).ToList();
                     foreach (var item in list)
                     {<td>Week @item.WORKWEEK</td>
                     }<td><b>Total</b></td>
                    }</tr><tr class="w3-border"><td class=""></td><td><b>BUDGET</b></td>

                    @for (int i = Convert.ToInt32(ViewBag.month1); i <= Convert.ToInt32(ViewBag.month2); i++)
                    {
                        var list = Model.Where(m => m.MONTH == i).OrderBy(m => m.WORKWEEK).ToList();
                        foreach (var item in list)
                        {<td>@Html.TextBoxFor(model => item.BUDGET)<input type="submit" value="Save" class="btn btn-primary btn-xs" /></td>
                        }<td class="total"></td>
                    }</tr><tr class="w3-light-grey"><td class=""></td><td><b>ACTUAL</b></td>
               @for (int i = Convert.ToInt32(ViewBag.month1); i <= Convert.ToInt32(ViewBag.month2); i++)
{
    var list = Model.Where(m => m.MONTH == i).OrderBy(m => m.WORKWEEK).ToList();
    foreach (var item in list)
    {<td>@item.EXPENCES</td>
    }<td class="total"></td>
}</tr><tr class="w3-border"><td></td><td><b>DIFFERENCE</b></td>

                    @for (int i = Convert.ToInt32(ViewBag.month1); i <= Convert.ToInt32(ViewBag.month2); i++)
                    {
                        var list = Model.Where(m => m.MONTH == i).OrderBy(m => m.WORKWEEK).ToList();
                        foreach (var item in list)
                        {<td>@item.BALANCE</td>
                        }<td class="total"></td>
                    }</tr></table></div></div></div>

@section scripts{
    <script>$(".total").each(function () {
            var total = 0;
            if ($(this).prev().children().length > 0) {
                total += parseInt($(this).prev().children().val());
                total += parseInt($(this).prev().prev().children().val());
                total += parseInt($(this).prev().prev().prev().children().val());
                total += parseInt($(this).prev().prev().prev().prev().children().val());
                if ($(this).prev().prev().prev().prev().prev().children().length != 0) {
                    total += parseInt($(this).prev().prev().prev().prev().prev().children().val());
                }$(this).html(total);
            } else {
                total += parseInt($(this).prev().html());
                total += parseInt($(this).prev().prev().html());
                total += parseInt($(this).prev().prev().prev().html());
                total += parseInt($(this).prev().prev().prev().prev().html());
                if ($(this).prev().prev().prev().prev().prev().html() != "ACTUAL" && $(this).prev().prev().prev().prev().prev().html() != "DIFFERENCE" && $(this).prev().prev().prev().prev().prev().attr('class') != "total") {
                    total += parseInt($(this).prev().prev().prev().prev().prev().html());
                }$(this).html(total);
            }
        })
        firstDay = new Date(2017, 0, 1).getDay();
        console.log(firstDay);
        var year = 2017;
        var week = 1;
        var d = new Date("Jan 01, " + year + " 01:00:00");
        var w = d.getTime() - (3600000 * 24 * (firstDay - 1)) + 604800000 * (week - 1)
        var n1 = new Date(w);
        var n2 = new Date(w + 518400000)

        console.log(n1);
        console.log(n2);
    </script><link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css" /><script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script><script>
    var $j = jQuery.noConflict();$j("a").click(function () {$j("#showModal").html("");$j.ajax({
            url: '/Budget/Create',
            data: { month: 1, WORKWEEK: 1/*,other...*/ },
            success: function (data) {$j("#showModal").html(data);$j("#myModal").show();$j("#myModal").draggable({ handle: ".modal-header" }); //Here add.
            }
        })
    })$j("body").on("click", ".close", function () {$j("#showModal").html("");
    })</script>

}

Desired Output

https://imgur.com/a/bsSo2 

Books

$
0
0

Can anyone recommend some really good books or articles covering the .net entity framework and linq. The books or tutorials dont have two discuss these technologies together. I want to make sure that I could use the .net entity framework as a repository as someone suggested. Thanks !

bulk excel data insertion into sql with encrpttion in C#

$
0
0

Hi

I want to insert the bulk excel records in to sql  with encryption using C#

and also i want to Decrption the data while i  retrving in C#.

thanks and regards

siddu

Set default value on property in Entity Framework 6.1.3

$
0
0

I have the following class.

publicclassUser{publicintId{ get;set;}publicstringFirstName{ get;set;}publicstringLastName{ get;set;}publicbyte[]RowVersion{ get;set;}publicboolIsDeleted{ get;set;}}

How can I set default value for property IsDeleted using Fluent API. Method HasDefaultValue is not available. I have tried to set via constructor, the same result. In constructor I have tried false value, field still doesn't have default value. 

The solution presented below, also didn't succeed.

public bool IsDeleted { get; set; } = false;

filterexpression

$
0
0

Hello guys,

I want to make amendment to below function to accommodate filter-expression and  not sure how to achieve it. can someone help me with this?

  public static IQueryable<T> PagedResult<T, TResult>(IQueryable<T> query, int pageNum, int pageSize,
                Expression<Func<T, TResult>> orderByProperty, bool isAscendingOrder, string filterExpression, out int rowsCount)
        {
            //if (pageSize <= 0) pageSize = 20;

            //Total result count
            rowsCount = query.Count();

            //If page number should be > 0 else set to first page
            if (rowsCount <= pageSize || pageNum <= 0) pageNum = 1;

            //Calculate nunber of rows to skip on pagesize
            int excludedRows = (pageNum - 1) * pageSize;

            query = isAscendingOrder ? query.OrderBy(orderByProperty) : query.OrderByDescending(orderByProperty);

query= query.Where(????);

            //Skip the required rows for the current page and take the next records of pagesize count
            return query.Skip(excludedRows).Take(pageSize);
        }


 

lambda expression

$
0
0

Hello,

I want to build dynamic lambda expression like this: x=> x.ID.

From one of the posts i could so far build x => x.Id >= 3. Can someone help me toachieve x=> x.ID using code below:

var parameter = Expression.Parameter(typeof(Person), "x");
                var member = Expression.Property(parameter, "Id"); //x.Id
                var constant = Expression.Constant(3);
                var body = Expression.GreaterThanOrEqual(member, constant); //x.Id >= 3
                var finalExpression = Expression.Lambda<Func<Person, bool>>(body, param); x => x.Id >= 3


</div>


How to get the same data using EntityFramework

$
0
0

How would get the below data using entity framework?

public int InsertPersonActivityLog(int logId, string edi, string personFormalName, DateTime activityDateTime, string activityTypeDescriptor, string additionalDetails, string reasonMessage, string notes)
        {
            StringBuilder errorMessages = new StringBuilder();
            try
            {
                // Get the connection string from the appsettings.json.
                conn.ConnectionString = myConn.DefaultConnectionString(configuration);                                                                                          // Open the connection.
                conn.Open();
                cmd.Connection = conn;

                // Set the command type of the command object.
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                // Assign values as "parameters to avoid 'SQL Injections.'"
                cmd.Parameters.AddWithValue("@edi", edi);
                cmd.Parameters.AddWithValue("@formalName", personFormalName);
                cmd.Parameters.AddWithValue("@date", activityDateTime);
                cmd.Parameters.AddWithValue("@descriptor", activityTypeDescriptor);
                cmd.Parameters.AddWithValue("@details", additionalDetails);
                cmd.Parameters.AddWithValue("@reason", reasonMessage);
                cmd.Parameters.AddWithValue("@notes", notes);

                return cmd.ExecuteNonQuery();
            }
            catch(SqlException ex)
            {
                for (int i = 0; i < ex.Errors.Count; i++)
                {
                    errorMessages.Append("Index #" + i + "\n" +"Message: " + ex.Errors[i].Message + "\n" +"LineNumber: " + ex.Errors[i].LineNumber + "\n" +"Source: " + ex.Errors[i].Source + "\n" +"Procedure: " + ex.Errors[i].Procedure + "\n");
                }
                Console.WriteLine(errorMessages.ToString());
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
            return 0;
        }

EF - A member of the type, 'X', does not have a corresponding column in the data reader with the same name.

$
0
0

Hi,

I have a class that represents one of my tables (I used EntityFramework with Code-First):

    [Table("Logística$Sales Invoice Header")]
    public partial class Logística_Sales_Invoice_Header
    {
        [Column(TypeName = "timestamp")]
        [MaxLength(8)]
        [Timestamp]
        public byte[] timestamp { get; set; }

        [Key]
        [StringLength(20)]
        public string No_ { get; set; }

        [Column("Sell-to Customer No_")]
        [Required]
        [StringLength(20)]
        public string Sell_to_Customer_No_ { get; set; }

And when I am trying to pass a result of a query to an instance of this class, shows this error:

The data reader is incompatible with the specified 'FAMO.BaseItems.Database.urano.famNAV.Logística_Sales_Invoice_Header'. A member of the type, 'Sell_to_Customer_No_', does not have a corresponding column in the data reader with the same name.

This is my query:

SELECT a.* FROM [Logística$Sales Invoice Header] AS a INNER JOIN [Logística$Sales Invoice Line] AS b ON a.No_ = b.[Document No_] WHERE 1 = 1 AND b.Type = 2 AND a.[Bill-to Customer No_] = 'IC00029' AND b.No_ = 'XFMR2812B' AND b.[Cross-Reference No_] = '20M39' AND a.[Document Date] >= CONVERT(datetime, '02/01/2018', 103) AND a.[Document Date] <= CONVERT(datetime, '01/02/2018', 103)

Can someone help me?

Comparing the value in datatable in c#.net

$
0
0

    DbDataAdapter da = _dataFactory.CreateDataAdapter();
          
               DbParameter param1 = null;
              
                DataTable dt = new DataTable("USER1");
             
            try
            {
                conn.ConnectionString = _connectionString;
                conn.Open();
                string _sql1 = "SELECT * FROM USERGROUP WHERE CODE='ABC' ";
                da.SelectCommand = conn.CreateCommand();
                da.SelectCommand.CommandText = OracleHelper.FixCommandText(_sql1);
                da.SelectCommand.CommandType = CommandType.Text;

                OracleHelper.CreateParameter(ref da, ref param108, "@CODE", DbType.String, ParameterDirection.Input,_code);

                da.Fill(dt);

                if (dt._CODE = "ABC")
                {
                
                   
                  }

In above queries , the Values from usergroup is filling into dt. Now i want to check value of code inside the dt is equal to "ABC". Error is showing for  if (dt._CODE = "ABC")

What is the efficient way to Copy properties of source object to destination object in batches (Linq)

$
0
0

Below is my case:
I have a dictionary of 1000 items as ProductDict<Upc1, Upc2> where Upc1 and Upc2 are strings which are different records in Product table. I am trying to copy properties from one object to another which are of same type. 

I don't want to do as below:
a. For loop for 1000 items
b. Linq select query to get product object for Upc1
c. Linq select query to Get product object for Upc2
d. Copy attributes from Upc2 to Upc1

Also the dictionary is one-to-one like object 'A' has to be copied to 'A1' and B to 'B1' and etc. Is there any better way to do it batches? I am using Linq sql queries.

context.Database.ExecuteSqlCommand EFCore return -1

$
0
0

i've  a stored procedure with not output parameters,  when i try running it, i get -1  as output, i've a delete statement inside sp, sp runs individually on sql server, but when i call from ef core it returns -1





var parameters = new []{newSqlParameter("@returnVal", (object)param1),
newSqlParameter("@returnVal", (object)param2),
newSqlParameter("@returnVal", (object)param3),
..........
}; var b = await _stagingContext.Database.ExecuteSqlCommandAsync("exec proacName",parameters);//optionally i tried

var result =  _stagingContext.SaveChanges();

//b = -1 and c =0;

I'm using EFCore, 

Viewing all 1698 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>