问:
How do I hide navbar when i select login or signup in react?
I am trying to hide the Menu component when I select log in my app. I am working with react hooks and I have no idea how to do it.

My main looks like this :

```<code> <div>
        <Menu/>
        <Router>
            {
                domainList === "error" ?
                    (
                        <ErrorMessage
                            message="Error"
                        />
                    )
                    :
                    Boolean(domainList) === true ?
                        (
                            <Main
                                endpoint={endpoint}
                                callbackReFetchDomains={reFetchDomains}
                                domainList={domainList}
                                hasDomainListError={hasDomainListError}
                                appendDomainList={appendDomainList}
                                changeDomainList={changeDomainList}
                            />
                        )
                        :
                        (
                            <LoadingSpinner/>
                        )
            }
        </Router>
    </div>
</code>```

My main looks like this :

```<code><>
        <div>
            {/*Switch will only render the first matched <Route/> child.*/}
            <Menu/>
            <Switch>
                <Route path="/topics">
                    <ExampleComponentStructure/>
                </Route>
                <Route path="/login">
                    <Login/>
                </Route>
                <Route path="/domains">
                    <DomainList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        appendDomainList={props.appendDomainList}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>
                <Route path="/signup">
                    <Signup/>
                </Route>
                <Route path="/users">
                    <UserMaintainList
                        endpoint={props.endpoint}
                    />
                </Route>
                <Route path="/">
                    <StickerList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>

            </Switch>
        </div>
    </>
</code>```

I know that the code is not clean. I am just starting with react and need some help doing this login screen. Thank you.

答:
here is how i done

```<code>       <PublicRoute exact path="/welcome" component={WelcomePageView} />
       <PublicRoute exact path="/signin" component={SignInView} />
        <PublicRoute
          exact
          path="/forgotPassword"
          component={ResetPasswordView}
        />
        <PublicRoute
          exact
          path="/resetPassword"
          component={SetNewPasswordView}
        />
        <RouteWithLayout
          component={UserDashboardView}
          exact
          layout={MainLayout}
          noAccess={true}
          path="/dashboard"
        />
        <RouteWithLayout
          component={ProfileView}
          exact
          layout={MainLayout}
          path="/Profile"
        />
</code>```

PublicRoute.jsx

```<code>import React, { useEffect } from "react"
import { Route, Redirect } from "react-router"
import { connect } from "react-redux"
import { isUserAuthenticated, getAuthErrors, getAccessToken, getUserID } from "../selectors"
import { validateToken, logout } from "../actions/auth"
import { getPersistStatus } from "../selectors/persist"

const PublicRoute = ({
    component: Component,
    isAuthenticated,
    authErrors,
    access_token,
    uid,
    persistStatus,
    logoutUser,
    ...rest
}) => {

    useEffect(() => {
      if (persistStatus && !isAuthenticated) {
            logoutUser()
      }
    }, [persistStatus, isAuthenticated, logoutUser])

    return (
        <Route {...rest} render={props => (
            !isAuthenticated ? (
                <Component {...props} />
            ) : (
                    <Redirect to={{
                        pathname: "/dashboard",
                        state: { from: props.location }
                    }} />
                )
        )} />
    )
}

const mapStateToProps = (state) => ({
    isAuthenticated: isUserAuthenticated(state),
    authErrors: getAuthErrors(state),
    access_token: getAccessToken(state),
    uid: getUserID(state),
    persistStatus: getPersistStatus(state)
})

const mapDispatchToProps = (dispatch) => ({
    logoutUser: () => {
        dispatch(logout())
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(PublicRoute)
</code>```

RouteWithLayout.jsx

```<code>import React from "react"
import { Route } from "react-router-dom"
import PropTypes from "prop-types"

import { useAuthorization } from "./Permissions"

const RouteWithLayout = (props) => {
  const { layout: Layout, component: Component, path, noAccess, ...rest } = props

  const userAccess = useAuthorization(path)

  return (
    <Route
      {...{ path, ...rest }}
      render={(matchProps) => (
        <Layout>
          {noAccess || userAccess.includes("R") ? (
            <Component {...matchProps} />
          ) : (
            <p>You do not have sufficient permissions to view this page</p>
          )}
        </Layout>
      )}
    />
  )
}

RouteWithLayout.propTypes = {
  component: PropTypes.any.isRequired,
  layout: PropTypes.any.isRequired,
  path: PropTypes.string,
}

export default RouteWithLayout

</code>```

Body:
I am trying to hide the Menu component when I select log in my app. I am working with react hooks and I have no idea how to do it.

My main looks like this :

        <Menu/>
        <Router>
            {
                domainList === "error" ?
                    (
                        <ErrorMessage
                            message="Error"
                        />
                    )
                    :
                    Boolean(domainList) === true ?
                        (

                        )
                        :
                        (
                            <LoadingSpinner/>
                        )
            }
        </Router>

My main looks like this :

<>

            {/*Switch will only render the first matched <Route/> child.*/}
            <Menu/>
            <Switch>
                <Route path="/topics">
                    <ExampleComponentStructure/>
                </Route>
                <Route path="/login">
                    <Login/>
                </Route>
                <Route path="/domains">
                    <DomainList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        appendDomainList={props.appendDomainList}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>
                <Route path="/signup">
                    <Signup/>
                </Route>
                <Route path="/users">
                    <UserMaintainList
                        endpoint={props.endpoint}
                    />
                </Route>
                <Route path="/">
                    <StickerList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>

            </Switch>

    </>

I know that the code is not clean. I am just starting with react and need some help doing this login screen. Thank you.

Body:
here is how i done

       <PublicRoute exact path="/welcome" component={WelcomePageView} />
       <PublicRoute exact path="/signin" component={SignInView} />
        <PublicRoute
          exact
          path="/forgotPassword"
          component={ResetPasswordView}
        />
        <PublicRoute
          exact
          path="/resetPassword"
          component={SetNewPasswordView}
        />
        <RouteWithLayout
          component={UserDashboardView}
          exact
          layout={MainLayout}
          noAccess={true}
          path="/dashboard"
        />
        <RouteWithLayout
          component={ProfileView}
          exact
          layout={MainLayout}
          path="/Profile"
        />

PublicRoute.jsx

import React, { useEffect } from "react"
import { Route, Redirect } from "react-router"
import { connect } from "react-redux"
import { isUserAuthenticated, getAuthErrors, getAccessToken, getUserID } from "../selectors"
import { validateToken, logout } from "../actions/auth"
import { getPersistStatus } from "../selectors/persist"

const PublicRoute = ({
    component: Component,
    isAuthenticated,
    authErrors,
    access_token,
    uid,
    persistStatus,
    logoutUser,
    ...rest
}) => {

    useEffect(() => {
      if (persistStatus && !isAuthenticated) {
            logoutUser()
      }
    }, [persistStatus, isAuthenticated, logoutUser])

    return (
        <Route {...rest} render={props => (
            !isAuthenticated ? (
                <Component {...props} />
            ) : (
                    <Redirect to={{
                        pathname: "/dashboard",
                        state: { from: props.location }
                    }} />
                )
        )} />
    )
}

const mapStateToProps = (state) => ({
    isAuthenticated: isUserAuthenticated(state),
    authErrors: getAuthErrors(state),
    access_token: getAccessToken(state),
    uid: getUserID(state),
    persistStatus: getPersistStatus(state)
})

