Suppose I have a method in my controller class that updates the score of a key,value pair in a Redis database. I want to write a unit test to check if the score is not null and is incremented by 1. I just want to see how unit testing works with Redis and how you extract the score from a particular key, value pair and check its validity.

Controller Class //When user refreshes api/do/v1/togglelike/{id}", the score is updated in redis for that user and is incremented by 1;

[HttpGet]
        [Route("api/do/v1/togglelike/{id}")]
        public IHttpActionResult ToggleLike(String id)
        {
            var currentUser = "mike";


            var likeSet = redis1.SortedSetRangeByScore("likes:" + id);
            var likeStatus = redis1.SortedSetScore("likes:" + id, currentUser);

            //Current user has not yet liked the profile
            if (likeStatus == null)
            {
                redis1.SortedSetAdd("likes:" + id, currentUser, 1);
                return Ok("Like Added");

            }
            /*redis1.SortedSetAdd("likes:" + id, currentUser, 1);
            return Ok("Like Added");*/
            else
            {
                double counter = redis1.SortedSetIncrement("likes:" + id, currentUser, 1);
                 redis1.SortedSetAdd("likes:" + id, currentUser, counter);
                 return Ok("Like Added");
                /*redis1.SortedSetRemove("likes:" + id, currentUser);
                return Ok("Like Removed");*/
            }
        }

Test Class: I want to get the score from the key,value pair and check that it is equal to a valid number;

namespace VideoControllerTest
{
    [TestClass]
    public class VideoControllerTest
    {
         IDatabase redis1;

        public VideoControllerTest()
        {
            redis1 = RedisFactory.Connection.GetDatabase();
        }

        [TestMethod]
        public void VideoController_Adview()
        {
            //Arrange
            VideoController controller = new VideoController();
            //Act
            IHttpActionResult actionResult = controller.ToggleLike("video123");

            //Assert; Check to see the counter is incremented by 1 and is not null;

        }
    }
}

I am using the FileUploader control in my web application. I'd like to upload the file in a specified folder. As the specific folder does not exist yet, I have to create the path it in my codes.

However, when I run my application on browser, it gives me UnauthorizedAccessException - An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code.

Additional information: Access to the path 'XFiles/thegiants/' is denied.

I have full permissions for my System and PC administrator account. So I'm not sure how to resolve this.

This is a portion of my codes :

  string teamName= Session["team"].ToString(); 

  string filePath = "XFiles/" + teamName+ "/";

  //If directory does not exist
  if (!Directory.Exists(filePath)) { // if it doesn't exist, create
  Directory.CreateDirectory(filePath);
  }

   f_sourceCode.SaveAs(Server.MapPath(filePath + src));

can somebody help me with this code which is inside a loop?

<td>(@db.Query(selectcorrectanswers + " AND ItemId=@1",userid,row.ItemId).Count * 3 - @db.Query(selectincorrectanswers + " AND ItemId=@1",userid,row.ItemId).Count) / (@db.Query(selectquestions + " AND ItemId=@0",row.ItemId).Count * 3)*100</td>

what i see as output is this: (1 * 3 - 1) / (2 * 3)*100

the numbers are right but the ultimate calculation doesn't take place

I want a floating number with two digits of precision. thanks

