interpret string as variable in C# - c#-4.0

I have some public const strings in c# console application as shown below:
//Account one
public const string POP_USER1 = "abc#abcd.com";
public const string POP_PWD1 = "abc";
//Account two
public const string POP_USER2 = "xyz#abcd.com";
public const string POP_PWD2 = "xyz";
//Account three
public const string POP_USER3 = "pqr#abcd.com";
public const string POP_PWD3 = "pqr;
We are using c# MailMan to retrieve emails present in those accounts.
I simply wrote a for loop 3 times:
for (int i = 1; i <= 3; i++)
{
eEmails obj = new eEmails (i);
}
In the constructor of eEmails, I am writing the below logic:
public eEmails (int counter)
{
MailMan obj = new MailMan()
obj.PopUsername = "POP_USER" + counter;
obj.PopPassword = "POP_PWD" + counter;
}
The lines where I am assigning user name and passwords, I need to fetch the exact const variable (i.e., POP_USER1, POP_USER2, POP_USER3 etc.,)
However I am not able to get the variable dynamically.
I can simply write 3 if blocks in eEmails (int counter), but I didnt like that way.
can somebody advise a better way of handling this situation without using separate if blocks for each user??

Use a class instead of strings, then your code becomes more redable and maintainable and it'll also be less error-prone. Here is an example using a List<PopServerAccount> as container:
public class PopServerAccount
{
public string Username {get;set;}
public string Password {get;set;}
public override bool Equals(object obj)
{
PopServerAccount p2 = obj as PopServerAccount;
if (p2 == null) return false;
return Username == p2.Username;
}
public override int GetHashCode()
{
return Username.GetHashCode();
}
public override string ToString()
{
return Username;
}
}
now change the signature of your method:
public eEmails (PopServerAccount pop)
{
MailMan obj = new MailMan()
obj.PopUsername = pop.Username;
obj.PopPassword = pop.Password;
}
Sample data:
var myPopServers = new List<PopServerAccount>
{
new PopServerAccount{ Username = "abc#abcd.com", Password = "abc"},new PopServerAccount{ Username = "xyz#abcd.com", Password = "xyz"}
};
Use a loop and call your method:
foreach (PopServerAccount pop in myPopServers)
{
eEmails(pop);
}

Related

How can I export tables in Excel file using ASP.Net MVC?

My View consists of multiple tables, and I am looking to Export multiple tables from View in Excel file. My current function only helps me to export 1 table.
Can any one help me to complete this code so that multiple tables can be exported?
Report VM
public class ReportVM
{
public string ScenName { get; set; }
public int Count { get; set; }
public string CreateTickYes { get; set; }
public int TickYes { get; set; }
public string RegionName { get; set; }
public int RegionCount { get; set; }
public string UserName { get; set; }
public int ChatCountUser { get; set; }
}
Action Method to export
public FileContentResult DownloadReport(DateTime start, DateTime end)
{
//var uName = User.Identity.Name;
var fileDownloadName = String.Format("Report.xlsx");
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Pass your ef data to method
ExcelPackage package = GenerateExcelFile(db.Chats.Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) >= start && System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) <= end)
.GroupBy(a => a.ScenarioList).Select(b => new ReportVM()
{
ScenName = b.Key,
Count = b.Count()
}).ToList());
var fsr = new FileContentResult(package.GetAsByteArray(), contentType);
fsr.FileDownloadName = fileDownloadName;
return fsr;
}
private static ExcelPackage GenerateExcelFile(IEnumerable<ReportVM> datasource)
{
ExcelPackage pck = new ExcelPackage();
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1");
// Sets Headers
ws.Cells[1, 1].Value = "Scenario";
ws.Cells[1, 2].Value = "No.Of Chats";
// Inserts Data
for (int i = 0; i < datasource.Count(); i++)
{
ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).ScenName;
ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).Count;
}
//Sheet2
// Format Header of Table
using (ExcelRange rng = ws.Cells["A1:B1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Gold); //Set color to DarkGray
rng.Style.Font.Color.SetColor(Color.Black);
}
return pck;
}
So, now it export data for Table GroubBy = ScenarioList. I want to also include another column in groupBy = Username. So when Export data, Excel file should contain 2 Sheets. 1 for Table ScenarioList, and 2nd for Table Username.
Help is much appreciated. Thank you in advance.
You need create div/table under which put all tables and then by using below javascript function. Please call this javascript function on button click on same page which have all data. This is working for me which I already used in my project.
function DownloadToExcel() {
var htmls = $("#compareBodyContent")[0].innerHTML; // this main element under which
//all you data
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
};
var ctx = {
worksheet: 'Worksheet',
table: '<table>' + htmls + '</table>'
}
var compareLink = document.createElement("a");
compareLink.download = "Compare_Test.xls";
compareLink.href = uri + base64(format(template, ctx));
compareLink.click();
}
Hope this will help you. Let me know if you have any question on this.