const mapDispatchToProps = (dispatch) => ({
    logoutUser: () => {
        dispatch(logout())
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(PublicRoute)

RouteWithLayout.jsx

import React from "react"
import { Route } from "react-router-dom"
import PropTypes from "prop-types"

import { useAuthorization } from "./Permissions"

const RouteWithLayout = (props) => {
  const { layout: Layout, component: Component, path, noAccess, ...rest } = props

  const userAccess = useAuthorization(path)

  return (
    <Route
      {...{ path, ...rest }}
      render={(matchProps) => (
        <Layout>
          {noAccess || userAccess.includes("R") ? (
            <Component {...matchProps} />
          ) : (
            <p>You do not have sufficient permissions to view this page</p>
          )}
        </Layout>
      )}
    />
  )
}

RouteWithLayout.propTypes = {
  component: PropTypes.any.isRequired,
  layout: PropTypes.any.isRequired,
  path: PropTypes.string,
}

export default RouteWithLayout


来源: stackexchange

问:
Need suggestion to use suitable design pattern to create JAVA objects
I am currently having below parent child relation java objects
JCL > JOB > steps > step > dd

Class looks like below

```<code>public class Jcl {
Private  Job job;
}

public class Job {

private  String jobname;
//Below is direct property of job object
 private  List<Jobparam> jobparam;
//Below is child object of the job object
 private  List<Step> step;

}

public class Step {
private  String stepname;
//Below is direct property of step object
 private  List<Stepparam> stepparam;
//Below is child object of the step object
 private  List<Ddstatement> ddstatement;
 }

public class Stepparam {
private  String name;
private  String value;
}

public class Jobparam{
private  String name;
private  String value;
 }
</code>```

I am using getters and setters to create objects with new instance of each object.

```<code>  Job job = new Job();
    ArrayList<Jobparam> myList = new ArrayList<Jobparam>();

    job.getJobparam().addAll(myList);

   Step step = new Step();
    ArrayList<Stepparam> myList = new ArrayList<Stepparam>();

   jcl.getJob().getStep().add(step);
</code>```

And also jobparam and stepparam have same property.(I want to reuse but donno how)
I feel I am creating each new object every time and this long coding can be avoided by java design pattern.
Any suggestion  how should I proceed to make simple code would be helpful.

答:
```<code>public class Jcl {
    Private  Job job;
}
</code>```

Snippet above isn't really parent-child relation. You're only defining the attribute of class, which you have defined.

However such hierarchical relations could be used to simplify your last two classes eg.:

```<code>public class Parent {
    private  String name;
    private  String value;
}
</code>```

```<code>public class Stepparam extends Parent {
    // whatever makes it different from Jobparam
}
</code>```

```<code>public class Jobparam extends Parent {
    // whatever makes it different from Stepparam
 }
</code>```

I'd suggest you to google object relations in java or check out this article.

ContentLicense: CC BY-SA 4.0

Body:
I am currently having below parent child relation java objects
JCL > JOB > steps > step > dd

Class looks like below

public class Jcl {
Private  Job job;
}

public class Job {

private  String jobname;
//Below is direct property of job object
 private  List<Jobparam> jobparam;
//Below is child object of the job object
 private  List<Step> step;

}

public class Step {
private  String stepname;
//Below is direct property of step object
 private  List<Stepparam> stepparam;
//Below is child object of the step object
 private  List<Ddstatement> ddstatement;
 }

public class Stepparam {
private  String name;
private  String value;
}

public class Jobparam{
private  String name;
private  String value;
 }

I am using getters and setters to create objects with new instance of each object.

  Job job = new Job();
    ArrayList<Jobparam> myList = new ArrayList<Jobparam>();

    job.getJobparam().addAll(myList);

   Step step = new Step();
    ArrayList<Stepparam> myList = new ArrayList<Stepparam>();

   jcl.getJob().getStep().add(step);

And also jobparam and stepparam have same property.(I want to reuse but donno how)
I feel I am creating each new object every time and this long coding can be avoided by java design pattern.
Any suggestion  how should I proceed to make simple code would be helpful.

Body:
public class Jcl {
    Private  Job job;
}

Snippet above isn't really parent-child relation. You're only defining the attribute of class, which you have defined.

However such hierarchical relations could be used to simplify your last two classes eg.:

public class Parent {
    private  String name;
    private  String value;
}

public class Stepparam extends Parent {
    // whatever makes it different from Jobparam
}

public class Jobparam extends Parent {
    // whatever makes it different from Stepparam
 }

I'd suggest you to google object relations in java or check out this article.


问:
How to add a item on title bar in SwiftUI?
I have a navigation bar, and I want to custom it. Here is I want:
navigationBar
I tried the navigationBarItems, but it’s not working.</p>

答:
Adjust to you're needs: </p>

```<code>struct ContentView: View {

    var body: some View {

        NavigationView {
            VStack {
                Text("Test")
            }

            .navigationBarTitle("Summary")
            .navigationBarItems(trailing: Button(action: { }, label: {
                Image("Your image name")
            })
            )

        }

    }

}
</code>```

Body:
Adjust to you're needs:

struct ContentView: View {

    var body: some View {

        NavigationView {
            VStack {
                Text("Test")
            }

            .navigationBarTitle("Summary")
            .navigationBarItems(trailing: Button(action: { }, label: {
                Image("Your image name")
            })
            )

        }

    }

}


问:
PIL: can i have multiple sizes of text of the SAME font? (Python)
Currently trying to have the same font for an image with PIL but with different sizes.

Tried to have two different font instances but it didn't work. How can I do that?

答:
If you're using ImageFont.truetype(), you'll need multiple instances for multiple sizes.

You could neatly wrap this using functools.lru_cache() so a single font/size gets loaded only once during your app:

```<code>from functools import lru_cache

get_font = lru_cache()(ImageFont.truetype)

draw.text((10, 10), "hello", font=get_font("Arial.ttf", 10))
draw.text((10, 50), "world", font=get_font("Arial.ttf", 50))
</code>```

Body:
If you're using ImageFont.truetype(), you'll need multiple instances for multiple sizes.

You could neatly wrap this using functools.lru_cache() so a single font/size gets loaded only once during your app:

from functools import lru_cache

get_font = lru_cache()(ImageFont.truetype)

draw.text((10, 10), "hello", font=get_font("Arial.ttf", 10))
draw.text((10, 50), "world", font=get_font("Arial.ttf", 50))


问:
What is the difference between a theme and a template?
I am trying to migrate my site to Drupal and I am confused about themes and templates. The look and feel of the pages in my current site are completely controlled by template files and CSS. How does it work in Drupal?</p>

答:
I'm confused...

The first answer says that templates and themes have nothing to do with each other, while the second one says themes are just collections of answers.

Which one is right?

OwnerDisplayName: Joana

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: nelovishk


问:
Call function/axios function before component died
I would like to know if it's possible to call function before component died.
I tried a lot of things like the code bellow but it's not working as expected.
Like :

```<code>export const  isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i);
export const  eventName = isOnIOS ? "pagehide" : "beforeunload";
</code>```

```<code>  componentDidUpdate() {
    window.addEventListener(eventName, () => {
      this.handleLogOut();
    });
  }
  componentWillUnmount() {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }
</code>```

It's almost working on computer but quite weird cause sometimes I haven't log of my axios function; on Iphone/Ipad it's not working at all.
So I would like to know if you guys have others ideas about this ?
Thx a lot and have a good day!

答:
We cant get 100% accurate event that the component "died", the componentWillUnmount() method runs only if the window isn't closed and the component went away from browser "paint".
the "beforeunload" event can help but we can't rely on it
read docs
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

as well ass this package also can help

https://www.npmjs.com/package/react-beforeunload

Body:
I would like to know if it's possible to call function before component died.
I tried a lot of things like the code bellow but it's not working as expected.
Like :

export const  isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i);
export const  eventName = isOnIOS ? "pagehide" : "beforeunload";

  componentDidUpdate() {
    window.addEventListener(eventName, () => {
      this.handleLogOut();
    });
  }
  componentWillUnmount() {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }

It's almost working on computer but quite weird cause sometimes I haven't log of my axios function; on Iphone/Ipad it's not working at all.
So I would like to know if you guys have others ideas about this ?
Thx a lot and have a good day!


问:
How to display .cshtml content based on ActionLink in .NET MVC?
My Register.cshtml page contains both Patient and Doctor registration. I have written a script to check if the user is Patient then displays only  information relevant to patient and vice-versa.
If click on register patient then patient information only should insert into the database and the vice-versa for doctor registration.

Currently, If I register patient then it should not take specialization data into database because it is doctor's specific information.

Another problem is that, If I change the specialization or city value from drop down then it throws error:

The ViewData item that has the key 'Specialization' is of type
  'System.String' but must be of type 'IEnumerable'.

Exception Details: System.InvalidOperationException: The ViewData item
  that has the key 'Specialization' is of type 'System.String' but must
  be of type 'IEnumerable'.

Source Error:  @Html.DropDownListFor(x
  => Model.Specialization, Model.Specializations, htmlAttributes: new { @class = "form-control form-control-sm" })

Register.cshtml

```<code>model Aayumitra.Models.RegisterViewModel

<!-- Register Form -->
<div id="accounts-form">
    <div class="account-nav">
        <div class="row">
            <div class="col-md-12 text-center">
                <ul class="d-flex align-items-center justify-content-center">

                    <li>@Html.ActionLink("Login", "Login", "Account", null, new { @class = "mr-4" })</li>
                    <li>@Html.ActionLink("Register", "Register", "Account", null, new { @class = "active" })</li>

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

    <script>
        function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
                vars[key] = value;
            });
            return vars;
        }

        var text = getUrlVars()["profile"];

        let profile;
        if (text) {
            if (text == 'doctor') {
                profile = 'doctor';
            }
            if (text == 'patient') {
                profile = 'patient';
            }
        } else {
            profile = 'patient';
        }
        $(document).ready(function () {
            if (profile === "doctor") {
                $(".doctor").show();
            }
            else {
                $(".doctor").hide();
            }
        });
    </script>

    <div class="container">
        <div class="row py-5 border-top">
            <div class="col-md-6">
                <div class="form-img text-right">
                    <img src="~/Content/images/accounts.png" class="img-fluid" alt="Accounts Image">
                </div>
            </div>
            <div class="col-md-5">
                <div class="card">
                    <div id="form-card-header" class="card-header d-flex justify-content-between bg-white">
                        <h6>Join Aayumitra </h6>
                        <span class="float-right">Are you a Doctor? <span>@Html.ActionLink("register here", "register", "Account", new { profile = "doctor" }, null)</span>

                    </div>

                    <script>
    var formCardHeader = document.getElementById('form-card-header');

    if(profile == 'patient'){
        formCardHeader.innerHTML = `
        <h6>Join Aayumitra </h6>
                            <span class="float-right">Are you a Doctor? <span>@Html.ActionLink("register here", "register", "Account", new { profile="doctor"}, null)</</span>
        `
    }

    if (profile == 'doctor'){
        formCardHeader.innerHTML = `
        <h6 id="join-doctors">Join 1000+ doctors</h6>
                            <span id="not-doctor" class=""text-primary>@Html.ActionLink("Not a doctor?", "register", "Account", new { profile="patient"}, null)</span>
         `
                        }

                    </script>

                    @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {

                        <div class="card-body">
                            <form action="register.chtml?profile=doctor">
                                <div class="form-group">
                                    <label for="FullName">First Name</label>
                                    @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control form-control-sm", placeholder = "First Name" })
                                </div>
                                <div class="form-group">
                                    <label for="FullName">Last Name</label>
                                    @Html.TextBoxFor(m => m.LastName, new { @class = "form-control form-control-sm", placeholder = "First Name" })
                                </div>
                                <div class="form-group">
                                    <label for="email">Email</label>
                                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control form-control-sm", placeholder = "Email ID" })

                                </div>

                                <div class="form-group doctor">
                                    <label for="number">Specialization</label>
                                    @Html.DropDownListFor(x => Model.Specialization, Model.Specializations, htmlAttributes: new { @class = "form-control form-control-sm", placeholder = "Specialization" })
                                </div>

                                <div class="form-group">
                                    <label for="number">City</label>
                                    @Html.DropDownListFor(x => Model.City, Model.Cities, htmlAttributes: new { @class = "form-control form-control-sm", placeholder = "City" })
                                </div>
                                <div class="form-group">
                                    <label for="number">Mobile Number</label>

                                        <div class="col-md-8">
                                            <div class="form-group">
                                                @Html.TextBoxFor(m => m.MobileNumber, new { @class = "form-control form-control-sm", placeholder = "Mobile Number" })
                                            </div>
                                        </div>

                                </div>
                                <div class="form-group">
                                    <label for="password">Create Password</label>
                                    @Html.PasswordFor(m => m.Password, new { @class = "form-control form-control-sm", placeholder = "Password" })

                                </div>

                                <div class="form-group">
                                    <input type="submit" value="Send" class="btn btn-primary btn-block">
                                </div>

                               </form>

                        </div>

                    }

                </div>
            </div>
        </div>
    </div>
</div>
<!-- Register Form End -->
</code>```

Controller

```<code>// GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        var model = new RegisterViewModel();
        List<SelectListItem> SpecialitiesList = GetSpecialities();
        List<SelectListItem> CitiesList = GetCities();
        model.Specializations = SpecialitiesList;
        model.Cities = GetCities();
        return View(model);
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email,FirstName=model.FirstName,LastName=model.LastName,City=model.City, IsDoctor = model.IsDoctor, NMC_Number = model.NMC_Number, Specialization = model.Specialization};

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
               return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }
        return View(model);
    }
</code>```

答: I think the best way to solve it write two register action(doctor,Patient)that doctor and Patient have own view </p>

Body:
My Register.cshtml page contains both Patient and Doctor registration. I have written a script to check if the user is Patient then displays only  information relevant to patient and vice-versa.
If click on register patient then patient information only should insert into the database and the vice-versa for doctor registration.

Currently, If I register patient then it should not take specialization data into database because it is doctor's specific information.

Another problem is that, If I change the specialization or city value from drop down then it throws error:

The ViewData item that has the key 'Specialization' is of type
  'System.String' but must be of type 'IEnumerable'.

Exception Details: System.InvalidOperationException: The ViewData item
  that has the key 'Specialization' is of type 'System.String' but must
  be of type 'IEnumerable'.

Source Error:  @Html.DropDownListFor(x
  => Model.Specialization, Model.Specializations, htmlAttributes: new { @class = "form-control form-control-sm" })

Register.cshtml

model Aayumitra.Models.RegisterViewModel

@Html.ActionLink("Login", "Login", "Account", null, new { @class = "mr-4" })

@Html.ActionLink("Register", "Register", "Account", null, new { @class = "active" })

Join Aayumitra

                        Are you a Doctor? @Html.ActionLink("register here", "register", "Account", new { profile = "doctor" }, null)

                    @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {

                            <form action="register.chtml?profile=doctor">

                                    First Name
                                    @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control form-control-sm", placeholder = "First Name" })

                                    Last Name
                                    @Html.TextBoxFor(m => m.LastName, new { @class = "form-control form-control-sm", placeholder = "First Name" })

                                    Email
                                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control form-control-sm", placeholder = "Email ID" })

                                    Specialization
                                    @Html.DropDownListFor(x => Model.Specialization, Model.Specializations, htmlAttributes: new { @class = "form-control form-control-sm", placeholder = "Specialization" })

                                    City
                                    @Html.DropDownListFor(x => Model.City, Model.Cities, htmlAttributes: new { @class = "form-control form-control-sm", placeholder = "City" })

                                    Mobile Number

                                                @Html.TextBoxFor(m => m.MobileNumber, new { @class = "form-control form-control-sm", placeholder = "Mobile Number" })

                                    Create Password
                                    @Html.PasswordFor(m => m.Password, new { @class = "form-control form-control-sm", placeholder = "Password" })

                                    <input type="submit" value="Send" class="btn btn-primary btn-block">

                               </form>

                    }

Controller

// GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        var model = new RegisterViewModel();
        List<SelectListItem> SpecialitiesList = GetSpecialities();
        List<SelectListItem> CitiesList = GetCities();
        model.Specializations = SpecialitiesList;
        model.Cities = GetCities();
        return View(model);
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email,FirstName=model.FirstName,LastName=model.LastName,City=model.City, IsDoctor = model.IsDoctor, NMC_Number = model.NMC_Number, Specialization = model.Specialization};

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
               return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }
        return View(model);
    }


