vendredi 14 août 2015

How dynamicly add new partial form and how get data from them in ASP MVC?

I have project on ASP MVC 5. I have a model "Article". This model have HashSet and ICollection of Author. Author - second model:

 public partial class Article
{
    public Article()
    {
        Authors = new HashSet<Author>();
    }

    [DisplayName("Авторы")]
    public virtual ICollection<Author> Authors { get; set; }

I need to add page of creating Article, on which you can increase the number of authors(using AJAX), and each author to register the fields. I decided to use partial view of Author's model, without "Create" button(Create button used only view of creating Article). I need in unlimited adding new partial views, and after fill them - get all data from them. How make it? I newbie in MVC, and can't imagine how it will works.

http://ift.tt/1UFGYKD - an illustration of how it should look



via Chebli Mohamed

Settings in web.config for initialize database

I have Error :HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       Unknown
Handler    Not yet determined
Error Code     0x80070032
Config Error       The configuration section 'entityFramework' cannot be read because it is missing a section declaration
Config File    \\?\C:\Project\web.config

I use Entity Fremework Code First. And i'm initialize data for my table:

 namespace Project.NewFolder1.Initializer
{
    public class StackOverFlowInitializer : DropCreateDatabaseAlways<Test123Db>
    {
        protected override void Seed(Test123Db context)
        {
            var category = new List<Category>
            {
                new Category() {NameCategory = "C#"},
                new Category() {NameCategory = "ASP.NET"},
                new Category() {NameCategory = "ASP.NET MVC"},
                new Category() {NameCategory = "HTML"},
            };
            category.ForEach(s => context.Category.Add(s));
            context.SaveChanges();
        }
    }
}

In web.config i set:

 <connectionStrings>  
    <add name="Test123Db" connectionString="data source=.\SQLEXPRESS;initial catalog=StacjOverFlow;integrated security=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>

<entityFramework>
   <contexts>
    <context type="Project.NewFolder1.Test123Db, Project">
      <databaseInitializer type="Project.NewFolder1.Initializer.StackOverFlowInitializer, Project" />
    </context>
</contexts>

</entityFramework>

What may be the problem?



via Chebli Mohamed

Import Certificate installed in browser to sign a document digitally and encrypting the excel file

I had an project in which the documents were digitally signed using .pfx files but now with the change in requirement, the organisation uses E-Tokens( usb devices), which when plugged in the computer, installs certificates into the browsers, now i need to digitally sign the pdf file and encrypt the excel file as, the digital signature is of class 3, signing and encryption both, signing for pdf file and encryption for excel file.

Can any one help me with a way on how to import the certificate installed in browser and den use the keys to sign and encrypt the excel file.



via Chebli Mohamed

How can I change the style of a line to dotted in a graph when exceeding a limit by using d3.js

I have created multi line graph in d3.js and I wanted to make the path of line to dotted when it exceeds a particular limit



via Chebli Mohamed

What are these ASP.NET Identity, Memberships? When to use them?

I have a website developed by using ASP.NET and DB is MYSQL. In there user authentication is done against registered users inside a table.

So What is this ASP.NET identity? Membership? things. When to use them? Are they secured approaches? Are they differ from what I am currently doing?

Thank you very much.



via Chebli Mohamed

retrieving multiple data from one column using vb.net

I m new to asp.net is there any way that i could display different data in one row where the data is pulled from same column of another table? where the column is name hello and contains 3 types of data let`s say my code is like this:

    cmd1.CommandText = " SELECT hello FROM link where mode=@model and procedure =@procedure "
    cmd1.CommandType = System.Data.CommandType.Text
    Dim da1 As New SqlDataAdapter()
    da1.SelectCommand = cmd1
    Dim dt1 As New DataTable()
    da1.Fill(dt1)
    Dim myDataReader1 As SqlDataReader
    myDataReader1 = cmd1.ExecuteReader()
    Dim hello As String
    If myDataReader1.HasRows Then

        Do While myDataReader1.Read()
            hello= myDataReader1("hello").ToString()

        Loop
        lblhello.Text = hello
    Else
        lblhello.Text = ""
    End If


    myDataReader1.Close()  

my data output should be like:

hihi,yoyo,heyhey

but i ended up getting

heyhey

only please help me on this issue



via Chebli Mohamed

how to create message box in public static void method

I have a public static method and I would like a message to be displayed if certain values are selected. This is in asp.net so adding using System.Windows.Forms; causes problems because I am using using System.Web.UI.WebControls;. So how do I create a message?

public static void UpdateSerialQtyRcvd(int SerNoID, int QtyRcvd)
     {
            if (SerNo.QtyRcvd != 1)
            {
                if (SerNo.Reason == "")
                {
                    //message
                }
            }
        }



via Chebli Mohamed

jeudi 13 août 2015

Posting data from a single table row asp.net mvc

I'm still quite new to MVC and I'm wondering if I am implementing the following in a correct way.

I have a table that is being build in a foreach loop. On each row there is a dropdown box. I attached an eventlistener to the dropdown for on change using jQuery. In the onchange event I post my data. Now my biggest concern is how to retrieve the data for the row that was changed. I'm currently using a hiddenfield for this. In webforms, this would have been a simple repeater and than all the data would be available on postback. Please find a basic version of my loop below.

@foreach (var item in Model)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Bar)
    </td>
    <td>
        @Html.DropDownListFor(modelItem => item.Foo, new SelectList(item.Foos, "Id", "Name", item.FooID), htmlAttributes: new { @class = "form-control ddlFoo" })
        @Html.HiddenFor(modelItem => item.Bar, htmlAttributes: new { @class = "hfBar" })
    </td>
</tr>
}

So is this the correct approach? Or what would be a better way? Thank you for helping out a MVC newbie



via Chebli Mohamed

getting error -Procedure or function 'sp_InsertContentForhomepage' expects parameter '@company', which was not supplied

getting error - getting error -Procedure or function 'sp_InsertContentForhomepage' expects parameter '@company', which was not supplied.

im trying to insert two values ...im new in using sp .

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ShoppingConnectionString"].ConnectionString);
            con.Open();
            string text = FCKeditor.Value;
            string company = txtCompany.Text.Trim();
            DataSet ds = new DataSet();

            SqlCommand cmd = new SqlCommand("sp_InsertContentForhomepage", con);
             cmd.CommandType = CommandType.StoredProcedure;
             cmd.Parameters.AddWithValue(@text, text);
             cmd.Parameters.AddWithValue(@company,company);

            cmd.ExecuteNonQuery();
            con.Close();

my strode procedure

 create PROCEDURE sp_InsertContentForhomepage
   @company    VARCHAR(50),
    @text  VARCHAR(max)

AS
BEGIN

INSERT INTO tbl_HomepageContent (company, text)
VALUES (@company,@text)

END



via Chebli Mohamed

Using ARR how do you rewrite a url if a cookie is missing?

I know I can rewrite a url based on values from a cookie using the {HTTP_COOKIE} variable in the conditions part of the rule. This rule grabs a cookie called ServerProxy and does a rewrite to that server url.

    <rule name="SendTrafficToServerProxyCookieValue" stopProcessing="true">
        <match url="(.*)" />
        <action type="Rewrite" url="http://{C:1}/{R:0}" />
        <conditions>
            <add input="{HTTP_COOKIE}" pattern="ServerProxy=(.*)" />
        </conditions>
    </rule>

If the ServerProxy cookie is absent or unset I would like to direct the traffic to an authentication server called authenticate.app. How do I write a rewrite rule that will do that?



via Chebli Mohamed

Easy implementation of Repository Pattern

I am using ADO.NET directly with MVC 5 and not Entity Framework.

I am referring to this example to implement Repository Pattern.

For a simple implementation of Repository Pattern:

  1. I will create a Model
  2. I will create an interface with CRUD method declarations
  3. I will create a class in Data Access Layer which will implement the above interface and will have CRUD method implementations

I want to know why Interface is used? Can I not directly use a class, as per point (3) above.

What is the role of interface?

As per the above three points mentioned, is it the correct implementation of Repository Pattern?



via Chebli Mohamed

Closing a fancybox from controller in asp.net mvc 5 (vb)

Iam calling form inside a fancybox. After filling the form it saves data and redirect to index page. But the page redirection is happening in within the fancybox. Is it possible to close the fancybox from controller and redirect to index page? here is a method I used but don't worked

Return RedirectToAction("Index",Nothing,New With{.href="/Home/Index",.target="_parent"})



via Chebli Mohamed

Is it too early to start an ASP.NET 5 web project?

We are about to begin development on a completely new web application. It's a big project and will take years to finish and will probably have quite a long lifetime.

Since ASP.NET 5 is just around the corner, but still in BETA - is it too early to start a web project using the new ASP.NET version?

I can understand that we might have to face a few tricky upgrades before it hits Beta8 and RC, but the benefits of using it right away might beat the costs of upgrading later (or never).

What are your thoughts?



via Chebli Mohamed

OnPropertyValidating method for CustomModelBinder never gets called

Hi I am new to asp net mvc programming and I am wondering why the OnPropertyValidating method for my CustomModelBinder class is not being called.

Here is my declaration for the CUstomModelBinder.

public class AnotherModelBinder : DefaultModelBinder
{
    protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
    {
        if (value is string && (controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)))
        {
            if (controllerContext.Controller.ValidateRequest && bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
            {
                int index;
                if (IsDangerousString(value.ToString(), out index))
                {
                    throw new HttpRequestValidationException("Dangerous Input Detected");
                }
            }               
        }
        return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
    }

}

and here is what I added to the Global.asax

    ModelBinders.Binders.Add(typeof(AnotherModelBinder), new AnotherModelBinder());
    ModelBinders.Binders.DefaultBinder = new AnotherModelBinder();

now I am assuming that this OnPropertyValidating method will get called everytime I call a controller action something like :

[HttpPost]
public JsonResult TestMethod(int param1, string param2, string param3)
{
    ...
}

but the OnPropertyValidating method on my customModelBinder never gets called.

Can anyone help me to understand why? Is there any good tutorial sites for this?

Thank in advance!



via Chebli Mohamed

Asp.net Call Code Behind with JavaScript

since i didn´t find any solution that helped me, i thought i asked. I need a JavaScriptfunction with calls a method in my code-behind, and since i´m really new to this, i dont understand what am i doing wrong. On my Master Page (Site.Master) i enabled PageMethods:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

And in the Content of my Page i have put the Script:

        function reply_click(clicked_id) {
            alert(clicked_id);
            PageMethods.javascriptTest(clicked_id);

And now my method in the code-behind:

    [WebMethod]
    public void javascriptTest(int buttonID)
    {

        Test2.Text += buttonID + "***";

        // Use the ID for DB access

    }

I need that ID for later, when i have to do stuff in my database, but i´m always getting PageMethods undefined errors and i dont know why :/



via Chebli Mohamed

Retrieving user_location from the access_token returns empty string

I have successfully generated access_token for my website. I am able to retrieve all the required information, except one i.e., user_location. I tried to use the following two methods to retrieve location , but both return empty string.

Method-1

string access_tokens = tokens["access_token"];

var client = new FacebookClient(access_tokens);

dynamic me = client.Get("me");

string user_location me["user_location"].ToString();

Method-2

string user_location = GetUserLocation(fb_id);

//and here is the method

 public static string GetUserLocation(string faceBookId)
            {
                WebResponse response = null;
                string user_location = string.Empty;
                try
                {
                    WebRequest request = WebRequest.Create(string.Format("http://ift.tt/1DOYmIM", faceBookId));
                    response = request.GetResponse();
                    user_location = response.ResponseUri.ToString();
                }
                catch (Exception e)
                {
                    //catch exception
                }
                finally
                {
                    if (response != null) response.Close();
                }
                return user_location;
            }

Location is actually received when I try to debug in the Graph API Explorer at developer.facebook.com ! When I put the parameter location - the location is received as expected.

Alternately I also tried to change the request URL with this :

WebRequest request = WebRequest.Create(string.Format("http://ift.tt/1HKpRxV", faceBookId));

Why is this happening ?



via Chebli Mohamed

unable to connect to the remote server from .com domain

i have create a one web service and tested it in local machine, it working fine. So i have hosted it in .com domain. but when i call that web service, it gives me "unable to connect to the remote server". so i have also hosted it .in domain. it working fine with .in domain.

I have already tried with proxy but still same error.

my code is

 //Call Send SMS API
        string sendSMSUri = "http://ift.tt/1UGL1GH";

        //Create HTTPWebrequest
        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(sendSMSUri);
        httpWReq.Proxy = new System.Net.WebProxy(sendSMSUri);
        //Prepare and Add URL Encoded data
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] data = encoding.GetBytes(sbPostData.ToString());
        //Specify post method
        httpWReq.Method = "POST";
        httpWReq.ContentType = "application/x-www-form-urlencoded";
        httpWReq.ContentLength = data.Length;
        using (Stream stream = httpWReq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        //Get the response
        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseString = reader.ReadToEnd();
        //Close the response
        reader.Close();
        response.Close();

can anybody help me how to resolve that issue?



via Chebli Mohamed

Add Calander functionality same as window taskbar tray

I need to develop in WEB calendar functionality same as what in windows tray.

Including showing clock and other functionality like change of timezone,

Please suggest some tip.

Platform : .NET 3.5 - 4.5 C# Webform,

Thank you,



via Chebli Mohamed

NUnit NHibernate and Moq unit test throwing NHibernate.MappingException

I'm using Ayende's code from his blog on unit testing with NHibernate and it calls for testing with SQLite, code as follows:

using System;
using System.Reflection;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Tool.hbm2ddl;
using Environment = NHibernate.Cfg.Environment;

namespace WebAPI.Tests
{
    /// <summary>
    /// http://ift.tt/1q8TEN7
    /// </summary>
    public class InMemoryDatabaseTest : IDisposable
    {
        private static Configuration _configuration;
        private static ISessionFactory _sessionFactory;
        protected ISession Session;

        public InMemoryDatabaseTest(Assembly assemblyContainingMapping)
        {
            if (_configuration == null)
            {
                _configuration = new Configuration()
                    .SetProperty(Environment.ReleaseConnections, "on_close")
                    .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                    .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                    .SetProperty(Environment.ConnectionString, "data source=:memory:")
                    .AddAssembly(assemblyContainingMapping);

                _sessionFactory = _configuration.BuildSessionFactory();
            }

            Session = _sessionFactory.OpenSession();

            new SchemaExport(_configuration).Execute(false, true, false);
        }

        public void Dispose()
        {
            Session.Dispose();
        }
    }
}

My test class is:

[TestFixture]
public class FilmsControllerTests : InMemoryDatabaseTest
{
    public FilmsControllerTests() : base(typeof(Film).Assembly)
    {
    }

    static readonly Guid ValidFilmId = new Guid("35d3ee0f5ee011bd8822ed629e5");

    [Test]
    public void CanSaveAndLoadFilm()
    {
        object id;

        using (var tx = Session.BeginTransaction())
        {
            id = Session.Save(new PdfFilm
            {
                IsEnabled = true,
                Id = ValidFilmId,
                PremiumLevel = 1,
                PublishDate = new DateTime(20121010),
                Pdf = new Document(new byte[byte.Parse(" 162")], new DateTime(20121010)),
                Title = "jel",
                Authors = "smel",

            });

            tx.Commit();
        }

        Session.Clear();


        using (var tx = Session.BeginTransaction())
        {
            var Film = Session.Get<PdfFilm>(id);

            Assert.AreEqual(new DateTime(2012, 10, 10), Film.PublishDate);

            tx.Commit();
        }
    }

And Model:

public abstract class Film : Entity<Film>

Which has a nested class:

public class PdfFilm: Film

And starts it's mapping config in the same file as the parent as:

<subclass name="PdfFilm" discriminator-value="Pdf">

The NUnit unit test returns:

NHibernate.MappingException : No persister for: Core.PdfFilm

I've checked the properties of the Film mapping file and it's set as embedded resource - could anyone please also confirm if this is the simplest way of testing and also any idea what the error message means?

Stack trace:

at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.Save(Object obj)



via Chebli Mohamed

Custom error message displyed only while debugging

I have this entry in my web config.

<customErrors mode="On" defaultRedirect="~/ErrorPage.aspx" />
<compilation debug="false" targetFramework="4.0">.

Basically I am trying to show custom error page whenever there is an unhandled exception in the application. I get the custom error page only when I am debugging the application i.e. when w3wp(worker) process is attached. It shows the generic error page when not debugging.

I am obviously missing something here?



via Chebli Mohamed

Large soql queries(over 5000 charcter length) to socrata is not supporting

I am using SodaClient to get information from a private data set in Socrata using the following code.

var records = (dynamic)null;

string searchCondition = "column1='something'AND (column2='something' OR 'somethingelse') ";

var clientExport = new SodaClient("host name", "app token", "username","password");

var dataset = clientExport.GetResource<modelname>("resourceid");
var offset = 0;
var limit = 1000;

var soql = new SoqlQuery().Where(searchCondition).Offset(offset).Limit(limit);
records = dataset.Query<modelname>(soql).ToList();

return records;

The problem is that sometimes the 'searchCondition ' can be very large say over 5000 characters, then the Sodaclient is returning error.

How can I send large soql queries to socrata? I also tried to get information using restful calls httpclient method but it also showing errors like.

An error occurred while sending the request. The server committed a protocol violation. Section=ResponseStatusLine



via Chebli Mohamed

How to query Unicode characters from SQL Server 2008

With NVARCHAR data type, I store my local language text in a column. I face a problem how to query that value from the database.

  • ዜናገብርኤልስ is stored value.

I wrote SQL like this

select DivisionName 
from t_Et_Divisions 
where DivisionName = 'ዜናገብርኤልስ'

select unicode (DivisionName) 
from t_Et_Divisions 
where DivisionName = 'ዜናገብርኤልስ'

The above didn't work. Does anyone have any ideas how to fix it?

Thanks!



via Chebli Mohamed

How to resolve IIdentity for SignalR?

I am using structureMap for injecting dependencies, I'd like to know Which implementation should I provide for IIdentity in SignalR?



via Chebli Mohamed

Why @User.IsInRole not working?

I installed Dotconnect PostgreSql with folowing this tutorial http://ift.tt/1h8NCef All works fine, but when I call Admin role from View.cshtml with this operation : @(User.IsInRole("admin")) { } , after that showing error as

"Operation is not Supported"

But Rolemanager was enabled in web.config

Showing Exception that :

An exception of type 'System.InvalidOperationException' occurred in Devart.Data.PostgreSql.Web.dll but was not handled in user code

Additional information: Operation is not supported

Code:

<roleManager defaultProvider="PgSqlExtendedRoleProvider" enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" cookieTimeout="30" cookiePath="/" cookieProtection="All">
  <providers>
    <add name="PgSqlExtendedRoleProvider" type="Devart.Data.PostgreSql.Web.Providers.PgSqlExtendedRoleProvider, Devart.Data.PostgreSql.Web, Version=7.3.457.5, Culture=neutral, PublicKeyToken=09af7300eec23701" description="dotConnect for PostgreSQL extended role provider" connectionStringName="DefaultConnection"/>
  </providers>
</roleManager>

Quick watch showing : false.
Why is this function throwing an exception? How can I fix it ?



via Chebli Mohamed

How can the password be hidden from Firebug's Net panel?

I am a web developer and using Firebug to track my AJAX requests. But some days back I came to know that every network request you do is tracked by Firebug not only asyncronous requests.

If you submit a form normally using the HTTP protocol (not an AJAX call), it is still logged in Firebug's Net panel and is shown openly. I checked it on various reputable sites (names can't be disclosed) having SSL certificates and using the HTTPS protocol, though they are also having this problem.

Is there any technique to encrypt the password before a normal form submit?

Suppose I am using $.ajax(), then I can encrypt the password using base64, or my custom encryption technique, but what in case of normal HTTP submits?

Steps to reproduce:

  1. Open Firefox.
  2. Start Firebug if you have it or install it, then start it.
  3. Go to the Net panel in Firebug.
  4. Open any website where you have an account and just log in with your credentials.
  5. Just check the POST requests where you got your original password as a plain text.


via Chebli Mohamed

[ ASP.Net ][ MVC ] Linq to SQL " 2 Query "

this is my database : http://ift.tt/1TA1c65

this is my coding

public ActionResult Index()
    {
        IList<TicketListModel> TicketList = new List<TicketListModel>();
        var TicketListQuery = from Tickets in db.Tickets
                              select new TicketListModel
                              {
                                  Number = Tickets.Number,
                                  RequestDate = Tickets.RequestDate,
                                  Applicant = (from Applicants in db.Employees where Applicants.ID = Tickets.ID select new { Applicants.Name }).First(),
                                  ComName = ComLibs.Name,
                                  ProbType = Tickets.ProbType,
                                  ProbDetail = Tickets.ProbDetail,
                                  Status = Tickets.Status
                              };
        TicketList = TicketListQuery.ToList();
        return View(TicketList);
    }

I'm want to show "Applicant name" but in table "Ticket" the Applicant is a "int" so just select Applicant name in table Employee where Applicant ID equals Employee ID then select a Employee name

plz help me thanks



via Chebli Mohamed

IIS Remote Exception

I have an IIS Application which references a plugin manager which reads all available plugins from a folder, when it is hosted after about 5-10 minutes I start getting the following Exception

[RemotingException: Object '/1608465e_9d80_4b40_be20_4c96904643e0/wizi+0g5od5gwmunm_indiws_253.rem' has been disconnected or does not exist at the server.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14416170
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +388
PluginManager.Core.Interfaces.IPluggin.get_Id() +0
PluginManager.PluginDetails.get_Id() +27

I did some research and came accross ILease and ISponsor but I have no Idea how to implement it or how it works. My current code as it is at this moment, I just removed parts the body of the methods for clarity [Edit : added the method bodies]

public class AssemblyReflectionProxy : MarshalByRefObject
{
    private string _assemblyPath;

    public AssemblyReflectionProxy()
    {
        Id = "";
    }

    public void LoadAssembly(String assemblyPath)
    {
        try
        {
            _assemblyPath = assemblyPath;
            Assembly.ReflectionOnlyLoadFrom(assemblyPath);
        }
        catch (FileNotFoundException)
        {
        }
    }

    public TResult Reflect<TResult>(Func<Assembly, TResult> func)
    {
        var directory = new FileInfo(_assemblyPath).Directory;
        ResolveEventHandler resolveEventHandler = (s, e) => OnReflectionOnlyResolve(e, directory);
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler;
        var assembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault(a => String.Compare(a.Location, _assemblyPath, StringComparison.Ordinal) == 0);
        var result = func(assembly);
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler;

        return result;
    }

    public T GetEntryType<T>()
    {
        var directory = new FileInfo(_assemblyPath).Directory;
        ResolveEventHandler resolveEventHandler = (s, e) => OnReflectionOnlyResolve(e, directory);
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler;
        var assembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault(a => string.Compare(a.Location, _assemblyPath, StringComparison.Ordinal) == 0);
        if (assembly != null)
        {
            var result = assembly.GetTypes();
            var type = result.FirstOrDefault(x => x.GetInterface(typeof(T).Name) != null);
            if (type != null)
            {
                var remoteObject = AppDomain.CurrentDomain.CreateInstanceFrom(type.Assembly.Location, type.FullName);                   
                var obj = remoteObject.Unwrap();
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler;
                return (T)obj;
            }
        }
        return default(T);
    }

    private Assembly OnReflectionOnlyResolve(ResolveEventArgs args, DirectoryInfo directory)
    {
        var loadedAssembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault(asm => string.Equals(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase));

        if (loadedAssembly != null)
        {
            return loadedAssembly;
        }

        var assemblyName = new AssemblyName(args.Name);
        var dependentAssemblyFilename = Path.Combine(directory.FullName, assemblyName.Name + ".dll");

        if (File.Exists(dependentAssemblyFilename))
        {
            return Assembly.ReflectionOnlyLoadFrom(dependentAssemblyFilename);
        }
        return Assembly.ReflectionOnlyLoad(args.Name);
    }

    private string Id { get; set; }
    internal string GetId()
    {
        if (String.IsNullOrEmpty(Id))
        {
            var fileBytes = File.ReadAllBytes(_assemblyPath);
            var hash = Convert.ToBase64String(fileBytes).GetHashCode();
            var bytes = BitConverter.GetBytes(hash);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes)
                sb.Append(b.ToString("X2"));
            Id = sb.ToString();
        }
        return Id;
    }
}


public sealed class AssemblyManager : MarshalByRefObject, IDisposable
{
    private readonly Dictionary<string, AppDomain> _assemblyDomains = new Dictionary<string, AppDomain>();
    readonly Dictionary<string, AssemblyReflectionProxy> _proxies = new Dictionary<string, AssemblyReflectionProxy>();
    public AssemblyManager()
    {

    }

    public string LoadAssembly(string assemblyPath)
    {
        var fileInfo = new FileInfo(assemblyPath);
        var name = fileInfo.Name.Replace(".dll", "");
        if (fileInfo.Exists)
        {
            if (!_assemblyDomains.ContainsKey(name))
            {
                var appDomain = CreateChildDomain(AppDomain.CurrentDomain, fileInfo.Name);
                _assemblyDomains[name] = appDomain;
                try
                {
                    Type proxyType = typeof(AssemblyReflectionProxy);
                    {
                        var proxy = (AssemblyReflectionProxy)appDomain.CreateInstanceFrom(proxyType.Assembly.Location, proxyType.FullName).Unwrap();
                        proxy.LoadAssembly(assemblyPath);
                        _proxies[name] = proxy;
                        return name;
                    }
                }
                catch
                { }
            }
            else
            {
                return name;
            }
        }
        return "";
    }

    public void Unload()
    {

    }

    private AppDomain CreateChildDomain(AppDomain parentDomain, string domainName)
    {
        var evidence = new Evidence(parentDomain.Evidence);
        var setup = parentDomain.SetupInformation;
        return AppDomain.CreateDomain(domainName, evidence, setup);
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~AssemblyManager()
    {
        Dispose(false);
    }

    public IPluggin GetEntryPluggin(string name)
    {
        IPluggin plugin = default(IPluggin);
        if (_proxies.ContainsKey(name))
        {
            plugin = _proxies[name].GetEntryType<IPluggin>();
        }
        return plugin;
    }

    private void Dispose(bool disposing)
    {
        if (disposing)
        {
            foreach (var appDomain in _assemblyDomains.Values)
                AppDomain.Unload(appDomain);
            _assemblyDomains.Clear();
        }
    }

    internal string GetEntryPlugginID(string name)
    {
        string Id = "";
        if (_proxies.ContainsKey(name))
        {
            Id = _proxies[name].GetId();
        }
        return Id;
    }
}

My Interface is

public interface IPluggin
{
    string Name { get; }
    string Version { get; }
    string Id { get; }
    void Initialize();
    string[] GetElements();
    void SaveSettings(string settings);
    void SetBasePath(string path);
}



via Chebli Mohamed

How can i set viewbag value to hidden field and access from jquery

how can I set viewbag value into hidden fiels and access the value from jquery



via Chebli Mohamed

ASP MVC EditorTemplates for ComplexType

I am a silent reader of stackoverflow and in almost all cases I find solution to my problems from others' posts from this website until yesterday when I got stuck on something and can't find a solution.

here is a little explanation on my app architecture.

I have code-first entity model in a separate c# project and I am referencing it to my web project.

I have following entities

public class Employee
{
    public Employee();
    public int EmployeeId {get;set;}
    public DateTime? DegreeCompleted{ get; set; }
    public virtual University University { get; set; }
}
public class University 
{
    public University();
    public int UniversityId {get;set;}
    public short? TotalDegrees{ get; set; }
    public short? TempTotalDegrees{ get; set; }
}

On view side, I have a Home view with Index.cshtml which is referring Views/Shared/EditorTemplates/University.cshtml as this:

 @using (Ajax.BeginForm("SaveEmployee", new AjaxOptions
 { 
            HttpMethod="POST",
            OnBegin="disableSubmit",
            OnComplete = "enableSubmit",
            OnFailure = "enableSubmit",
            InsertionMode=InsertionMode.Replace
            }))
      {
      @Html.HiddenFor(model=>model.EmployeeId)
      @Html.EditorFor(m => m.University, new { EmployeeId = Model.EmployeeId})

here is how University.cshtml looks:

@Html.HiddenFor(model=>model.UniversityId)
@Html.TextBoxFor(x => Model.TotalDegrees, new { @class="form-control", @min="5",@max="100",@type="number",@value=(Model.TotalDegrees.HasValue ? Model.TotalDegrees.Value : 5)})

on Index.cshtml, when I click on submit button it posts back the Employee object to server but

Employee.University.TotalDegrees is null, even though user fills in the value

If I remove @Html.HiddenFor(model=>model.UniversityId) from University.cshtml, Employee.University comes as null on post.

I have tried to use @Html.EditorFor(model=>model.TotalDegrees) and @Html.TextBoxFor(model=>model.TotalDegrees) but none of them seems to work

If I moved everyfrom from University.cshtml to main View, everything seems to work fine.

Any help or suggestion appreciated.



via Chebli Mohamed

Web API Accept XML Request and pass to another Web API as JSON

We have 2 Web API Layers one for public facing and another one is for internal facing which handles more complex logic etc. All request received by public facing are intercepted,transformed and passed to internal Web API Layer methods.

The Internal Web API only accepts JSON, the public facing can receive XML or JSON request. Can you help/guide how to transform the request posted from public web api into JSON format before it passed to internal facing web api for processing.



via Chebli Mohamed

Navbar does not collapse when zoomed

I am using bootstrap and trying to make navbar to collapse when the browser zoomed. The navbar is displaying when zoomed but cannot display the contents !. What went wrong here? How to enable navbar to collapse and show its contents?

 <div class="navbar navbar-inverse navbar-fixed-top" style="height:70px"> <%--change header div size--%>
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" style="background-color:black" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
               <img src="/pic/photoHeader.jpg" height="60" />
            </div>

            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a runat="server" href="~/">Home</a></li>
                    <li><a runat="server" href="~/About">About Company</a></li>
                    <li id="businessU">
                        <a href="#">Business Units  </a>
                        <ul class="sub-menu">
                            <li><a runat="server" href="~/BusinessUnits/Engineering">Solution Engineering Sdn Bhd</a></li>
                            <li><a runat="server" href="~/BusinessUnits/Bioforce">Solution Bioforce Sdn Bhd </a></li>
                            <li><a runat="server" href="~/BusinessUnits/Biogen">Solution Biogen Sdn Bhd</a></li>
                            <li><a runat="server" href="~/BusinessUnits/AC">Solution A&C Technology Sdn Bhd</a></li>

                        </ul>
                    </li>
                    <li id="Investor">
                        <a href="#">Investor Relations</a>
                        <ul class="sub-menu2">
                            <li><a runat="server" href="~/InvestorRelation/Directors">Directors</a></li>
                            <li><a runat="server" href="~/InvestorRelation/CorporateStructure">Corporate Structure </a></li>
                            <li><a runat="server" href="~/InvestorRelation/News">News</a></li>
                            <li><a runat="server" href="~/InvestorRelation/Events">Events</a></li>
                            <li><a runat="server" href="~/InvestorRelation/Anno">Announcements</a></li>

                        </ul>
                    </li>
                    <li id="contact">
                        <a runat="server" href="#">Contact Us</a>
                        <ul class="sub-menu3">
                          <li><a runat="server" href="~/Contact/Contact">Contact</a></li>
                            <li><a runat="server" href="~/Contact/Whist">Whistleblowing</a></li>
                        </ul>
                    </li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li><asp:LinkButton ID="login1" runat="server" PostBackUrl="~/Login.aspx">Admin Login</asp:LinkButton> </li>
                    <li> <asp:LinkButton ID="Logout" runat="server" CausesValidation="False" onclick="Logout_Click" style="text-align: right">(logout)</asp:LinkButton></li>

               </ul>
            </div>
        </div>
    </div>



via Chebli Mohamed

Security between .NET MVC and WEB API

We are starting a project which will consist in:

  • Web project (ASP.NET MVC)
  • IOS app

and both will consume data from a .NET WEB API service.

The WEB API service will expose a POST Method with the url "user/create". But i don't know how can i avoid another apps for making post to this url? I know i need a security protocol, but i wanted to know which one you recommend me, and if you have, an article where is it explained.

Thanks



via Chebli Mohamed

How to identify the color format of eps/tiff using c#?

I am looking for the library to identify the color format of eps/tiff (grayscale, cmyk or rgb). I have set of file and get the files one by one and identify the color property of eps/tiff. For getting the files I am using iterate one by one using loop then I am strucked to use which library to identify the image property. Please be gentle I am new to Programming world and suggest the logic for my task. :-)



via Chebli Mohamed

Combine multiple SQL queries in SQL Server 2008 into a datatable on ASP.NET using C#

I am trying to combine 2 big SQL queries into one datatable, so I can load it on the webpage.

Query #1:

select
    isnull(SALES_NUM4, '') SalesNo, 
    count(CUS_ID) NumOfCust, 
    count(distinct sales_num) NumOfRep
from 
    (select 
         SALES_NUM4, CUS_ID, SLS_TYPE, SALES_NUM 
     from customer

     union

     select 
         SALES_NUM4, CUS_ID, SLS_TYPE, SALES_NUM 
     from omsdata7.dbo.customer) a
where 
    SALES_NUM4 != '' and SLS_TYPE = '1'
group by 
    SALES_NUM4
order by 
    SALES_NUM4

Query #2:

select 
    isnull(SALES_NUM4, '') SalesNo, 
    count(ORD_NUM) MTD_Ord, 
    convert(decimal(10, 2), sum(ORD_AMT)) MTD_Amt
from 
    (select 
         SALES_NUM4, ORD_DT, ORD_NUM, ORD_AMT 
     from orders

     union

     select 
         SALES_NUM4, ORD_DT, ORD_NUM, ORD_AMT 
     from omsdata7.dbo.orders) a
where 
    DATEADD(day, ORD_DT-4, '1801-01-01') >= DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)
    and DATEADD(day, ORD_DT-4, '1801-01-01') < getdate()
    and SALES_NUM4 != ''
group by 
    SALES_NUM4
order by 
    SALES_NUM4



via Chebli Mohamed

export excel cannot be open .xlsx

I am using asp.net C#, currently doing export excel file. I wish to export in .xlsx. everything seems fine until I open it. The code below is my code for export.

DataTable dt = GetData(sqlcommand);

            if(dt.Rows.Count >0){
                //Create a dummy GridView
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = dt;
                GridView1.DataBind();

                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=InventoryReport.xlsx");
                Response.ContentEncoding = System.Text.Encoding.Unicode;
                Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    //Apply text style to each Row
                    GridView1.Rows[i].Attributes.Add("class", "textmode");
                }
                GridView1.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();

The image below is the error I got after open the .xlsx file.

enter image description here

I hope someone could help on my work. Thanks!! really appreciate if yo could help me on this.. much appreciate!



via Chebli Mohamed

Particular field getting NULL after form post

Hi I'm using Angulajs as front end and ASP.NET WebAPI as backend.

This is my Model class:

 public class UserModel
 {
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 7)]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Phone")]
    public string PhoneNumber { get; set; }


 }

Controller:

// POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await _repo.RegisterUser(userModel);

            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return errorResult;
            }
            return Ok();
        }

This is my Angular Service:

var _saveRegistration = function (registration) {

return $http.post('http://localhost:26264/api/account/register', registration).then(function (response) {

       return response;
 });
};

I'm sending payload P.S This is made up payload

registration:{
    userName:"UserName",
    email: "eamil@emal.com",
    password:"password",
    confirmPassword:"password",
    phone: "9898989898"
  }

When I debug I see all the values in payload but when I set debugger at API Controller "register" method field "PhoneNumber" is null. enter image description here I don't know what wrong I'm doing, please help



via Chebli Mohamed

Sql query to fetch only few records from 1 column based on Condition and show/display it separately using Select query

EDITED: In my Database table, I have 4 column ID ,Action, Name and DateTime with below records:

Action        Name         DateTime

Submit         AA        'date time'
Update         BB        'date time'
Save           CC          'date time'
Match           DD        'date time'
Submit          EE       'date time'
Submit          FF       'date time'
Update         GG      'date time'
Approve       HH    'date time'
Approve        II       'date time'
Update         JJ      'date time'
Match          KK       'date time'
Save           LL        'date time'
Match         MM      'date time'
etc                         'date time'
etc                         'date time'

These records can be repeate multiple time.

I want to select the Name and DateTime from above Table that has Action = Submit and Action = Update; into two separate columns using select query(Just like we get the data using select query).

Example Query:
SELECT Name as SubmitterName , DateTime AS SubmitterDateTime FROM [tbl_WorkflowHistory] Where Action = 'Submit'

SELECT Name as UpdateName , DateTime AS UpdateDateTime FROM [tbl_WorkflowHistory] Where Action = 'Update'

only thing is I want to show the records of both the query together but in 4 separate columns, like below Format:

Output Needed:

SubmitName     SubmitDateTime     UpdateName     UpdateDateTime

    AA                       'datetime'                     BB                       'datetime'
    EE                       'datetime'                     GG                       'datetime'
    FF                       'datetime'                      JJ                        'datetime'
    etc                                                           etc

Under "SubmitName" column, all Names shall come that has Action=Submit along with there respective DateTime in SubmitDateTime column.
Similarly, under "UpdateName" column, all all Names shall come that has Action=Update along with there respective DateTime in UpdateDateTime column. I dont know how to write this query, its just sample to explain my requirement.

And after selecting records like above Output, using sql query, I have to display it in a RadGrid in which data coming inside "SubmitDateTime" column have to show separately (Date separate , Time separate) in 2 different columms of RadGrid i.e., SubmitDate, SubmitTime. Similarly for "UpdateDateTime" i.e., UpdateDate, UpdateTime; as described as Below:

SubmitAction      SubmitDate     SubmitTime     UpdateAction     UpdateDate     UpdateTime

Submit                    'date'                 'time'             Update                    'date'              'time'
Submit                    'date'                 'time'             Update                    'date'              'time'
Submit                    'date'                 'time'             Update                    'date'              'time'
etc

I hope I made my requirement clear. Please let me know how to do this. I am using SQL server database. Please reply. Thanks in advance



via Chebli Mohamed

Can't get email address using Facebook SDK for asp.net

I am using Facebook SDK to get email of user. I write this code in Startup.Auth.css class :

        var x = new FacebookAuthenticationOptions();
        x.Scope.Add("email");
        x.AppId = "421656951358309";
        x.AppSecret = "5a2e5ccf163fe6918b6d6fdc8dda5184";
        x.Provider = new FacebookAuthenticationProvider()
        {
            OnAuthenticated = async context =>
            {

                context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
            }
        };
        x.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
        app.UseFacebookAuthentication(x);

And in controller, I use two method to get email but both methods fail. Here is the methods :

Method 1 : By default, after executing the first line the variable info has email property. But it always return null.

var info = await AuthenticationManager.GetExternalLoginInfoAsync();
string email = info.Email;

Method 2 : I use the following code, it also return null.

var fb = new FacebookClient(access_token.Value);
dynamic me = fb.Get("email");
string email = me.email;

Did I miss something ? or there is another method that I can use. I can get others information such as username, but for email I can't.



via Chebli Mohamed

@Html.LabelFor with an tag inside it

This should be a fairly simple question, all I want to do is use @Html.LabelFor within a razor view. One of my labels is different, it has an <a> tag in it. the problem is when I use LabelFor, it encodes the html as & lt;. I've tried a lot of different approaches to making this happen but none of them are working. Here's the code.

@Html.LabelFor(model => model.Question, new { @for = "Question" })

what should get outputted:

<label for="question"><a href=\"mailto:support@testdomain.com">support@testdomain.com</a></label> ( formatted as a mailto link, stackoverflow just doesn't show it, whether i use code or not)

what does get outputted: <label for="question">support@testdomain.com</a>

(my < have been replaced with & lt ; without the spaces, thus the code shows on the page instead of rendering as a link)

how can I make it output what it should?

note, model.Question is set to <a href="mailto:support@testdomain.com">support@testdomain.com</a>



via Chebli Mohamed

RavenDB within ASP.NET MVC with Unity causes ResolutionFailedException

I have the following:

  • ASP.NET MVC 5
  • RavenDB.Client version="3.0.3690"
  • Unity version="3.5.1404.0"
  • Unity.Mvc latest

Periodically, especially after the ASP.NET application has been idle for some time, upon loading the page I get the following exception:

Exception information: 
    Exception type: ResolutionFailedException 
    Exception message: Resolution of the dependency failed, type = "MyCompany.Web.Controllers.MainController", name = "(none)".
Exception occurred while: Calling constructor XXXXXXXX.
Exception is: FileNotFoundException - Could not load file or assembly 'ICSharpCode.NRefactory.CSharp, Version=5.0.0.0, Culture=neutral, PublicKeyToken=d4bfe873e7598c49' or one of its dependencies. The system cannot find the file specified.

Note that ICSharpCode.NRefactory.CSharp appears to be an embedded assembly inside RavenDB. I don't reference it anywhere in my code, and it's not in the bin folder. I never get this error in a console or WPF application, so it must be something with unloading AppDomains and/or recycling ASP.NET AppPools.

Perhaps the code in Unity.Mvc doesn't handle the unloading of embedded assemblies properly. Or perhaps something is missing from the section of my web.config.

Once I get the error, I hit the F5 (Refresh) button in the browser, and viola, the error goes away and the page loads as expected.

Any idea?

Thanks, -Alec.



via Chebli Mohamed

Button in Gridview showing UpdateProgress on Click

I have a gridview that has many columns within an UpdatePanel, 2 of those columns that are populated with buttons. There is a "Update" button outside of the gridview. When the user clicks "Update", there is a UpdateProgress div that shows up, which is expected. However, when the buttons in the gridview are clicked, it also shows up, which is not what I am intending. How can I exclude these buttons from the UpdateProgress if the gridview itself is in the UpdatePanel? I've tried ChildrenAsTriggers=False and UpdateMode=Conditional but doesn't help. See code being used below.

<asp:UpdateProgress id="UpdateProgress" runat="server">
<ProgressTemplate>
    <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
        <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Updating PO, please wait ..." ToolTip="Updating PO, please wait ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
    </div>
</ProgressTemplate>
</asp:UpdateProgress>


<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="UpdateButton" EventName="Click"/>
</Triggers>

<ContentTemplate>
<!-- Gridview is here -->

</ContentTemplate>

</asp:UpdatePanel>

Example of what's in the gridview:

        <asp:TemplateField HeaderText="Button Column One">
            <HeaderStyle Width="70px" />
            <ItemStyle Wrap="False" HorizontalAlign="Center" Width="70px" />
            <ItemTemplate>
                <asp:Button ID="btnG" runat="server" OnCommand="btnG_Command" Text="View"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False" HeaderText="Drug Details">
            <ItemTemplate>
                <asp:Button ID="btnA" runat="server" OnCommand="btnA_Command" Text="View" />
            </ItemTemplate>
            <HeaderStyle Width="60px" HorizontalAlign="Center" />
            <ItemStyle Width="60px" HorizontalAlign="Center" />
        </asp:TemplateField>



via Chebli Mohamed

Passing Class as an argument to an image click event Handler

I have a Trip object which I am getting from list TripsByTripIds which I want to pass as a parameter to image click event handler down below. how do I pass it?

  foreach (Tripclass Trip in TripsByTripIds )
  {
      ImageButton imageButton = new ImageButton();
      imageButton.ImageUrl = "~/" +Trip.CorridorName+"/"+Trip.Time+"/"+Trip.ImgFileName;
      imageButton.Height = Unit.Pixel(100);
      imageButton.Style.Add("padding", "5px");
      imageButton.Width = Unit.Pixel(100);
      imageButton.Click += new ImageClickEventHandler(imageButton_Click);
      AMSPanel1.Controls.Add(imageButton);
      AMSPanel1.Height = Unit.Pixel(860);
  }

  protected void imageButton_Click(object sender, ImageClickEventArgs fi)
  {
      testimage.ImageUrl = ((ImageButton)sender).ImageUrl;
      lblTime.Text = Trip.Time; 
      lblLocation.Text = Trip.Location; //can't access trip object here
  }    



via Chebli Mohamed

(using ephtmltopdf.dll)Html to pdf conversion is giving a couple of blank pages in pdf while the html looks perfect

using ephtmltopdf.dll and engine.dll Html to pdf conversion is giving a couple of blank pages in pdf while the html looks perfect



via Chebli Mohamed

cannot open database, on code execution - shows exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Cannot open database "aspnet-mywebsite-20150813211505" requested by the login. The login failed.

Trying to connect on local .mdf database in visual studio 2013 - web forms. Created database and c# code for connecting to database. Error shows when i try to execute :

using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-mywebsite-20150813211505;Integrated Security=SSPI;"))
                {
                    SqlCommand cmd = new SqlCommand("select * from Users;");
                    cmd.Connection = con;
                    con.Open();
                    DataSet ds = new DataSet();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds);
                    con.Close();
                }



via Chebli Mohamed

How do I instantiate CachedDataAnnotationsModelMetadata?

I'm trying to test a custom model binder. As part of that process I am creating a new ModelBindingContext to pass into the BindModel method of the custom binder. The problem is that I need to set the MetaData property of the ModelBindingContext as a CachedDataAnnotationsModelMetadata object, but honestly am not sure how to instantiate the object.

The signature for the CachedDataAnnotationsModelMetadata object is:

public CachedDataAnnotationsModelMetadata( CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor )

Does anyone have an example of what the prototype and modelAccessor parameters are supposed to be?

Here's a snippet of the non-functional code.

        // Assemble
        var formCollection = new List<KeyValuePair<string, string>> {
            new KeyValuePair<string, string> ("SomeRequiredProperty", "SomeValue")
        };

        var valueProvider = new System.Web.Http.ValueProviders.Providers.NameValuePairsValueProvider(formCollection, null);

        var metadata = new System.Web.Http.Metadata.Providers.CachedDataAnnotationsModelMetadata(????, ????)

        var bindingContext = new ModelBindingContext {
            ModelName = "ClaimsModelBinderInputModel",
            ValueProvider = valueProvider,
            ModelMetadata = metadata
        };
        var actionContext = new HttpActionContext();

        var httpControllerContext = new HttpControllerContext();
        httpControllerContext.Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/someUri");
        actionContext.ControllerContext = httpControllerContext;

        var cmb = new ClaimsModelBinder();

        // Act
        cmb.BindModel(actionContext, bindingContext);
        // Assert...

I've found a few examples around the net and SO of people interacting with this class, but no concrete example of implementing it.

Thanks in advance!



via Chebli Mohamed

how to make the items in the listview to show eveyone in a line?

i want to make the items in the listview come everyone in a line when it get the data needed from sql. what am trying to do is when i search for a text in the database it shows in the listview and when i search for a new text and show it also in the listview but am recieving them in the same line while i want it to switch to a new line whenever i start a new search. here is the code:

 SqlConnection connection = new SqlConnection("Data Source= localhost; Initial Catalog=wform database; User ID = sa; Password=look@me");
                            string str = "select Add_user From msn_user_tbl where Add_user='" + searchtextbox.Text + "'";

                        SqlCommand  com = new SqlCommand(str, connection);
                        connection.Open();
                        SqlDataAdapter     ad = new SqlDataAdapter(com);
                         DataSet   ds = new DataSet();

                            SqlDataReader reader = com.ExecuteReader();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {

                                ColumnHeader ch = new ColumnHeader();
                                ch.Text = reader.GetName(i);
                                listView1.Columns.Add(ch);
                            }


                            ListViewItem itmX;   


                            while (reader.Read())
                            {
                                itmX = new ListViewItem();
                                itmX.Text = reader.GetValue(0).ToString();

                                for (int i = 1; i < reader.FieldCount; i++)
                                {
                                    itmX.SubItems.Add(reader.GetValue(i).ToString());


                                }
                                listView1.Items.Add(itmX);
                            }  



via Chebli Mohamed

ASP .NET Identity 2.0 and LINQ compound query with group by

I am using ASP .NET Identity 2.0 as my user manager. Right now I want to retrieve the list of all users with RoleId different from "4". My LINQ query looks like this:

            var userList = from entry in this.UserManager.Users
                           from roles in entry.Roles
                           where roles.RoleId != "4"
                           group entry by entry.Id into g
                           select new { g.Id, g.UserName, g.Email, g.EmailConfirmed, g.PhoneNumber, g.PhoneNumberConfirmed, g.Roles };

Unfortunately, group by completely doesn't work and g's parameters are not recognized. Without grouping the list contains separate rows for every user->role and it is not my desired effect. What is wrong in my query?

Edit: Of course each user has a number of roles. If one of them is RoleId == 4 then I do not want his record to be retrieved.



via Chebli Mohamed

.Net Web Application Performance

I have a .net web application utilizing bootstraps. At our office we have very high end machines with great wireless network cards. However people on slower pc's and cheaper network cards are increadably slower, even when they are on a great internet connection. For instance I am writing this on my home machine which is an HP i7-3630QM CPU 2.4GHz, 8gb ram, RalinkRT5390R 802.11 WiFi Card on a 30mbps internet connection. Now I realize HP is crap and the network card is crap. But the problem is this is the type of system most people buy. Long story short the system is at least twice as slow on these machines, most of the time 4 times slower elements just never load at all and my users have to refresh the page a few times to get things to work.

We also have New Relic to measure server speed and it never maxed out on the Microsoft Azure platform. In fact our slowest page is only about a 3.5 second loading time.

We are working on the system to try to implement more ajax, dom cacheing and what not. But nothing so far seems to make a big impact.

So I guess my questions are why would things be so dramatically slower and not work at all some of the time on these machines with crap network cards? Is there any software out there that could help us track down speed issues on the client side? Also is there any services out there anyone could recommend that specializes in .net code optimization for speed improvement?

Thank you in advance.



via Chebli Mohamed

Swashbuckle rename Data Type in Model

I'm putting together a web API that needs to match an external sources XML format and was looking to rename the Data Type objects in the swagger output.

It's working fine on the members of the class but I was wondering if it was possible to override the class name as well.

Example:

[DataContract(Name="OVERRIDECLASSNAME")]
public class TestItem
{
   [DataMember(Name="OVERRIDETHIS")]
   public string toOverride {get; set;}
}

In the generated output I end up seeing Model:

   TestItem {
      OVERRIDETHIS (string, optional)
   }

I'd hope to see

OVERRIDECLASSNAME { OVERRIDETHIS (string, optional) }

Is this possible?

Thanks,



via Chebli Mohamed

ASP.NET Web Api Authentication Methods

I am trying to implement authentication for my web api. I have read about different techniques of api authentication and the token technique is the most reasonable for me.

I read different articles about how to implement token based authentication in asp.net but they all rely on different libraries such as OAuth or Owin which also provide their own method of database interactions.

The thing is that I have already implemented database interaction with abstract repositories and entities and I would like to find out how can I implement api authentication easily and simply without interfering with my current design.

(By the way, my project is built on top of an empty web api project, so it doesn't come with all the bootstrap and authentication classes).

Thank you



via Chebli Mohamed

vendredi 31 juillet 2015

Pivoting a date and value column to get their combination

I have a table with this structure:

+--------+-----------+------------+------+
| userid |   date    |    item    | rank |
+--------+-----------+------------+------+
|  34444 | 01-Jul-15 | pen        |    3 |
|  34444 | 04-Jul-15 | TV         |    2 |
|  34444 | 09-Jul-15 | controller |    1 |
|    531 | 03-Jul-15 | keyboard   |    3 |
|    531 | 06-Jul-15 | pen        |    2 |
|    531 | 10-Jul-15 | bowl       |    1 |
+--------+-----------+------------+------+

Each item has already been ranked based on their dates with a limit of 3 items per user. I have their last 3 items and the dates associated with them. The items can be anything.

I want to produce a view in a way that pivots the date and item combination. For example, the desired view for this table is:

+--------+------------+-----------+-------+-----------+----------+-----------+
| userid |   item1    |   date1   | item2 |   date2   |  item3   |   date3   |
+--------+------------+-----------+-------+-----------+----------+-----------+
|  34444 | controller | 09-Jul-15 | TV    | 04-Jul-15 | pen      | 01-Jul-15 |
|    531 | bowl       | 10-Jul-15 | pen   | 06-Jul-15 | keyboard | 03-Jul-15 |
+--------+------------+-----------+-------+-----------+----------+-----------+

Is this possible?

Thanks

Select rows where jsonb array contains any string in array

This is my SQL so far:

select * from table where table.json_info @> '{"search_tags":["hello", "world"]}'

And this works if the row has BOTH hello and world in the search_tags

I'm wondering if there is a way to include rows that have EITHER hello OR world and of course those that have both.

Thanks to all ahead of time!

Replicating Count() on two querysets from different models in Django

I'm trying to query two models in Django. Both have similar data. Once the queries are merged I want to be able to count the occurences of unique values and add a count column to show this. So far I have:

queryCount = table.objects.values(last_name, first_name)
queryCount = queryCount.annotate(count=Count(last_name))

This works but only for one table. If I add another table (repeat the query with another table) I have options of how to merge the two queries.

I've tried itertools chain but that means I can no longer use distinct() to get unique values.

I've tried the snippet here but again no distinct() function.

I've also tried removing the .annotate(Count) and just getting all the values (without counting) and adding the count() method after merging the two querysets. I'm having the same problem as the merged querysets don't have the Count() method available.

Is this possible in Django or should I just drop to Raw SQL?

Select all MySQL records in the last day that are between a time range of 7am and midnight

I have this query

SELECT * FROM `timeclock_timecard` 
WHERE `clock_in_datetime` > DATE_SUB(CURDATE(), INTERVAL 1 DAY)  

which can get record in the last day but I need to limit to records created after 7AM

Any help please?

Alternative to UDF in aws redshift

I am creating views on a redshift table, but would like to have some sort of argument that I can pass to limit the data I get back from the view. The table is for the whole month and joins take a lot of time. I looked into redshift documentation but it says that redshift doesnot support user-defined functions. Is there any alternative to choose besides views/UDF....

To be particular, I have a query like: “with lookup as(Select DISTINCT * from Table where property_value = 'myproperty' AND time_stamp > ‘2015-07-##’ AND time_stamp < ‘2015-07-##’ order by sortkey) Select * from lookup where ……..”

I wanted to be flexible in changing the time_stamp. Also, would like user to pass arguments to the created view and grab data just for specified timestamps.

Thanks

Doctrine Query Builder Select Count with Case

I have the following sql-statement that I want to transform into doctrine query builder. The goal is to count how many ratings exist with rating value 1 and with rating value 2.

SELECT 
COUNT(CASE WHEN rating.rating = 1 THEN rating.rating END) as rat1, 
COUNT(CASE WHEN rating.rating = 2 THEN rating.rating END) as rat2 
FROM rating 

This sql statement is working fine - but when I try to transform it into a Doctrine statement, it does not anymore. When nothing should get counted (because no ratings for this value exist), it returns me a "1" instead of a 0. How can I tell doctrine to simply return a zero when there is nothing to count? I tried it by removing the "ELSE 0" , but then I get an error that this part is required..

return $qb
        ->addSelect('COUNT(CASE WHEN r.rating = 1 THEN r.rating ELSE 0 END) as rat_1')
        ->addSelect('COUNT(CASE WHEN r.rating = 2 THEN r.rating ELSE 0 END) as rat_2')
        ->getQuery()
        ->getResult();

Regards,

"sum" is not required - example: votings 2,2,2,2,2 should return 5 , because the rating with value 2 got voted 5 times.

How can I group rows that aren't familiar?

My data looks like this: http://ift.tt/1IzPWF4

But I want it to look like:

+------------+------+---+
| 2015-01-01 | walk | 1 |
| 2015-01-01 | run  | 0 |
| 2015-01-01 | bike | 0 |
| 2015-01-02 | walk | 0 |
| 2015-01-02 | run  | 0 |
| 2015-01-02 | bike | 0 |
| 2015-01-03 | walk | 0 |
| 2015-01-03 | run  | 1 |
| 2015-01-03 | bike | 0 |
| 2015-01-04 | walk | 0 |
| 2015-01-04 | run  | 0 |
| 2015-01-04 | bike | 0 |
| 2015-01-05 | walk | 0 |
| 2015-01-05 | run  | 1 |
| 2015-01-05 | bike | 0 |
+------------+------+---+

Each day should have a collection of how many occurrences of each event response happened.

  • The dates are collected from a calendar table and are thus purely static.
  • The event names are numerous and likely to change.
  • Event responses join events for name and other context rules.

Would be a big help to figure this out. At least offer tips for better title (search terms) so I can figure out how to resolve this issue.

This is for processing graphs at activezoo.com. Any advice for other approaches or methods for analyzing data is very welcome.

Thanks

SQL Date Queries

Please help me to understand this SQL Select statement:

Select DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 1, 0)

The 0s are throwing me off.

What is the solution when i want to update list data from Application to exists large records in SQL server (more then 800million records)

Please tell me how to update list data from Application to exists large records in SQL server (more then 800million records).

This mean : i will foreach my List data --> then [select record by id from table in SQL] then if exist record i will update record from Application to SQL server. Because the database very large then 1 record want to be updated will find more than 800million records in SQL--> 1*800million--> so i want to update 100 record then --> 100*800million.

Please help me the best solution to solve this prolem. Thank you so much!

SQL Query taking long time with STUFF function

Example Dataset:

ID  seat    code
15098   1   AA21
15098   2   AA21
15105   1   AA21
15105   1   DD15
15105   1   NN60
15196   1   AA21
15196   2   DD50
15196   2   DD51
15209   1   AA21
15209   3   AA21
15209   2   CC50
15209   1   DD01
15209   3   DD01
15210   1   AA21
15210   2   AA21
15210   3   AA21
15210   1   DD21
15210   2   DD21
15210   3   DD21
15211   1   CC51
15211   1   DD20
15212   1   AA21
15212   1   DD03

and Desired Result is:

ID  seat    Codes
15098   1    AA21
15098   2    AA21
15105   1    AA21, DD15, NN60
15196   1    AA21
15196   2    DD50, DD51
15209   1    AA21, DD01
15209   2    CC50
15209   3    AA21, DD01
15210   1    AA21, DD21
15210   2    AA21, DD21
15210   3    AA21, DD21
15211   1    CC51, DD20
15212   1    AA21, DD03


Example Dataset table query:

CREATE TABLE #Temp(
ID varchar(50),
seat varchar(50), 
code varchar(150))

INSERT INTO #Temp VALUES ('15098', '1', 'AA21');
INSERT INTO #Temp VALUES ('15098', '2', 'AA21');
INSERT INTO #Temp VALUES ('15105', '1', 'AA21');
INSERT INTO #Temp VALUES ('15105', '1', 'DD15');
INSERT INTO #Temp VALUES ('15105', '1', 'NN60');
INSERT INTO #Temp VALUES ('15196', '1', 'AA21');
INSERT INTO #Temp VALUES ('15196', '2', 'DD50');
INSERT INTO #Temp VALUES ('15196', '2', 'DD51');
INSERT INTO #Temp VALUES ('15209', '1', 'AA21');
INSERT INTO #Temp VALUES ('15209', '3', 'AA21');
INSERT INTO #Temp VALUES ('15209', '2', 'CC50');
INSERT INTO #Temp VALUES ('15209', '1', 'DD01');
INSERT INTO #Temp VALUES ('15209', '3', 'DD01');
INSERT INTO #Temp VALUES ('15210', '1', 'AA21');
INSERT INTO #Temp VALUES ('15210', '2', 'AA21');
INSERT INTO #Temp VALUES ('15210', '3', 'AA21');
INSERT INTO #Temp VALUES ('15210', '1', 'DD21');
INSERT INTO #Temp VALUES ('15210', '2', 'DD21');
INSERT INTO #Temp VALUES ('15210', '3', 'DD21');
INSERT INTO #Temp VALUES ('15211', '1', 'CC51');
INSERT INTO #Temp VALUES ('15211', '1', 'DD20');
INSERT INTO #Temp VALUES ('15212', '1', 'AA21');
INSERT INTO #Temp VALUES ('15212', '1', 'DD03');

I am using below query as a part of my SSRS report stored procedure to get the result but it is taking too long to run as my original dataset is more than a 100000 rows. Is there any other efficient way to get the result.

SELECT 
 SS.ID
,SS.seat
,STUFF((SELECT ', ' + CAST(LTRIM(RTRIM(CR.Code)) AS VARCHAR(10)) [text()]
        FROM #Temp CR 
        WHERE CR.ID = SS.ID and CR.seat = SS.seat
        FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,' ') Codes
FROM #Temp SS
GROUP BY SS.ID, SS.seat

Count group by in laravel

My current select statement:

return User::select('id', 'created_at')
                    ->orderBy('created_at', 'desc')
                    ->get()
                    ->groupBy(function($date) {
                        return Carbon::parse($date->created_at)->format('Y m d');
                    });

This currently returns

2015 07 28: [
{
id: 935,
created_at: "2015-07-28 23:00:20"
}
],

2015 07 27: [
{
id: 926,
created_at: "2015-07-27 17:13:58"
},
{
id: 925,
created_at: "2015-07-27 15:00:36"
},
{
id: 924,
created_at: "2015-07-27 13:37:00"
}
]

What I just want is:

Date | Users
-----+------
7/28 | 1
7/27 | 3

table alias for LATERAL VIEW query

Not sure if tableAlias has any practical values in Hive Lateral view query? I think people may be able to use columnAlias directly? It will be great if anyone could show an example when tableAlias has values? Thanks.

http://ift.tt/1pzhrVp

thanks in advance, Lin

retrieve value from sql statement for later use

How can I retrieve the value of TOTAL from the SQL statement below in c# and save it as a variable for use in a following query ?

SELECT  detail.branch, SUM(CONVERT(DECIMAL(8, 2), detail.total)) AS TOTAL, 
        SUM(CONVERT(DECIMAL(8, 2),detail.typeA / 1.2)) AS TA, 
        COUNT(DISTINCT detail.orderid) AS NOR, 
        SUM(DISTINCT header.coupon) AS coupon
FROM    detail INNER JOIN header ON detail.filename = header.filename
WHERE   detail.dates BETWEEN '04/01/2015' AND '04/30/2015' AND branch='SW1'
GROUP BY detail.branch

Primary Key assignment in PostGres

I have table tmp in my postgres database that contains roughly 139 million records. I am trying to move the the columns col1, col2, and col3 to col1, col2, and col3 of another tabled named r4a. I created the table r4a with this query:

CREATE TABLE r4a(
    gid serial NOT NULL,
    col1 double precision,
    col2 double precision,
    col3 double precision,
    the_geom geometry,
    CONSTRAINT r4a_pkey PRIMARY KEY (gid));

I created this insert into query to populate fields in r4a:

INSERT INTO r4a (col1,col2,col3)
SELECT col1, col2, col3
FROM tmp
limit 500;

It populates the gid [PK] serial column with numbers ranging from [14816024-14816523].

How does it determine which 500 records to limit the query too?
Is it choosing to import rows [14816024-14816523] or is it just arbitrarily assigning numbers?

Ideally I want the primary key to begin at 1 and count upwards. Being new to postgres and having such a large (in my opinion) table, I want to make sure I understand what is going on.

Thanks in advance,

dubbbdan

Hive query execution issue

When executing a hive query, here is the output, wondering for "Map 1" and "Reducer 2", what does the 1 and 2 mean?

Map 1: 21/27    Reducer 2: 0/1
Map 1: 22/27    Reducer 2: 0/1
Map 1: 23/27    Reducer 2: 0/1
Map 1: 24/27    Reducer 2: 0/1
Map 1: 26/27    Reducer 2: 0/1
Map 1: 27/27    Reducer 2: 0/1
Map 1: 27/27    Reducer 2: 1/1

thanks in advance, Lin

resultSet not open, works in one case another case not

Why if i query the database from the db class using queryFromDb() i get "ResultSet not open" when it try to do rs.next() for the second time and instead if i try to use queryFromMain everything works?

public class Db {

private String protocol = "jdbc:derby:";
private ResultSet resultSet = null;
private Connection connection = null;
private Statement statement;

public Db(){

    try{
        Properties props = new Properties(); 
        props.put("user", "user");
        props.put("password", "password");

        String dbName = "database";
        connection = DriverManager.getConnection(protocol + dbName  , props);

    }
    catch(SQLException sqle){
        printSQLException(sqle);
    }
}

public ResultSet returnValue(String query){

    try{
        statement = connection.createStatement();

        resultSet = statement.executeQuery(query);  
    }
    catch(SQLException sqle){
        printSQLException(sqle);
    }

    return resultSet;   
}


public void queryFromDb(){
         try {
            statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("SELECT * FROM clsbck ORDER BY id");  
            while(rs.next()){
                System.out.println(rs.getString(2));
                String str = "INSERT INTO cls rck VALUES 2";
                [...]           
                statement.execute(str); 
            }
         } catch (SQLException e) {
            printSQLException(e);
         }  
    }

   }
}

public class Main {
    private static Db db;

    public static void main(String[] args){
        db = new Db();
    }

    public static void queryFromMain(){
        ResultSet rs = db.returnValue("SELECT * FROM clsbck ORDER BY id");
        try {   
           while(rs.next()){
               String str = "INSERT INTO cls rck VALUES 2";     
               [...]
               db.addValue(str);
           }
        } catch (SQLException e) {
            printSQLException(e);
        }   
    }
}

How to order queries of one table based on the sum of a column in a related table

Hello I have a users table with columns

id, username, password

I also have an orders table with columns

id, user_id, price, status

In the index method of the UsersController, I would like to order my users based on the amount of purchases they have made. The purchases of each user can be gotten as the sum of the price of all the orders in which the user_id of the order is equal to the id of a user and in which the order.status of such an order is equal to 4

The restriction in order status is made because users have the possibility of cancelling orders in my system so I'll like to query only the orders which have not been canceled.

Trials

I tried getting the users based on

$users = User::leftJoin('orders', 'users.id', '=', 'orders.user_id')
     ->where('orders.status', '!=', 2)->where('orders.status', '!=', 5)
     ->groupBy('orders.user_id');

But yet I still get errors.

Based on my Models, I could get all the purchases of a particular user by usinng a query such as

 User::find(1)->orders()->where('orders.status', '=', 4)->sum('orders.price') 

Dynamically Using Sheetname in Sql-VBA

rs.Open "SELECT [Sheet1$].ID FROM [Sheet1$] WHERE [Sheet1$].ID IS NULL ", cn, adOpenKeyset, adLockReadOnly

Sheet1, i.e. the name of the sheet in my case is variable in my case and I want to repeat this query for 100 sheets, so how do I dynamically specify the name?

Thanks in advance.

Dapper must declare the scalar variable

I am experiencing issues when trying to used a paramaterized query in Dapper. I have found a number of other users with similar issues but have not been able to resolve the issue.

The code

    public User GetUser(int employeeId)
    {
        var args = new
        {
            EmployeeId = employeeId
        };

        const string sql = @"
                    select 
                        first_name 'FirstName', 
                        last_name 'LastName'
                    from 
                        users 
                    where 
                        employee_id = @EmployeeId 
                ";

        using (var con = MakeConnection())
        {
            var r = con.Query<User>(sql, args);
            return r.FirstOrDefault();
        }
    }

The error

A first chance exception of type 'System.Data.Odbc.OdbcException' occurred in System.Data.dll

Additional information: ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the scalar variable "@EmployeeId".

I have also tried using DynamicParameters and passing that instead but that is not working either

var p = new DynamicParameters();
p.Add("@EmployeeId", employeeId); // I have also tried without the @
//...
var r = con.Query<User>(sql,p);

SQL Server 2014 ShowPlanXML hyperlink crashes ssms

On SQL Server 2014, my client crashes after running a DMV query that shows a query plan. An example of the code:

SELECT TOP 10 
DB_NAME(qt.dbid) as dbname, 
OBJECT_NAME(qt.objectid) 
spname, 
qs.execution_count,
qs.total_logical_reads, 
qs.last_logical_reads,
qs.total_logical_writes, 
qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time,
qs.last_elapsed_time,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE qt.dbid not in (1,2,3,4,18) --system & distribution databases
ORDER BY qs.last_logical_writes DESC, execution_count DESC

The result set for the query_plan column is a hyperlink that displays the actual query plan. Once I click on a row in the query_plan column, the ssms client crashes.

DB2 SQL SELECT top 1 group with join

I'm connecting to a DB2 database and want to use the Max(PO180M1.POORDT) or the TOP 1 grouping by the PO180M2.PHPPN (PARTNO). How would I do this? I think I keep getting close but not getting it to work.

SELECT PO180M2.PHPPN AS PartNo, (PO180M2.PHVNPD || ' ' || PO180M2.PHVNP2) AS PartDesc, 
       PO180M1.POORDT AS OrderDate, PO180M2.PHUNCT AS UnitCost
FROM PO180M1, PO180M2 
WHERE PO180M1.POORNO = PO180M2.PHORNO 
ORDER BY PartNo, OrderDate DESC

Query runs faster without an index. Why?

I have two tables. One of those tables has this schema:

CREATE TABLE `object_master_70974_` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `id_object` int(10) unsigned NOT NULL DEFAULT '0',
 `id_master` int(10) unsigned NOT NULL DEFAULT '0',
 `id_slave` int(10) unsigned NOT NULL DEFAULT '0',
 `id_field` bigint(20) unsigned NOT NULL DEFAULT '0',
 `id_slave_field` bigint(20) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_object`    (`id_object`,`id_master`,`id_slave`,`id_field`,`id_slave_field`),
 KEY `id_object_2` (`id_object`,`id_master`,`id_field`,`id_slave_field`),
 KEY `id_object_3` (`id_object`,`id_slave`,`id_field`),
 KEY `id_object_4` (`id_object`,`id_slave_field`),
 KEY `id_object_5` (`id_object`,`id_master`,`id_slave`,`id_field`),
 KEY `id_object_6` (`id_object`,`id_master`,`id_slave`,`id_slave_field`),
 KEY `id_master` (`id_master`,`id_slave_field`),
 KEY `id_object_7` (`id_object`,`id_field`)
) ENGINE=InnoDB AUTO_INCREMENT=17827 DEFAULT CHARSET=utf8;

