How do I "Unit Test" in C#? [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So I have this method in my project:
public static String MD5Hash(string TextToHash)
{
if ((TextToHash == null) || (TextToHash.Length == 0))
{
return String.Empty;
}
MD5 md5 = new MD5CryptoServiceProvider();
byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
byte[] result = md5.ComputeHash(textToHash);
return System.BitConverter.ToString(result);
}
And I've tried testing like this:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BugMon;
namespace BugMonTesting
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
string pwd = "Password";
string expected = "DC-64-7E-B6-5E-67-11-E1-55-37-52-18-21-2B-39-64";
frmLogIn.MD5Hash(pwd);
Assert.AreEqual(pwd, expected);
}
}
}
But the string pwd does not seem to be passing through the Method when I run the test and stays as "Password".
What am I doing wrong?
Sorry if this is obvious but I've never had to use these tests before.

You're never doing anything with the return value from MD5Hash.
Try this:
string hash = frmLogIn.MD5Hash(pwd);
Assert.AreEqual(hash, expected);
Note that this will only work if MD5Hash returns a string formatted like the expected variable.

Related

Check if cyclic string or not

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 hours ago.
Improve this question
Enter a string of characters S. Indicates whether the string S is cyclic or not.
For example S='abcdabcdabcdabcd' is cyclic.
My teacher want me to do this but i think it's too hard. I'm thinking using SplitString but it's just an idea and i dont know how to do. I'm very thankful if someone gives me help
using System;
using System.Collections;
public class MYCLASSNAME {
public static void Main(string[] args){
var str = "abcdabcdabcdabcd";
Console.Write(checkCyclicString(str));
}
static bool checkCyclicString (string str){
var checkString ="";
for(var i=0;i<str.Length-1;i++){
checkString= checkString+ str[i];
var countOfCycles =0;
var haveCycles = false;
for(var j=i+1;j<str.Length-checkString.Length+1;j= j+checkString.Length){
if(checkString==str.Substring(j,checkString.Length)){
haveCycles = true;
countOfCycles++;
}else{
haveCycles =false;
}
}
if(haveCycles && countOfCycles == Math.Ceiling((double)(str.Length/checkString.Length))-1){
return true;
}
}
return false;
}
}
check the cyclic behavior by creating substrigs and comparing them with all the parts of the given string

C# string equals wont work properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I get response string "true" from php file...
but ,my function always return false ... here is piece of code
public Boolean authorization(String korisnik, String zaporka) {
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["korisnik"] = korisnik;
values["zaporka"] = zaporka;
var response = client.UploadValues("http://localhost/projectX/autorizacija.php", values);
String responseString = Encoding.Default.GetString(response);
System.Diagnostics.Debug.WriteLine(responseString);
if (responseString.Equals("true"))
{
return true;
}
else
{
return false;
}
}
}
Try:
if (responseString.Trim().Equals("true", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else
{
System.Diagnostics.Debug.WriteLine(responseString);
return false;
}
InvariantCultureIgnoreCase = compares strings in a linguistically relevant manner that ignores case
Trim = remove whitespaces
And if false, check output value

C# Error Index was outside the bounds of the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code:
//other streamreader code
var splitsByLine = content.Split('\n');
foreach (var s in splitsByLine)
{
var nameAndSize = s.Split(',');
FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
}
foreach (var item in FileNameAndSizes)
{
if(File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "cleo", item.Key)))
{
FileInfo f = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "cleo", item.Key));
var s1 = f.Length;
if (s1 != item.Value)
{
MessageBox.Show(f.Name + " modified file, please change it to default");
}
}
}
When I run code, i have error in this code:
FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
Index was outside the bounds of the array. and something about 0x0.. I'm C# newbie, how can i fix it?
It's content value:
AnimModByxXx2o1o.cs, 18616
anims.cs, 18780
Dance.cs, 18661
emergencylights.cs, 32213
fps-de-limiter.cs, 17575
neon.cs, 19019
StreamMemFix.cs, 17560
sun.cs, 17662
WEATHERMENUE.cs, 18437
anim.cs, 17637
anim[0].cs, 20684
anim_0_.cs, 19392
anim1.cs, 18744
anim2.cs, 19012
Anim4.cs, 22900
anim228.cs, 19465
P.S I'm tested it with two files:
First file (current) is getting value from mysql, prints it, and then I need to read value with C# app
Second file (working) is create custom file write to it this content, and it's work ok :?
You need to do simple tests to ensure your values before try to work with them:
http://ideone.com/Iyle5C
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Test
{
public static void Main()
{
//other streamreader code
string[] splitsByLine = new string[] { "AnimModByxXx2o1o.cs, 18616",
"anims.cs, 18780",
"Dance.cs, 18661",
"emergencylights.cs, 32213",
"fps-de-limiter.cs, 17575",
"neon.cs, 19019",
"StreamMemFix.cs, 17560",
"sun.cs, 17662",
"WEATHERMENUE.cs, 18437",
"anim.cs, 17637",
"anim[0].cs, 20684",
"anim_0_.cs, 19392",
"anim1.cs, 18744",
"anim2.cs, 19012",
"Anim4.cs, 22900",
"anim228.cs, 19465",
"" };
if (splitsByLine != null && splitsByLine.Any()) // Test
{
foreach (string s in splitsByLine)
{
var nameAndSize = s.Split(',');
if (nameAndSize != null && nameAndSize.Any() && nameAndSize.Count() > 1) // Test
{
Console.WriteLine(String.Concat(nameAndSize[0], " - ", Convert.ToInt64(nameAndSize[1])));
//FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
}
}
}
}
}