How do you make Music shuffle on Android Studio? Using or without using arrays

I need help making the songs Shuffle (mixed) but I don't know how and also I want it to go to another music each time without repeating.
public class MusicMix {
private Music music1, music2, music3, music4, music5,music6,music7,music8,music9,music10,music11,music12,music13,music14,music15,music16,music17;
music1 = Gdx.audio.newMusic(Gdx.files.internal("musicA.mp3"));
music2 = Gdx.audio.newMusic(Gdx.files.internal("musicB.mp3"));
music3 = Gdx.audio.newMusic(Gdx.files.internal("musicC.mp3"));
music4 = Gdx.audio.newMusic(Gdx.files.internal("musicD.mp3"));
music5 = Gdx.audio.newMusic(Gdx.files.internal("musicE.mp3"));
music6 = Gdx.audio.newMusic(Gdx.files.internal("musicF.mp3"));
music7 = Gdx.audio.newMusic(Gdx.files.internal("musicG.mp3"));
music8 = Gdx.audio.newMusic(Gdx.files.internal("musicH.mp3"));
music9 = Gdx.audio.newMusic(Gdx.files.internal("musicJ.mp3"));
music10 = Gdx.audio.newMusic(Gdx.files.internal("musicK.mp3"));
music11 = Gdx.audio.newMusic(Gdx.files.internal("musicL.mp3"));
music12 = Gdx.audio.newMusic(Gdx.files.internal("musicM.mp3"));
music13 = Gdx.audio.newMusic(Gdx.files.internal("musicN.mp3"));
music14 = Gdx.audio.newMusic(Gdx.files.internal("musicO.mp3"));
music15 = Gdx.audio.newMusic(Gdx.files.internal("musicP.mp3"));
music16 = Gdx.audio.newMusic(Gdx.files.internal("musicQ.mp3"));
music17 = Gdx.audio.newMusic(Gdx.files.internal("musicR.mp3"));
}
First of all create first an array that should make your life easier. Instead of manually doing it one by one.
Array<Music> musics = new Array<Music>();
for (int i = 65; i < 25; i++) {
//The ascii of 65 = A
char ascii = (char) i;
Music music = Gdx.audio.newMusic(Gdx.files.internal("music" + ascii + ".mp3"));
musics.add(music);
}
Then after that just call this method. It's a built-in method in Libgdx. This method should answer your question.
musics.shuffle();
I tried to implement your requirement in this way.
public class TestGame extends Game {
private Array<String> musicName;
private Array<Music> musicList;
private IntArray intArray;
#Override
public void create() {
musicName=new Array<String>(new String[]{"sound/x1.ogg","sound/x2.ogg","sound/x3.ogg","sound/x4.ogg","sound/x5.ogg"});
musicList=new Array<Music>();
intArray=new IntArray();
for (String path:musicName) {
Music music=Gdx.audio.newMusic(Gdx.files.internal(path));
musicList.add(music);
intArray.add(musicName.indexOf(path,true));
music.setOnCompletionListener(new OnComplete(this));
}
int value=MathUtils.random(musicList.size-1);
intArray.removeValue(value);
musicList.get(value).play();
}
public class OnComplete implements Music.OnCompletionListener {
private TestGame testGame;
public OnComplete(TestGame game){
testGame=game;
}
#Override
public void onCompletion(Music music) {
testGame.playUnPlayedMusic();
}
}
public void playUnPlayedMusic(){
int value ;
if(intArray.size>0) {
value = intArray.get(MathUtils.random(intArray.size - 1));
intArray.removeValue(value);
}else {
for (int i=0;i<musicList.size;i++)
intArray.add(i);
value = intArray.get(MathUtils.random(intArray.size - 1));
intArray.removeValue(value);
}
Music music= musicList.get(value);
music.play();
}
#Override
public void render() {
}
}