问:
Edit and Continue using a Local IIS
Is it possible to have the Edit and Continue option enabled on Visual Studio when debugging using Local IIS instead of IIS express?

答:
Based on Ondrej answer, here is a simple code to enable edit-and-continue on all your application-pools in one click:

```<code>SET "APPCMD=%systemroot%\system32\inetsrv\AppCmd.exe"
FOR /F "TOKENS=*" %%f IN ('%APPCMD% list apppool /text:name') DO %APPCMD% set apppool "%%~f" /+environmentVariables.add[@start,name='COMPLUS_ForceEnC',value='1']
PAUSE
</code>```

save this code as "Enable Edit And Continue.bat" and run it (right click on the file and choose "Run as Administrator").

Enjoy!

Title: Edit and Continue using a Local IIS

Body:
Based on Ondrej answer, here is a simple code to enable edit-and-continue on all your application-pools in one click:

SET "APPCMD=%systemroot%\system32\inetsrv\AppCmd.exe"
FOR /F "TOKENS=*" %%f IN ('%APPCMD% list apppool /text:name') DO %APPCMD% set apppool "%%~f" /+environmentVariables.add[@start,name='COMPLUS_ForceEnC',value='1']
PAUSE

save this code as "Enable Edit And Continue.bat" and run it (right click on the file and choose "Run as Administrator").

Enjoy!


问:
socket stops after first receive
I have a BackGroundWorker that i use to listen in a port

It works pretty well, the problems is that after the first receiving it stops working, i tried with a "while(true)" and restarting it in the RunWorkerComplete event but had no success

With stopPoints i can see that it does a console.writeline() with the correct message, then it stops working

```<code>    using System.Net.Sockets;

class Program
{

    private static BackgroundWorker worker = new BackgroundWorker();

    static void Main(string[] args)
    {
        Program P = new Program();

        P.notifyIcon1.Visible = true;
        P.ipaddress = IPAddress.Any;
        P.tcpServer = new TcpServer(P.ipaddress.ToString(), 3001);

        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        //worker.ProgressChanged += worker_ProgressChanged;
        worker.WorkerReportsProgress = true;
        worker.WorkerSupportsCancellation = true;
        if (!worker.IsBusy) worker.RunWorkerAsync();

        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
         IPEndPoint endPoint;
        Socket tcpClient;
        Socket listener;
        int pendingConnectionQueueSize;
        IPAddress ipaddress = IPAddress.Any;

        endPoint = new IPEndPoint(ipaddress, 3001);

        pendingConnectionQueueSize = 100;
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(endPoint);
        listener.Listen(pendingConnectionQueueSize);

        Console.WriteLine("conn..");
        byte[] receiveBuffer = new byte[4096];
        tcpClient = listener.Accept();
        tcpClient.RemoteEndPoint.ToString();

        while (true)
        {
            int rc = tcpClient.Receive(receiveBuffer);
             string msg = Encoding.ASCII.GetString(receiveBuffer);

            if (rc == 0)
                break;

            Console.WriteLine(msg.Trim());
        }

        listener.Close();
    }
    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (!worker.IsBusy) worker.RunWorkerAsync();//restart

    }

}
</code>```