this is the code that run on codebehind

    protected void Page_Load(object sender, EventArgs e)
    { 
        string type = Request.QueryString["type"];
        string q =(string) Session["query"];
        string b=(string) Session["bg"];
        string r=(string) Session["rh"];
        string k=(string) Session["key"];

        if (type == "browse") {
            SqlConnection c= db.getConnection();
            c.Open();
            SqlDataAdapter x=new SqlDataAdapter(q,c);
            DataSet ds = new DataSet();
            x.Fill(ds);
            ReportParameter[] parm = new ReportParameter[3];
            parm[0] = new ReportParameter("BT","");
            parm[1] = new ReportParameter("RH",r );
            parm[2] = new ReportParameter("KEY",k );
            ReportViewer1.LocalReport.ReportPath = @".\Reports\DonorsBrowse.rdlc" ;
            ReportViewer1.LocalReport.SetParameters(parm);
            ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1",ds.Tables[0]));
            ReportViewer1.DataBind();

            ReportViewer1.LocalReport.Refresh();


        }

this is the aspx page code

<form id="form1" runat="server">
<div>

</div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">        </asp:ScriptManager>
        <rsweb:ReportViewer ID="ReportViewer1" runat="server"></rsweb:ReportViewer>

</form>

what am i missing.the report view loads but it is empty. it there missing options

I am new to JWT, I am trying to create a simple JWT in javascript, send it to a controller (using web-api), check it in sql database. when I googled the net I found a examples like: //HEAD

  {"typ":"JWT",
          "alg":"HS256"}

//claims

{
  "Id": 445566,
  "name": "Meme Jhon",
  "password": "ticktack"
}

//and signature.

I want to create in Javascript my First JWT but i feel something is missing.. what is the full structure? it's not seem logical to start only with the head (like example above..)I need a full example or explaination or a link to a full example. Thank you

Move data between dual listboxs in asp.net suppose two listboxes have to transfer item of listbox <<, >> using these symbol

I have a DetailsView as Popup and there multiple Textbox rows. All that I need is to find these Text boxes in the c# codebehind. I this it should be seems like this. OnButtonClikc event { TextBox1.Visible = false/true; }

But I can't get the value of TextBox1 in c# code, thanks for any advises.

If i have set of business processes like that :

  • Reward
  • Vacation
  • Course
  • Overtime

And every process has an Insert Method Like this :

 public string InsertReward()
        {
            using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["rr35"].ToString()))
            {
                int affectedRow = -1;
                int req_serial = 0;
                    req_serial = GetMaxSerial(DateTime.Now.Year);
                    StringBuilder cmdTxt = new StringBuilder();
                    cmdTxt.Append(" INSERT INTO RewardProcess(gen_year,gen_ser,bonus_type,bonus_date,bonus_desc,main_code,year,emp_num,active_ser) VALUES (?,?,?,?,?,?,?,?,? ) ");
                    using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
                    {
                        myIfxCmd.CommandType = CommandType.Text;
                        myIfxCmd.Parameters.Add("gen_year", IfxType.Integer);
                        myIfxCmd.Parameters.Add("gen_ser", IfxType.Integer);
                        myIfxCmd.Parameters.Add("bonus_type", IfxType.SmallInt);
                        myIfxCmd.Parameters.Add("bonus_date", IfxType.Date);
                        myIfxCmd.Parameters.Add("bonus_desc", IfxType.NVarChar);
                        myIfxCmd.Parameters.Add("main_code", IfxType.Integer);
                        myIfxCmd.Parameters.Add("year", IfxType.Integer);
                        myIfxCmd.Parameters.Add("emp_num", IfxType.Integer);
                        myIfxCmd.Parameters.Add("active_ser", IfxType.SmallInt);

                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }

                        myIfxCmd.Parameters[0].Value = ((object)Req_year) ?? DBNull.Value;
                        myIfxCmd.Parameters[1].Value = ((object)req_serial) ?? DBNull.Value;
                        myIfxCmd.Parameters[2].Value = ((object)Bonus_type) ?? DBNull.Value;
                        myIfxCmd.Parameters[3].Value = ((object)Bonus_date) ?? DBNull.Value;
                        myIfxCmd.Parameters[4].Value = ((object)Bonus_desc) ?? DBNull.Value;
                        myIfxCmd.Parameters[5].Value = ((object)Main_code) ?? DBNull.Value;
                        myIfxCmd.Parameters[6].Value = ((object)Year) ?? DBNull.Value;
                        myIfxCmd.Parameters[7].Value = ((object)Emp_num) ?? DBNull.Value;
                        myIfxCmd.Parameters[8].Value = ((object)Active_ser) ?? DBNull.Value;
                        affectedRow = myIfxCmd.ExecuteNonQuery();
                    }
                    con.Close();
                    con.Dispose();
                    if (affectedRow > 0)
                    {
                        return DateTime.Now.Year + "," + req_serial;
                    }
                    else if (affectedRow == 0)
                    {
                        return string.Empty;
                    }
                    else
                    {
                        return affectedRow.ToString();
                    }
            }
        }

And After the business process insertion ,i insert transaction with the process ID .

Now I want to create a general method(for all Processes) , this method will check the process ID and call its insertion method and after that call the second method concerning the transaction method . i want all this in one transaction using ambient transaction

Is there something in .net allow to call the method knowing its signature as a string?

Void RootMethod(int processId)
{
   using(TransactionScope scope = new TransactionScope())
     {
         //1-Detect the signature of the insertion method by process id then call it by passing the suitable filled object 
         //2-call transaction method
      } 
}

