Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, August 13, 2025

Error: Configuration system failed to initialize

C#

Windows Service.


I was never going to fix this one by myself there was no ChatGPT.

The cause was the corruption of the user.config file.

That was located in a folder that I did not even know about:

C:\Windows\system32\config\systemprofile\AppData\Local\<AppName>\<AppName.exe>_Url_<hash>\<version>\user.config


Friday, April 2, 2021

Fastest C# compare string

 Use 


string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)


instead of toupper or tolower

Tuesday, April 26, 2011

DataTable move the Column

If I don't put the code here, I bet I'll never find it again when I need it ...





DataColumn dc = dtRatesManagerAll.Columns["RateId"];
dc.SetOrdinal(dtRatesManagerAll.Columns.Count - 1);



Thursday, March 10, 2011

Download file from server

Download xlsx file from server
(already created)






public void GenerateXLSXFile(string fileName, ExcelDocument theDocument)
{
string filePath = Server.MapPath("~/TempFiles/" + fileName + ".xlsx");
theDocument.esd_WriteXLSXFile(filePath);

Response.Clear();
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
Response.WriteFile(filePath);

Response.Flush();
System.IO.File.Delete(filePath);
Response.End();
}



Tuesday, August 31, 2010

Textbox validate characters digits only - Desktop App

I wanted to let the user enter onlydigits in a Textbox and validate the characters when the types.
I came up with this:





private void numericUpDown_Count_KeyPress(object sender, KeyPressEventArgs e)
{
if ("1234567890".IndexOf(e.KeyChar.ToString()) > 0)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}





tell me if there's an easier way :)

Tuesday, March 2, 2010

Enum to DataTable

I had a lot of ENUM-s and needed to make DataTable - s with the same structure for pretty much all of them.
I came up with this:




private static DataTable CreateDataTable < TheSQLtable > ()
{
Type t = typeof(TheSQLtable);
if (!t.IsEnum)
{
throw new InvalidOperationException("Type is not Enum");
}

DataTable dt = new DataTable();
dt.TableName = t.Name;
DataColumn dc;

string[] names = Enum.GetNames(t);
foreach (string name in names)
{
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = name;
dc.Unique = false;
dt.Columns.Add(dc);
}

return dt;
}





(with a little help from stackoverflow)

Wednesday, February 24, 2010

How to check in C# if a DataRow is Empty. (nothing in any column)

I was hoping i find something like dr.isEmpty(), but there's nothing "this nice". So you do something plain like:





bool AreAllColumnsEmpty(DataRow dr)
{
if (dr == null)
{
return true;
}
else
{
foreach(var value in dr.ItemArray)
{
if (value != null)
{
if (value.ToString() != "")
{
return false;
}
}
}
return true;
}
}



Monday, September 29, 2008

The ConnectionString property has not been initialized.

The ConnectionString property has not been initialized.

????

:D

it is sooo easy. but you can waste a lot of time on this one.

Here is what was my problem:
1.) web.config:

< appSettings >
< add key="aaa" value="server=swoosh\sqlserver2k5;database=swdb;uid=sa;password=;" />
< / appSettings >

2.) accessing:
string strConnRSS = System.Configuration.ConfigurationManager.AppSettings["bbb"];

yes.
aaa <> bbb

Hope this'll help someone :)
don't look for anything too complicated :)

Friday, September 19, 2008

Monthname in C# (C Sharp)

I think there's no Monthname (like is asp for ex. - which is weird)

But this is easy:

DateTime swTest = new DateTime(2000, 11, 1);
Page.Response.Write(swTest.ToString("MMMM"));

Monday, September 1, 2008

Calling a server side from client's Javascript

Did you ever need something like calling a server side thing from client's? Javascript ... ?

I think this is an easy way of doing that:





Response.Write ( " < script language="javascript"> function SetPmoR_Id() { document.all('" + lkbPmoRepAdd.ClientID + "').click(); } < / script>")

//or:

ClientScript.RegisterClientScriptBlock(this.GetType(), "somethn", " < script type='text/javascript'> function whatdoyouwannacalit() { try {document.all('" + yourlinkbutton.ClientID + "').click();} catch(e){} } < / script>");






what do you think?

you think there's an easier way? comment!

Wednesday, August 20, 2008

DataTable C# Primary Key column .Contains

I needed to do something like use DataTable in C#, set Primary Key column, and later on maybe a "contains" ... to see if my set of ID is inside the DataTable
Anyways: this is how I did it:





DataTable myFilteredTerms = objSomethn.getresultsinDT ...
DataColumn[] myPrimaryKeyColumn = new DataColumn[1];
myPrimaryKeyColumn.SetValue(myFilteredTerms.Columns[0], 0);
myFilteredTerms.PrimaryKey = myPrimaryKeyColumn;

...

if (myFilteredTerms.Rows.Contains(intTheIdYouAreLookingFor))
{
...
}





(first column is the one with the ID-s ...)

as always, if you got pro or contra ... tell me bout it

Friday, August 15, 2008

How to count enum elements in C#?

If you need to count the enum elements ...

this is how you do it:

int nYourNumber = Enum.GetValues(typeof(YourEnumName)).Length;