答:
then it stops working

The code shown works, and reads as many times as data is available; I tested it with telnet, and it worked fine (ish - there are still some bugs around the ASCII decode of the buffer, as discussed in comments)!

If it is only reading once, then I can only assume that your client isn't sending more data on the same connection. The code shown only accepts one connection, and then reads it to the end.

Title: socket stops after first receive

Body:
I have a BackGroundWorker that i use to listen in a port

It works pretty well, the problems is that after the first receiving it stops working, i tried with a "while(true)" and restarting it in the RunWorkerComplete event but had no success

With stopPoints i can see that it does a console.writeline() with the correct message, then it stops working

    using System.Net.Sockets;

class Program
{

    private static BackgroundWorker worker = new BackgroundWorker();

    static void Main(string[] args)
    {
        Program P = new Program();

        P.notifyIcon1.Visible = true;
        P.ipaddress = IPAddress.Any;
        P.tcpServer = new TcpServer(P.ipaddress.ToString(), 3001);

        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        //worker.ProgressChanged += worker_ProgressChanged;
        worker.WorkerReportsProgress = true;
        worker.WorkerSupportsCancellation = true;
        if (!worker.IsBusy) worker.RunWorkerAsync();

        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
         IPEndPoint endPoint;
        Socket tcpClient;
        Socket listener;
        int pendingConnectionQueueSize;
        IPAddress ipaddress = IPAddress.Any;

        endPoint = new IPEndPoint(ipaddress, 3001);

        pendingConnectionQueueSize = 100;
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(endPoint);
        listener.Listen(pendingConnectionQueueSize);

        Console.WriteLine("conn..");
        byte[] receiveBuffer = new byte[4096];
        tcpClient = listener.Accept();
        tcpClient.RemoteEndPoint.ToString();

        while (true)
        {
            int rc = tcpClient.Receive(receiveBuffer);
             string msg = Encoding.ASCII.GetString(receiveBuffer);

            if (rc == 0)
                break;

            Console.WriteLine(msg.Trim());
        }

        listener.Close();
    }
    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (!worker.IsBusy) worker.RunWorkerAsync();//restart

    }

}


问:
Bootstrap 4 Change Tab on Hover
Here is the Bootstrap 4 Tab Default tab structure, How to toggle between the tabs on mouse hover? someone kindly add solution using jquery or javascript.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

    Home

    Profile

    Contact

Home

Profile

Contact

```

答:
Try this.</p>

```<code>$(".nav-link").hover(function(){
    $(this).tab('show');
});
</code>```

Title: Bootstrap 4 Change Tab on Hover

Body:
Try this.

$(".nav-link").hover(function(){
    $(this).tab('show');
});


问:
Italic TextView with wrap_contents seems to clip the text at right edge
```<code><TextView android:id="@+id/prodLbl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="#FFFFFF"
    android:textSize="30dip"
    android:textStyle="italic"
    android:text="Magnifico"
    />
</code>```

Seems to clip few pixels from the rightmost character, at least on 480x800 emulator or Nexus One.

To me it looks like a bug, but I'm just an Android beginner.
I tried to add margins to left and right, but it still kept on clipping.
In the end my hack around it was to add a single space on both sides of the text.
Any other solutions?

答:
Add a 3dp padding to the right on your TextView. I tried with 1dp and 2dp, but 3dp seemed to do the trick fully.

android:paddingRight="3dp"

ContentLicense: CC BY-SA 3.0

Body:
<TextView android:id="@+id/prodLbl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="#FFFFFF"
    android:textSize="30dip"
    android:textStyle="italic"
    android:text="Magnifico"
    />

Seems to clip few pixels from the rightmost character, at least on 480x800 emulator or Nexus One.

To me it looks like a bug, but I'm just an Android beginner.
I tried to add margins to left and right, but it still kept on clipping.
In the end my hack around it was to add a single space on both sides of the text.
Any other solutions?


问:
select2 MULTIPLE placeholder does not work
I'm using the following piece of code to select item but placeholder already is not visible. I am using this example select2-bootstrap</p>

```<code>   <div class="form-group" style="width:70px; height:44px;">
  <select class="form-control select2" multiple="multiple" id="select2" placeholder="cawky parky">
    <option>ahoj</option>
    <option>more</option>
    <option>ideme</option>
    <option>na </option>
    <option>pivo?</option>
  </select>
</div>
  <script src="//select2.github.io/select2/select2-3.4.2/select2.js"></script>

$(document).ready(function () {
$("#select2").select2({
    multiple:true,
    placeholder: "haha",
});
</code>```

答:
In your script file:

```<code>$("select").each(function(i,v){
    var that = $(this);
    var placeholder = $(that).attr("data-placeholder");
    $(that).select2({
        placeholder:placeholder
    });
});
</code>```

in your html (add data-placeholder="Your text"):

```<code><select data-placeholder="Yours Placeholder" multiple>
    <option>Value A</option>
    <option>Value B</option>
</select>
</code>```

Body:
I'm using the following piece of code to select item but placeholder already is not visible. I am using this example select2-bootstrap

  <select class="form-control select2" multiple="multiple" id="select2" placeholder="cawky parky">
    <option>ahoj</option>
    <option>more</option>
    <option>ideme</option>
    <option>na </option>
    <option>pivo?</option>
  </select>

$(document).ready(function () {
$("#select2").select2({
    multiple:true,
    placeholder: "haha",
});

Body:
In your script file:

$("select").each(function(i,v){
    var that = $(this);
    var placeholder = $(that).attr("data-placeholder");
    $(that).select2({
        placeholder:placeholder
    });
});

in your html (add data-placeholder="Your text"):

<select data-placeholder="Yours Placeholder" multiple>
    <option>Value A</option>
    <option>Value B</option>
</select>


问:
Excel file not being downloaded when function is called via ajax method
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />
```

<p>This is the code which downloads the file. It was a simple button I added.</p>

<pre class="lang-js prettyprint-override"><code>function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}
</code>```

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}
```

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

答:
There are multiple solutions to this problem:

Solution 1

Let's imagine you have a Product model like this:

```<code>public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

In you controller:

```<code>[HttpPost]
public JsonResult ReportExcel(string id)
{
   // Your Logic Here: <DB operation> on input id
   // or whatsoever ...

    List<Product> list = new List<Product>() {
        new Product{  Id = 1, Name = "A"},
        new Product{  Id = 2, Name = "B"},
        new Product{  Id = 3, Name = "C"},
    };

    return Json(new { records = list }, JsonRequestBehavior.AllowGet);
}
</code>```

Then inside your View (.cshtml), use the JSONToCSVConvertor as a utility function and just Don't touch it as it converts the array of json objects received into Excel and prompts for download.

```<code>@{
    ViewBag.Title = "View export to Excel";
}

<h2>....</h2>

@*  All Your View Content goes here *@
@* This is a sample form *@

<form>
    <div class="form-group">
        <label>Product ID</label>
        <div class="col-md-10">
            <input id="productID" name="productID" class="form-control"/>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input id="submit" type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</form>

@section scripts{
    <script>
        $('#submit').click(function (e) {
            e.preventDefault();

            var ID = $('#productID').val();

            $.ajax({
                cache: false,
                type: 'POST',
                url: '/YourControllerName/ReportExcel',
                data: {id: ID},
                success: function (data) {
                    console.log(data);
                    JSONToCSVConvertor(data.records, "Sample Report", true);
                }
            })
        });

        function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
            //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

            var CSV = 'sep=,' + '\r\n\n';

            //This condition will generate the Label/Header
            if (ShowLabel) {
                var row = "";

                //This loop will extract the label from 1st index of on array
                for (var index in arrData[0]) {

                    //Now convert each value to string and comma-seprated
                    row += index + ',';
                }

                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }

            //1st loop is to extract each row
            for (var i = 0; i < arrData.length; i++) {
                var row = "";

                //2nd loop will extract each column and convert it in string comma-seprated
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }

                row.slice(0, row.length - 1);

                //add a line break after each row
                CSV += row + '\r\n';
            }

            if (CSV == '') {
                alert("Invalid data");
                return;
            }

            //Generate a file name
            var fileName = "MyReport_";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g, "_");

            //Initialize file format you want csv or xls
            var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

            // Now the little tricky part.
            // you can use either>> window.open(uri);
            // but this will not work in some browsers
            // or you will not get the correct file extension

            //this trick will generate a temp <a /> tag
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    </script>
}