i want open file xml and find string then replace. but when replace string Only to find two strings and replace this my code

var realpath = "~/template/xml/xmlback";
var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmltest") + ".xml");
var filePath2 = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmlback/test2") + ".xml");
DirectoryInfo dir = new DirectoryInfo(Path.Combine(HttpContext.Current.Server.MapPath(realpath)));
foreach (FileInfo files in dir.GetFiles())
{
    files.Delete();
}
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
strVal = strVal.Replace("Test1", "amir");
strVal = strVal.Replace("Test2", "amir1");
strVal = strVal.Replace("Test3", "amir2");
strVal = strVal.Replace("Test4", "amir3");
strVal = strVal.Replace("Test5", "amir4");
strVal = strVal.Replace("Test6", "amir5");
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);

im try open xml with word and see resultpic

I am working on an asp.net project. Now the thing is that I have to place something at the placeholder after fetching it from database. The problem I am facing is that it's not been placed at the place holder. I have attached the codes. Kindly help.

<div class="form" >
          Recovery Email
            <input type="text" class ="form-control" placeholder= <asp:placeholder id = "DisID" runat ="server"/> <br />

C# Code

public void userName()
{
        String name = "";

        SqlCommand thisCommand = cn.CreateCommand();
        thisCommand.CommandText = "Select * from person;";

        cn.Open();

        SqlDataReader reader = thisCommand.ExecuteReader();

        while (reader.Read())
        {
            name = reader.GetString(0);
        }

        DisID.Controls.Add(new LiteralControl(name));
}

How to get data from a client side database in asp.net web application? I want to build a web application in Visual Studio 2010 where the web application takes data from the user's database which is stored on user's computer and process this data and then copy this data to the web application's database. Is this possible?

I'm pretty new in .Net community, please show mercy haha. I got two questions:

  1. is there any similar implementation of symfony's @paramconverter annotation in ASP.NET (such as a converter attributes)? e.g. the request url, no matter GET/POST/PUT/DELETE, the api request with an id of certain entity and we are able to convert/bind such id into a entity object(say productId in int and convert to Product object)

Expected PseudoCode:

[Route("products/{productId}/comments")]
[ProductConverter]
public HttpResponseMessage getProductComments(Product product) {
    // product here not only with `productId` field, but already converted/bind into `Product`, through repository/data store
    ....
}
  1. Is this good implementation in .Net? I ask for this implementation because I think this pattern able to reduce duplicate code when API requests mainly rely on object id and I able to convert id into an object, before actual use of the object. I can even throw an exception if such Product object not found by such string.

Quite simple question. I have the following code

@Html.Raw(following.Description).ToString()

when this comes from database it has some markup in it (its a forum post but i want to show a snippet in the list without the markup

is there any way to remove this and replace this line or shall I just regex it from the controller?

I want to display different menu items in my header when someone is logged in to my site. Is using mixed code in Razor the best way to do this? or is there a more appropriate way? Also this property is getting set when the user logs into the site, where in the startup process should this be done?

Ex

@if (UserProfiles.IsTeacher)
{
    <li>@Html.ActionLink("Show Teacher Profile", "showteacherprofile", "teacherprofile")</li>
}
else
{
    <li>@Html.ActionLink("Create Teacher Profile", "createteacherprofile", "teacherprofile")</li>
}

i have the following code inside my asp.net mvc Razor view, and i am using Bootstrap 3:-

<dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd>
            @Html.EditorFor(model => model.Name,new { htmlAttributes = new { @class = "form-control", disabled = "disabled" } })
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Description)
        </dt>

        <dd>
            @Html.TextAreaFor(model => model.Description,new { @class = "form-control", disabled = "disabled" } )
        </dd>

The result is that all the editorfor will be too close to each other as follow:-

enter image description here so can anyone adivce how to add some vertical space between items?

I have "ActionResult CreateRecipe(){...}" which calls "Register(){...}" method. I would like to call another view "Login" and return inserted values at view "Login" to "Register(){...}" method:

CreateRecipe View:

[HTTPPost]
public ActionResult CreateRecipe(RecipeModel im)
{
        string userName=string.Empty;
        if (User.Identity.Name == "")
        { userName = Register(im.UserPhone);  }
 }

Register method:

private string Register(string phone)
{
    string userName="";
    userName=RedirectToAction("Login"); //sure enough, it does not work as types are not equal. But, please, whether there is some decision?
    userName=Login();//sure enough, it does not work as types are not equal. But, please, whether there is some decision?
    WebSecurity.Login(userName, userName);                        
}