as always: if you have something neater ;) comment ... I'll update the post if needed ;)

Friday, July 11, 2008

Ajax Databind – javascript error “unknown runtime error”

I had this error a few minutes ago. It was the weirdest thing. On a Save button (linkbutton) I had a gridview repopulated using Ajax. The Save linkbutton was also added as a trigger for the Ajax’s UpdatePanel. The save went well, saved in the database, but when it came to refresh the gridview, this javascript error popped up.

The fix was move the stuff around. Scriptmanager, UpdatePanel, ObjectDataSource … all of them inside the form … Anyways … if you have this error, you don’t necessarily have a big problem, you just need to figure out what did you put in the wrong place.





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

< ajax:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true">
< Services>
< ajax:ServiceReference Path="../Include/WebService.asmx" InlineScript="true" />
< /Services>
< /ajax:ScriptManager>
< ajax:UpdatePanel ID="up2" runat="server">
< ContentTemplate>
< asp:GridView>
...
< /asp:GridView>
< /ContentTemplate>
< Triggers>
< ajax:AsyncPostBackTrigger ControlID="lbnSave" EventName="Click" />
< /Triggers>
< /ajax:UpdatePanel>

< asp:ObjectDataSource ID="ods" ...
< SelectParameters>
< asp:QueryStringParameter ...
< /SelectParameters>
< /asp:ObjectDataSource>

< /form>






see ya

Thursday, July 3, 2008

C# convert mm/dd/yyyy string to "5 minute(s) ago"

this is how utube does it:



For a forum-kinda thing I wanted to (C#) convert mm/dd/yyyy string to "5 minute(s) ago" - like Youtube does.

Here's how u I did it:
(please feel free to comment, get me a better way to do this :D)





/// < summary>
/// transform into "9 hours ago" or "8 days ago" etc ...
/// < /summary>
/// < param name="makeThisNiceDateFormat">some date string ... "mm/dd/yyyy"< /param>
/// < returns >example: "5 minute(s) ago"< /returns>
public static string ConvertDateToHoursAgo(string makeThisNiceDateFormat)
{
if (!IsDate(makeThisNiceDateFormat))
{
return makeThisNiceDateFormat;
}
else
{
DateTime dtOriginal = DateTime.Parse(makeThisNiceDateFormat);
//check if we need to display minutes
if (Math.Abs(DateDiff(DateInterval.Minute, dtOriginal, DateTime.Now)) < 60)
{
if (DateDiff(DateInterval.Minute, dtOriginal, DateTime.Now) == 0)
{
return "just now";
}
return (Math.Abs(DateDiff(DateInterval.Minute, dtOriginal, DateTime.Now)) + " minute(s) ago");
}
//check if we need to display hours
if (Math.Abs(DateDiff(DateInterval.Hour, dtOriginal, DateTime.Now)) < 24)
{
return Math.Abs(DateDiff(DateInterval.Hour, dtOriginal, DateTime.Now)) + " hour(s) ago";
}
//check if we need to display days
if (Math.Abs(DateDiff(DateInterval.Day, dtOriginal, DateTime.Now)) < 31)
{
return Math.Abs(DateDiff(DateInterval.Day, dtOriginal, DateTime.Now)) + " day(s) ago";
}
//check if we need to display months
if (Math.Abs(DateDiff(DateInterval.Month, dtOriginal, DateTime.Now)) < 12)
{
return Math.Abs(DateDiff(DateInterval.Month, dtOriginal, DateTime.Now)) + " month(s) ago";
}
return Math.Abs(DateDiff(DateInterval.Year, dtOriginal, DateTime.Now)) + " year(s) ago";
}
}





thoughts?
Note: I got an IsDate function in there which returns true/false ... in case someone tries to send me something that is not a date ...

Tuesday, June 24, 2008

nHibernate - a thing i like

I have a table: Act, and an other table Service Name
between them, there's an other table, that has actId and ServicenameId too ...

I needed somehow for the act object to see all the servicenames. somehow ... in a list maybe? or an ilist?

Here's how u do it:




< bag name="ServiceNameList" lazy="false" table="BOMMSS_ServiceNameAct">
< key column="TARFSS_ActId"/>
< many-to-many class="Atlas.Tariff.DataAccess.ServiceName,Atlas.Tariff.DataAccess" column="ServiceNameId"/>
< /bag>




in the mapping file (xml), and add something like this:




public IList ServiceNameList
{
get { return m_servicenamelist; }
set { m_isChanged |= (m_servicenamelist != value); m_servicenamelist = value; }
}




in the class def.

Thursday, June 5, 2008

nHibernate vs. Active Record

I have used nHibernate in 3 projects

read more on it here and here

I didn't like it because of the XML stuff.

next time i'll use Active Record (read more about that here), to see how that behaves, maybe i'll post something new afterwards ;)

Wednesday, April 16, 2008

GridView Id column

If I make a "BoundColumn" for the Id, with visible - false, I can't get the Id ...

This one works:
(rowdatabound)




e.Row.Cells["mycolumn"].Style.Add("display", "none");




this way the Id is still there, you just cannot see it...