As you can see, there is an overlapping index KEY id_object_5 (id_object,id_master,id_slave,id_field) and there is no index that would cover these three fields: id_object, id_master, id_field. However, when I run these two queries:

SELECT f1.id 
FROM object_70974_ f1  
LEFT JOIN object_master_70974_ mss0 ON mss0.id_object IN (70974,71759)  
AND mss0.id_master = 71100 AND mss0.id_slave = 70912 AND mss0.id_field = f1.id

and

SELECT f1.id 
FROM object_70974_ f1  
LEFT JOIN object_master_70974_ mss0 ON mss0.id_object IN (70974,71759)  
AND mss0.id_master = 71100 AND mss0.id_field = f1.id

they both return the same number of rows (since in fact id_slave field does not really matter) - 3530, however, the first query is slower than the second query by one second - 8 and 7 seconds respectively. So, I guess I have to ask two questions - 1) why does the second query run faster, even though it does not use index and 2) why does the first query run so slowly and why does not it use an index (obviously). In short, what the heck is going on?

EDIT

This is the result of EXPLAIN command (identical for both queries):

"id"    "select_type"   "table" "type"  "possible_keys" "key"   "key_len"   "ref"   "rows"  "Extra"
"1" "SIMPLE"    "f1"    "index" \N  "attr_80420_"   "5" \N  "3340"  "Using index"
"1" "SIMPLE"    "mss0"  "ref"   "id_object,id_object_2,id_object_3,id_object_4,id_object_5,id_object_6,id_master,id_object_7"   "id_master" "4" "const" "3529"  "Using where"