</code>```

I ran and built the above code successfully, so feel free to grab and tweak it as you wish.

Also here is the jsFiddle link, thanks to its developer: https://jsfiddle.net/1ecj1rtz/

Solution 2

Call this action method through $.ajax and get the file downloaded:

```<code>public FileResult Export(int id)
 {
    //......... create the physical file ....//

    byte[] fileBytes = File.ReadAllBytes(filePath);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
 }
</code>```

Along with Solution 2, this thread gives you a good idea: https://stackoverflow.com/a/16670517/4687359

Hope this helped. :)

Body:
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />

This is the code which downloads the file. It was a simple button I added.

function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

Body:
There are multiple solutions to this problem:

Solution 1

Let's imagine you have a Product model like this:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

In you controller:

[HttpPost]
public JsonResult ReportExcel(string id)
{
   // Your Logic Here: <DB operation> on input id
   // or whatsoever ...

    List<Product> list = new List<Product>() {
        new Product{  Id = 1, Name = "A"},
        new Product{  Id = 2, Name = "B"},
        new Product{  Id = 3, Name = "C"},
    };

    return Json(new { records = list }, JsonRequestBehavior.AllowGet);
}

Then inside your View (.cshtml), use the JSONToCSVConvertor as a utility function and just Don't touch it as it converts the array of json objects received into Excel and prompts for download.

@{
    ViewBag.Title = "View export to Excel";
}

<h2>....</h2>

@*  All Your View Content goes here *@
@* This is a sample form *@

<form>
    <div class="form-group">
        <label>Product ID</label>
        <div class="col-md-10">
            <input id="productID" name="productID" class="form-control"/>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input id="submit" type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</form>

@section scripts{
    <script>
        $('#submit').click(function (e) {
            e.preventDefault();

            var ID = $('#productID').val();

            $.ajax({
                cache: false,
                type: 'POST',
                url: '/YourControllerName/ReportExcel',
                data: {id: ID},
                success: function (data) {
                    console.log(data);
                    JSONToCSVConvertor(data.records, "Sample Report", true);
                }
            })
        });

        function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
            //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

            var CSV = 'sep=,' + '\r\n\n';

            //This condition will generate the Label/Header
            if (ShowLabel) {
                var row = "";

                //This loop will extract the label from 1st index of on array
                for (var index in arrData[0]) {

                    //Now convert each value to string and comma-seprated
                    row += index + ',';
                }

                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }

            //1st loop is to extract each row
            for (var i = 0; i < arrData.length; i++) {
                var row = "";

                //2nd loop will extract each column and convert it in string comma-seprated
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }

                row.slice(0, row.length - 1);

                //add a line break after each row
                CSV += row + '\r\n';
            }

            if (CSV == '') {
                alert("Invalid data");
                return;
            }

            //Generate a file name
            var fileName = "MyReport_";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g, "_");

            //Initialize file format you want csv or xls
            var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

            // Now the little tricky part.
            // you can use either>> window.open(uri);
            // but this will not work in some browsers
            // or you will not get the correct file extension

            //this trick will generate a temp <a /> tag
            var link = document.createElement("a");
            link.href = uri;

            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";

            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    </script>
}

I ran and built the above code successfully, so feel free to grab and tweak it as you wish.

Also here is the jsFiddle link, thanks to its developer: https://jsfiddle.net/1ecj1rtz/

Solution 2

Call this action method through $.ajax and get the file downloaded:

public FileResult Export(int id)
 {
    //......... create the physical file ....//

    byte[] fileBytes = File.ReadAllBytes(filePath);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
 }

Along with Solution 2, this thread gives you a good idea: https://stackoverflow.com/a/16670517/4687359

Hope this helped. :)


问:
Selenium try/catch click seems to take a long time?
I always have an issue when writing Selenium tests where trying to issue a click on an element that's not ready can result in a StaleElementReference/ElementClickIntercepted exception. This was able to make tests flaky by making tests fail where they succeed if I just wait 2 seconds for an item to be clickable.

I already had a fix for WebElement retrieval where I use implicit waits to wait for an element's appearance for about 2 seconds before I deem it missing, and I've been trying to create a clickElement() function that surrounds the basic click() function to fulfill the same purpose.

Its purpose is to keep trying to click in 100ms increments until it can. I do this by catching exceptions and incrementing a counter for every click and only break out of the loop when either the element is clicked or too many attempts to click have raised exceptions.

This is the function I wrote:

public void clickElement(WebElement element) {
    int maxTimeOut = 50;
    int timeOutCt = 0;
    boolean isTimedOut = false;
    System.out.println("=> Try to click on <" + element.getTagName() + ">");
    while ( !isTimedOut ) {
        try {
            element.click();
            isTimedOut = true; // could click
            System.out.println("\n OK \n");
        } catch (Exception e) {
            waitSeconds(0.1);
            timeOutCt++;
            System.out.println(" \t => Error while attempting to click for the " + timeOutCt +"nd time \n");
            if ( timeOutCt > maxTimeOut ) {
                isTimedOut = true;
                fail("Element <" + element.getTagName() + "> is not clickable. See exception:  " + e);
            }
        }
    }
}
```

<p>waitSeconds is:</p>

```public void waitSeconds(double t) {
    long mT = (long) (t * 1000);
    try {
        System.out.print("\n \t \t ( ) Sleep de " + mT + "secondes");
        Thread.sleep(mT);
        System.out.print(" ... Done \n ");
    }
    catch (InterruptedException e) {
       e.printStackTrace();
    }
}
```

The problem I have is that doing this seems to take an absurdly long time, longer than a millisecond at the very least, at the very least I can say that it lasts more than a second.
I thought maybe my waitSeconds() function didn't work properly but I tested it in a simple program and it works as it should: waitSeconds(0.1) results in a 100ms wait.

So why is it that when clickElement is called and it tries to click on an element multiple times, it can take up to two seconds between two attempts?

Is it the console outputs that are slowing it down?

Or is it the try/catch that's messing everything up?

答:
Suggestion

If you are using implicit wait at the beginning, please remove it and use explicit wait whenever you want to wait.

Use if condition before you trying to perform click i.e if the element is visible then only click on the element

Use the break keyword after you perform to click

Please try this, hope this will resolve your issue.

Body:
I always have an issue when writing Selenium tests where trying to issue a click on an element that's not ready can result in a StaleElementReference/ElementClickIntercepted exception. This was able to make tests flaky by making tests fail where they succeed if I just wait 2 seconds for an item to be clickable.

I already had a fix for WebElement retrieval where I use implicit waits to wait for an element's appearance for about 2 seconds before I deem it missing, and I've been trying to create a clickElement() function that surrounds the basic click() function to fulfill the same purpose.

Its purpose is to keep trying to click in 100ms increments until it can. I do this by catching exceptions and incrementing a counter for every click and only break out of the loop when either the element is clicked or too many attempts to click have raised exceptions.

This is the function I wrote:

public void clickElement(WebElement element) {
    int maxTimeOut = 50;
    int timeOutCt = 0;
    boolean isTimedOut = false;
    System.out.println("=> Try to click on <" + element.getTagName() + ">");
    while ( !isTimedOut ) {
        try {
            element.click();
            isTimedOut = true; // could click
            System.out.println("\n OK \n");
        } catch (Exception e) {
            waitSeconds(0.1);
            timeOutCt++;
            System.out.println(" \t => Error while attempting to click for the " + timeOutCt +"nd time \n");
            if ( timeOutCt > maxTimeOut ) {
                isTimedOut = true;
                fail("Element <" + element.getTagName() + "> is not clickable. See exception:  " + e);
            }
        }
    }
}

waitSeconds is:

public void waitSeconds(double t) {
    long mT = (long) (t * 1000);
    try {
        System.out.print("\n \t \t ( ) Sleep de " + mT + "secondes");
        Thread.sleep(mT);
        System.out.print(" ... Done \n ");
    }
    catch (InterruptedException e) {
       e.printStackTrace();
    }
}

The problem I have is that doing this seems to take an absurdly long time, longer than a millisecond at the very least, at the very least I can say that it lasts more than a second.
I thought maybe my waitSeconds() function didn't work properly but I tested it in a simple program and it works as it should: waitSeconds(0.1) results in a 100ms wait.

So why is it that when clickElement is called and it tries to click on an element multiple times, it can take up to two seconds between two attempts?

Is it the console outputs that are slowing it down?

Or is it the try/catch that's messing everything up?


问:
Passing today's date in Gatling Body using session.set but no success
I am trying to pass today's date in Gatling Body using session.set but no success

