Wednesday

c# return zip stream from api

  
        public Stream GetDataFile(string locationId)
        {
            int cid;
            DateTime tran = DateTime.Now.Date;

            Check(string.IsNullOrWhiteSpace(locationId), "locationId field is missing.");
            Check(!int.TryParse(locationId, out cid), "locationId must be numeric.");


            DataFileRepository repository = new DataFileRepository();
            /*returning stream*/
            var resp = WebOperationContext.Current.OutgoingResponse;
            resp.ContentType = "application/octet-stream";
            resp.Headers.Add("Content-Disposition", "attachment; filename=\"myfile.zip\"");

            return ZipStream(repository.GetCSVStream(cid));
        }

        /// <summary>
        ///  Check condition and generate exception if condition met.
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="exp"></param>
        public void Check(bool condition, string exp)
        {
            if (condition)
            {
                AssertionException up = new AssertionException(exp);
                throw up;
            }
        }

        /// <summary>
        ///  Method for zipping streams 
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public Stream ZipStream(Stream stream)
        {
            stream.Position = 0;
            var ar = new ZipArchive();
            ar.AddItem("myfile.csv", stream, true, FileAttributes.Normal);

            var zip = new TempFileStream();
            ar.Save(zip, false);
            zip.Position = 0;
            return zip;
        }
interface declaration in API webservice is very simple:
      
  [OperationContract]
        [WebGet(UriTemplate = "menu/datafile/{locationId}")]
        Stream GetDataFile(string locationId);
   

IDataReader into csv

        
        /// <summary>
        ///  Method for converting reader into CSV
        /// </summary>
        /// <param name="dataReader"></param>
        /// <param name="includeHeaderAsFirstRow"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public  Stream ToCSV(IDataReader dataReader, bool includeHeaderAsFirstRow, string separator)
        {
            Stream csv = new TempFileStream();
            StreamWriter csvRows = new StreamWriter(csv);
            StringBuilder sb = null;

            if (includeHeaderAsFirstRow)
            {
                sb = new StringBuilder();
                for (int index = 0; index < dataReader.FieldCount; index++)
                {
                    if (dataReader.GetName(index) != null)
                        sb.Append(dataReader.GetName(index));

                    if (index < dataReader.FieldCount - 1)
                        sb.Append(separator);
                }
                csvRows.WriteLine(sb.ToString());
            }

            while (dataReader.Read())
            {
                sb = new StringBuilder();
                for (int index = 0; index < dataReader.FieldCount - 1; index++)
                {
                    if (!dataReader.IsDBNull(index))
                    {
                        string value = dataReader.GetValue(index).ToString();
                        if (dataReader.GetFieldType(index) == typeof(String))
                        {
                            //If double quotes are used in value, ensure each are replaced but 2.
                            if (value.IndexOf("\"") >= 0)
                                value = value.Replace("\"", "\"\"");

                            //If separtor are is in value, ensure it is put in double quotes.
                            if (value.IndexOf(separator) >= 0)
                                value = "\"" + value + "\"";
                        }
                        sb.Append(value);
                    }

                    if (index < dataReader.FieldCount - 1)
                        sb.Append(separator);
                }

                if (!dataReader.IsDBNull(dataReader.FieldCount - 1))
                    sb.Append(dataReader.GetValue(dataReader.FieldCount - 1).ToString().Replace(separator, " "));

                csvRows.WriteLine(sb.ToString());
            }

            csvRows.Flush();
            dataReader.Close();
            return csv;
        }
 

Monday

register dlls into GAC on server 2012

You may noticed that gacutil is missing in on server 2012.There is no clear way to download and install gacutil or have portable gacutil.exe to deploy. This powershell script will register multiple dlls from folder.
   
# adds all dll files from folders into GAC 
# **** Attention *** in case of permission/signature  error Execute this command from powershell to allow run powershell files : Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