program not updating database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Im trying to create a form that allows users to edit a value in the database. My code below runs without error however
This is the calling method
private void BTNSavePool_Click(object sender, EventArgs e)
{
RWCStatTracker.Database.CLSDB.EditPool(TXTEditPool.Text, CMBBXSearchPool.SelectedItem.ToString());
CMBBXSearchPool.Text = "Please select a Pool....";
MessageBox.Show("Pool edited", "Alert");
this.FRMEditPool_Load(this, null);
PNLEditPoolSearch.Show();
}
This is the code in my database connection class
public static void EditPool(String OldName, String NewName)
{
string UPDTStmt = "UPDATE TBL_Pool SET Name = #NewName WHERE Name = #OldName";
SqlConnection conn = GetConnection();
SqlCommand UPDTCmd = new SqlCommand(UPDTStmt, conn);
UPDTCmd.Parameters.AddWithValue("#NewName", NewName);
UPDTCmd.Parameters.AddWithValue("#OldName", OldName);
try { conn.Open(); UPDTCmd.ExecuteNonQuery(); }
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
}
Any ideas why it's not updating?
Most likely the WHERE clause isn't selecting any records.
It may have spaces: "Smith " will not match "Smith" or it may be case sensitive: "Smith" will not match "smith".
Check the data to see if it has spaces and string trim your parameters.
I've just figured out the issue with it, the arguments are in the wrong order
This
public static void EditPool(String OldName, String NewName)
Should be
public static void EditPool(String NewName, String OldName)

ASP.Net Web API Parameter is null [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am using ASP.Net web api for my service, that is called from a third party application. When I test it in chrome postman it works fine in localhost and deployed server, but I have tried it in fiddler, hurl it and the string val is always null, should I be adding something else? I cant understand why it works fine in postman! Going kinda crazy with this one !
Thanks in advance
public bool PostProperty([FromBody] string val)
{
try
{
var reader = new StringReader(val);
var serializer = new XmlSerializer(typeof(property));
var instance = (property)serializer.Deserialize(reader);
}
}
Change your signature to be
public async Task<bool> PostProperty()
{
try
{
var reader = new StringReader(await Request.Content.ReadAsStringAsync());
var serializer = new XmlSerializer(typeof(property));
var instance = (property)serializer.Deserialize(reader);
}
}
or
public bool PostProperty([FromBody] property val)
{
}
If you do the second option, you might have to add the following line to your setup,
config.Formatters.XmlFormatter.UseXmlSerializer = true;

Categories

Resources