I have below code where using joda-time(https://www.joda.org/joda-time/)  timestampfeeder variable is set

```<code>class gamekeeper extends BaseSimulation {
  val  timestampFeeder: String = DateTimeFormat.forPattern("yyyy-MM-dd").print(DateTime.now())

  exec { session => session.set( "TimestampFeeder", timestampFeeder )}

  val createPrivateEvent ={
    exec(
      http("Create Event As WER")
      .post("https://api.cloud/" + {Env} + "/silve-griffin-service/graphql")
      .headers(header)
      .body(ElFileBody("<filename>"))
      .check(status.in(200,201))
      .check(bodyString.saveAs("EventAsWER_Response"))
      .check(jsonPath(path="$.data.createEvent.id")
        .saveAs(key="EventId")
      )
    )
    .exec { session => session.set("NEW_ID", session("EventId").as[String]) }
    .exec{session=>println(session);session}
     //.pause(40,50)
 }

 val scenario4 = scenario("Full GameKeeper tests“)
   .exec(createPrivateEvent)

 setUp(

    scenario4.inject(
      constantConcurrentUsers(userCount) during(testDuration))
      .protocols(httpProtocol)
    )
    .maxDuration(testDuration)

}
</code>```

Here are the contents  of createeventasWERwithcurrentdatetime.txt

```<code>        {
      "query": "mutation createEvent($input: CreateEventInput!) {\n createEvent(input: $input) {\n ...EventFields\n __typename\n }\n}\n\nfragment EventFields on Event {\n id\n status\n title\n format\n limitedSet\n rulesEnforcementLevel\n pairingType\n entryFee {\n amount\n currency\n __typename\n }\n venue {\n id\n name\n latitude\n longitude\n address\n timeZone\n phoneNumber\n emailAddress\n __typename\n }\n capacity\n description\n scheduledStartTime\n estimatedEndTime\n latitude\n longitude\n address\n timeZone\n phoneNumber\n emailAddress\n shortCode\n __typename\n}",
      "variables": {
        "input": {
          "organizationId": "14540",
          "latitude": 47.66499,
          "longitude": -122.38043,
          "phoneNumber": "206-523-9605",
          "emailAddress": "test@gameot.com",
          "title": "PerfTestServicesEvent",
          "format": "DRAFT",
          "pairingType":"SWISS",
          "limitedSet": "CORE2020",
          "rulesEnforcementLevel": "CASUAL",
          "entryFeeAmount": 500,
          "entryFeeCurrency": "USD",
          "venueId": null,
          "capacity": 8,
          "description": "test",
          "timeZone": "America/Los_Angeles",
          "scheduledStartTime": ${TimestampFeeder},
          "estimatedEndTime": "2020-02-15T16:00Z"
        }
      }
    }
</code>```

Seems No success in value substitution ,why session.set is not able to replace the value of TimestampFeeder

答:
The reason that your variable setting doesn't work is that the exec to run that session function isn't chained to or called by anything else - it's just defined in the middle of the gamekeeper class.

You also seem to be confused about feeders - unless you're using the gatling construct of this name, it's probably best to call it something else.

You can easily get this working by having a session function that sets the date and including it at the start of the scenario.

```<code>val scenario4 = scenario("Full GameKeeper tests“)
   .exec(session => session.set("TimestampFeeder",DateTimeFormat.forPattern("yyyy-MM-dd").print(DateTime.now())
   .exec(createPrivateEvent)
</code>```

I don't think you can used your existing TimestampFeeder val as it's only going to get set once at the start of the run - you'd have to make it a function if you want to structure things that way.

Body:
I am trying to pass today's date in Gatling Body using session.set but no success

I have below code where using joda-time(https://www.joda.org/joda-time/)  timestampfeeder variable is set

class gamekeeper extends BaseSimulation {
  val  timestampFeeder: String = DateTimeFormat.forPattern("yyyy-MM-dd").print(DateTime.now())

  exec { session => session.set( "TimestampFeeder", timestampFeeder )}

  val createPrivateEvent ={
    exec(
      http("Create Event As WER")
      .post("https://api.cloud/" + {Env} + "/silve-griffin-service/graphql")
      .headers(header)
      .body(ElFileBody("<filename>"))
      .check(status.in(200,201))
      .check(bodyString.saveAs("EventAsWER_Response"))
      .check(jsonPath(path="$.data.createEvent.id")
        .saveAs(key="EventId")
      )
    )
    .exec { session => session.set("NEW_ID", session("EventId").as[String]) }
    .exec{session=>println(session);session}
     //.pause(40,50)
 }

 val scenario4 = scenario("Full GameKeeper tests“)
   .exec(createPrivateEvent)

 setUp(

    scenario4.inject(
      constantConcurrentUsers(userCount) during(testDuration))
      .protocols(httpProtocol)
    )
    .maxDuration(testDuration)

}

Here are the contents  of createeventasWERwithcurrentdatetime.txt

        {
      "query": "mutation createEvent($input: CreateEventInput!) {\n createEvent(input: $input) {\n ...EventFields\n __typename\n }\n}\n\nfragment EventFields on Event {\n id\n status\n title\n format\n limitedSet\n rulesEnforcementLevel\n pairingType\n entryFee {\n amount\n currency\n __typename\n }\n venue {\n id\n name\n latitude\n longitude\n address\n timeZone\n phoneNumber\n emailAddress\n __typename\n }\n capacity\n description\n scheduledStartTime\n estimatedEndTime\n latitude\n longitude\n address\n timeZone\n phoneNumber\n emailAddress\n shortCode\n __typename\n}",
      "variables": {
        "input": {
          "organizationId": "14540",
          "latitude": 47.66499,
          "longitude": -122.38043,
          "phoneNumber": "206-523-9605",
          "emailAddress": "test@gameot.com",
          "title": "PerfTestServicesEvent",
          "format": "DRAFT",
          "pairingType":"SWISS",
          "limitedSet": "CORE2020",
          "rulesEnforcementLevel": "CASUAL",
          "entryFeeAmount": 500,
          "entryFeeCurrency": "USD",
          "venueId": null,
          "capacity": 8,
          "description": "test",
          "timeZone": "America/Los_Angeles",
          "scheduledStartTime": ${TimestampFeeder},
          "estimatedEndTime": "2020-02-15T16:00Z"
        }
      }
    }

Seems No success in value substitution ,why session.set is not able to replace the value of TimestampFeeder

Body:
The reason that your variable setting doesn't work is that the exec to run that session function isn't chained to or called by anything else - it's just defined in the middle of the gamekeeper class.

You also seem to be confused about feeders - unless you're using the gatling construct of this name, it's probably best to call it something else.

You can easily get this working by having a session function that sets the date and including it at the start of the scenario.

val scenario4 = scenario("Full GameKeeper tests“)
   .exec(session => session.set("TimestampFeeder",DateTimeFormat.forPattern("yyyy-MM-dd").print(DateTime.now())
   .exec(createPrivateEvent)

I don't think you can used your existing TimestampFeeder val as it's only going to get set once at the start of the run - you'd have to make it a function if you want to structure things that way.


问:
change view size relative to anchor point
I'm trying to enable user of scaling images from edges ( touch the edge then drag it )
I've been looking around for a way to change the view size dynamically using LayoutParams while keeping the view position anchored to a specific edge.

```<code>fun View.setSize(width: Int, height: Int) {
val layoutP = layoutParams as ConstraintLayout.LayoutParams
layoutP.width = width
layoutP.height = height
layoutParams = layoutP
requestLayout()}
</code>```

The default behaviour when trying the code above is changing the view width and height while keeping the centre point as its.

I tried to set the desired x,y after changing width and height but this resulted in vibrated behaviour going to centre then my new x,y

I'm looking for the same effect as setting pivotY and pivotX on scaling animation.

答:
I can just put this reference due the fact i never used this, but i think the documentation it's pretty clear about this:

https://developer.android.com/training/gestures/scale

Body:
I'm trying to enable user of scaling images from edges ( touch the edge then drag it )
I've been looking around for a way to change the view size dynamically using LayoutParams while keeping the view position anchored to a specific edge.

fun View.setSize(width: Int, height: Int) {
val layoutP = layoutParams as ConstraintLayout.LayoutParams
layoutP.width = width
layoutP.height = height
layoutParams = layoutP
requestLayout()}

The default behaviour when trying the code above is changing the view width and height while keeping the centre point as its.

I tried to set the desired x,y after changing width and height but this resulted in vibrated behaviour going to centre then my new x,y

I'm looking for the same effect as setting pivotY and pivotX on scaling animation.


问:
How to process 301 redirects with Nuxt ServerMiddleware and Apollo GraphQL
I am currently building a Vue / Nuxt app coupled with a modified Saleor installation to sell products online.

As we are migrating from an existing system we need to be able to process 301 redirects from our old website's URLs into the new websites URLs.

I have modified the API to respond to the following GraphQL query.

```<code>export const CHECK_REDIRECTS_QUERY = gql`
  query Redirect($oldPath: String) {
    redirect(oldPath: $oldPath) {
      oldPath
      newPath
    }
  }
`
</code>```

Following on from this recommendation I have created the following code in a ~/serverMiddleware/redirect.js file

```<code>import { CHECK_REDIRECTS_QUERY } from '~/graphql/navigation/queries'

export default function(req, res, next) {
  console.log('redirects middleware')
  // context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
  this.$apollo
    .query({
      query: CHECK_REDIRECTS_QUERY,
      variables: {
        oldPath: '/test/11/old/'
      }
    })
    .then(({ data }) => {
      if (data.redirect.newUrl !== '') {
        res.writeHead(301, { Location: data.redirect.newUrl })
        res.end()
      }
    })
}
</code>```

I have also added this to my nuxt.config.js file as follows:

```<code> ...
 serverMiddleware: ['~/serverMiddleware/redirect.js'],
 ...
</code>```

This does not work but not only do I not get the redirect I would expect the console.log at the beginning of the function also does not fire.

Additionally, I have also tried using the code as it was written in the github recommendation and this is very "flakey" firing probably twice in about 50 server restarts.

I'm not picking up any console notifications that apollo cannot be used within the servermiddleware and the rest of the site seems to function correctly.

Also, - for clarification - I assume the middleware should just fire automatically on every page and does not need to be called manually from a component?

答:
finally, I found the solution in nuxtjs's github

```<code>res.writeHead(301, { Location: redirect.to })
res.end()
</code>```

Done!

Body:
I am currently building a Vue / Nuxt app coupled with a modified Saleor installation to sell products online.

As we are migrating from an existing system we need to be able to process 301 redirects from our old website's URLs into the new websites URLs.

I have modified the API to respond to the following GraphQL query.

export const CHECK_REDIRECTS_QUERY = gql`
  query Redirect($oldPath: String) {
    redirect(oldPath: $oldPath) {
      oldPath
      newPath
    }
  }
`

Following on from this recommendation I have created the following code in a ~/serverMiddleware/redirect.js file

import { CHECK_REDIRECTS_QUERY } from '~/graphql/navigation/queries'

export default function(req, res, next) {
  console.log('redirects middleware')
  // context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
  this.$apollo
    .query({
      query: CHECK_REDIRECTS_QUERY,
      variables: {
        oldPath: '/test/11/old/'
      }
    })
    .then(({ data }) => {
      if (data.redirect.newUrl !== '') {
        res.writeHead(301, { Location: data.redirect.newUrl })
        res.end()
      }
    })
}

I have also added this to my nuxt.config.js file as follows:

 ...
 serverMiddleware: ['~/serverMiddleware/redirect.js'],
 ...

This does not work but not only do I not get the redirect I would expect the console.log at the beginning of the function also does not fire.

Additionally, I have also tried using the code as it was written in the github recommendation and this is very "flakey" firing probably twice in about 50 server restarts.

I'm not picking up any console notifications that apollo cannot be used within the servermiddleware and the rest of the site seems to function correctly.

Also, - for clarification - I assume the middleware should just fire automatically on every page and does not need to be called manually from a component?

Body:
finally, I found the solution in nuxtjs's github

res.writeHead(301, { Location: redirect.to })
res.end()

Done!


问:
How to pass class type as property
public class Myclass
{
Public Type type {get;set;}
}

While Json serialisation I am getting error “Could not cast or convert from System.String to System.Type”

Can some one help me out here ?

答:
You can implement your own Converter. Take a look on this example and implement on your way.

public class MyClass
{
    [JsonConverter(typeof(JsonTypeConverter))]
    public Type Type { get; set; }
}

public class JsonTypeConverter: JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var type = value as Type;
        writer.WriteValue(type.Name);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Type);
    }
}

```

Title: How to pass class type as property


答:
The exact same code is being injected into the index.html file on one of my sites. By looking at the logs we determined that someone with the IP address 84.16.226.245 had gotten access via FTP. We're not exactly sure how he got in yet, but you might want to take a look at your logs and block that address.

Good luck!

Title: What does this script do?

Body:
Would anybody be able to tell me what the below script does? It keeps injecting itself into our site about every two weeks (always between Sundays and Mondays). We've reloaded our "clean" site dozens of times but it just keeps happening. We've installed and made every security recommendation that we've read but it just keeps getting into all of our index.html files and a few of our php files.

Anybody have any idea of what it does or where it comes from? We could really use some help!


问:
Ruby convert DD/MM/YYYY string to YYYY,MM,DD
I'm collecting a users input as "DD/MM/YYYY"

The aim is to pass into  mktime as csv YYYY,MM,DD.

```<code>puts "Please enter dob in dd/mm/yyyy format;"
inp = gets.chomp
inp = inp.gsub(" ","")
while inp.length != 10
  puts "Please use dd/mm/yyyy format"
  inp = gets.chomp
end
bday = inp.gsub("/",",")

ctime = Time.new
btime = Time.mktime(bday)
lsecs = ctime - btime
ysecs = Time.mktime(2001) - Time.mktime(2000)
rsecs = 1000000000 - lsecs
ryears = rsecs / ysecs
puts "You are currently #{lsecs} seconds old"
puts "You have #{ryears} years until you are a billion seconds old!!"
</code>```

As you can see the only task remaining is to reverse the users input, having trouble finding a compact solution. Feel free to help make this code shorter if you see a way.

Solution:
(with seconds old and years rounded down/delimited)

```<code>def reformat_date(str)
    str.split("/").reverse.join(",")
end

puts "Please enter dob in dd/mm/yyyy format;"
inp = gets.chomp
inp = inp.gsub(" ","")
while inp.length != 10
  puts "Please use dd/mm/yyyy format"
  inp = gets.chomp
  inp = inp.gsub(" ","")
end

ctime = Time.new
btime = Time.mktime(reformat_date(inp))
lsecs = ctime - btime
**lsecdel = lsecs.round(0).to_s.reverse.gsub(/...(?=.)/,'\&,').reverse**
ysecs = Time.mktime(2001) - Time.mktime(2000)
rsecs = 1000000000 - lsecs
ryears = rsecs / ysecs
puts "You are currently #{lsecdel} seconds old"
puts "You have #{ryears.round(2)} years until you are a billion seconds old!!"
</code>```

答:
you can get input in any desired format and use this below to convert into yyyy,mm,dd format

```<code>Date.parse("10/12/1995").strftime('%Y,%m,%d')
</code>```

output : 1995,12,10

Body:
I'm collecting a users input as "DD/MM/YYYY"

The aim is to pass into  mktime as csv YYYY,MM,DD.

puts "Please enter dob in dd/mm/yyyy format;"
inp = gets.chomp
inp = inp.gsub(" ","")
while inp.length != 10
  puts "Please use dd/mm/yyyy format"
  inp = gets.chomp
end
bday = inp.gsub("/",",")

ctime = Time.new
btime = Time.mktime(bday)
lsecs = ctime - btime
ysecs = Time.mktime(2001) - Time.mktime(2000)
rsecs = 1000000000 - lsecs
ryears = rsecs / ysecs
puts "You are currently #{lsecs} seconds old"
puts "You have #{ryears} years until you are a billion seconds old!!"

As you can see the only task remaining is to reverse the users input, having trouble finding a compact solution. Feel free to help make this code shorter if you see a way.

Solution:
(with seconds old and years rounded down/delimited)

def reformat_date(str)
    str.split("/").reverse.join(",")
end

puts "Please enter dob in dd/mm/yyyy format;"
inp = gets.chomp
inp = inp.gsub(" ","")
while inp.length != 10
  puts "Please use dd/mm/yyyy format"
  inp = gets.chomp
  inp = inp.gsub(" ","")
end

ctime = Time.new
btime = Time.mktime(reformat_date(inp))
lsecs = ctime - btime
**lsecdel = lsecs.round(0).to_s.reverse.gsub(/...(?=.)/,'\&,').reverse**
ysecs = Time.mktime(2001) - Time.mktime(2000)
rsecs = 1000000000 - lsecs
ryears = rsecs / ysecs
puts "You are currently #{lsecdel} seconds old"
puts "You have #{ryears.round(2)} years until you are a billion seconds old!!"

Body:
you can get input in any desired format and use this below to convert into yyyy,mm,dd format

Date.parse("10/12/1995").strftime('%Y,%m,%d')

output : 1995,12,10


问:
How can I change datagridview table with combobox?
I try change datagridview table with combobox. But I can't change with parameters. How can I change database table?

```<code>public DataTable TableLoad()
    {
        DataSet AL2020DS = new DataSet();
        SqlDataAdapter SQLDA = new SqlDataAdapter();
        SqlCommand Cmd1;
        string Sql = "SELECT * FROM @value ORDER BY [Donanım Seri No] ASC";
        Cmd1 = new SqlCommand(Sql, con);
        Cmd1.Parameters.AddWithValue("@value", cbbox_llisteler.Text);
        SQLDA.SelectCommand = Cmd1;
        DataTable AL2020DT = new DataTable();
        SQLDA.Fill(AL2020DT);
        return AL2020DT;
    }

public Form1()
    {
        InitializeComponent();
        dataGridView1.DataSource = TableLoad();
    }
</code>```

When I try this parameters command ı get this error : Must declare the table variable "@value"

答:
Your @value is not interpolated. Either use string.Format() or if you are using C#6 then use the below syntax. Also, notice I have removed ASC as that's default and no need of mentioning it.

```<code>string Sql = $"SELECT * FROM {value} ORDER BY [Donanım Seri No]";
</code>```

Again, in the below code line you are trying to pass table name as parameter which is not possible. You can only pass query parameter as parameter and not table/column name.

So essentially you would do like

```<code>    string Sql = $"SELECT * FROM {cbbox_llisteler.Text} ORDER BY [Donanım Seri No] ASC";
    Cmd1 = new SqlCommand(Sql, con);
    SQLDA.SelectCommand = Cmd1;
</code>```

Body:
I try change datagridview table with combobox. But I can't change with parameters. How can I change database table?

public DataTable TableLoad()
    {
        DataSet AL2020DS = new DataSet();
        SqlDataAdapter SQLDA = new SqlDataAdapter();
        SqlCommand Cmd1;
        string Sql = "SELECT * FROM @value ORDER BY [Donanım Seri No] ASC";
        Cmd1 = new SqlCommand(Sql, con);
        Cmd1.Parameters.AddWithValue("@value", cbbox_llisteler.Text);
        SQLDA.SelectCommand = Cmd1;
        DataTable AL2020DT = new DataTable();
        SQLDA.Fill(AL2020DT);
        return AL2020DT;
    }

public Form1()
    {
        InitializeComponent();
        dataGridView1.DataSource = TableLoad();
    }

When I try this parameters command ı get this error : Must declare the table variable "@value"

Body:
Your @value is not interpolated. Either use string.Format() or if you are using C#6 then use the below syntax. Also, notice I have removed ASC as that's default and no need of mentioning it.

string Sql = $"SELECT * FROM {value} ORDER BY [Donanım Seri No]";

Again, in the below code line you are trying to pass table name as parameter which is not possible. You can only pass query parameter as parameter and not table/column name.

So essentially you would do like

    string Sql = $"SELECT * FROM {cbbox_llisteler.Text} ORDER BY [Donanım Seri No] ASC";
    Cmd1 = new SqlCommand(Sql, con);
    SQLDA.SelectCommand = Cmd1;


问:
Not able to show , as a decimal separator in android softkeyboard
I am trying to show "," instead of "." as a decimal separator in android soft keyboard, but I am not able to achieve the same. Below is the code what i tried.
...

```<code>DecimalFormat decFormat = (DecimalFormat)
DecimalFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
</code>```

...

I also wrote class which is extending NumberKeyListener and used the same while setting keylistener for editext. But Still not working

```<code>public class DecimalDigitsInputFilter extends NumberKeyListener {

    private static final char[][] CHARACTERS = new char[][] {
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' },
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' },
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',' },
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', ',' },
    };

    private char[] mAccepted;
    private boolean mSign;
    private boolean mDecimal;

    private static final int SIGN = 1;
    private static final int DECIMAL = 2;

    private static DecimalDigitsInputFilter[] sInstance = new DecimalDigitsInputFilter[4];

    @Override
    protected char[] getAcceptedChars() {
        return mAccepted;
    }

    public DecimalDigitsInputFilter() {
        this(false, false);
    }

    public DecimalDigitsInputFilter(boolean sign, boolean decimal) {
        mSign = sign;
        mDecimal = decimal;

        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);
        mAccepted = CHARACTERS[kind];
    }

    public static DecimalDigitsInputFilter getInstance() {
        return getInstance(false, false);
    }

    public static DecimalDigitsInputFilter getInstance(boolean sign, boolean decimal) {
        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);

        if (sInstance[kind] != null)
            return sInstance[kind];

        sInstance[kind] = new DecimalDigitsInputFilter(sign, decimal);
        return sInstance[kind];
    }

    public static DecimalDigitsInputFilter getInstance(String accepted) {
        DecimalDigitsInputFilter dim = new DecimalDigitsInputFilter();

        dim.mAccepted = new char[accepted.length()];
        accepted.getChars(0, accepted.length(), dim.mAccepted, 0);

        return dim;
    }

    @Override
    public int getInputType() {
        return InputType.TYPE_CLASS_NUMBER
                | InputType.TYPE_NUMBER_FLAG_DECIMAL
                | InputType.TYPE_NUMBER_FLAG_SIGNED;
    }

}
</code>```

And used above class like this

```<code>mWeightEditText.setKeyListener(new DecimalDigitsInputFilter(false, true));
</code>```

答:
you can not show a comma instead of the dot on the android soft keyboard.

You can extend the NumberKeyListener to accept ',' and '.' like this:

```<code>@Override
public int getInputType() {
   return InputType.TYPE_CLASS_NUMBER
          | InputType.TYPE_NUMBER_FLAG_DECIMAL
          | InputType.TYPE_NUMBER_FLAG_SIGNED;
}
</code>```

Furthermore you can set a TextWatcher on the EditText, which replaced all '.' with ',' in afterTextChanged() method.

another way that you can try is the followings:
xml:

```<code><EditText
    android:inputType="number"
    android:digits="0123456789.," />