EDIT

It's extremely interesting, because if I DROP id_master index (which for some strange reason is used by both queries), then it starts to use id_object_5 index.

EDIT

And, yes, with id_master index being dropped, both queries start to run super-fast. So, I guess there is some trouble with optimizer.

EDIT

I even have a guess what trouble faces the optimizer - it may be incorrectly treats id_slave_field field name in the key, as if it were two fields instead - id_slave and id_field. In this case it becomes reasonable, why it firstly used this key in both queries.

Manipulating a data structure in Pig/Hive

I'm not really sure how to phrase this question, so please redirect me if there is a better place for this question.

Right now I have a data structure, more or less organized like this: enter image description here

I want my data to look like this: enter image description here

Sorry for the images, apparently I can't use markdown to make these!

I realize my question is similar to this one, but ideally I would like to be able to do this in Pig, but knowing how to do it in Hive, R, Python, or Excel/LibreCalc would be useful/interesting too.

I'm not even sure what this kind of data manipulation is called, so directing me to some sort of general wiki page would be helpful.

Stored procedure with parameters in Access

I have this stored procedure that I run in Access.

Private Sub ReviewTrns_Click()
    Dim cdb As DAO.Database, qdf As DAO.QueryDef
        Set cdb = CurrentDb
        Set qdf = cdb.CreateQueryDef("")
        ' get .Connect property from existing ODBC linked table
        qdf.Connect = cdb.TableDefs("dbo_FreeShipping").Connect
        qdf.SQL = "EXEC dbo.UpdateTrns"
        qdf.ReturnsRecords = False
        qdf.Execute dbFailOnError
        Set qdf = Nothing
        Set cdb = Nothing
MsgBox "Records Updated!"

End Sub

It works perfectly. dbo_FreeShipping is a linked table, dbo.UpdateTrns is a stored procedure. I also want to add input value for parameter @variable1

Could it be done with message box input?

Entity Framework SQL query on DateTime

I want to get 5 popular stories using Entity Framework query in a time span for example in 7 days or 14 days. I am storing views in a separate table with DateTime parameters with StoryID.

Stories table:

StoryID   Story
--------------------
1         story one
2         story two 
3         story three
4         story four
5         story five
6         story six

Views table:

ViewID     ViewDate             StoryID
---------------------------------------
  1        2015 07 17 19:00:00        1
  2        2015 07 17 20:00:00        1
  3        2015 07 17 21:00:00        2
  4        2015 07 18 19:00:00        2
  5        2015 07 19 19:00:00        2
  6        2015 07 21 19:00:00        1
  7        2015 07 23 19:00:00        2

Can you guys please help me figuring this out. Thanks

Edit: (so far this is what how I think I should do it)

return _viewdb.ObjectSet.Where(p => DateTime.Now >= EntityFunctions.AddDays(p.ViewDate, -14)).Select(p => new ExampleViewModel
            {
                StoryTitle = p.Sotries.Story,
            }).Take(5);