how to generate sequence number using c# in window application

private string GenerateID()
{
}
private void auto()
{
AdmissionNo.Text = "A-" + GenerateID();
}
with prefix of A like below
A-0001
A-0002 and so on .
You can use below code.
private string GenerateId()
{
int lastAddedId = 8; // get this value from database
string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
return demo;
// it will return 0009
}
private void Auto()
{
AdmissionNo.Text = "A-" + GenerateId();
// here it will set the text as "A-0009"
}
Look at this
public class Program
{
private static int _globalSequence;
static void Main(string[] args)
{
_globalSequence = 0;
for (int i = 0; i < 10; i++)
{
Randomize(i);
Console.WriteLine("----------------------------------------->");
}
Console.ReadLine();
}
static void Randomize(int seed)
{
Random r = new Random();
if (_globalSequence == 0) _globalSequence = r.Next();
Console.WriteLine("Random: {0}", _globalSequence);
int localSequence = Interlocked.Increment(ref _globalSequence);
Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
}
}
Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:
public sealed class Sequence
{
private int value = 0;
public Sequence(string prefix)
{
this.Prefix = prefix;
}
public string Prefix { get; }
public int GetNextValue()
{
return System.Threading.Interlocked.Increment(ref this.value);
}
public string GetNextNumber()
{
return $"{this.Prefix}{this.GetNextValue():0000}";
}
}
This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.

Limit string to eight characters and return it with asterisk

I have a studentDto. I want to determine the number
of characters for LastName. If number of characters is greater
than 8, I want to return the last name of 8 characters with two asterisk thus
cutting off the other characters
e.g Abumadem**
Here is how I started.I am unable to get it to work. Can you please assist?
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
int count=0;
List<char> storeStrings = new List<char>();
if (checkLength > 8)
{
foreach (var c in LastName)
{
storeStrings.Add(c);
if ()
{
}
count++;
}
}
}
}
}
Here is new attempt and no luck yet.
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
if (checkLength > 8)
{
First8Chars = LastName.Substring(0, 7) + "**";
return First8Chars;
}
}
set { }
}
}
Just do it like this:
string _backingFieldLastName;
public string LastName
{
get
{
return _backingFieldLastName == null || backingFieldLastName.Length <=8 ?
_backingFieldLastName :
_backingFieldLastName.Substring(0,8) +"**"; // second parameter of substring is count of chars from the start index (first parameter)
}
set
{
_backingFieldLastName = value;
}
}
If you cant use library functions for some reason:
private string _lastName = "";
public string LastName
{
get
{
var checkLength = _lastName.Length;
string First8Chars = string.Empty;
string storeStrings = "";
if (checkLength > 8)
{
foreach (var c in _lastName)
{
storeStrings += c;
if (storeStrings.Length == 8)
{
storeStrings += "**";
return storeStrings;
}
}
}
return storeStrings;
}
set { _lastName = value; }
}
One thing I noticed is your use of LastName in the LastName property getter, a big no no, its causing recursion and you probably are getting a stack overflow exception
This could be written more concise, but I'll leave that as an exercise for you
The Linq way:
var lastname = "Abumademal";
var formatted = (new string(lastname.Take(8).ToArray())).PadRight(lastname.Length, '*');
// will yield "Abumadem**"
"Take 8 chars and create a new string from this array, then pad it with as many * as needed."
full implementation:
private string lastname;
public string LastName
{
get
{
if (null == this.lastname)
{
return null;
}
char[] firsteight = this.lastname.Take(8).ToArray();
string tmp = new string(firsteight);
// padding this way wasn't the actual requirement ...
string result = tmp.PadRight(this.lastname.Length, '*');
return result;
}
set
{
this.lastname = value;
}
}

Reverse String Palindrome

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.

Resources