# load System.EnterpriseServices assembly
[Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") > $null

# create an instance of publish class
[System.EnterpriseServices.Internal.Publish] $publish = new-object System.EnterpriseServices.Internal.Publish


Get-ChildItem "C:\Program Files (x86)\Microsoft Enterprise Library 5.0\Bin" -Filter *.dll |
Foreach-Object {
    $content = $_.FullName
    Write-Output "registering "+$content;
    $publish.GacInstall($content)
}

Change path if you have to do batch install dlls from another directory.

Wednesday

add xml to xmldocument

     
static string module = @"
    <Module>
      <CustomerSortOrder>60</CustomerSortOrder>
      <LinkText_Customer>{0}</LinkText_Customer>
      <LocationId>4291</LocationId>
      <LocationModuleId>26544</LocationModuleId>
      <ModuleId>30</ModuleId>
      <ModuleName>Menu</ModuleName>
      <NavigateUrl>menu.aspx</NavigateUrl>
      <pageId>20</pageId>
      <IsModuleGroup>1</IsModuleGroup>
      <sort_order>1</sort_order>
      <MenuId>{1}</MenuId>
    </Module>
";
        public string AddWeekMenu(string xml2015, string xml2010) {
            string result = xml2015;
            try
            {
                XmlDocument x2015 = new XmlDocument();
                x2015.LoadXml(xml2015);

                //step 1 find menu tag group
                var menutag = x2015.SelectSingleNode("//Group[Group_Name='Menu']");
                //remove Menu text from second list
                menutag.ChildNodes[0].SelectSingleNode("//LinkText_Customer").InnerText = "";

                XmlDocument x2010 = new XmlDocument();
                x2010.LoadXml(xml2010);
                XmlNodeList m2010 = x2010.SelectNodes("//ChildNavigation[moduleid=30]");

                foreach (XmlNode item in m2010)
                {
                    //append menu links from 2010
                    AppendMenuLink(x2015, menutag, item.SelectSingleNode("ChildLinkText").InnerText, item.SelectSingleNode("ChildLinkCustomPageID").InnerText);

                }

                //updting menu tag  with correct count 
                menutag.SelectSingleNode("//numModules").InnerText = ""+m2010.Count;
                return x2015.OuterXml;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }

            return result;
        }

Tuesday

Game servers sources

sources of lineage 2
java: bitbucket.org/…​com/l2jserver/?at=develop

go: github.com/mikesaidani/l2go

а WOW
github.com/mangoszero/server

handlebars.js subtemplate example


step1.create subtemplate
<script id="nutri" type="text/x-handlebars">
    <p>
     This is subtemplate in Handelbars
     </p>
</script>

step2.register it in javascript

<script type="text/javascript">
    Handlebars.registerPartial('nutri', $('#nutri').html());
</script>

step3. use it into another subtemplate

<script id="package-list-bottom" type="text/x-handlebars-template">
    <div class='po-qty form-el bottom'>        
                <p>
                {{> nutri}}
                </p>
    </div>
</script>

why my app is not popular on appstore?

You finished app uploaded it on appstore and .... nothing happens. You probably was expecting skyrocketing installs and in-app sales but after days,weeks you got some 10,20 installs. And you thinking what is wrong with my app.

The best way to look at this situation is to look at app like art-artifact. Let's say when you have painting picture or sculpture you are not expecting it to look like Rembrant's or Michelangelo's aren't you ? So why it is different in regards of apps ?

Probably because at first look all applications are looking alike and have unified interface and same buttons and UI elements. But the most important things are in details, in iterations between application and user.

The best way to handle this situation is to continue perfecting and creating more apps and make them looks closer to perfect apps every day and learn. As Michelangelo said : "I am still learning."

Monday

c# custom webservice logging and error handling

//step1.declare delagate
public delegate T UnSafeProcedure<T>();

/*step2. add performance and error handling methods */
        public string Concat(params object[] arguments)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in arguments)
            {
                sb.AppendFormat("\"{0}\",", item);
            }
            return sb.ToString();
        }

        public T RunSafe<T>(UnSafeProcedure<T> s, params object[] arguments)
        {
            DateTime st = DateTime.Now;
            try
            {
               return  s();
            }
            catch (Exception e1)
            {
                {
                    Debug.Write("Error," + Concat(arguments) + "\r\n" + e1.ToString());
                }
                return default(T);
            }
            finally
            {
                var sec = DateTime.Now.Subtract(st).TotalSeconds;
                if (sec > 20)
                {
                    string tm = ">20sec,start," + st.ToLongTimeString() + ",End," + DateTime.Now.ToLongTimeString();
                    Debug.Write(tm+ Concat(arguments));
                }
            }
        }

/*3.performance counting procedures will looks like:*/

public Receipt VerifyUser(int Id, string username, string password)
{
           return  RunSafe<Receipt>(delegate()
            {
                //internal procedure that needs to be chcked troubleshooted
                using (var service = Instance())
                {
                    return service.VerifyAccount(Id, username, password);
                }

            }, "VerifyUser,facilityId",Id,"username",username,"password",password);
}

how to add vim pandoc integration for markdown files

autocmd BufEnter *.md exe 'noremap <F5> :silent !start c:\tools\pd.bat  % <CR>'

and autorefresh plugin for chrome: so every time I hit F5 on markdown (.md) file I can see compiled html version in chrome

Where pd.bat file is following:

pandoc "%1" -f markdown -t html -s -o "%1.html"

create sign up form for google group

here is javascrip/html code how to do it:

<script type="text/javascript">
   function msgbox() {   alert("An Invatation has been sent to " + _gel("emailconf").value 
+ ". You will have to confirm the email invitation to join and recieve future emails. 
You can opt out of our group at anytime using the Unsubscribe link in the email."); }
</script>

    Sign up with our google group to receive [product] updates or ask questions.
  <form action="http://groups.google.com/group/whiterocksoftware/boxsubscribe" id="formconf" onsubmit="msgbox()">
  Email: <input type=text name=email id="emailconf">
   <input type="submit" value="Subscribe">
</form>

Thursday

rainmeter slideshow skin tutorial

here is skin I used to show images :
 
[Rainmeter]
Update=100000
BackgroundMode=3
SolidColor=0,0,0,255
BackgroundMode=3
BackgroundMargins=0,34,0,14

[MeasureQuote]
Measure=Plugin
Plugin=QuotePlugin
PathName=c:\temp\trig
Subfolders=1
FileFilter=*.jpg;*.png;*.gif

[MeterQuote]
Meter=Image
MeasureName=MeasureQuote
X=0
Y=0
W=200
PreserveAspectRatio=1
LeftMouseUpAction=[!Refresh]

test smtp server with powershell

Send-MailMessage -SMTPServer smtp.domain.com -To [email protected] -From [email protected] -Subject "This is a test email" -Body ...