Login View:

 @model Recipes.Models.Confirmation
 Input name: @Html.TextBoxFor(m=>m.User)

So I have "CreateRecipe view" which takes some data and button to call "Login view". If the user calls Login view and fills data at the Login view, then the data should be returned to Register method.

Is it possible? How to do it? Any help would be greatly appreciated!

This code create thumbnails dynamically:

@foreach (var image in Umbraco.Field("Photo").ToString().Split(',').Select(x=>Umbraco.Media(int.Parse(x))))
{
    <li slideIndex="0"> <a href="#"><img class="t02" src="image.jpg"></a> </li>
}

i need a script to add +1 the [slideIndex], to get this result:

<li slideIndex="0"> <a href="#"><img class="t02" src="image.jpg"></a> </li>
<li slideIndex="1"> <a href="#"><img class="t02" src="image.jpg"></a> </li>
<li slideIndex="2"> <a href="#"><img class="t02" src="image.jpg"></a> </li>

thanks in advance

I'm trying to use a form to gather data and store them in a table and immediately do some calculations on that data and store the results in a separate table.. but I don't seem to be able to read the first table immediately after insertion.. I always encounter a zero in my calculation meaning that the first table is considered empty when trying to calculate (but is not empty when the page is refreshed, meaning that the data finally finds its way to the first table anyway) .. this is the example:

@{
// this is the code that gathers data from a form and stores the data in a table
 foreach(var row in db.Query(selectquestions))
 {
    var questionid = row.QuestionId;
    var answer = Request["Q" + row.QuestionId.ToString()];
    var insertanswers = "INSERT into Answers (UserId,QuestionId,Answer,ExamId) VALUES(@0, @1, @2, @3)";
    db.Execute(insertanswers,userid,questionid,answer,1);
  }

//this is the code that tries to immediately use the data stored by the above statement and store the new calculation results in a separate table

    int totalquestions= db.Query( some query using the first table ).Count();
    int correctanswers= db.Query( some query using the first table ).Count();
    int incorrectanswers=db.Query( some query using the first table ).Count();
    var score= (float)(correctanswers * 3 - incorrectanswers) / (totalquestions * 3)*100;

    var insertscores = "INSERT into Scores (UserId,ExamId,ItemId,Score) VALUES(@0, @1, @2, @3)"; 
    db.Execute(insertscores,userid,1,1,score.ToString());
}

I'm Using web pages/razor/sqlCE .. any advice would be appreciated

I want to manipulate the view that eventually MVC is going to render at run time.

For example at HomeConttroller I do this:

public ActionResult Index()
{
     return View();
}

asp.net mvc has decided to render ~/Views/Home/Index.cshtml i want to change it to something like "~/en/Views/Homem/Index.cshtml". update: i do`not want to use the View(string path) overload.

i mean i want to change the path at the last moment. this question is not a duplicate so please dont vote for closing when you havent undertand the question ... pff

I have a small project which i have a question for. Users fill out a form and after submitting it i wish to wrap each new line in the textarea with <li></li>.

So basically i have the following code.

<textarea name="Questions"></textarea>

On the other submit.cshtml i wish to wrap each newline with <li></li> before the email is sent out. So the email will contain the following

  • Question 1
  • Question 2
  • Question 3
  • Question 4

the information in the textarea gets stored in a variable called Questions I wish to break that variables each new line into <li></li> and store the new value in a second variable called EmailBody to be included in an email.

I know how to do this i PhP but in Razor view engine i'm kind of at a loss. Thanks in advance!

UPDATE Solved it by modifying Aron's code to this.

    foreach (var line in Questions.Split('\n'))
    {
        EmailBody = EmailBody + "<li>" + @line + "</li>";
    }  

My problem is pretty simple, Razer don't render right path to files in Content dictionary. Here is example how I want to render logo:

<img src="@Url.Content("~/Content/assets/img/logo_white.png")" 
     alt="logo" class="brand" 
     data-src="@Url.Content("~/Content/assets/img/logo_white.png")" 
     data-src-retina="@Url.Content("~/Content/assets/img/logo_white_2x.png")" 
     width="93" height="25">

But razer output is just "assets/img/logo_white.png" without Content at begining and right path is "Content/assets/img/logo_white.png".

Where is problem? It seems to me like a bug, but maybe I miss something.