</code>```

in the code:

```<code>EditText input = new EditText(THE_CONTEXT);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));
</code>```

In this way, the Android will show the numbers' keyboard and allow the input of the comma and also if the user presses the '.' button nothing happens. (you can add '.' in xml and code so user be able to enter '.' too).

Body:
I am trying to show "," instead of "." as a decimal separator in android soft keyboard, but I am not able to achieve the same. Below is the code what i tried.
...

DecimalFormat decFormat = (DecimalFormat)
DecimalFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));

...

I also wrote class which is extending NumberKeyListener and used the same while setting keylistener for editext. But Still not working

public class DecimalDigitsInputFilter extends NumberKeyListener {

    private static final char[][] CHARACTERS = new char[][] {
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' },
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' },
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',' },
            new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', ',' },
    };

    private char[] mAccepted;
    private boolean mSign;
    private boolean mDecimal;

    private static final int SIGN = 1;
    private static final int DECIMAL = 2;

    private static DecimalDigitsInputFilter[] sInstance = new DecimalDigitsInputFilter[4];

    @Override
    protected char[] getAcceptedChars() {
        return mAccepted;
    }

    public DecimalDigitsInputFilter() {
        this(false, false);
    }

    public DecimalDigitsInputFilter(boolean sign, boolean decimal) {
        mSign = sign;
        mDecimal = decimal;

        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);
        mAccepted = CHARACTERS[kind];
    }

    public static DecimalDigitsInputFilter getInstance() {
        return getInstance(false, false);
    }

    public static DecimalDigitsInputFilter getInstance(boolean sign, boolean decimal) {
        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);

        if (sInstance[kind] != null)
            return sInstance[kind];

        sInstance[kind] = new DecimalDigitsInputFilter(sign, decimal);
        return sInstance[kind];
    }

    public static DecimalDigitsInputFilter getInstance(String accepted) {
        DecimalDigitsInputFilter dim = new DecimalDigitsInputFilter();

        dim.mAccepted = new char[accepted.length()];
        accepted.getChars(0, accepted.length(), dim.mAccepted, 0);

        return dim;
    }

    @Override
    public int getInputType() {
        return InputType.TYPE_CLASS_NUMBER
                | InputType.TYPE_NUMBER_FLAG_DECIMAL
                | InputType.TYPE_NUMBER_FLAG_SIGNED;
    }

}

And used above class like this

mWeightEditText.setKeyListener(new DecimalDigitsInputFilter(false, true));

Body:
you can not show a comma instead of the dot on the android soft keyboard.

You can extend the NumberKeyListener to accept ',' and '.' like this:

@Override
public int getInputType() {
   return InputType.TYPE_CLASS_NUMBER
          | InputType.TYPE_NUMBER_FLAG_DECIMAL
          | InputType.TYPE_NUMBER_FLAG_SIGNED;
}

Furthermore you can set a TextWatcher on the EditText, which replaced all '.' with ',' in afterTextChanged() method.

another way that you can try is the followings:
xml:

<EditText
    android:inputType="number"
    android:digits="0123456789.," />

in the code:

EditText input = new EditText(THE_CONTEXT);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));

In this way, the Android will show the numbers' keyboard and allow the input of the comma and also if the user presses the '.' button nothing happens. (you can add '.' in xml and code so user be able to enter '.' too).